<?php

require_once('config.php');
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

function push_notification_android($token, $message, $title, $sitecode, $tokenlist, $RowID, $row, $tkn_site, $LOGINID) {

    require_once('f_insert_notification_log_send.php');
    require '../../vendor/autoload.php';
	
	
	global $conn;
	
	// === 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) {
        //file_put_contents('_token_error.log', date('Y-m-d H:i:s') . ' >>> Token Error: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
        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";

    $payload = [
        'message' => [	
            'token' => $token,
            'data' => [
                'title'    => $title,
                'body'     => $message,
                'message'  => $sitecode,
                'activity' => 'Web'
            ],
            'android' => [
                'priority' => 'high',
            ],
            'apns' => [
				'headers' => [
                    'apns-priority' => '10',
					
                ],
                'payload' => [
                    'aps' => [
						'alert' => [
                            'title' => $title,
                            'body' => $message
                        ],
					   'sound' => 'default'
					],
                ]
            ]
        ]
    ];

    $client = new Client();

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

        $responseBody = json_decode($response->getBody()->getContents(), true);
        //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);
		insert_notification_log_send($sitecode, $row, $tkn_site, $tokenlist, $RowID, 'S', 'Sucess: ' . json_encode($responseBody, JSON_PRETTY_PRINT), $LOGINID);

    } 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);
		insert_notification_log_send($sitecode, $row, $tkn_site, $tokenlist, $RowID, 'E', 'FCM Error: ' . json_encode($errorJson, JSON_PRETTY_PRINT), $LOGINID);
		// 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";
			//insert_notification_log_send($sitecode, $row, $tkn_site, $tokenlist, $RowID, 'E', 'UNREGISTERED Error: ' . json_encode($errorJson, JSON_PRETTY_PRINT), $LOGINID);
			
			// 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($sitecode,$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";
    }
}


?>