<?php
include '../connect/cms-config.php' ;
include '../requires/function.php' ;
include_once( '../vendor/autoload.php' ) ;


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

$credentialsPath    = 'hr-system-b0af6-firebase-adminsdk-u5wel-5bcb3596d4.json' ; // Replace with your actual path
$projectId          = '517510861795' ; // Your Firebase project ID or project number

function getAccessToken($credentialsPath) {
    $scopes         = ['https://www.googleapis.com/auth/firebase.messaging'];

    // Get OAuth2 token using service account credentials
    $credentials    = json_decode(file_get_contents($credentialsPath), true);
    $client         = new Google_Client();
    $client->setAuthConfig($credentials);
    $client->setScopes($scopes);

    // Get the token
    $accessToken    = $client->fetchAccessTokenWithAssertion()['access_token'];

    return $accessToken;
}


// single send
function sendFCMNotification($projectId, $deviceTokens, $messageTitle, $messageBody, $dataPayload, $credentialsPath) {
    $accessToken    = getAccessToken($credentialsPath);
    $url            = 'https://fcm.googleapis.com/v1/projects/' . $projectId . '/messages:send';

    $client         = new \GuzzleHttp\Client();

    foreach ($deviceTokens as $deviceToken) {
        $message    = [
            'message' => [
                'token' => $deviceToken,
                'notification' => [
                    'title' => $messageTitle,
                    'body'  => $messageBody
                ],
                'android' => [
                    'notification' => [
                        'sound' => 'default'  // Use this for Android specific sound settings
                    ]
                ],
                'apns' => [
                    'payload' => [
                        'aps' => [
                            'sound' => 'default'  // Use this for iOS specific sound settings
                        ]
                    ]
                ],
                'data' => $dataPayload // Custom data payload
            ]
        ];

        $headers = [
            'Authorization' => 'Bearer ' . $accessToken,
            'Content-Type'  => 'application/json',
        ];

        print_r($message) ;
        print_r($headers) ;

        try {
            $response = $client->post($url, [
                'headers' => $headers,
                'json'    => $message
            ]);

            echo 'Notification sent to ' . $deviceToken . ': ' . $response->getBody()->getContents() . PHP_EOL;
        } catch (RequestException $e) {
            if ($e->hasResponse()) {
                echo 'Error sending to ' . $deviceToken . ': ' . $e->getResponse()->getBody()->getContents() . PHP_EOL;
            } else {
                echo 'Error: ' . $e->getMessage() . PHP_EOL;
            }
        }
    }
}

function pushToNotificationUser( $type, $type_id, $staff_id, $title, $message, $cron_id = '', $inbox_id = '' ){
	global $mysqli, $projectId, $credentialsPath ;

	$push     			= array() ;

	$notifications_query = $mysqli->query( "SELECT notificationid, notification, badge FROM staff_notification
										    WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' ORDER BY notificationid DESC LIMIT 1") ;

	if ( $notifications_query->num_rows > 0 ){

		$notification  = $notifications_query->fetch_assoc() ;
		$token_id      = $notification['notificationid'] ;
		$badge         = ( $notification['badge'] + 1 ) ;

		$is_create     = true ;
		if ( $inbox_id != '' && $inbox_id > 0 ){
			$is_create = false ;
		}

		if ( $is_create ){
			$mysqli->query( "INSERT INTO inbox  ( staff_id, from_table, from_id, receiver_type, view_format, title, description, created_at ) VALUES ( '/".$staff_id."/', '".$type."', '".$type_id."', '3', 'message', '".$title."', '".$message."', '".TODAYDATE."' )" ) ;

			$inbox_id  = $mysqli->insert_id ;

			$mysqli->query( "INSERT INTO staff_inbox_view ( inbox_id, staff_id, is_read ) VALUES ( '".$inbox_id."', '".$staff_id."', '0' )" ) ;

			$mysqli->query( "UPDATE staff_notification_cron SET inbox_id = '".$inbox_id."' WHERE cron_id = '".$cron_id."'" ) ;
		}

		sendFCMNotification( $projectId, [ $notification['notification'] ], dataFilter( $title ), dataFilter( $message ), [
            'go_messageid'  => '',
            'go_page'       => '',
            'go_param'      => ''
        ], $credentialsPath ) ;

		// update badge
		$mysqli->query("UPDATE staff_notification SET badge = '".$badge."' WHERE notificationid = '".$token_id."'") ;
	}

}




$select = $mysqli->query( "SELECT * FROM staff_notification_cron
						   WHERE deleted_at IS NULL AND is_sent = 'no' LIMIT 50" ) ;
if ( $select->num_rows > 0 ){
	while ( $row = $select->fetch_assoc() ){
		pushToNotificationUser( $row['type'], $row['type_id'], $row['staff_id'], $row['title'], $row['message'], $row['cron_id'], $row['inbox_id'] ) ;
		
		$mysqli->query( "UPDATE staff_notification_cron SET is_sent = 'yes' WHERE cron_id = '".$row['cron_id']."'" ) ;
	}
}

?>