<?php
require_once 'includes/config.php';

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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

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

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

try {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT * FROM maintenance_logs WHERE vehicle_id = ? ORDER BY status DESC, start_date DESC");
    $stmt->execute([$vehicle_id]);
    $logs = $stmt->fetchAll();

    echo json_encode([
        'success' => true,
        'logs' => $logs
    ]);
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
