<?php
session_start();
include 'layouts/dbconn.php';
include 'includes/menu_config.php';

// Set timezone
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role_name'] ?? 'User';

// Fetch user details
$sql_user = "SELECT u.*, ur.role_name FROM users u 
             INNER JOIN user_roles ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details) {
    header('Location: logout.php');
    exit();
}

// Handle AJAX requests
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'add_vehicle':
            $vehicle_number = trim($_POST['vehicle_number']);
            $vehicle_type = $_POST['vehicle_type'];
            $make = trim($_POST['make']);
            $model = trim($_POST['model']);
            $year = intval($_POST['year']);
            $capacity_weight = floatval($_POST['capacity_weight']);
            $capacity_volume = floatval($_POST['capacity_volume']);
            $fuel_type = $_POST['fuel_type'];
            $insurance_expiry = $_POST['insurance_expiry'];
            $license_expiry = $_POST['license_expiry'];
            $status = $_POST['status'];
            
            // Check for duplicate vehicle number
            $check_sql = "SELECT vehicle_id FROM vehicles WHERE vehicle_number = ?";
            $stmt_check = $conn->prepare($check_sql);
            $stmt_check->bind_param("s", $vehicle_number);
            $stmt_check->execute();
            
            if ($stmt_check->get_result()->num_rows > 0) {
                echo json_encode(['success' => false, 'message' => 'Vehicle number already exists']);
                exit();
            }
            
            $insert_sql = "INSERT INTO vehicles (vehicle_number, vehicle_type, make, model, year, 
                          capacity_weight, capacity_volume, fuel_type, insurance_expiry, 
                          license_expiry, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt_insert = $conn->prepare($insert_sql);
            $stmt_insert->bind_param("ssssiidssss", $vehicle_number, $vehicle_type, $make, $model, 
                                   $year, $capacity_weight, $capacity_volume, $fuel_type, 
                                   $insurance_expiry, $license_expiry, $status);
            
            if ($stmt_insert->execute()) {
                $vehicle_id = $conn->insert_id;
                
                // Log activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                           VALUES (?, 'CREATE', 'vehicles', ?, ?)";
                $stmt_log = $conn->prepare($log_sql);
                $details = json_encode(['vehicle_number' => $vehicle_number, 'type' => $vehicle_type]);
                $stmt_log->bind_param("iss", $user_id, $vehicle_id, $details);
                $stmt_log->execute();
                
                echo json_encode(['success' => true, 'message' => 'Vehicle added successfully', 'vehicle_id' => $vehicle_id]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to add vehicle']);
            }
            break;
            
        case 'update_vehicle':
            $vehicle_id = intval($_POST['vehicle_id']);
            $vehicle_number = trim($_POST['vehicle_number']);
            $vehicle_type = $_POST['vehicle_type'];
            $make = trim($_POST['make']);
            $model = trim($_POST['model']);
            $year = intval($_POST['year']);
            $capacity_weight = floatval($_POST['capacity_weight']);
            $capacity_volume = floatval($_POST['capacity_volume']);
            $fuel_type = $_POST['fuel_type'];
            $insurance_expiry = $_POST['insurance_expiry'];
            $license_expiry = $_POST['license_expiry'];
            $status = $_POST['status'];
            
            $update_sql = "UPDATE vehicles SET vehicle_number = ?, vehicle_type = ?, make = ?, 
                          model = ?, year = ?, capacity_weight = ?, capacity_volume = ?, 
                          fuel_type = ?, insurance_expiry = ?, license_expiry = ?, status = ?, 
                          updated_at = NOW() WHERE vehicle_id = ?";
            $stmt_update = $conn->prepare($update_sql);
            $stmt_update->bind_param("ssssiiissssi", $vehicle_number, $vehicle_type, $make, $model, 
                                   $year, $capacity_weight, $capacity_volume, $fuel_type, 
                                   $insurance_expiry, $license_expiry, $status, $vehicle_id);
            
            if ($stmt_update->execute()) {
                echo json_encode(['success' => true, 'message' => 'Vehicle updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update vehicle']);
            }
            break;
            
        case 'assign_driver':
            $vehicle_id = intval($_POST['vehicle_id']);
            $driver_id = intval($_POST['driver_id']);
            $assigned_date = $_POST['assigned_date'];
            
            // End current assignment if any
            $end_sql = "UPDATE vehicle_assignments SET unassigned_date = CURDATE(), is_active = 0 
                       WHERE vehicle_id = ? AND is_active = 1";
            $stmt_end = $conn->prepare($end_sql);
            $stmt_end->bind_param("i", $vehicle_id);
            $stmt_end->execute();
            
            // Create new assignment
            $assign_sql = "INSERT INTO vehicle_assignments (vehicle_id, driver_id, assigned_date, assigned_by) 
                          VALUES (?, ?, ?, ?)";
            $stmt_assign = $conn->prepare($assign_sql);
            $stmt_assign->bind_param("iisi", $vehicle_id, $driver_id, $assigned_date, $user_id);
            
            if ($stmt_assign->execute()) {
                echo json_encode(['success' => true, 'message' => 'Driver assigned successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to assign driver']);
            }
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit();
}

// Filter parameters
$status_filter = $_GET['status'] ?? '';
$type_filter = $_GET['type'] ?? '';
$fuel_filter = $_GET['fuel'] ?? '';
$maintenance_filter = $_GET['maintenance'] ?? '';

// Build WHERE clause
$where_conditions = [];
$params = [];
$param_types = '';

if ($status_filter) {
    $where_conditions[] = "v.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if ($type_filter) {
    $where_conditions[] = "v.vehicle_type = ?";
    $params[] = $type_filter;
    $param_types .= 's';
}

if ($fuel_filter) {
    $where_conditions[] = "v.fuel_type = ?";
    $params[] = $fuel_filter;
    $param_types .= 's';
}

if ($maintenance_filter == 'due') {
    $where_conditions[] = "(v.insurance_expiry <= DATE_ADD(CURDATE(), INTERVAL 30 DAY) OR v.license_expiry <= DATE_ADD(CURDATE(), INTERVAL 30 DAY))";
}

$where_clause = empty($where_conditions) ? '' : 'WHERE ' . implode(' AND ', $where_conditions);

// Get vehicles with driver assignments
$sql_vehicles = "
    SELECT 
        v.*,
        d.first_name as driver_first_name,
        d.last_name as driver_last_name,
        d.driver_code,
        d.phone as driver_phone,
        va.assigned_date,
        COUNT(DISTINCT sr.run_id) as total_runs,
        COALESCE(SUM(sr.capacity_used_weight), 0) as total_weight_carried,
        AVG(CASE WHEN sr.status = 'COMPLETED' THEN 1 ELSE 0 END) * 100 as completion_rate,
        DATEDIFF(v.insurance_expiry, CURDATE()) as insurance_days_left,
        DATEDIFF(v.license_expiry, CURDATE()) as license_days_left
    FROM vehicles v
    LEFT JOIN vehicle_assignments va ON v.vehicle_id = va.vehicle_id AND va.is_active = 1
    LEFT JOIN drivers d ON va.driver_id = d.driver_id
    LEFT JOIN scheduled_runs sr ON v.vehicle_id = sr.vehicle_id AND sr.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    $where_clause
    GROUP BY v.vehicle_id, v.vehicle_number, v.vehicle_type, v.make, v.model, v.year,
             v.capacity_weight, v.capacity_volume, v.fuel_type, v.insurance_expiry,
             v.license_expiry, v.status, v.created_at, v.updated_at,
             d.first_name, d.last_name, d.driver_code, d.phone, va.assigned_date
    ORDER BY v.created_at DESC";

$stmt_vehicles = $conn->prepare($sql_vehicles);
if (!empty($params)) {
    $stmt_vehicles->bind_param($param_types, ...$params);
}
$stmt_vehicles->execute();
$vehicles_result = $stmt_vehicles->get_result();

// Get summary statistics
$sql_summary = "
    SELECT 
        COUNT(*) as total_vehicles,
        SUM(CASE WHEN v.status = 'ACTIVE' THEN 1 ELSE 0 END) as active_vehicles,
        SUM(CASE WHEN v.status = 'MAINTENANCE' THEN 1 ELSE 0 END) as maintenance_vehicles,
        SUM(CASE WHEN v.status = 'INACTIVE' THEN 1 ELSE 0 END) as inactive_vehicles,
        SUM(v.capacity_weight) as total_capacity_weight,
        SUM(v.capacity_volume) as total_capacity_volume,
        AVG(YEAR(CURDATE()) - v.year) as avg_vehicle_age,
        COUNT(CASE WHEN v.insurance_expiry <= DATE_ADD(CURDATE(), INTERVAL 30 DAY) THEN 1 END) as insurance_expiring,
        COUNT(CASE WHEN v.license_expiry <= DATE_ADD(CURDATE(), INTERVAL 30 DAY) THEN 1 END) as license_expiring
    FROM vehicles v
    $where_clause";

$stmt_summary = $conn->prepare($sql_summary);
if (!empty($params)) {
    $stmt_summary->bind_param($param_types, ...$params);
}
$stmt_summary->execute();
$summary = $stmt_summary->get_result()->fetch_assoc();

// Get available drivers for assignment
$sql_drivers = "SELECT driver_id, driver_code, first_name, last_name, phone, status 
                FROM drivers WHERE status = 'ACTIVE' ORDER BY first_name, last_name";
$drivers_result = $conn->query($sql_drivers);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Vehicle Fleet Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .fleet-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
        }
        
        .fleet-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
            margin-bottom: 1.5rem;
        }
        
        .summary-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            transform: translate(30px, -30px);
        }
        
        .summary-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .summary-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .status-badge {
            padding: 0.35rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-active { background: #d1e7dd; color: #0a3622; }
        .status-maintenance { background: #fff3cd; color: #664d03; }
        .status-inactive { background: #f8d7da; color: #58151c; }
        
        .vehicle-type-badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            border-radius: 8px;
            font-size: 0.7rem;
            font-weight: 600;
            margin: 0.1rem;
        }
        
        .type-truck { background: #e3f2fd; color: #1976d2; }
        .type-van { background: #e8f5e8; color: #2e7d32; }
        .type-motorcycle { background: #fff3e0; color: #ef6c00; }
        .type-car { background: #f3e5f5; color: #7b1fa2; }
        .type-other { background: #f5f5f5; color: #616161; }
        
        .capacity-indicator {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 0.5rem;
            margin-top: 0.5rem;
        }
        
        .capacity-bar {
            height: 4px;
            background: #e9ecef;
            border-radius: 2px;
            overflow: hidden;
            margin-top: 0.25rem;
        }
        
        .capacity-fill {
            height: 100%;
            background: linear-gradient(90deg, #28a745, #20c997);
            transition: width 0.3s ease;
        }
        
        .vehicle-stats {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
            margin-top: 0.5rem;
        }
        
        .stat-item {
            text-align: center;
        }
        
        .stat-value {
            font-size: 1.25rem;
            font-weight: 700;
            color: #2c3e50;
        }
        
        .stat-label {
            font-size: 0.75rem;
            color: #6c757d;
            text-transform: uppercase;
        }
        
        .expiry-warning {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 6px;
            padding: 0.5rem;
            margin-top: 0.5rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .expiry-danger {
            background: #f8d7da;
            border-color: #f5c6cb;
        }
        
        .driver-info {
            background: #e3f2fd;
            border-radius: 8px;
            padding: 0.75rem;
            margin-top: 0.5rem;
        }
        
        .filter-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e9ecef;
        }
        
        .action-btn {
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            font-size: 0.75rem;
            margin: 0.1rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-view { background: #e3f2fd; color: #1976d2; }
        .btn-edit { background: #fff3e0; color: #ef6c00; }
        .btn-assign { background: #e8f5e8; color: #2e7d32; }
        .btn-maintenance { background: #fff3cd; color: #d97706; }
        .btn-delete { background: #ffebee; color: #c62828; }
        
        .action-btn:hover {
            transform: scale(1.05);
        }
        
        .add-vehicle-btn {
            background: linear-gradient(45deg, #28a745, #20c997);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(40,167,69,0.3);
        }
        
        .add-vehicle-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(40,167,69,0.4);
            color: white;
        }
        
        .vehicle-image {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
        }
        
        @media (max-width: 768px) {
            .summary-card {
                margin-bottom: 1rem;
            }
            
            .summary-value {
                font-size: 1.5rem;
            }
            
            .table-responsive {
                font-size: 0.875rem;
            }
            
            .vehicle-stats {
                flex-direction: column;
                gap: 0.5rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><i class="ri-truck-line me-2"></i>Vehicle Fleet Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="operations_dashboard.php">Operations</a></li>
                                        <li class="breadcrumb-item active">Vehicles</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                <div class="summary-value"><?php echo number_format($summary['total_vehicles']); ?></div>
                                <div class="summary-label">Total Vehicles</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                <div class="summary-value"><?php echo number_format($summary['active_vehicles']); ?></div>
                                <div class="summary-label">Active Vehicles</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                <div class="summary-value"><?php echo number_format($summary['total_capacity_weight'], 1); ?>T</div>
                                <div class="summary-label">Total Capacity</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                                <div class="summary-value"><?php echo number_format($summary['avg_vehicle_age'], 1); ?></div>
                                <div class="summary-label">Avg Vehicle Age</div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions and Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="fleet-card">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-6">
                                            <button class="btn add-vehicle-btn me-2" onclick="showAddVehicleModal()">
                                                <i class="ri-add-line me-1"></i>Add Vehicle
                                            </button>
                                            <button class="btn btn-outline-success me-2" onclick="bulkAssignments()">
                                                <i class="ri-user-settings-line me-1"></i>Bulk Assign
                                            </button>
                                            <button class="btn btn-outline-info me-2" onclick="maintenanceSchedule()">
                                                <i class="ri-settings-3-line me-1"></i>Maintenance
                                            </button>
                                            <button class="btn btn-outline-warning" onclick="exportVehicles()">
                                                <i class="ri-download-line me-1"></i>Export
                                            </button>
                                        </div>
                                        <div class="col-md-6 text-end">
                                            <button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#filterSection">
                                                <i class="ri-filter-3-line me-1"></i>Filters
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="collapse" id="filterSection">
                        <div class="filter-section">
                            <form method="GET" class="row g-3">
                                <div class="col-md-2">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" name="status" id="status">
                                        <option value="">All Status</option>
                                        <option value="ACTIVE" <?php echo $status_filter == 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                        <option value="MAINTENANCE" <?php echo $status_filter == 'MAINTENANCE' ? 'selected' : ''; ?>>Maintenance</option>
                                        <option value="INACTIVE" <?php echo $status_filter == 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="type" class="form-label">Vehicle Type</label>
                                    <select class="form-select" name="type" id="type">
                                        <option value="">All Types</option>
                                        <option value="TRUCK" <?php echo $type_filter == 'TRUCK' ? 'selected' : ''; ?>>Truck</option>
                                        <option value="VAN" <?php echo $type_filter == 'VAN' ? 'selected' : ''; ?>>Van</option>
                                        <option value="MOTORCYCLE" <?php echo $type_filter == 'MOTORCYCLE' ? 'selected' : ''; ?>>Motorcycle</option>
                                        <option value="CAR" <?php echo $type_filter == 'CAR' ? 'selected' : ''; ?>>Car</option>
                                        <option value="OTHER" <?php echo $type_filter == 'OTHER' ? 'selected' : ''; ?>>Other</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="fuel" class="form-label">Fuel Type</label>
                                    <select class="form-select" name="fuel" id="fuel">
                                        <option value="">All Fuel Types</option>
                                        <option value="PETROL" <?php echo $fuel_filter == 'PETROL' ? 'selected' : ''; ?>>Petrol</option>
                                        <option value="DIESEL" <?php echo $fuel_filter == 'DIESEL' ? 'selected' : ''; ?>>Diesel</option>
                                        <option value="ELECTRIC" <?php echo $fuel_filter == 'ELECTRIC' ? 'selected' : ''; ?>>Electric</option>
                                        <option value="HYBRID" <?php echo $fuel_filter == 'HYBRID' ? 'selected' : ''; ?>>Hybrid</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-3">
                                    <label for="maintenance" class="form-label">Maintenance</label>
                                    <select class="form-select" name="maintenance" id="maintenance">
                                        <option value="">All Vehicles</option>
                                        <option value="due" <?php echo $maintenance_filter == 'due' ? 'selected' : ''; ?>>Maintenance Due</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-3">
                                    <label class="form-label">&nbsp;</label>
                                    <div class="d-flex gap-2">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-search-line me-1"></i>Filter
                                        </button>
                                        <a href="vehicles.php" class="btn btn-outline-secondary">
                                            <i class="ri-refresh-line me-1"></i>Reset
                                        </a>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Vehicles Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="fleet-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-truck-line me-2"></i>Vehicle Fleet
                                        <?php if ($summary['insurance_expiring'] > 0 || $summary['license_expiring'] > 0): ?>
                                        <span class="badge bg-warning ms-2">
                                            <?php echo ($summary['insurance_expiring'] + $summary['license_expiring']); ?> Expiring Soon
                                        </span>
                                        <?php endif; ?>
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover" id="vehiclesTable">
                                            <thead>
                                                <tr>
                                                    <th>Vehicle</th>
                                                    <th>Specifications</th>
                                                    <th>Capacity</th>
                                                    <th>Driver</th>
                                                    <th>Performance</th>
                                                    <th>Maintenance</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($vehicle = $vehicles_result->fetch_assoc()): ?>
                                                <?php
                                                    $insurance_warning = $vehicle['insurance_days_left'] <= 30 && $vehicle['insurance_days_left'] > 0;
                                                    $insurance_expired = $vehicle['insurance_days_left'] <= 0;
                                                    $license_warning = $vehicle['license_days_left'] <= 30 && $vehicle['license_days_left'] > 0;
                                                    $license_expired = $vehicle['license_days_left'] <= 0;
                                                    
                                                    $utilization = $vehicle['capacity_weight'] > 0 ? 
                                                        min(100, ($vehicle['total_weight_carried'] / ($vehicle['capacity_weight'] * 30)) * 100) : 0;
                                                ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="vehicle-image me-3">
                                                                <i class="ri-truck-line"></i>
                                                            </div>
                                                            <div>
                                                                <div class="fw-bold"><?php echo $vehicle['vehicle_number']; ?></div>
                                                                <small class="text-muted">
                                                                    <?php echo $vehicle['make'] . ' ' . $vehicle['model']; ?>
                                                                    (<?php echo $vehicle['year']; ?>)
                                                                </small>
                                                                <div class="mt-1">
                                                                    <span class="vehicle-type-badge type-<?php echo strtolower($vehicle['vehicle_type']); ?>">
                                                                        <?php echo $vehicle['vehicle_type']; ?>
                                                                    </span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <strong>Fuel:</strong> <?php echo $vehicle['fuel_type']; ?><br>
                                                            <strong>Age:</strong> <?php echo (date('Y') - $vehicle['year']); ?> years<br>
                                                            <small class="text-muted">
                                                                Added: <?php echo date('M j, Y', strtotime($vehicle['created_at'])); ?>
                                                            </small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="capacity-indicator">
                                                            <div><strong>Weight:</strong> <?php echo number_format($vehicle['capacity_weight'], 1); ?> tons</div>
                                                            <div><strong>Volume:</strong> <?php echo number_format($vehicle['capacity_volume'], 1); ?> m³</div>
                                                            <div class="capacity-bar">
                                                                <div class="capacity-fill" style="width: <?php echo min(100, $utilization); ?>%"></div>
                                                            </div>
                                                            <small class="text-muted"><?php echo number_format($utilization, 1); ?>% utilized (30 days)</small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <?php if ($vehicle['driver_first_name']): ?>
                                                        <div class="driver-info">
                                                            <div class="fw-bold">
                                                                <?php echo $vehicle['driver_first_name'] . ' ' . $vehicle['driver_last_name']; ?>
                                                            </div>
                                                            <small class="text-muted">
                                                                <?php echo $vehicle['driver_code']; ?><br>
                                                                <?php echo $vehicle['driver_phone']; ?><br>
                                                                Since: <?php echo date('M j, Y', strtotime($vehicle['assigned_date'])); ?>
                                                            </small>
                                                        </div>
                                                        <?php else: ?>
                                                        <div class="text-center text-muted">
                                                            <i class="ri-user-unfollow-line fs-4"></i>
                                                            <div>No Driver Assigned</div>
                                                            <button class="btn btn-sm btn-outline-primary mt-1" 
                                                                    onclick="assignDriver(<?php echo $vehicle['vehicle_id']; ?>)">
                                                                Assign Driver
                                                            </button>
                                                        </div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="vehicle-stats">
                                                            <div class="stat-item">
                                                                <div class="stat-value"><?php echo $vehicle['total_runs']; ?></div>
                                                                <div class="stat-label">Runs</div>
                                                            </div>
                                                            <div class="stat-item">
                                                                <div class="stat-value"><?php echo number_format($vehicle['completion_rate'], 1); ?>%</div>
                                                                <div class="stat-label">Success Rate</div>
                                                            </div>
                                                        </div>
                                                        <div class="mt-2">
                                                            <small class="text-muted">
                                                                Total Weight: <?php echo number_format($vehicle['total_weight_carried'], 1); ?>kg
                                                            </small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <div class="mb-2">
                                                                <strong>Insurance:</strong>
                                                                <span class="<?php echo $insurance_expired ? 'text-danger' : ($insurance_warning ? 'text-warning' : 'text-success'); ?>">
                                                                    <?php echo date('M j, Y', strtotime($vehicle['insurance_expiry'])); ?>
                                                                </span>
                                                            </div>
                                                            <div class="mb-2">
                                                                <strong>License:</strong>
                                                                <span class="<?php echo $license_expired ? 'text-danger' : ($license_warning ? 'text-warning' : 'text-success'); ?>">
                                                                    <?php echo date('M j, Y', strtotime($vehicle['license_expiry'])); ?>
                                                                </span>
                                                            </div>
                                                        </div>
                                                        
                                                        <?php if ($insurance_warning || $insurance_expired || $license_warning || $license_expired): ?>
                                                        <div class="expiry-warning <?php echo ($insurance_expired || $license_expired) ? 'expiry-danger' : ''; ?>">
                                                            <i class="ri-alert-line"></i>
                                                            <span>
                                                                <?php if ($insurance_expired || $license_expired): ?>
                                                                    Expired Documents
                                                                <?php else: ?>
                                                                    Expiring Soon
                                                                <?php endif; ?>
                                                            </span>
                                                        </div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <select class="form-select form-select-sm status-badge status-<?php echo strtolower($vehicle['status']); ?>" 
                                                                onchange="updateVehicleStatus(<?php echo $vehicle['vehicle_id']; ?>, this.value)"
                                                                style="border: none; background: transparent; font-weight: 600;">
                                                            <option value="ACTIVE" <?php echo $vehicle['status'] == 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                                            <option value="MAINTENANCE" <?php echo $vehicle['status'] == 'MAINTENANCE' ? 'selected' : ''; ?>>Maintenance</option>
                                                            <option value="INACTIVE" <?php echo $vehicle['status'] == 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group" role="group">
                                                            <button class="action-btn btn-view" onclick="viewVehicle(<?php echo $vehicle['vehicle_id']; ?>)" 
                                                                    title="View Details">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-edit" onclick="editVehicle(<?php echo $vehicle['vehicle_id']; ?>)" 
                                                                    title="Edit Vehicle">
                                                                <i class="ri-edit-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-assign" onclick="assignDriver(<?php echo $vehicle['vehicle_id']; ?>)" 
                                                                    title="Assign Driver">
                                                                <i class="ri-user-settings-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-maintenance" onclick="scheduleMaintenancePage(<?php echo $vehicle['vehicle_id']; ?>)" 
                                                                    title="Maintenance">
                                                                <i class="ri-settings-3-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-delete" onclick="deleteVehicle(<?php echo $vehicle['vehicle_id']; ?>)" 
                                                                    title="Delete Vehicle">
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Add Vehicle Modal -->
    <div class="modal fade" id="addVehicleModal" tabindex="-1" aria-labelledby="addVehicleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addVehicleModalLabel">
                        <i class="ri-truck-line me-2"></i>Add New Vehicle
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="addVehicleForm">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="vehicle_number" class="form-label">Vehicle Number *</label>
                                <input type="text" class="form-control" id="vehicle_number" name="vehicle_number" required 
                                       placeholder="e.g., KAB 123A">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="vehicle_type" class="form-label">Vehicle Type *</label>
                                <select class="form-select" id="vehicle_type" name="vehicle_type" required>
                                    <option value="">Select Type</option>
                                    <option value="TRUCK">Truck</option>
                                    <option value="VAN">Van</option>
                                    <option value="MOTORCYCLE">Motorcycle</option>
                                    <option value="CAR">Car</option>
                                    <option value="OTHER">Other</option>
                                </select>
                            </div>
                            
                            <div class="col-md-4">
                                <label for="make" class="form-label">Make</label>
                                <input type="text" class="form-control" id="make" name="make" placeholder="e.g., Toyota">
                            </div>
                            
                            <div class="col-md-4">
                                <label for="model" class="form-label">Model</label>
                                <input type="text" class="form-control" id="model" name="model" placeholder="e.g., Hilux">
                            </div>
                            
                            <div class="col-md-4">
                                <label for="year" class="form-label">Year</label>
                                <input type="number" class="form-control" id="year" name="year" 
                                       min="1990" max="<?php echo date('Y') + 1; ?>" value="<?php echo date('Y'); ?>">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="capacity_weight" class="form-label">Weight Capacity (tons)</label>
                                <input type="number" class="form-control" id="capacity_weight" name="capacity_weight" 
                                       step="0.1" min="0" placeholder="e.g., 3.5">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="capacity_volume" class="form-label">Volume Capacity (m³)</label>
                                <input type="number" class="form-control" id="capacity_volume" name="capacity_volume" 
                                       step="0.1" min="0" placeholder="e.g., 12.5">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="fuel_type" class="form-label">Fuel Type</label>
                                <select class="form-select" id="fuel_type" name="fuel_type">
                                    <option value="">Select Fuel Type</option>
                                    <option value="PETROL">Petrol</option>
                                    <option value="DIESEL">Diesel</option>
                                    <option value="ELECTRIC">Electric</option>
                                    <option value="HYBRID">Hybrid</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="status" class="form-label">Status</label>
                                <select class="form-select" id="status" name="status" required>
                                    <option value="ACTIVE">Active</option>
                                    <option value="MAINTENANCE">Maintenance</option>
                                    <option value="INACTIVE">Inactive</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="insurance_expiry" class="form-label">Insurance Expiry Date</label>
                                <input type="date" class="form-control" id="insurance_expiry" name="insurance_expiry">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="license_expiry" class="form-label">License Expiry Date</label>
                                <input type="date" class="form-control" id="license_expiry" name="license_expiry">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">
                            <i class="ri-truck-line me-1"></i>Add Vehicle
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Assign Driver Modal -->
    <div class="modal fade" id="assignDriverModal" tabindex="-1" aria-labelledby="assignDriverModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="assignDriverModalLabel">
                        <i class="ri-user-settings-line me-2"></i>Assign Driver to Vehicle
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="assignDriverForm">
                    <div class="modal-body">
                        <input type="hidden" id="assign_vehicle_id" name="vehicle_id">
                        
                        <div class="mb-3">
                            <label for="assign_driver_id" class="form-label">Select Driver *</label>
                            <select class="form-select" id="assign_driver_id" name="driver_id" required>
                                <option value="">Choose a driver...</option>
                                <?php 
                                $drivers_result->data_seek(0);
                                while ($driver = $drivers_result->fetch_assoc()): 
                                ?>
                                <option value="<?php echo $driver['driver_id']; ?>">
                                    <?php echo $driver['first_name'] . ' ' . $driver['last_name']; ?> 
                                    (<?php echo $driver['driver_code']; ?>)
                                </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="assigned_date" class="form-label">Assignment Date *</label>
                            <input type="date" class="form-control" id="assigned_date" name="assigned_date" 
                                   value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="ri-information-line me-2"></i>
                            This will end any current driver assignment for this vehicle.
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">
                            <i class="ri-user-settings-line me-1"></i>Assign Driver
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
$(document).ready(function() {
    // Initialize DataTable
    $('#vehiclesTable').DataTable({
        responsive: true,
        pageLength: 25,
        order: [[0, 'asc']],
        columnDefs: [
            { targets: [7], orderable: false }
        ],
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'excel',
                text: '<i class="ri-file-excel-line me-1"></i>Excel',
                className: 'btn btn-success btn-sm'
            },
            {
                extend: 'pdf',
                text: '<i class="ri-file-pdf-line me-1"></i>PDF', 
                className: 'btn btn-danger btn-sm'
            }
        ]
    });

    // Add Vehicle Form Handler
    $('#addVehicleForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'add_vehicle');
        
        // Show loading
        Swal.fire({
            title: 'Adding Vehicle...',
            text: 'Please wait while we add the vehicle to your fleet.',
            icon: 'info',
            allowOutsideClick: false,
            showConfirmButton: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        $.ajax({
            url: 'vehicles.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'Vehicle Added!',
                        text: response.message,
                        icon: 'success',
                        timer: 2000,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error',
                        text: response.message,
                        icon: 'error'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error',
                    text: 'An error occurred while adding the vehicle.',
                    icon: 'error'
                });
            }
        });
    });

    // Assign Driver Form Handler
    $('#assignDriverForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'assign_driver');
        
        Swal.fire({
            title: 'Assigning Driver...',
            text: 'Please wait while we assign the driver.',
            icon: 'info',
            allowOutsideClick: false,
            showConfirmButton: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        $.ajax({
            url: 'vehicles.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'Driver Assigned!',
                        text: response.message,
                        icon: 'success',
                        timer: 2000,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error',
                        text: response.message,
                        icon: 'error'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error',
                    text: 'An error occurred while assigning the driver.',
                    icon: 'error'
                });
            }
        });
    });
});

// Global Functions
window.showAddVehicleModal = function() {
    $('#addVehicleModal').modal('show');
};

window.assignDriver = function(vehicleId) {
    $('#assign_vehicle_id').val(vehicleId);
    $('#assignDriverModal').modal('show');
};

window.updateVehicleStatus = function(vehicleId, newStatus) {
    const originalSelect = event.target;
    const originalValue = originalSelect.getAttribute('data-original-value') || originalSelect.value;
    
    if (newStatus === originalValue) return;
    
    Swal.fire({
        title: 'Update Vehicle Status',
        text: `Change vehicle status to ${newStatus.toLowerCase()}?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Update',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'vehicles.php',
                method: 'POST',
                data: {
                    action: 'update_vehicle_status',
                    vehicle_id: vehicleId,
                    status: newStatus
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        originalSelect.setAttribute('data-original-value', newStatus);
                        originalSelect.className = `form-select form-select-sm status-badge status-${newStatus.toLowerCase()}`;
                        
                        Swal.fire({
                            title: 'Success',
                            text: response.message,
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false
                        });
                    } else {
                        originalSelect.value = originalValue;
                        Swal.fire({
                            title: 'Error',
                            text: response.message,
                            icon: 'error'
                        });
                    }
                },
                error: function() {
                    originalSelect.value = originalValue;
                    Swal.fire({
                        title: 'Error',
                        text: 'An error occurred while updating the status.',
                        icon: 'error'
                    });
                }
            });
        } else {
            originalSelect.value = originalValue;
        }
    });
};

window.viewVehicle = function(vehicleId) {
    window.location.href = `vehicle_details.php?id=${vehicleId}`;
};

window.editVehicle = function(vehicleId) {
    window.location.href = `edit_vehicle.php?id=${vehicleId}`;
};

window.scheduleMaintenancePage = function(vehicleId) {
    window.location.href = `vehicle_maintenance.php?id=${vehicleId}`;
};

window.deleteVehicle = function(vehicleId) {
    Swal.fire({
        title: 'Delete Vehicle',
        text: 'Are you sure you want to delete this vehicle? This action cannot be undone.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Delete',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#d33'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Deleted!',
                text: 'The vehicle has been deleted.',
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            }).then(() => {
                location.reload();
            });
        }
    });
};

window.bulkAssignments = function() {
    window.location.href = 'bulk_vehicle_assignments.php';
};

window.maintenanceSchedule = function() {
    window.location.href = 'maintenance_schedule.php';
};

window.exportVehicles = function() {
    Swal.fire({
        title: 'Export Vehicle Data',
        html: `
            <div class="mb-3">
                <label class="form-label">Export Format:</label>
                <select class="form-select" id="exportFormat">
                    <option value="excel">Excel (.xlsx)</option>
                    <option value="pdf">PDF Report</option>
                    <option value="csv">CSV Data</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Include:</label>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includePerformance" checked>
                    <label class="form-check-label" for="includePerformance">Performance Data</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includeMaintenance" checked>
                    <label class="form-check-label" for="includeMaintenance">Maintenance Records</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includeAssignments" checked>
                    <label class="form-check-label" for="includeAssignments">Driver Assignments</label>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Export',
        preConfirm: () => {
            return {
                format: document.getElementById('exportFormat').value,
                includePerformance: document.getElementById('includePerformance').checked,
                includeMaintenance: document.getElementById('includeMaintenance').checked,
                includeAssignments: document.getElementById('includeAssignments').checked
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Generating Export...',
                text: 'Please wait while we prepare your export.',
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                    setTimeout(() => {
                        Swal.close();
                        // Trigger download
                        const link = document.createElement('a');
                        link.href = `exports/vehicles_export.php?format=${result.value.format}&performance=${result.value.includePerformance}&maintenance=${result.value.includeMaintenance}&assignments=${result.value.includeAssignments}`;
                        link.download = `vehicles_${new Date().toISOString().split('T')[0]}.${result.value.format}`;
                        link.click();
                    }, 2000);
                }
            });
        }
    });
};
</script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>