<?php
declare(strict_types=1);

require_once __DIR__ . '/../bootstrap.php';

/* =========================
   METHOD CHECK
   ========================= */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    error_bad_request('Invalid method');
}

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

if (!is_array($input)) {
    error_bad_request('Invalid JSON');
}

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

if (!$breakdown_id || $po_number === '') {
    error_bad_request('Missing required fields');
}

/* =========================
   FETCH BREAKDOWN
   ========================= */

$stmt = $pdo->prepare("
    SELECT id, status
    FROM dpa_breakdowns
    WHERE id = :id
    LIMIT 1
");
$stmt->execute(['id' => $breakdown_id]);
$breakdown = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$breakdown) {
    error_bad_request('Breakdown not found');
}

if ($breakdown['status'] !== 'awaiting_po') {
    error_bad_request('PO already submitted or invalid state');
}

/* =========================
   UPDATE BREAKDOWN
   ========================= */

$stmt = $pdo->prepare("
    UPDATE dpa_breakdowns
    SET po_number = :po_number,
        status = 'broadcasting',
        broadcast_started_at = NOW(),
        current_radius_km = 25,
        tier_level = 1
    WHERE id = :id
");

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

/* =========================
   AUDIT LOG
   ========================= */

$pdo->prepare("
    INSERT INTO dpa_audit_log (
        entity_type,
        entity_id,
        action,
        user_id,
        metadata_json
    ) VALUES (
        'breakdown',
        :entity_id,
        'po_submitted',
        :user_id,
        :meta
    )
")->execute([
    'entity_id' => $breakdown_id,
    'user_id'   => $auth_user_id,
    'meta'      => json_encode(['po_number' => $po_number])
]);

success('PO submitted, broadcast started', [
    'breakdown_id' => $breakdown_id
]);
