<?php
require_once('config.php');
require '../../vendor/autoload.php';

use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

// === SETUP SERVICE ACCOUNT ===
$serviceAccountPath = '../../react-native-cmms-firebase-adminsdk-l1avp-dfd52abfc2.json';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $serviceAccountPath);

$scopes = ['https://www.googleapis.com/auth/firebase.messaging'];

// === AUTHENTICATE ===
try {
	$auth = ApplicationDefaultCredentials::getCredentials($scopes);
	$accessToken = $auth->fetchAuthToken()['access_token'];
} catch (\Exception $e) {
	insert_notification_log_send($sitecode, $row, $tkn_site, $tokenlist, $RowID, 'E', 'Token Error: ' . $e->getMessage(), $LOGINID);
	return false;
}

// === FIREBASE PROJECT ID ===
$projectId = 'react-native-cmms';
$url = "https://fcm.googleapis.com/v1/projects/{$projectId}/messages:send";


$sql_wko_tkn_mst = "	SELECT 	tkn_site,
									tkn_online,
									tkn_dvc_id,
									RowID,
									tkn_token 
							FROM	tkn_mst (NOLOCK) 
							WHERE  	tkn_user = ? 
							AND		tkn_online = '1'
							AND		tkn_site = ? ";

	//$params_wko_tkn_mst = array('EVANTAGE001', 'CPI');	
$params_wko_tkn_mst = array('SEKHAR_EMP', 'CPI');	
	$stmt_wko_tkn_mst = sqlsrv_query( $conn, $sql_wko_tkn_mst, $params_wko_tkn_mst);	
			
	if( !$stmt_wko_tkn_mst ) {
		$error_message = "Error Select table (tkn_mst)";
		returnError($error_message);
		die( print_r( sqlsrv_errors(), true));
	}
	do {
		 while ($row = sqlsrv_fetch_array($stmt_wko_tkn_mst, SQLSRV_FETCH_ASSOC)) {
		 
		 $tkn_dvc_id = $row['tkn_dvc_id'];
		 $deviceTokens[] = $row['tkn_token'];
		 $tkn_online = $row['tkn_online'];
		 $tkn_site = $row['tkn_site']; 
		 $RowID = $row['RowID'];
		 $a1[]=array("token"=>$row['tkn_token'],"RowID"=>$row['RowID'],"tkn_site"=>$row['tkn_site']);

	   }
	} while ( sqlsrv_next_result($stmt_wko_tkn_mst));
	
	sqlsrv_free_stmt( $stmt_wko_tkn_mst);
	

// === STATIC MESSAGE DATA ===
$title = 'New Work Request';
$body  = 'The work Request WKR100444 is subitted';
$extraData = ['extra_key' => 'extra_value'];

// === INIT HTTP CLIENT ===
$client = new Client();

// === SEND NOTIFICATION TO EACH TOKEN ===
foreach ($deviceTokens as $token) {
    $data = [
        'message' => [
            'token' => $token,
            'data' => [
                'title' => $title,
                'body' => $body,
                'message' => $body,
                'activity' => 'Web'
            ],
            'android' => [
                'priority' => 'high',
                
            ],
            'apns' => [
                'headers' => [
                    'apns-priority' => '10'
                ],
                'payload' => [
                    'aps' => [
                        'alert' => [
                            'title' => $title,
                            'body' => $body
                        ],
                        'sound' => 'default'
                    ]
                ]
            ]
        ]
    ];

    try {
        $response = $client->post($url, [
            'headers' => [
                'Authorization' => 'Bearer ' . $accessToken,
                'Content-Type'  => 'application/json',
            ],
            'body' => json_encode($data),
            'timeout' => 10
        ]);

        $responseBody = json_decode($response->getBody()->getContents(), true);
        echo "✅ Sent to token: $token\n";
        print_r($responseBody);

        // Log success
        file_put_contents('_payload.log', date('Y-m-d H:i:s') . " >>> Token: $token\n" . json_encode($data, JSON_PRETTY_PRINT) . PHP_EOL, FILE_APPEND);

    } catch (RequestException $e) {
        $errorBody = $e->hasResponse()
        ? $e->getResponse()->getBody()->getContents()
        : $e->getMessage();

		// Decode JSON error safely
		$errorJson = json_decode($errorBody, true);

		// Log full error raw (optional)
		file_put_contents('_fcm_error.log', date('Y-m-d H:i:s') . " >>> Token: $token >>> $errorBody\n", FILE_APPEND);

		// Check if it's UNREGISTERED
		if (
			isset($errorJson['error']['details'][0]['errorCode']) &&
			$errorJson['error']['details'][0]['errorCode'] === 'UNREGISTERED'
		) {
			file_put_contents('_fcm_invalid_tokens.log', date('Y-m-d H:i:s') . " >>> UNREGISTERED Token: $token\n", FILE_APPEND);
			//echo "⚠  Token is UNREGISTERED and should be removed.\n";
			
			// Update tkn_mst to logout the previous session
			$sql_tkn_mst = "UPDATE tkn_mst 
							SET tkn_logout = GetDate(),
								tkn_online = '0'							
							WHERE tkn_site =?
							AND tkn_token =?";

			$params_tkn_mst = array('CPI',$token);
			$stmt_tkn_mst = sqlsrv_query($conn, $sql_tkn_mst, $params_tkn_mst);

			if (!$stmt_tkn_mst) {
				$error_message = "Error updating tkn_mst table: " . print_r(sqlsrv_errors(), true);
				sqlsrv_rollback($conn);
				returnError($error_message);
			}

			sqlsrv_free_stmt($stmt_tkn_mst);
		}

		// Optional: print full error
		echo "❌ Failed for token: $token\n$errorBody\n";
    }
}