<?php
require 'vendor/autoload.php';

use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\HttpHandler\HttpHandlerFactory;

function sendFCMNotification($deviceToken, $title, $body) {
    $projectId = 'sna-crm-software';
    $keyFilePath = 'sna-crm-software-firebase-adminsdk-fbsvc-dd5228bd05.json';

    // 1. Get OAuth2 Access Token
    $credential = new ServiceAccountCredentials(
        'https://www.googleapis.com/auth/cloud-platform',
        $keyFilePath
    );
    $tokenArray = $credential->fetchAuthToken(HttpHandlerFactory::build());
    $accessToken = $tokenArray['access_token'];

    // 2. Prepare the Message
    $url = "https://fcm.googleapis.com/v1/projects/{$projectId}/messages:send";
    $data = [
        "message" => [
            "token" => $deviceToken,
            "notification" => [
                "title" => $title,
                "body" => $body
            ]
        ]
    ];

    // 3. Send using cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

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

    return $response;
}

// Usage:
echo sendFCMNotification('dB-l9Z89lOfGHDbrg5sk-a:APA91bHe7PpbNO1eId8Wwep5x3DRIPhULDPN1JWj7zbLLRu0rGSF3ecekXcdHzqV1Oof-LyWi98_WcIJRgZfJUJpknQGJpo5wZ_8V-7P5nLET9qcwj9urFo', 'Hi SNA!', 'This is a test notification.');
?>