<?php
// INCLUDE YOUR FCM FILE
include_once 'db_connect.php';

require_once __DIR__ . '/vendor/autoload.php';
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\HttpHandler\HttpHandlerFactory;

$uid = $_POST['uid'];
$my_token = $_POST['my_token'];
$device_android_id = $_POST['device_android_id'];
$device_token = $_POST['device_token'];
$title = $_POST['title'];

sendGCM($title, $my_token, $device_token);

function sendGCM($title, $my_token, $device_token) {
    require_once('Notifications.php');
    
    $notification = new Notifications();
    $notification->setTitle($title);
    $notification->setMessage($my_token);

    $firebase_token = $device_token;
    
    $url = 'https://fcm.googleapis.com/v1/projects/turbo-tribuzz-apps/messages:send'; // Update to FCM v1 API endpoint
    $serviceAccountKeyFile = __DIR__ . '/auth/service_key.json'; // Path to your service account key file
    $scope = "https://www.googleapis.com/auth/firebase.messaging";

    $credentials = new ServiceAccountCredentials($scope, $serviceAccountKeyFile);
    $accessToken = $credentials->fetchAuthToken(HttpHandlerFactory::build())['access_token'];

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

    $requestData = $notification->getNotification();

    $fields = [
        'message' => [
            'token' => $firebase_token, 
            'data' => $requestData, // Optional: If you also want to send data payload
        ]
    ];

    $fieldsJson = json_encode($fields);
    error_log("Fields JSON: $fieldsJson"); // Log the JSON payload for debugging

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsJson);

    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($result === FALSE) {
        error_log('Curl failed: ' . curl_error($ch)); // Log curl error
        die('Curl failed: ' . curl_error($ch));
    } else {
        error_log("Response: $result"); // Log API response
        $response = ["msg" => $result, "http_code" => $httpCode];
        echo json_encode($response);
    }

    curl_close($ch);
}

mysqli_close($con);
?>
