<?php
// send_notification.php

require __DIR__ . '/vendor/autoload.php';

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
use Kreait\Firebase\Messaging\RawMessageFromArray;

// Set headers for API usage
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST");

// Read JSON input
$data = json_decode(file_get_contents("php://input"));

if (!isset($data->token) || !isset($data->title) || !isset($data->body)) {
    http_response_code(400);
    echo json_encode(["error" => "Missing required fields: token, title, body"]);
    exit;
}

// Optional field
$id = isset($data->id) ? $data->id : '0';

$deviceToken = $data->token;
$title = $data->title;
$body = $data->body;

// Initialize Firebase
$serviceAccountPath = __DIR__ . '/serviceAccountKey.json';
$factory = (new Factory)->withServiceAccount($serviceAccountPath);
$messaging = $factory->createMessaging();

// Create the message with notification and custom data
$message = CloudMessage::withTarget('token', $deviceToken)
    ->withNotification(Notification::create($title, $body))
    ->withData([
        'id' => $id
    ]);

try {
    $messaging->send($message);
    echo json_encode([
        "success" => true,
        "message" => "Notification sent",
        "sent_to" => $deviceToken,
        "data_sent" => ["title" => $title, "body" => $body, "id" => $id]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        "error" => "Failed to send notification",
        "details" => $e->getMessage()
    ]);
}
