<?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');
}

$fleet_id       = (int)($input['fleet_id'] ?? 0);
$vehicle_id     = (int)($input['vehicle_id'] ?? 0);
$issue_division = (int)($input['issue_division'] ?? 0);
$description    = trim($input['description'] ?? '');
$latitude       = (float)($input['latitude'] ?? 0);
$longitude      = (float)($input['longitude'] ?? 0);

if (!$fleet_id || !$vehicle_id || !$issue_division) {
    error_bad_request('Missing required fields');
}

/* =========================
   INSERT BREAKDOWN
   ========================= */

$stmt = $pdo->prepare("
    INSERT INTO dpa_breakdowns (
        cust_id,
        fleet_id,
        vehicle_id,
        driver_user_id,
        issue_division,
        description,
        latitude,
        longitude,
        status
    ) VALUES (
        :cust_id,
        :fleet_id,
        :vehicle_id,
        :driver_user_id,
        :issue_division,
        :description,
        :latitude,
        :longitude,
        'awaiting_po'
    )
");

$stmt->execute([
    'cust_id'        => $auth_company_id,
    'fleet_id'       => $fleet_id,
    'vehicle_id'     => $vehicle_id,
    'driver_user_id' => $auth_user_id,
    'issue_division' => $issue_division,
    'description'    => $description,
    'latitude'       => $latitude,
    'longitude'      => $longitude
]);

$breakdown_id = (int)$pdo->lastInsertId();

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

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

success('Breakdown created', [
    'breakdown_id' => $breakdown_id
]);
