<?php
// Shared helper — returns the highest ODO reading across ALL sources for a vehicle
function getVehicleLatestOdo($db, $vehicleId) {
    $stmt = $db->prepare("
        SELECT MAX(odo) AS latest FROM (
            SELECT odo_reading AS odo FROM fleet_travel_log
              WHERE vehicle_id = ? AND odo_reading IS NOT NULL
            UNION ALL
            SELECT odo_reading FROM fleet_costs
              WHERE vehicle_id = ? AND odo_reading IS NOT NULL AND odo_reading > 0
            UNION ALL
            SELECT odo_start FROM job_cards
              WHERE vehicle_id = ? AND odo_start IS NOT NULL AND odo_start > 0
            UNION ALL
            SELECT odo_end FROM job_cards
              WHERE vehicle_id = ? AND odo_end IS NOT NULL AND odo_end > 0
            UNION ALL
            SELECT jctl.odo_reading FROM job_card_time_logs jctl
              JOIN job_cards jc ON jc.id = jctl.job_card_id
              WHERE jc.vehicle_id = ? AND jctl.odo_reading IS NOT NULL AND jctl.odo_reading > 0
        ) AS all_odos
    ");
    $stmt->execute([$vehicleId, $vehicleId, $vehicleId, $vehicleId, $vehicleId]);
    $row = $stmt->fetch();
    return (int)($row['latest'] ?? 0);
}

function validateOdo($db, $vehicleId, $newOdo) {
    if (!$vehicleId || $newOdo <= 0) return; // no vehicle or no value, skip
    $latest = getVehicleLatestOdo($db, $vehicleId);
    if ($latest > 0 && $newOdo < $latest) {
        apiError("ODO reading ({$newOdo} km) cannot be less than the latest recorded reading ({$latest} km).", 422);
    }
}