<?php

// Include the get-access-token.php for FCM
require 'get-access-token.php';

// Path to your service account key file
$serviceAccountKeyFile = 'service-account-file.json';

// Obtain the OAuth 2.0 Bearer Token
$accessToken = getAccessToken($serviceAccountKeyFile);

// Get POST data
$fcm_token = $_POST['fcm_token'];
$point = $_POST['point'];

// Validate inputs
if (empty($fcm_token) || empty($point)) {
    echo json_encode(array("status" => "error", "message" => "Missing required fields"));
    exit();
}

// FCM message details
$title = "Points Successfully Added!";
$body = "Your new point total is: " . $point;

// Prepare FCM message data
$datamsg = array(
    'title' => $title,
    'body' => $body
);

$arrayToSend = array('token' => $fcm_token, 'data' => $datamsg);
$json = json_encode(['message' => $arrayToSend]);

// Prepare headers for the FCM request
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer ' . $accessToken;

// Initialize curl session for FCM
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/v1/projects/online-course-72a05/messages:send");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Send the request to FCM
$response = curl_exec($ch);

// Check for curl errors
if ($response === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
}

// Close curl session
curl_close($ch);

// Respond back with success message
echo json_encode(array("status" => "success", "message" => "FCM notification sent successfully."));
?>
