<?php
header('Content-Type: application/json; charset=utf-8');

include 'connection.php';
require 'get-access-token.php';  // helper to get FCM access token

$response = [];

try {
    // Hardcode user id for testing
    $userId = 3;

    // Fetch FCM token directly (plain text)
    $stmt = $conn->prepare("SELECT FCM_Token FROM User_Database WHERE id = ?");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        $fcm_token = $row['FCM_Token'];

        if (strlen($fcm_token) < 50) {
            throw new Exception("Invalid or missing FCM token for user.");
        }

        // Get Bearer Token (absolute path!)
        $accessToken = getAccessToken('/home/screensh/public_html/Bond_Data/service-account-file.json');

        if (empty($accessToken)) {
            throw new Exception("Access token not retrieved. Check service account JSON.");
        }

        // Notification content
        $title = "Test Notification";
        $body  = "This is a test message sent to user id 3.";

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

        // FCM payload
        $payload = json_encode([
            'message' => [
                'token' => $fcm_token,
                'notification' => [
                    'title' => $title,
                    'body'  => $body
                ],
                'data' => [
                    'type' => 'user_notification'
                ]
            ]
        ]);

        // Send via cURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/v1/projects/bond-aa1e8/messages:send");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $fcmResponse = curl_exec($ch);
        if ($fcmResponse === FALSE) {
            throw new Exception("FCM Send Error: " . curl_error($ch));
        }
        curl_close($ch);

        $response = ["status" => "success", "message" => "Notification sent", "fcm_response" => $fcmResponse];
    } else {
        throw new Exception("User not found");
    }
    $stmt->close();

} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
} finally {
    $conn->close();
}

echo json_encode($response);
?>
