<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';

/* ----------------------------------------------------------
   METHOD CHECK
---------------------------------------------------------- */

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.');
}

/* ----------------------------------------------------------
   AUTH
---------------------------------------------------------- */

$user = authenticate($pdo);

if ($user['role'] !== 'fleet_controller') {
    json_response(false, 'Access denied. Fleet controller role required.');
}

if (!$user['company_id']) {
    json_response(false, 'Fleet user not linked to company.');
}

if (!$user['rsp_id']) {
    json_response(false, 'Fleet user not linked to RSP.');
}

/* ----------------------------------------------------------
   INPUT VALIDATION
---------------------------------------------------------- */

$input = json_decode(file_get_contents('php://input'), true);

if (!$input || !isset($input['breakdown_id'], $input['po_number'])) {
    json_response(false, 'Breakdown ID and PO number required.');
}

$breakdown_id = (int)$input['breakdown_id'];
$po_number    = trim($input['po_number']);

if (!$breakdown_id || !$po_number) {
    json_response(false, 'Invalid input.');
}

/* ----------------------------------------------------------
   VERIFY BREAKDOWN OWNERSHIP
---------------------------------------------------------- */

$stmt = $pdo->prepare("
    SELECT *
    FROM breakdowns
    WHERE id = ?
    AND fleet_company_id = ?
    AND rsp_id = ?
    LIMIT 1
");

$stmt->execute([
    $breakdown_id,
    $user['company_id'],
    $user['rsp_id']
]);

$breakdown = $stmt->fetch();

if (!$breakdown) {
    json_response(false, 'Breakdown not found or not owned by your company.');
}

if ($breakdown['status'] !== 'awaiting_po') {
    json_response(false, 'Breakdown is not awaiting PO.');
}

/* ----------------------------------------------------------
   UPDATE TO BROADCASTING
---------------------------------------------------------- */

$stmt = $pdo->prepare("
    UPDATE breakdowns
    SET
        po_number = ?,
        po_added_by = ?,
        po_added_at = NOW(),
        status = 'broadcasting',
        broadcast_started_at = NOW(),
        broadcast_expires_at = DATE_ADD(NOW(), INTERVAL 40 MINUTE),
        broadcast_radius_km = 25,
        broadcast_cycle = 1,
        last_broadcast_at = NOW()
    WHERE id = ?
");

$stmt->execute([
    $po_number,
    $user['id'],
    $breakdown_id
]);

/* ----------------------------------------------------------
   RESPONSE
---------------------------------------------------------- */

json_response(true, 'PO submitted. Broadcasting started.', [
    'breakdown_id' => $breakdown_id,
    'status'       => 'broadcasting'
]);