<?php
/**
 * Fleet Management - Admin Page
 */

$page_title = 'Fleet Management';
require_once 'includes/header.php';

$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $pdo = getDBConnection();
        
        if (isset($_POST['add_vehicle'])) {
            // Process images - handle both URLs and uploaded files
            $images = [];
            
            // Handle image URLs if provided
            if (!empty($_POST['image_urls'])) {
                $urls = array_map('trim', explode(',', $_POST['image_urls']));
                $images = array_merge($images, array_filter($urls));
            }
            
            // Handle uploaded files
            if (!empty($_FILES['image_files']['name'][0])) {
                $uploadDir = '../uploads/vehicles/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                foreach ($_FILES['image_files']['tmp_name'] as $key => $tmpName) {
                    if ($_FILES['image_files']['error'][$key] === UPLOAD_ERR_OK) {
                        $extension = pathinfo($_FILES['image_files']['name'][$key], PATHINFO_EXTENSION);
                        $filename = 'vehicle_' . uniqid() . '_' . time() . '.' . $extension;
                        $filepath = $uploadDir . $filename;
                        
                        if (move_uploaded_file($tmpName, $filepath)) {
                            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
                            $host = $_SERVER['HTTP_HOST'];
                            $baseUrl = $protocol . '://' . $host . dirname(dirname($_SERVER['SCRIPT_NAME']));
                            $images[] = $baseUrl . '/uploads/vehicles/' . $filename;
                        }
                    }
                }
            }
            
            $imagesJson = json_encode(array_values(array_unique(array_filter($images))));
            $has_rear_camera = isset($_POST['has_rear_camera']) ? 1 : 0;
            $stmt = $pdo->prepare("INSERT INTO vehicles (make, model, year, color, plate_number, gps_device_id, vehicle_type, transmission, fuel_type, seats, daily_rate, status, images, description, has_rear_camera) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $_POST['make'], $_POST['model'], $_POST['year'], $_POST['color'],
                $_POST['plate_number'], $_POST['gps_device_id'] ?? null, $_POST['vehicle_type'], $_POST['transmission'],
                $_POST['fuel_type'], $_POST['seats'], $_POST['daily_rate'], $_POST['status'],
                $imagesJson, $_POST['description'] ?? '', $has_rear_camera
            ]);
            $message = 'Vehicle added successfully! It will now appear on the user website.';
        } elseif (isset($_POST['update_vehicle'])) {
            // Process images - handle both URLs and uploaded files
            $images = [];
            
            // Keep existing images if checkbox is checked
            if (isset($_POST['keep_existing_images']) && $_POST['keep_existing_images'] === '1') {
                $stmt = $pdo->prepare("SELECT images FROM vehicles WHERE id = ?");
                $stmt->execute([$_POST['vehicle_id']]);
                $existing = $stmt->fetch();
                $existingImages = json_decode($existing['images'] ?? '[]', true);
                if (is_array($existingImages)) {
                    $images = $existingImages;
                }
            }
            
            // Handle image URLs if provided
            if (!empty($_POST['image_urls'])) {
                $urls = array_map('trim', explode(',', $_POST['image_urls']));
                $images = array_merge($images, array_filter($urls));
            }
            
            // Handle uploaded files
            if (!empty($_FILES['image_files']['name'][0])) {
                $uploadDir = '../uploads/vehicles/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                foreach ($_FILES['image_files']['tmp_name'] as $key => $tmpName) {
                    if ($_FILES['image_files']['error'][$key] === UPLOAD_ERR_OK) {
                        $extension = pathinfo($_FILES['image_files']['name'][$key], PATHINFO_EXTENSION);
                        $filename = 'vehicle_' . uniqid() . '_' . time() . '.' . $extension;
                        $filepath = $uploadDir . $filename;
                        
                        if (move_uploaded_file($tmpName, $filepath)) {
                            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
                            $host = $_SERVER['HTTP_HOST'];
                            $baseUrl = $protocol . '://' . $host . dirname(dirname($_SERVER['SCRIPT_NAME']));
                            $images[] = $baseUrl . '/uploads/vehicles/' . $filename;
                        }
                    }
                }
            }
            
            $imagesJson = json_encode(array_values(array_unique(array_filter($images))));
            $has_rear_camera = isset($_POST['has_rear_camera']) ? 1 : 0;
            $stmt = $pdo->prepare("UPDATE vehicles SET make=?, model=?, year=?, color=?, plate_number=?, gps_device_id=?, vehicle_type=?, transmission=?, fuel_type=?, seats=?, daily_rate=?, status=?, images=?, description=?, has_rear_camera=? WHERE id=?");
            $stmt->execute([
                $_POST['make'], $_POST['model'], $_POST['year'], $_POST['color'],
                $_POST['plate_number'], $_POST['gps_device_id'] ?? null, $_POST['vehicle_type'], $_POST['transmission'],
                $_POST['fuel_type'], $_POST['seats'], $_POST['daily_rate'], $_POST['status'],
                $imagesJson, $_POST['description'] ?? '', $has_rear_camera, $_POST['vehicle_id']
            ]);
            $message = 'Vehicle updated successfully! Changes are live on the user website.';
        } elseif (isset($_POST['update_status'])) {
            $stmt = $pdo->prepare("UPDATE vehicles SET status = ? WHERE id = ?");
            $stmt->execute([$_POST['status'], $_POST['vehicle_id']]);

            // If status is changed to maintenance, we might want to prompt for a log entry
            // This is handled via JavaScript to show a modal if maintenance is selected
            $message = 'Vehicle status updated! Real-time update reflects on user website.';
        } elseif (isset($_POST['add_maintenance_log'])) {
            $stmt = $pdo->prepare("INSERT INTO maintenance_logs (vehicle_id, reason, description, start_date, status) VALUES (?, ?, ?, CURDATE(), 'ongoing')");
            $stmt->execute([$_POST['vehicle_id'], $_POST['reason'], $_POST['description'] ?? '']);

            // Also update vehicle status to maintenance
            $stmt = $pdo->prepare("UPDATE vehicles SET status = 'maintenance' WHERE id = ?");
            $stmt->execute([$_POST['vehicle_id']]);

            $message = 'Maintenance log added and vehicle status updated!';
        } elseif (isset($_POST['complete_maintenance'])) {
            $stmt = $pdo->prepare("UPDATE maintenance_logs SET status = 'completed', end_date = CURDATE(), cost = ? WHERE id = ?");
            $stmt->execute([$_POST['cost'] ?? 0, $_POST['log_id']]);

            // If all logs for this vehicle are completed, we could suggest changing status back to available
            // But let's keep it simple for now and just update the log.
            $message = 'Maintenance record marked as completed!';
        } elseif (isset($_POST['delete_vehicle'])) {
            $stmt = $pdo->prepare("DELETE FROM vehicles WHERE id = ?");
            $stmt->execute([$_POST['vehicle_id']]);
            $message = 'Vehicle removed! It is no longer available on the user website.';
        } elseif (isset($_POST['toggle_featured'])) {
            $stmt = $pdo->prepare("UPDATE vehicles SET is_featured = !is_featured WHERE id = ?");
            $stmt->execute([$_POST['vehicle_id']]);
            $message = 'Featured status updated!';
        }
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Get all vehicles
$vehicles = [];
$ongoing_logs_by_vehicle = [];
$status_counts = ['available' => 0, 'rented' => 0, 'maintenance' => 0];
$dynamic_types = ['sedan', 'suv', 'luxury', 'electric'];

try {
    $pdo = getDBConnection();

    $status_filter = $_GET['status'] ?? '';
    $sql = "SELECT * FROM vehicles";
    if ($status_filter) {
        $sql .= " WHERE status = :status";
    }
    $sql .= " ORDER BY created_at DESC";

    $stmt = $pdo->prepare($sql);
    if ($status_filter) {
        $stmt->bindParam(':status', $status_filter);
    }
    $stmt->execute();
    $vehicles = $stmt->fetchAll();
    
    // Get ongoing maintenance logs to show reasons
    try {
        $stmt = $pdo->query("SELECT * FROM maintenance_logs WHERE status = 'ongoing'");
        $ongoing_logs = $stmt->fetchAll();
        foreach ($ongoing_logs as $log) {
            $ongoing_logs_by_vehicle[$log['vehicle_id']] = $log;
        }
    } catch (Exception $e) {
        // Fallback if maintenance_logs table has issues
        error_log("Error fetching maintenance logs: " . $e->getMessage());
    }

    // Stats
    try {
        $stmt = $pdo->query("SELECT status, COUNT(*) as count FROM vehicles GROUP BY status");
        $counts = $stmt->fetchAll();
        foreach ($counts as $row) {
            $status_counts[$row['status']] = $row['count'];
        }
    } catch (Exception $e) {
        error_log("Error fetching vehicle stats: " . $e->getMessage());
    }

    // Get dynamic vehicle types from pricing_settings
    try {
        $stmt = $pdo->query("SELECT setting_type FROM pricing_settings ORDER BY setting_type ASC");
        $types = $stmt->fetchAll(PDO::FETCH_COLUMN);
        if (!empty($types)) {
            $dynamic_types = $types;
        }
    } catch (Exception $e) {
        error_log("Error fetching vehicle types: " . $e->getMessage());
    }
} catch (Exception $e) {
    $error = "Critical error loading fleet data: " . $e->getMessage();
}
?>

<div class="flex h-screen overflow-hidden">
    <?php include 'includes/sidebar.php'; ?>
    
    <div class="flex-1 flex flex-col overflow-hidden">
        <header class="sticky top-0 z-30 flex items-center bg-white/80 dark:bg-background-dark/80 backdrop-blur-md p-4 justify-between border-b border-slate-200 dark:border-slate-800 lg:px-8">
            <div class="flex items-center gap-4">
                <button class="text-slate-900 dark:text-white flex size-10 items-center justify-center hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full lg:hidden" onclick="toggleSidebar()">
                    <span class="material-symbols-outlined">menu</span>
                </button>
                <h2 class="text-slate-900 dark:text-white text-clamp-lg font-bold leading-tight tracking-[-0.015em]">Fleet Management</h2>
            </div>
            
            <div class="flex items-center gap-4">
                <button onclick="document.getElementById('addModal').classList.remove('hidden')" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 flex items-center gap-2 text-sm font-bold">
                    <span class="material-symbols-outlined">add</span>
                    <span class="hidden sm:inline">Add Vehicle</span>
                </button>
            </div>
        </header>

        <main class="flex-1 overflow-y-auto p-4 lg:p-8 pb-24 admin-content">
            <!-- Stats -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                <div class="bg-white dark:bg-surface-dark rounded-xl p-4 border border-slate-200 dark:border-slate-800 shadow-sm">
                    <p class="text-xs text-slate-500 font-medium uppercase tracking-wider">Total Fleet</p>
                    <p class="text-clamp-2xl font-bold"><?= count($vehicles) ?></p>
                </div>
                <div class="bg-white dark:bg-surface-dark rounded-xl p-4 border border-slate-200 dark:border-slate-800 shadow-sm">
                    <p class="text-xs text-slate-500 font-medium uppercase tracking-wider">Available</p>
                    <p class="text-clamp-2xl font-bold text-emerald-500"><?= $status_counts['available'] ?? 0 ?></p>
                </div>
                <div class="bg-white dark:bg-surface-dark rounded-xl p-4 border border-slate-200 dark:border-slate-800 shadow-sm">
                    <p class="text-xs text-slate-500 font-medium uppercase tracking-wider">Rented</p>
                    <p class="text-clamp-2xl font-bold text-primary"><?= $status_counts['rented'] ?? 0 ?></p>
                </div>
                <div class="bg-white dark:bg-surface-dark rounded-xl p-4 border border-slate-200 dark:border-slate-800 shadow-sm">
                    <p class="text-xs text-slate-500 font-medium uppercase tracking-wider">Maintenance</p>
                    <p class="text-clamp-2xl font-bold text-orange-500"><?= $status_counts['maintenance'] ?? 0 ?></p>
                </div>
            </div>

            <?php if ($message): ?>
                <div class="bg-emerald-100 dark:bg-emerald-900/30 border border-emerald-400 text-emerald-700 dark:text-emerald-300 px-4 py-3 rounded-xl mb-6">
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="bg-red-100 dark:bg-red-900/30 border border-red-400 text-red-700 dark:text-red-300 px-4 py-3 rounded-xl mb-6">
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <!-- Vehicles Grid (Responsive) -->
            <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4 5xl:grid-cols-6 7xl:grid-cols-8 8xl:grid-cols-12 gap-6">
                <?php foreach ($vehicles as $v): ?>
                <div class="bg-white dark:bg-surface-dark rounded-2xl border border-slate-200 dark:border-slate-800 overflow-hidden shadow-sm group">
                    <div class="relative aspect-video bg-slate-100 dark:bg-slate-800 overflow-hidden">
                        <?php 
                        $images = json_decode($v['images'] ?? '[]', true);
                        $image_url = !empty($images) ? $images[0] : 'https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?auto=format&fit=crop&q=80&w=400';
                        ?>
                        <img src="<?= $image_url ?>" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" alt="<?= $v['make'] ?>">
                        <div class="absolute top-4 right-4 flex flex-col gap-2 items-end">
                            <span class="px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider <?= 
                                $v['status'] === 'available' ? 'bg-emerald-500 text-white' : 
                                ($v['status'] === 'rented' ? 'bg-primary text-white' : 'bg-orange-500 text-white')
                            ?>">
                                <?= $v['status'] ?>
                            </span>
                            <?php if ($v['is_featured']): ?>
                                <span class="bg-amber-500 text-white p-1.5 rounded-full shadow-lg border border-amber-400">
                                    <span class="material-symbols-outlined text-sm fill-1">star</span>
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="p-6">
                        <div class="flex justify-between items-start mb-2">
                            <div>
                                <h3 class="font-bold text-lg"><?= htmlspecialchars($v['make'] . ' ' . $v['model']) ?></h3>
                                <p class="text-xs text-slate-500"><?= htmlspecialchars($v['year'] . ' • ' . $v['fuel_type'] . ' • ' . $v['transmission']) ?></p>
                            </div>
                            <p class="text-primary font-bold text-lg"><?= formatCurrency(convertCurrency($v['daily_rate'], 'PHP', $selected_currency), $selected_currency) ?><span class="text-[10px] text-slate-400 font-normal">/day</span></p>
                        </div>

                        <?php if ($v['status'] === 'maintenance' && isset($ongoing_logs_by_vehicle[$v['id']])): ?>
                            <div class="mb-4 p-2 bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800/50 rounded-lg">
                                <p class="text-[10px] font-bold text-orange-600 dark:text-orange-400 uppercase">Under Maintenance</p>
                                <p class="text-xs font-semibold"><?= htmlspecialchars($ongoing_logs_by_vehicle[$v['id']]['reason']) ?></p>
                                <?php if ($ongoing_logs_by_vehicle[$v['id']]['description']): ?>
                                    <p class="text-[10px] text-slate-500 italic"><?= htmlspecialchars($ongoing_logs_by_vehicle[$v['id']]['description']) ?></p>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>

                        <div class="flex items-center gap-4 text-xs text-slate-500 mb-6">
                            <div class="flex items-center gap-1">
                                <span class="material-symbols-outlined text-sm">event_seat</span>
                                <?= $v['seats'] ?> Seats
                            </div>
                            <div class="flex items-center gap-1">
                                <span class="material-symbols-outlined text-sm">pin</span>
                                <?= htmlspecialchars($v['plate_number']) ?>
                            </div>
                            <div class="flex items-center gap-1 <?= $v['has_rear_camera'] ? 'text-emerald-600 dark:text-emerald-400' : 'text-slate-400' ?>">
                                <span class="material-symbols-outlined text-sm"><?= $v['has_rear_camera'] ? 'videocam' : 'videocam_off' ?></span>
                                <?= $v['has_rear_camera'] ? 'With Camera' : 'No Camera' ?>
                            </div>
                        </div>

                        <div class="flex gap-2">
                            <form method="POST" class="flex-1" id="statusForm_<?= $v['id'] ?>">
                                <input type="hidden" name="vehicle_id" value="<?= $v['id'] ?>">
                                <input type="hidden" name="update_status" value="1">
                                <select name="status" onchange="handleStatusChange(this, <?= $v['id'] ?>, '<?= htmlspecialchars($v['make'] . ' ' . $v['model']) ?>')" class="w-full text-xs font-bold border-slate-200 dark:border-slate-800 rounded-lg bg-slate-50 dark:bg-slate-900 focus:ring-primary">
                                    <option value="available" <?= $v['status'] === 'available' ? 'selected' : '' ?>>Available</option>
                                    <option value="rented" <?= $v['status'] === 'rented' ? 'selected' : '' ?>>Rented</option>
                                    <option value="maintenance" <?= $v['status'] === 'maintenance' ? 'selected' : '' ?>>Maintenance</option>
                                </select>
                            </form>
                            <form method="POST" class="inline">
                                <input type="hidden" name="vehicle_id" value="<?= $v['id'] ?>">
                                <input type="hidden" name="toggle_featured" value="1">
                                <button type="submit" class="p-2 <?= $v['is_featured'] ? 'text-amber-500' : 'text-slate-400' ?> hover:text-amber-600 transition-colors" title="<?= $v['is_featured'] ? 'Unmark as Featured' : 'Mark as Featured' ?>">
                                    <span class="material-symbols-outlined <?= $v['is_featured'] ? 'fill-1' : '' ?>">star</span>
                                </button>
                            </form>
                            <button onclick="openMaintenanceModal(<?= $v['id'] ?>, '<?= htmlspecialchars($v['make'] . ' ' . $v['model']) ?>')" class="p-2 text-slate-400 hover:text-orange-500 transition-colors" title="Maintenance History">
                                <span class="material-symbols-outlined">build</span>
                            </button>
                            <button onclick="openEditModal(<?= htmlspecialchars(json_encode($v)) ?>)" class="p-2 text-slate-400 hover:text-primary transition-colors">
                                <span class="material-symbols-outlined">edit</span>
                            </button>
                            <form method="POST" onsubmit="return confirm('Delete this vehicle?');" class="inline">
                                <input type="hidden" name="vehicle_id" value="<?= $v['id'] ?>">
                                <button type="submit" name="delete_vehicle" class="p-2 text-slate-400 hover:text-rose-500 transition-colors">
                                    <span class="material-symbols-outlined">delete</span>
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </main>
    </div>
</div>

<!-- Add Modal -->
<div id="addModal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4 sm:p-6">
    <div class="bg-white dark:bg-surface-dark rounded-3xl w-full max-w-xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
        <div class="px-6 py-5 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-white dark:bg-surface-dark sticky top-0 z-10">
            <h3 class="text-xl font-bold text-slate-900 dark:text-white">Add New Vehicle</h3>
            <button onclick="document.getElementById('addModal').classList.add('hidden')" class="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full transition-colors text-slate-500">
                <span class="material-symbols-outlined">close</span>
            </button>
        </div>
        <form method="POST" enctype="multipart/form-data" class="p-6 space-y-6 overflow-y-auto flex-1 no-scrollbar">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Make</label>
                    <input type="text" name="make" required placeholder="e.g. Tesla" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all">
                </div>
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Model</label>
                    <input type="text" name="model" required placeholder="e.g. Model 3" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all">
                </div>
            </div>
            <div class="grid grid-cols-2 sm:grid-cols-3 gap-4">
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Year</label>
                    <input type="number" name="year" required value="2024" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all">
                </div>
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Color</label>
                    <input type="text" name="color" required placeholder="White" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all">
                </div>
                <div class="col-span-2 sm:col-span-1">
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Plate Number</label>
                    <input type="text" name="plate_number" required placeholder="ABC-123" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all">
                </div>
            </div>
            <div>
                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">SinoTrack Device ID / SN</label>
                <input type="text" name="gps_device_id" placeholder="e.g. 9170122744" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all">
                <p class="text-[10px] text-slate-500 mt-2 px-1">Enter the ID from your SinoTrack Pro account to enable live tracking.</p>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Vehicle Type</label>
                    <select name="vehicle_type" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all appearance-none">
                        <?php foreach ($dynamic_types as $type): ?>
                            <option value="<?= htmlspecialchars($type) ?>"><?= htmlspecialchars(ucfirst($type)) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Transmission</label>
                    <select name="transmission" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all">
                        <option value="automatic">Automatic</option>
                        <option value="manual">Manual</option>
                    </select>
                </div>
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Fuel Type</label>
                    <select name="fuel_type" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all">
                        <option value="gasoline">Gasoline</option>
                        <option value="diesel">Diesel</option>
                        <option value="electric">Electric</option>
                        <option value="hybrid">Hybrid</option>
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Seats</label>
                    <input type="number" name="seats" required value="5" min="2" max="12" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all">
                </div>
            </div>
            <div>
                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Daily Rate (₱)</label>
                <div class="relative">
                    <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-bold">₱</span>
                    <input type="number" name="daily_rate" required step="0.01" placeholder="0.00" class="w-full pl-8 pr-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all font-bold text-primary text-lg">
                </div>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Initial Status</label>
                    <select name="status" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all">
                        <option value="available">Available</option>
                        <option value="rented">Rented</option>
                        <option value="maintenance">Maintenance</option>
                    </select>
                </div>
                <div class="flex items-center pt-5">
                    <label class="flex items-center gap-3 cursor-pointer group">
                        <div class="relative">
                            <input type="checkbox" name="has_rear_camera" value="1" class="peer sr-only">
                            <div class="w-11 h-6 bg-slate-200 dark:bg-slate-800 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary transition-colors"></div>
                        </div>
                        <span class="text-sm font-bold text-slate-600 dark:text-slate-400 group-hover:text-primary transition-colors">Rear View Camera</span>
                    </label>
                </div>
            </div>
            
            <!-- Image Upload Options -->
            <div class="space-y-4 pt-2">
                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest ml-1">Vehicle Images</label>
                <div class="grid grid-cols-1 gap-4">
                    <div class="p-4 bg-slate-50 dark:bg-slate-900/30 rounded-2xl border border-dashed border-slate-200 dark:border-slate-800">
                        <label class="block text-[11px] font-bold text-slate-500 mb-2">Option 1: Image URLs</label>
                        <input type="text" name="image_urls" placeholder="https://example.com/image1.jpg, https://example.com/image2.jpg" class="w-full px-4 py-2.5 bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 rounded-xl focus:ring-2 focus:ring-primary/20 transition-all text-sm">
                    </div>
                    <div class="p-4 bg-slate-50 dark:bg-slate-900/30 rounded-2xl border border-dashed border-slate-200 dark:border-slate-800">
                        <label class="block text-[11px] font-bold text-slate-500 mb-2">Option 2: Direct Upload</label>
                        <input type="file" name="image_files[]" multiple accept="image/*" class="w-full text-xs text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-bold file:bg-primary file:text-white hover:file:bg-primary/90 transition-all">
                    </div>
                </div>
            </div>
            
            <div>
                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Vehicle Description</label>
                <textarea name="description" rows="3" placeholder="Describe the vehicle's features, condition, etc..." class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all resize-none"></textarea>
            </div>

            <div class="flex flex-col sm:flex-row gap-3 pt-4 sticky bottom-0 bg-white dark:bg-surface-dark -mx-6 -mb-6 p-6 border-t border-slate-100 dark:border-slate-800 mt-6">
                <button type="button" onclick="document.getElementById('addModal').classList.add('hidden')" class="w-full sm:flex-1 px-6 py-3.5 border border-slate-200 dark:border-slate-800 rounded-2xl font-bold text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900 transition-all active:scale-95">
                    Cancel
                </button>
                <button type="submit" name="add_vehicle" class="w-full sm:flex-1 px-6 py-3.5 bg-primary text-white rounded-2xl font-bold shadow-lg shadow-primary/25 hover:bg-primary/90 transition-all active:scale-95">
                    Add Vehicle
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Add Maintenance Log Modal -->
<div id="addMaintenanceModal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4 sm:p-6">
    <div class="bg-white dark:bg-surface-dark rounded-3xl w-full max-w-md shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
        <div class="px-6 py-5 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-white dark:bg-surface-dark sticky top-0 z-10">
            <h3 class="text-xl font-bold text-slate-900 dark:text-white">Add Maintenance Log</h3>
            <button onclick="document.getElementById('addMaintenanceModal').classList.add('hidden')" class="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full transition-colors text-slate-500">
                <span class="material-symbols-outlined">close</span>
            </button>
        </div>
        <form method="POST" class="p-6 space-y-6 overflow-y-auto flex-1 no-scrollbar">
            <input type="hidden" name="vehicle_id" id="m_vehicle_id">
            <input type="hidden" name="add_maintenance_log" value="1">
            <div class="p-4 bg-orange-50 dark:bg-orange-900/20 border border-orange-100 dark:border-orange-800/50 rounded-2xl">
                <p class="text-sm text-orange-700 dark:text-orange-300 leading-relaxed">
                    You are marking <span id="m_vehicle_name" class="font-bold"></span> as under maintenance. This will hide the vehicle from availability for users.
                </p>
            </div>

            <div>
                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2 ml-1">Reason / Main Issue</label>
                <input type="text" name="reason" required placeholder="e.g. Oil Change, Brake Repair" class="w-full px-4 py-3.5 bg-slate-50 dark:bg-slate-900 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all font-medium">
            </div>

            <div>
                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2 ml-1">Detailed Description (Optional)</label>
                <textarea name="description" rows="4" placeholder="Provide more details about the maintenance needed..." class="w-full px-4 py-3.5 bg-slate-50 dark:bg-slate-900 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all resize-none"></textarea>
            </div>

            <div class="flex flex-col sm:flex-row gap-3 pt-4 sticky bottom-0 bg-white dark:bg-surface-dark -mx-6 -mb-6 p-6 border-t border-slate-100 dark:border-slate-800 mt-6">
                <button type="button" onclick="document.getElementById('addMaintenanceModal').classList.add('hidden')" class="w-full sm:flex-1 px-6 py-3.5 border border-slate-200 dark:border-slate-800 rounded-2xl font-bold text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900 transition-all active:scale-95">
                    Cancel
                </button>
                <button type="submit" class="w-full sm:flex-1 px-6 py-3.5 bg-orange-500 text-white rounded-2xl font-bold shadow-lg shadow-orange-500/25 hover:bg-orange-600 transition-all active:scale-95">
                    Save & Update Status
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Maintenance History Modal -->
<div id="maintenanceHistoryModal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4 sm:p-6">
    <div class="bg-white dark:bg-surface-dark rounded-3xl w-full max-w-xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
        <div class="px-6 py-5 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-white dark:bg-surface-dark sticky top-0 z-10">
            <div>
                <h3 class="text-xl font-bold text-slate-900 dark:text-white">Maintenance History</h3>
                <p id="h_vehicle_name" class="text-xs text-slate-400 font-bold uppercase tracking-widest mt-0.5"></p>
            </div>
            <button onclick="document.getElementById('maintenanceHistoryModal').classList.add('hidden')" class="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full transition-colors text-slate-500">
                <span class="material-symbols-outlined">close</span>
            </button>
        </div>
        <div class="p-6 overflow-y-auto flex-1 no-scrollbar space-y-4" id="maintenanceLogsList">
            <!-- Logs will be loaded here via AJAX -->
        </div>
        <div class="p-6 border-t border-slate-100 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/20 flex flex-col sm:flex-row justify-between items-center gap-4">
            <input type="hidden" id="h_vehicle_id">
            <button onclick="document.getElementById('maintenanceHistoryModal').classList.add('hidden'); openAddMaintenanceModal(document.getElementById('h_vehicle_id').value, document.getElementById('h_vehicle_name').textContent)" class="w-full sm:w-auto px-4 py-2.5 bg-primary/10 text-primary rounded-xl text-sm font-bold flex items-center justify-center gap-2 hover:bg-primary hover:text-white transition-all">
                <span class="material-symbols-outlined text-lg">add_circle</span>
                New Maintenance Entry
            </button>
            <button onclick="document.getElementById('maintenanceHistoryModal').classList.add('hidden')" class="w-full sm:w-auto px-6 py-2.5 bg-slate-200 dark:bg-slate-800 rounded-xl text-sm font-bold text-slate-600 dark:text-slate-300 hover:bg-slate-300 dark:hover:bg-slate-700 transition-all">
                Close
            </button>
        </div>
    </div>
</div>

<!-- Complete Maintenance Modal -->
<div id="completeMaintenanceModal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4 sm:p-6">
    <div class="bg-white dark:bg-surface-dark rounded-3xl w-full max-w-md shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
        <div class="px-6 py-5 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-white dark:bg-surface-dark sticky top-0 z-10">
            <h3 class="text-xl font-bold text-slate-900 dark:text-white">Complete Maintenance</h3>
            <button onclick="document.getElementById('completeMaintenanceModal').classList.add('hidden')" class="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full transition-colors text-slate-500">
                <span class="material-symbols-outlined">close</span>
            </button>
        </div>
        <form method="POST" class="p-6 space-y-6 overflow-y-auto flex-1 no-scrollbar">
            <input type="hidden" name="log_id" id="c_log_id">
            <input type="hidden" name="complete_maintenance" value="1">

            <div class="p-4 bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-100 dark:border-emerald-800/50 rounded-2xl">
                <p class="text-xs text-emerald-700 dark:text-emerald-300 leading-relaxed">
                    Completing maintenance for: <span id="c_log_reason" class="font-bold"></span>. This will record the final cost and end date.
                </p>
            </div>

            <div>
                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2 ml-1">Maintenance Cost (₱)</label>
                <div class="relative">
                    <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-bold">₱</span>
                    <input type="number" name="cost" step="0.01" value="0.00" class="w-full pl-8 pr-4 py-3.5 bg-slate-50 dark:bg-slate-900 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all font-bold text-lg text-slate-900 dark:text-white">
                </div>
                <p class="text-[10px] text-slate-500 mt-2 px-1 italic">Note: Remember to manually set the vehicle status back to 'Available' if it's ready for rent.</p>
            </div>

            <div class="flex flex-col sm:flex-row gap-3 pt-4 sticky bottom-0 bg-white dark:bg-surface-dark -mx-6 -mb-6 p-6 border-t border-slate-100 dark:border-slate-800 mt-6">
                <button type="button" onclick="document.getElementById('completeMaintenanceModal').classList.add('hidden')" class="w-full sm:flex-1 px-6 py-3.5 border border-slate-200 dark:border-slate-800 rounded-2xl font-bold text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900 transition-all active:scale-95">
                    Cancel
                </button>
                <button type="submit" class="w-full sm:flex-1 px-6 py-3.5 bg-emerald-500 text-white rounded-2xl font-bold shadow-lg shadow-emerald-500/25 hover:bg-emerald-600 transition-all active:scale-95">
                    Complete Log
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Modal -->
<div id="editModal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4 sm:p-6">
    <div class="bg-white dark:bg-surface-dark rounded-3xl w-full max-w-xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
        <div class="px-6 py-5 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-white dark:bg-surface-dark sticky top-0 z-10">
            <h3 class="text-xl font-bold text-slate-900 dark:text-white">Edit Vehicle</h3>
            <button onclick="document.getElementById('editModal').classList.add('hidden')" class="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full transition-colors text-slate-500">
                <span class="material-symbols-outlined">close</span>
            </button>
        </div>
        <form method="POST" enctype="multipart/form-data" id="editForm" class="p-6 space-y-6 overflow-y-auto flex-1 no-scrollbar">
            <input type="hidden" name="vehicle_id">
            <input type="hidden" name="update_vehicle" value="1">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Make</label>
                    <input type="text" name="make" required class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all">
                </div>
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Model</label>
                    <input type="text" name="model" required class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all">
                </div>
            </div>
            <div class="grid grid-cols-2 sm:grid-cols-3 gap-4">
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Year</label>
                    <input type="number" name="year" required class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all">
                </div>
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Color</label>
                    <input type="text" name="color" required class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all">
                </div>
                <div class="col-span-2 sm:col-span-1">
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Plate Number</label>
                    <input type="text" name="plate_number" required class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all">
                </div>
            </div>
            <div>
                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">SinoTrack Device ID / SN</label>
                <input type="text" name="gps_device_id" placeholder="e.g. 9170122744" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all">
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Vehicle Type</label>
                    <select name="vehicle_type" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all">
                        <?php foreach ($dynamic_types as $type): ?>
                            <option value="<?= htmlspecialchars($type) ?>"><?= htmlspecialchars(ucfirst($type)) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Transmission</label>
                    <select name="transmission" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all">
                        <option value="automatic">Automatic</option>
                        <option value="manual">Manual</option>
                    </select>
                </div>
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Fuel Type</label>
                    <select name="fuel_type" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all">
                        <option value="gasoline">Gasoline</option>
                        <option value="diesel">Diesel</option>
                        <option value="electric">Electric</option>
                        <option value="hybrid">Hybrid</option>
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Seats</label>
                    <input type="number" name="seats" required min="2" max="12" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all">
                </div>
            </div>
            <div>
                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Daily Rate (₱)</label>
                <div class="relative">
                    <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-bold">₱</span>
                    <input type="number" name="daily_rate" required step="0.01" class="w-full pl-8 pr-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all font-bold text-primary text-lg">
                </div>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Status</label>
                    <select name="status" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all">
                        <option value="available">Available</option>
                        <option value="rented">Rented</option>
                        <option value="maintenance">Maintenance</option>
                    </select>
                </div>
                <div class="flex items-center pt-5">
                    <label class="flex items-center gap-3 cursor-pointer group">
                        <div class="relative">
                            <input type="checkbox" name="has_rear_camera" value="1" class="peer sr-only">
                            <div class="w-11 h-6 bg-slate-200 dark:bg-slate-800 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary transition-colors"></div>
                        </div>
                        <span class="text-sm font-bold text-slate-600 dark:text-slate-400 group-hover:text-primary transition-colors">Rear View Camera</span>
                    </label>
                </div>
            </div>

            <!-- Image Upload Options -->
            <div class="space-y-4 pt-2">
                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest ml-1">Update Images</label>
                <div class="flex items-center gap-3 px-1">
                    <input type="checkbox" name="keep_existing_images" value="1" id="keepImages" class="rounded-lg border-slate-300 dark:border-slate-700 text-primary focus:ring-primary w-5 h-5 transition-all">
                    <label for="keepImages" class="text-sm font-bold text-slate-500 cursor-pointer">Keep existing images</label>
                </div>
                <div class="grid grid-cols-1 gap-4">
                    <div class="p-4 bg-slate-50 dark:bg-slate-900/30 rounded-2xl border border-dashed border-slate-200 dark:border-slate-800">
                        <label class="block text-[11px] font-bold text-slate-500 mb-2">New Image URLs</label>
                        <input type="text" name="image_urls" class="w-full px-4 py-2.5 bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 rounded-xl focus:ring-2 focus:ring-primary/20 transition-all text-sm">
                    </div>
                    <div class="p-4 bg-slate-50 dark:bg-slate-900/30 rounded-2xl border border-dashed border-slate-200 dark:border-slate-800">
                        <label class="block text-[11px] font-bold text-slate-500 mb-2">Upload New Images</label>
                        <input type="file" name="image_files[]" multiple accept="image/*" class="w-full text-xs text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-bold file:bg-primary file:text-white hover:file:bg-primary/90 transition-all">
                    </div>
                </div>
            </div>

            <div>
                <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Vehicle Description</label>
                <textarea name="description" rows="3" class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 rounded-2xl focus:ring-2 focus:ring-primary/20 transition-all resize-none"></textarea>
            </div>

            <div class="flex flex-col sm:flex-row gap-3 pt-4 sticky bottom-0 bg-white dark:bg-surface-dark -mx-6 -mb-6 p-6 border-t border-slate-100 dark:border-slate-800 mt-6">
                <button type="button" onclick="document.getElementById('editModal').classList.add('hidden')" class="w-full sm:flex-1 px-6 py-3.5 border border-slate-200 dark:border-slate-800 rounded-2xl font-bold text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900 transition-all active:scale-95">
                    Cancel
                </button>
                <button type="submit" class="w-full sm:flex-1 px-6 py-3.5 bg-primary text-white rounded-2xl font-bold shadow-lg shadow-primary/25 hover:bg-primary/90 transition-all active:scale-95">
                    Update Vehicle
                </button>
            </div>
        </form>
    </div>
</div>


<script>
// Status change handler
function handleStatusChange(select, vehicleId, vehicleName) {
    if (select.value === 'maintenance') {
        openAddMaintenanceModal(vehicleId, vehicleName);
    } else {
        select.form.submit();
    }
}

function openAddMaintenanceModal(vehicleId, vehicleName) {
    const modal = document.getElementById('addMaintenanceModal');
    document.getElementById('m_vehicle_id').value = vehicleId;
    document.getElementById('m_vehicle_name').textContent = vehicleName;
    modal.classList.remove('hidden');
}

async function openMaintenanceModal(vehicleId, vehicleName) {
    const modal = document.getElementById('maintenanceHistoryModal');
    document.getElementById('h_vehicle_name').textContent = vehicleName;
    document.getElementById('h_vehicle_id').value = vehicleId;

    const listContainer = document.getElementById('maintenanceLogsList');
    listContainer.innerHTML = '<div class="flex justify-center p-8"><div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div></div>';

    modal.classList.remove('hidden');

    try {
        const response = await fetch(`ajax_maintenance_logs.php?vehicle_id=${vehicleId}`);
        const data = await response.json();

        if (data.success && data.logs.length > 0) {
            let html = '<div class="space-y-4">';
            data.logs.forEach(log => {
                const isOngoing = log.status === 'ongoing';
                html += `
                    <div class="p-4 rounded-xl border ${isOngoing ? 'border-orange-200 bg-orange-50/50 dark:border-orange-800/30 dark:bg-orange-900/10' : 'border-slate-100 bg-slate-50/50 dark:border-slate-800 dark:bg-slate-900/20'}">
                        <div class="flex justify-between items-start mb-2">
                            <div>
                                <span class="text-xs font-bold uppercase tracking-wider ${isOngoing ? 'text-orange-600' : 'text-slate-500'}">
                                    ${isOngoing ? 'Ongoing Maintenance' : 'Completed'}
                                </span>
                                <h4 class="font-bold text-slate-800 dark:text-white">${log.reason}</h4>
                            </div>
                            <div class="text-right">
                                <p class="text-xs text-slate-500">${log.start_date} ${log.end_date ? 'to ' + log.end_date : ''}</p>
                                ${log.cost > 0 ? `<p class="text-sm font-bold text-primary">₱${parseFloat(log.cost).toLocaleString()}</p>` : ''}
                            </div>
                        </div>
                        ${log.description ? `<p class="text-sm text-slate-600 dark:text-slate-400 mb-3">${log.description}</p>` : ''}

                        ${isOngoing ? `
                            <button onclick="openCompleteMaintenanceModal(${log.id}, '${log.reason}')" class="text-xs font-bold text-primary hover:underline flex items-center gap-1">
                                <span class="material-symbols-outlined text-sm">check_circle</span>
                                Mark as Completed
                            </button>
                        ` : ''}
                    </div>
                `;
            });
            html += '</div>';
            listContainer.innerHTML = html;
        } else {
            listContainer.innerHTML = `
                <div class="text-center py-12">
                    <span class="material-symbols-outlined text-4xl text-slate-300 mb-2">build_circle</span>
                    <p class="text-slate-500">No maintenance history found for this vehicle.</p>
                </div>
            `;
        }
    } catch (error) {
        listContainer.innerHTML = '<p class="text-red-500 text-center p-4">Error loading maintenance logs.</p>';
    }
}

function openCompleteMaintenanceModal(logId, reason) {
    const modal = document.getElementById('completeMaintenanceModal');
    document.getElementById('c_log_id').value = logId;
    document.getElementById('c_log_reason').textContent = reason;
    modal.classList.remove('hidden');
}

// Edit vehicle modal
function openEditModal(vehicle) {
    const modal = document.getElementById('editModal');
    const form = document.getElementById('editForm');
    
    // Fill form with vehicle data
    form.vehicle_id.value = vehicle.id;
    form.make.value = vehicle.make;
    form.model.value = vehicle.model;
    form.year.value = vehicle.year;
    form.color.value = vehicle.color;
    form.plate_number.value = vehicle.plate_number;
    form.gps_device_id.value = vehicle.gps_device_id || '';
    form.vehicle_type.value = vehicle.vehicle_type;
    form.transmission.value = vehicle.transmission;
    form.fuel_type.value = vehicle.fuel_type;
    form.seats.value = vehicle.seats;
    form.daily_rate.value = vehicle.daily_rate;
    form.status.value = vehicle.status;
    form.has_rear_camera.checked = vehicle.has_rear_camera == 1;
    
    // Handle images
    let images = [];
    try {
        images = typeof vehicle.images === 'string' ? JSON.parse(vehicle.images || '[]') : (vehicle.images || []);
    } catch(e) {
        images = [];
    }
    form.image_urls.value = images.join(',');
    
    form.description.value = vehicle.description || '';
    
    modal.classList.remove('hidden');
}
</script>

<?php include 'includes/footer.php'; ?>
