<?php
declare(strict_types=1);

require_once $_SERVER['DOCUMENT_ROOT'] . '/core/api_bootstrap.php';

/**
 * LOCKED CONTRACT:
 * - Runs via CRON every 2–5 minutes
 * - Escalates broadcast radius
 * - Updates broadcast_cycle
 * - Updates last_broadcast_at
 */

try {

    $db = db();

    // 1. Fetch active broadcasts
    $stmt = $db->prepare("
        SELECT *
        FROM breakdowns
        WHERE status = 'broadcasting'
        AND broadcast_expires_at > NOW()
        AND accepted_company_id IS NULL
    ");
    $stmt->execute();

    $breakdowns = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($breakdowns as $b) {

        $id = (int)$b['id'];
        $cycle = (int)$b['broadcast_cycle'];
        $last = $b['last_broadcast_at'];

        // SAFETY: skip if cycle already max
        if ($cycle >= 3) {
            continue;
        }

        // SAFETY: if last_broadcast_at is null → set it and skip
        if (!$last) {
            $stmt = $db->prepare("
                UPDATE breakdowns
                SET last_broadcast_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$id]);
            continue;
        }

        $lastTime = new DateTime($last);
        $now = new DateTime();

        $diffMinutes = ($now->getTimestamp() - $lastTime->getTimestamp()) / 60;

        // ⏱ ESCALATION TRIGGER (8 minutes)
        if ($diffMinutes < 8) {
            continue;
        }

        // 🔼 INCREASE CYCLE
        $newCycle = $cycle + 1;

        // 📏 SET RADIUS
        switch ($newCycle) {
            case 2:
                $newRadius = 50;
                break;
            case 3:
                $newRadius = 100;
                break;
            default:
                $newRadius = 25;
        }

        // 🔄 UPDATE
        $stmt = $db->prepare("
            UPDATE breakdowns
            SET 
                broadcast_cycle = ?,
                broadcast_radius_km = ?,
                last_broadcast_at = NOW()
            WHERE id = ?
        ");

        $stmt->execute([
            $newCycle,
            $newRadius,
            $id
        ]);

        // 🧠 OPTIONAL (NEXT PHASE)
        // trigger push notifications to SPs here

    }

    echo json_encode([
        "status" => "success",
        "processed" => count($breakdowns)
    ]);

} catch (Throwable $e) {

    http_response_code(500);

    echo json_encode([
        "status" => "error",
        "message" => $e->getMessage()
    ]);
}