<?php

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

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

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

/* ----------------------------------------------------------
   AUTHENTICATE
---------------------------------------------------------- */

$user = authenticate($pdo);

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

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

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

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

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

if (
    !$input ||
    !isset(
        $input['issue_division'],
        $input['latitude'],
        $input['longitude'],
        $input['vehicle_id'],
        $input['driver_name'],
        $input['driver_phone'],
        $input['direction']
    )
) {
    json_response(false, 'Missing required fields.');
}

$issue_division = trim($input['issue_division']);
$description    = $input['description'] ?? null;
$latitude       = (float)$input['latitude'];
$longitude      = (float)$input['longitude'];

$vehicle_id     = trim($input['vehicle_id']);
$driver_name    = trim($input['driver_name']);
$driver_phone   = trim($input['driver_phone']);
$direction      = trim($input['direction']);

if (!$issue_division) {
    json_response(false, 'Issue division is required.');
}

/* ----------------------------------------------------------
   INSERT BREAKDOWN
---------------------------------------------------------- */

$stmt = $pdo->prepare("
    INSERT INTO breakdowns (
        rsp_id,
        fleet_company_id,
        driver_id,
        vehicle_id,
        vehicle_label,
        lat,
        lng,
        division_required,
        description,
        driver_name,
        driver_phone,
        direction,
        status,
        created_at
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'awaiting_po', NOW())
");

$stmt->execute([
    $user['rsp_id'],
    $user['company_id'],
    $user['id'],
    0, // TEMP vehicle_id
    $input['vehicle_id'], // store text here
    $latitude,
    $longitude,
    $issue_division,
    $description,
    $driver_name,
    $driver_phone,
    $direction
]);

$breakdown_id = $pdo->lastInsertId();

/* ----------------------------------------------------------
   GENERATE JOB CARD NUMBER
---------------------------------------------------------- */

// Current timestamp
$timestamp = date('YmdHi');

// Get count of breakdowns in same minute
$stmt = $pdo->prepare("
    SELECT COUNT(*) as count
    FROM breakdowns
    WHERE DATE_FORMAT(created_at, '%Y%m%d%H%i') = ?
");

$stmt->execute([$timestamp]);
$count = $stmt->fetch()['count'] + 1;

// Pad sequence (001, 002, etc)
$sequence = str_pad($count, 3, '0', STR_PAD_LEFT);

// Final job card
$job_card_number = $timestamp . $sequence;

// Update breakdown
$stmt = $pdo->prepare("
    UPDATE breakdowns
    SET job_card_number = ?
    WHERE id = ?
");

$stmt->execute([$job_card_number, $breakdown_id]);

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

json_response(true, 'Breakdown created.', [
    'breakdown_id' => $breakdown_id,
    'job_card_number'=> $job_card_number,
    'status'       => 'awaiting_po'
]);