<?php
require_once('config.php');
require_once('f_insert_notification_log_send.php');

//composer require google/apiclient
require '../../vendor/autoload.php';

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


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


	// Path to your Firebase Service Account JSON file
	$serviceAccountPath = '..\..\react-native-cmms-firebase-adminsdk-l1avp-dfd52abfc2.json';

	// Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of your service account JSON
	putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $serviceAccountPath);


	// Define the required scope for FCM
	$scopes = ['https://www.googleapis.com/auth/firebase.messaging'];

	// Create the credentials object to retrieve the OAuth token
	$auth = ApplicationDefaultCredentials::getCredentials($scopes);

	// Fetch the access token
	$accessToken = $auth->fetchAuthToken()['access_token'];

	// Firebase Cloud Messaging v1 API URL
	$projectId = 'react-native-cmms';
	$url = "https://fcm.googleapis.com/v1/projects/{$projectId}/messages:send";

	$data = [
		'message' => [
			'token' => $token, // The FCM device token
			'notification' => [
				'title' => $title,
				'body'  => $message,
			],
			'data' => [
				'title' => $message,
				'message' =>$sitecode,
				'activity'=>'Web'
			],
			'apns'=>[
				'payload' =>[
					'aps'=>[
						'sound' =>'default'

					]
				]
			]
		]
	];




	// Encode the payload as JSON
	$payload = json_encode($data);

	// Initialize cURL session
	$ch = curl_init();

	// Set the cURL options
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	// Set the headers
	$headers = [
		'Authorization: Bearer ' . $accessToken,
		'Content-Type: application/json',
	];
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

	// Set the payload
	curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

	// Execute the cURL request and get the response
	$response = curl_exec($ch);

	// Check for cURL errors
	if (curl_errno($ch)) {
		//echo 'cURL error: ' . curl_error($ch);

		$insert_ntf_send = insert_notification_log_send($sitecode, $row, $tkn_site, $tokenlist, $RowID, 'E', curl_error($ch),$LOGINID);

	} else {
		// Decode the response (if needed) and print it
		//$responseBody = json_decode($response, true);
		//print_r($responseBody);

		$insert_ntf_send = insert_notification_log_send($sitecode, $row, $tkn_site, $tokenlist, $RowID, 'S',  $response,$LOGINID);

	}

	// Close the cURL session
	curl_close($ch);
	return $response;



}




?>