<?php
/**
 * Get Last Odometer AJAX Handler
 * Returns the last end odometer for a vehicle
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/db.php';

header('Content-Type: application/json');

$vehicle_id = $_GET['vehicle_id'] ?? '';
$type = $_GET['type'] ?? '';

if (!$vehicle_id || !$type) {
    echo json_encode(['success' => false, 'message' => 'Missing parameters']);
    exit;
}

$pdo = getPDO();

if ($type === 'dozar') {
    // Get last end odometer from dozar_records
    $stmt = $pdo->prepare("SELECT end_odometer FROM dozar_records WHERE vehicle_id = ? AND end_odometer IS NOT NULL ORDER BY created_date DESC, id DESC LIMIT 1");
    $stmt->execute([$vehicle_id]);
    $result = $stmt->fetch();
    
    if ($result && $result['end_odometer']) {
        echo json_encode(['success' => true, 'odometer' => $result['end_odometer']]);
    } else {
        echo json_encode(['success' => true, 'odometer' => null]);
    }
} else {
    // Get last end odometer from tripper_records (for loading start)
    $stmt = $pdo->prepare("SELECT unloading_end_odometer FROM tripper_records WHERE vehicle_id = ? AND unloading_end_odometer IS NOT NULL ORDER BY created_date DESC, id DESC LIMIT 1");
    $stmt->execute([$vehicle_id]);
    $result = $stmt->fetch();
    
    if ($result && $result['unloading_end_odometer']) {
        echo json_encode(['success' => true, 'odometer' => $result['unloading_end_odometer']]);
    } else {
        // If no unloading odometer, try loading start odometer
        $stmt = $pdo->prepare("SELECT loading_start_odometer FROM tripper_records WHERE vehicle_id = ? AND loading_start_odometer IS NOT NULL ORDER BY created_date DESC, id DESC LIMIT 1");
        $stmt->execute([$vehicle_id]);
        $result = $stmt->fetch();
        
        if ($result && $result['loading_start_odometer']) {
            echo json_encode(['success' => true, 'odometer' => $result['loading_start_odometer']]);
        } else {
            echo json_encode(['success' => true, 'odometer' => null]);
        }
    }
}
