<?php
include("metii.php");

$project_id = "metii-v3";
$fileJson = "metii-v3-firebase-adminsdk-fbsvc-51aeef0768.json";

#----------------------------------------
define( 'Firebase_ID', $project_id );
define( 'Firebase_FILE', $fileJson );
#---------------------------------------
function GetFirebaseToken(){
require_once 'vendor/autoload.php';
  $serviceAccountFilePath = Firebase_FILE;
  $serviceAccount = json_decode(file_get_contents($serviceAccountFilePath), true);

  // Generate the JWT using the service account credentials
  $clientEmail = $serviceAccount['client_email'];
  $privateKey = $serviceAccount['private_key'];

  $payload = [
      "iss" => $clientEmail,
      "scope" => "https://www.googleapis.com/auth/firebase.messaging",
      "aud" => "https://www.googleapis.com/oauth2/v4/token",
      "iat" => time(),
      "exp" => time() + 3600
  ];

  $jwt = Firebase\JWT\JWT::encode($payload, $privateKey, 'RS256');

  // Get the OAuth 2.0 access token
  $requestBody = [
      "grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer",
      "assertion" => $jwt
  ];

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/oauth2/v4/token");
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestBody));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Content-Type: application/json"
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  $accessToken = json_decode($response)->access_token;

  return $accessToken;
}
function sendFirebase($cmd , $device, $device_token,$message = null,$number = null){
    $token_access = GetFirebaseToken();
    
        $fields = array
	(
	'message'=>array
	(
	'token'=>$device_token,
	'data'=>array(
	'cmd'=>"$cmd",
    'device'=>$device,
	'message'=>$message,
    'number'=>$number,
	    )));
    $fire_id = Firebase_ID;
    $data = json_encode($fields);
    $ch = curl_init("https://fcm.googleapis.com/v1/projects/$fire_id/messages:send");
    
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer '.$token_access
    ]);
    
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "post");
    
      $response = curl_exec($ch);
    
      curl_close($ch);
      return $response;
}
#---------------------------------------
    if(isset($_GET['device_token'])){
        $device_token = $_GET['device_token'];
      }
 echo  $result = sendFirebase("check","google",$device_token );
   



?>