<?php
// send_notification_to_all.php

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

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

// 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->title) || !isset($data->body)) {
    http_response_code(400);
    echo json_encode(["error" => "Missing required fields: title, body"]);
    exit;
}

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

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

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

// Create the message to topic
$message = CloudMessage::withTarget('topic', 'all')
    ->withNotification(Notification::create($title, $body))
    ->withData([
        'id' => $id
    ]);

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