<?php
// POST /api/jobcards/set_odo.php
// Sets only odo_start or odo_end without touching other fields
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../fleet/odo_helper.php';
$user  = requireAuth();
$db    = getDB();
$id    = (int)post('id', 0);
$field = post('field', '');
$value = (int)post('value', 0);

if (!$id) apiError('Job card ID required.', 422);
if (!in_array($field, ['odo_start', 'odo_end'])) apiError('Invalid field.', 422);
if ($value <= 0) apiError('ODO value must be positive.', 422);

// Verify job card exists and get vehicle
$stmt = $db->prepare("SELECT id, vehicle_id FROM job_cards WHERE id = ?");
$stmt->execute([$id]);
$jcCheck = $stmt->fetch();
if (!$jcCheck) apiError('Job card not found.', 404);

// Validate odo not less than latest (checks all sources)
validateOdo($db, $jcCheck['vehicle_id'], $value);

$db->prepare("UPDATE job_cards SET `$field` = ? WHERE id = ?")->execute([$value, $id]);

// Also log to fleet travel log if vehicle assigned
$jc = $jcCheck;
if ($jc && $jc['vehicle_id']) {
    $db->prepare("INSERT INTO fleet_travel_log (vehicle_id, odo_reading, reading_date, source, source_id, recorded_by, notes)
                  VALUES (?, ?, CURDATE(), 'job_card', ?, ?, ?)")
       ->execute([$jc['vehicle_id'], $value, $id, $user['id'], ($field === 'odo_start' ? 'Departure ODO' : 'Return ODO')]);
    // Update vehicle current_odo if this reading is higher
    $db->prepare("UPDATE fleet_vehicles SET current_odo = GREATEST(COALESCE(current_odo,0), ?) WHERE id = ?")
       ->execute([$value, $jc['vehicle_id']]);
}

apiSuccess(['field' => $field, 'value' => $value], 'ODO updated.');
