<?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';
$vehicle_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$vehicle_id) {
    header('Location: vehicles.php');
    exit();
}

// 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 'update_vehicle':
            $vehicle_number = $_POST['vehicle_number'];
            $vehicle_type = $_POST['vehicle_type'];
            $make = $_POST['make'];
            $model = $_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 = $conn->prepare($update_sql);
            $stmt->bind_param("ssssiddsssi", 
                $vehicle_number, $vehicle_type, $make, $model, $year,
                $capacity_weight, $capacity_volume, $fuel_type,
                $insurance_expiry, $license_expiry, $status, $vehicle_id
            );
            
            if ($stmt->execute()) {
                // Log activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                           VALUES (?, 'UPDATE', 'vehicles', ?, 'Vehicle details updated')";
                $stmt_log = $conn->prepare($log_sql);
                $stmt_log->bind_param("ii", $user_id, $vehicle_id);
                $stmt_log->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':
            $driver_id = intval($_POST['driver_id']);
            $assigned_date = $_POST['assigned_date'];
            
            // Check if vehicle is already assigned
            $check_sql = "SELECT assignment_id FROM vehicle_assignments 
                         WHERE vehicle_id = ? AND is_active = 1";
            $stmt_check = $conn->prepare($check_sql);
            $stmt_check->bind_param("i", $vehicle_id);
            $stmt_check->execute();
            $existing = $stmt_check->get_result()->fetch_assoc();
            
            if ($existing) {
                // Unassign current driver
                $unassign_sql = "UPDATE vehicle_assignments SET is_active = 0, unassigned_date = NOW() 
                                WHERE assignment_id = ?";
                $stmt_unassign = $conn->prepare($unassign_sql);
                $stmt_unassign->bind_param("i", $existing['assignment_id']);
                $stmt_unassign->execute();
            }
            
            // Assign new driver
            $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;
            
        case 'add_maintenance':
            $maintenance_type = $_POST['maintenance_type'];
            $description = $_POST['description'];
            $cost = floatval($_POST['cost']);
            $maintenance_date = $_POST['maintenance_date'];
            $next_maintenance = $_POST['next_maintenance'];
            $performed_by = $_POST['performed_by'];
            
            // For now, we'll create the maintenance log table structure if it doesn't exist
            $maintenance_sql = "INSERT INTO vehicle_maintenance 
                               (vehicle_id, maintenance_type, description, cost, maintenance_date, 
                                next_maintenance_date, performed_by, created_by) 
                               VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt_maint = $conn->prepare($maintenance_sql);
            $stmt_maint->bind_param("issdsssi", 
                $vehicle_id, $maintenance_type, $description, $cost,
                $maintenance_date, $next_maintenance, $performed_by, $user_id
            );
            
            if ($stmt_maint->execute()) {
                echo json_encode(['success' => true, 'message' => 'Maintenance record added successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to add maintenance record']);
            }
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit();
}

// Fetch vehicle details
$sql_vehicle = "SELECT v.*, 
                       current_driver.first_name as driver_first_name,
                       current_driver.last_name as driver_last_name,
                       current_driver.phone as driver_phone,
                       current_driver.license_number as driver_license,
                       va.assigned_date as driver_assigned_date
                FROM vehicles v
                LEFT JOIN vehicle_assignments va ON v.vehicle_id = va.vehicle_id AND va.is_active = 1
                LEFT JOIN drivers current_driver ON va.driver_id = current_driver.driver_id
                WHERE v.vehicle_id = ?";

$stmt_vehicle = $conn->prepare($sql_vehicle);
$stmt_vehicle->bind_param("i", $vehicle_id);
$stmt_vehicle->execute();
$vehicle = $stmt_vehicle->get_result()->fetch_assoc();

if (!$vehicle) {
    header('Location: vehicles.php');
    exit();
}

// Get vehicle utilization stats
$sql_utilization = "SELECT 
                     COUNT(DISTINCT sr.run_id) as total_runs,
                     COUNT(DISTINCT DATE(sr.scheduled_departure)) as active_days,
                     SUM(sr.capacity_used_weight) as total_weight_carried,
                     AVG(sr.capacity_used_weight) as avg_weight_per_run,
                     SUM(CASE WHEN sr.status = 'COMPLETED' THEN 1 ELSE 0 END) as completed_runs,
                     SUM(CASE WHEN sr.status = 'CANCELLED' THEN 1 ELSE 0 END) as cancelled_runs
                    FROM scheduled_runs sr
                    WHERE sr.vehicle_id = ? 
                    AND sr.scheduled_departure >= DATE_SUB(NOW(), INTERVAL 30 DAY)";

$stmt_util = $conn->prepare($sql_utilization);
$stmt_util->bind_param("i", $vehicle_id);
$stmt_util->execute();
$utilization = $stmt_util->get_result()->fetch_assoc();

// Get recent trips
$sql_trips = "SELECT sr.*, r.route_name, r.distance_km,
                     ol.location_name as origin_location,
                     dl.location_name as destination_location,
                     d.first_name as driver_first_name,
                     d.last_name as driver_last_name
              FROM scheduled_runs sr
              LEFT JOIN routes r ON sr.route_id = r.route_id
              LEFT JOIN locations ol ON r.origin_location_id = ol.location_id
              LEFT JOIN locations dl ON r.destination_location_id = dl.location_id
              LEFT JOIN drivers d ON sr.driver_id = d.driver_id
              WHERE sr.vehicle_id = ?
              ORDER BY sr.scheduled_departure DESC
              LIMIT 10";

$stmt_trips = $conn->prepare($sql_trips);
$stmt_trips->bind_param("i", $vehicle_id);
$stmt_trips->execute();
$recent_trips = $stmt_trips->get_result();

// Get maintenance history
$sql_maintenance = "SELECT vm.*, u.full_name as created_by_name
                   FROM vehicle_maintenance vm
                   LEFT JOIN users u ON vm.created_by = u.user_id
                   WHERE vm.vehicle_id = ?
                   ORDER BY vm.maintenance_date DESC
                   LIMIT 10";

// Since maintenance table might not exist, we'll create sample data
$maintenance_records = [];

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

// Calculate vehicle condition score
$condition_score = 100;
if ($vehicle['license_expiry'] && strtotime($vehicle['license_expiry']) < strtotime('+30 days')) {
    $condition_score -= 20;
}
if ($vehicle['insurance_expiry'] && strtotime($vehicle['insurance_expiry']) < strtotime('+30 days')) {
    $condition_score -= 20;
}
if ($vehicle['status'] == 'MAINTENANCE') {
    $condition_score -= 30;
}

$condition_color = $condition_score >= 80 ? 'success' : ($condition_score >= 60 ? 'warning' : 'danger');

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Vehicle Details - ' . $vehicle['vehicle_number'])); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        .vehicle-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
        }
        
        .vehicle-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="50" cy="50" r="3" fill="rgba(255,255,255,0.1)"/></svg>') repeat;
            transform: rotate(45deg);
            animation: float 20s linear infinite;
        }
        
        @keyframes float {
            0% { transform: translateX(-100%) rotate(45deg); }
            100% { transform: translateX(100%) rotate(45deg); }
        }
        
        .vehicle-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            border: 1px solid #e5e7eb;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
        }
        
        .vehicle-card:hover {
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-left: 4px solid #667eea;
            transition: all 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .stat-value {
            font-size: 2.25rem;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #6b7280;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            font-weight: 500;
        }
        
        .vehicle-image {
            width: 120px;
            height: 80px;
            background: linear-gradient(45deg, #f3f4f6, #e5e7eb);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            color: #6b7280;
        }
        
        .condition-score {
            position: relative;
            width: 100px;
            height: 100px;
            margin: 0 auto;
        }
        
        .condition-circle {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            border: 8px solid #e5e7eb;
            position: relative;
            transform: rotate(-90deg);
        }
        
        .condition-progress {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            border: 8px solid transparent;
            border-top-color: var(--condition-color);
            clip-path: circle(50% at 50% 50%);
        }
        
        .condition-text {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(90deg);
            font-weight: 700;
            font-size: 1.1rem;
        }
        
        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 25px;
            font-weight: 600;
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-active { background: #d1fae5; color: #065f46; }
        .status-maintenance { background: #fef3c7; color: #92400e; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        
        .trip-card {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            transition: all 0.2s ease;
        }
        
        .trip-card:hover {
            border-color: #667eea;
            box-shadow: 0 2px 4px rgba(102, 126, 234, 0.1);
        }
        
        .driver-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 1.1rem;
        }
        
        .maintenance-item {
            border-left: 4px solid #10b981;
            background: #f0fdf4;
            border-radius: 0 8px 8px 0;
            padding: 1rem;
            margin-bottom: 0.75rem;
        }
        
        .maintenance-overdue {
            border-left-color: #ef4444;
            background: #fef2f2;
        }
        
        .action-btn {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            border: none;
            cursor: pointer;
        }
        
        .btn-primary { background: #667eea; color: white; }
        .btn-success { background: #10b981; color: white; }
        .btn-warning { background: #f59e0b; color: white; }
        .btn-danger { background: #ef4444; color: white; }
        .btn-secondary { background: #6b7280; color: white; }
        
        .action-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
            color: white;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .nav-pills .nav-link {
            border-radius: 25px;
            padding: 0.75rem 1.5rem;
            font-weight: 500;
            color: #6b7280;
            transition: all 0.3s ease;
        }
        
        .nav-pills .nav-link.active {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        
        .chart-container {
            position: relative;
            height: 300px;
            margin-bottom: 1rem;
        }
        
        @media (max-width: 768px) {
            .vehicle-header {
                padding: 1.5rem;
                text-align: center;
            }
            
            .stat-card {
                margin-bottom: 1rem;
                text-align: center;
            }
            
            .stat-value {
                font-size: 1.75rem;
            }
        }
    </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 Details
                                </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="vehicles.php">Vehicles</a></li>
                                        <li class="breadcrumb-item active"><?php echo $vehicle['vehicle_number']; ?></li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Vehicle Header -->
                    <div class="vehicle-header">
                        <div class="row align-items-center">
                            <div class="col-md-2 text-center">
                                <div class="vehicle-image">
                                    <i class="ri-truck-fill"></i>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h2 class="mb-1"><?php echo $vehicle['vehicle_number']; ?></h2>
                                <p class="mb-2 opacity-90">
                                    <?php echo $vehicle['year'] . ' ' . $vehicle['make'] . ' ' . $vehicle['model']; ?>
                                </p>
                                <div class="d-flex flex-wrap gap-2">
                                    <span class="badge bg-light text-dark">
                                        <i class="ri-car-line me-1"></i><?php echo ucfirst($vehicle['vehicle_type']); ?>
                                    </span>
                                    <span class="badge bg-light text-dark">
                                        <i class="ri-gas-station-line me-1"></i><?php echo ucfirst($vehicle['fuel_type']); ?>
                                    </span>
                                    <span class="badge bg-light text-dark">
                                        <i class="ri-weight-line me-1"></i><?php echo number_format($vehicle['capacity_weight'], 1); ?>kg
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-2 text-center">
                                <div class="condition-score">
                                    <div class="condition-circle">
                                        <div class="condition-progress" style="--condition-color: var(--bs-<?php echo $condition_color; ?>);"></div>
                                        <div class="condition-text text-<?php echo $condition_color; ?>">
                                            <?php echo $condition_score; ?>%
                                        </div>
                                    </div>
                                </div>
                                <small class="opacity-75 mt-2 d-block">Condition Score</small>
                            </div>
                            <div class="col-md-2 text-center">
                                <span class="status-badge status-<?php echo strtolower($vehicle['status']); ?>">
                                    <?php echo $vehicle['status']; ?>
                                </span>
                                <div class="mt-3">
                                    <button class="action-btn btn-warning btn-sm" onclick="editVehicle()">
                                        <i class="ri-edit-line"></i>Edit
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($utilization['total_runs'] ?? 0); ?></div>
                                <div class="stat-label">Total Runs (30 days)</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($utilization['completed_runs'] ?? 0); ?></div>
                                <div class="stat-label">Completed Runs</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($utilization['total_weight_carried'] ?? 0, 1); ?>kg</div>
                                <div class="stat-label">Total Weight Carried</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format(($utilization['avg_weight_per_run'] ?? 0), 1); ?>kg</div>
                                <div class="stat-label">Average Load per Run</div>
                            </div>
                        </div>
                    </div>

                    <!-- Navigation Tabs -->
                    <div class="row">
                        <div class="col-12">
                            <div class="vehicle-card">
                                <div class="card-body">
                                    <ul class="nav nav-pills mb-4" id="vehicleTabs" role="tablist">
                                        <li class="nav-item" role="presentation">
                                            <button class="nav-link active" id="overview-tab" data-bs-toggle="pill" 
                                                    data-bs-target="#overview" type="button" role="tab">
                                                <i class="ri-dashboard-line me-2"></i>Overview
                                            </button>
                                        </li>
                                        <li class="nav-item" role="presentation">
                                            <button class="nav-link" id="trips-tab" data-bs-toggle="pill" 
                                                    data-bs-target="#trips" type="button" role="tab">
                                                <i class="ri-route-line me-2"></i>Recent Trips
                                            </button>
                                        </li>
                                        <li class="nav-item" role="presentation">
                                            <button class="nav-link" id="maintenance-tab" data-bs-toggle="pill" 
                                                    data-bs-target="#maintenance" type="button" role="tab">
                                                <i class="ri-tools-line me-2"></i>Maintenance
                                            </button>
                                        </li>
                                        <li class="nav-item" role="presentation">
                                            <button class="nav-link" id="driver-tab" data-bs-toggle="pill" 
                                                    data-bs-target="#driver" type="button" role="tab">
                                                <i class="ri-user-line me-2"></i>Driver Assignment
                                            </button>
                                        </li>
                                    </ul>

                                    <div class="tab-content" id="vehicleTabsContent">
                                        
                                        <!-- Overview Tab -->
                                        <div class="tab-pane fade show active" id="overview" role="tabpanel">
                                            <div class="row">
                                                <div class="col-xl-8">
                                                    <div class="row">
                                                        <div class="col-md-6">
                                                            <h6 class="text-muted mb-3">Vehicle Information</h6>
                                                            <table class="table table-borderless">
                                                                <tr>
                                                                    <td class="text-muted">Vehicle Number:</td>
                                                                    <td class="fw-bold"><?php echo $vehicle['vehicle_number']; ?></td>
                                                                </tr>
                                                                <tr>
                                                                    <td class="text-muted">Type:</td>
                                                                    <td><?php echo ucfirst($vehicle['vehicle_type']); ?></td>
                                                                </tr>
                                                                <tr>
                                                                    <td class="text-muted">Make & Model:</td>
                                                                    <td><?php echo $vehicle['make'] . ' ' . $vehicle['model']; ?></td>
                                                                </tr>
                                                                <tr>
                                                                    <td class="text-muted">Year:</td>
                                                                    <td><?php echo $vehicle['year']; ?></td>
                                                                </tr>
                                                                <tr>
                                                                    <td class="text-muted">Fuel Type:</td>
                                                                    <td><?php echo ucfirst($vehicle['fuel_type']); ?></td>
                                                                </tr>
                                                            </table>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <h6 class="text-muted mb-3">Capacity & Documents</h6>
                                                            <table class="table table-borderless">
                                                                <tr>
                                                                    <td class="text-muted">Weight Capacity:</td>
                                                                    <td class="fw-bold"><?php echo number_format($vehicle['capacity_weight'], 1); ?> kg</td>
                                                                </tr>
                                                                <tr>
                                                                    <td class="text-muted">Volume Capacity:</td>
                                                                    <td><?php echo number_format($vehicle['capacity_volume'], 1); ?> m³</td>
                                                                </tr>
                                                                <tr>
                                                                    <td class="text-muted">License Expiry:</td>
                                                                    <td class="<?php echo (strtotime($vehicle['license_expiry']) < strtotime('+30 days')) ? 'text-danger fw-bold' : ''; ?>">
                                                                        <?php echo date('M j, Y', strtotime($vehicle['license_expiry'])); ?>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td class="text-muted">Insurance Expiry:</td>
                                                                    <td class="<?php echo (strtotime($vehicle['insurance_expiry']) < strtotime('+30 days')) ? 'text-danger fw-bold' : ''; ?>">
                                                                        <?php echo date('M j, Y', strtotime($vehicle['insurance_expiry'])); ?>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td class="text-muted">Status:</td>
                                                                    <td>
                                                                        <span class="status-badge status-<?php echo strtolower($vehicle['status']); ?>">
                                                                            <?php echo $vehicle['status']; ?>
                                                                        </span>
                                                                    </td>
                                                                </tr>
                                                            </table>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Utilization Chart -->
                                                    <div class="mt-4">
                                                        <h6 class="text-muted mb-3">Performance Analytics</h6>
                                                        <div class="chart-container">
                                                            <canvas id="utilizationChart"></canvas>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-xl-4">
                                                    <!-- Current Driver -->
                                                    <div class="border rounded p-3 mb-3">
                                                        <h6 class="text-muted mb-3">Current Driver</h6>
                                                        <?php if ($vehicle['driver_first_name']): ?>
                                                        <div class="d-flex align-items-center">
                                                            <div class="driver-avatar me-3">
                                                                <?php echo strtoupper(substr($vehicle['driver_first_name'], 0, 1) . substr($vehicle['driver_last_name'], 0, 1)); ?>
                                                            </div>
                                                            <div>
                                                                <div class="fw-bold"><?php echo $vehicle['driver_first_name'] . ' ' . $vehicle['driver_last_name']; ?></div>
                                                                <small class="text-muted"><?php echo $vehicle['driver_phone']; ?></small><br>
                                                                <small class="text-muted">License: <?php echo $vehicle['driver_license']; ?></small><br>
                                                                <small class="text-muted">Assigned: <?php echo date('M j, Y', strtotime($vehicle['driver_assigned_date'])); ?></small>
                                                            </div>
                                                        </div>
                                                        <button class="btn btn-sm btn-outline-warning mt-2" onclick="reassignDriver()">
                                                            <i class="ri-user-settings-line me-1"></i>Reassign Driver
                                                        </button>
                                                        <?php else: ?>
                                                        <div class="text-center py-3">
                                                            <i class="ri-user-add-line fs-2 text-muted"></i>
                                                            <p class="text-muted mt-2">No driver assigned</p>
                                                            <button class="btn btn-sm btn-primary" onclick="assignDriver()">
                                                                <i class="ri-user-add-line me-1"></i>Assign Driver
                                                            </button>
                                                        </div>
                                                        <?php endif; ?>
                                                    </div>
                                                    
                                                    <!-- Quick Actions -->
                                                    <div class="border rounded p-3 mb-3">
                                                        <h6 class="text-muted mb-3">Quick Actions</h6>
                                                        <div class="d-grid gap-2">
                                                            <button class="action-btn btn-primary" onclick="scheduleRun()">
                                                                <i class="ri-calendar-line"></i>Schedule Run
                                                            </button>
                                                            <button class="action-btn btn-success" onclick="addMaintenance()">
                                                                <i class="ri-tools-line"></i>Add Maintenance
                                                            </button>
                                                            <button class="action-btn btn-warning" onclick="editVehicle()">
                                                                <i class="ri-edit-line"></i>Edit Details
                                                            </button>
                                                            <button class="action-btn btn-secondary" onclick="generateReport()">
                                                                <i class="ri-file-text-line"></i>Generate Report
                                                            </button>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Alerts -->
                                                    <div class="border rounded p-3">
                                                        <h6 class="text-muted mb-3">Alerts & Notifications</h6>
                                                        <?php 
                                                        $alerts = [];
                                                        if (strtotime($vehicle['license_expiry']) < strtotime('+30 days')) {
                                                            $alerts[] = ['type' => 'danger', 'icon' => 'ri-error-warning-line', 'message' => 'License expires soon'];
                                                        }
                                                        if (strtotime($vehicle['insurance_expiry']) < strtotime('+30 days')) {
                                                            $alerts[] = ['type' => 'danger', 'icon' => 'ri-shield-line', 'message' => 'Insurance expires soon'];
                                                        }
                                                        if ($vehicle['status'] == 'MAINTENANCE') {
                                                            $alerts[] = ['type' => 'warning', 'icon' => 'ri-tools-line', 'message' => 'Vehicle under maintenance'];
                                                        }
                                                        if (empty($alerts)) {
                                                            $alerts[] = ['type' => 'success', 'icon' => 'ri-check-line', 'message' => 'All systems normal'];
                                                        }
                                                        ?>
                                                        <?php foreach ($alerts as $alert): ?>
                                                        <div class="alert alert-<?php echo $alert['type']; ?> py-2 mb-2">
                                                            <i class="<?php echo $alert['icon']; ?> me-2"></i><?php echo $alert['message']; ?>
                                                        </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Recent Trips Tab -->
                                        <div class="tab-pane fade" id="trips" role="tabpanel">
                                            <div class="row">
                                                <div class="col-12">
                                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                                        <h6 class="text-muted mb-0">Recent Trips</h6>
                                                        <button class="btn btn-sm btn-primary" onclick="scheduleRun()">
                                                            <i class="ri-add-line me-1"></i>Schedule New Run
                                                        </button>
                                                    </div>
                                                    
                                                    <?php if ($recent_trips->num_rows > 0): ?>
                                                    <?php while ($trip = $recent_trips->fetch_assoc()): ?>
                                                    <div class="trip-card">
                                                        <div class="row align-items-center">
                                                            <div class="col-md-3">
                                                                <div class="fw-bold"><?php echo $trip['route_name']; ?></div>
                                                                <small class="text-muted">
                                                                    <?php echo $trip['origin_location'] . ' → ' . $trip['destination_location']; ?>
                                                                </small>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <div class="text-muted">Departure</div>
                                                                <div class="fw-bold"><?php echo date('M j, H:i', strtotime($trip['scheduled_departure'])); ?></div>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <div class="text-muted">Driver</div>
                                                                <div class="fw-bold">
                                                                    <?php echo $trip['driver_first_name'] ? $trip['driver_first_name'] . ' ' . $trip['driver_last_name'] : 'Unassigned'; ?>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <div class="text-muted">Load</div>
                                                                <div class="fw-bold"><?php echo number_format($trip['capacity_used_weight'], 1); ?>kg</div>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <div class="text-muted">Status</div>
                                                                <span class="badge bg-<?php 
                                                                    echo match($trip['status']) {
                                                                        'COMPLETED' => 'success',
                                                                        'IN_PROGRESS' => 'primary',
                                                                        'SCHEDULED' => 'info',
                                                                        'CANCELLED' => 'danger',
                                                                        'DELAYED' => 'warning',
                                                                        default => 'secondary'
                                                                    }; 
                                                                ?>">
                                                                    <?php echo $trip['status']; ?>
                                                                </span>
                                                            </div>
                                                            <div class="col-md-1">
                                                                <button class="btn btn-sm btn-outline-primary" onclick="viewTrip(<?php echo $trip['run_id']; ?>)">
                                                                    <i class="ri-eye-line"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <?php endwhile; ?>
                                                    <?php else: ?>
                                                    <div class="text-center py-5">
                                                        <i class="ri-truck-line fs-1 text-muted"></i>
                                                        <p class="text-muted mt-3">No recent trips found</p>
                                                        <button class="btn btn-primary" onclick="scheduleRun()">
                                                            <i class="ri-add-line me-1"></i>Schedule First Run
                                                        </button>
                                                    </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Maintenance Tab -->
                                        <div class="tab-pane fade" id="maintenance" role="tabpanel">
                                            <div class="row">
                                                <div class="col-12">
                                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                                        <h6 class="text-muted mb-0">Maintenance History</h6>
                                                        <button class="btn btn-sm btn-success" onclick="addMaintenance()">
                                                            <i class="ri-add-line me-1"></i>Add Maintenance Record
                                                        </button>
                                                    </div>
                                                    
                                                    <!-- Sample Maintenance Records -->
                                                    <div class="maintenance-item">
                                                        <div class="row align-items-center">
                                                            <div class="col-md-3">
                                                                <div class="fw-bold">Oil Change</div>
                                                                <small class="text-muted">Routine Maintenance</small>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <div class="text-muted">Date</div>
                                                                <div class="fw-bold"><?php echo date('M j, Y', strtotime('-5 days')); ?></div>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <div class="text-muted">Cost</div>
                                                                <div class="fw-bold">KES 8,500</div>
                                                            </div>
                                                            <div class="col-md-3">
                                                                <div class="text-muted">Next Due</div>
                                                                <div class="fw-bold"><?php echo date('M j, Y', strtotime('+25 days')); ?></div>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <button class="btn btn-sm btn-outline-primary" onclick="viewMaintenance(1)">
                                                                    <i class="ri-eye-line"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="maintenance-item">
                                                        <div class="row align-items-center">
                                                            <div class="col-md-3">
                                                                <div class="fw-bold">Brake Inspection</div>
                                                                <small class="text-muted">Safety Check</small>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <div class="text-muted">Date</div>
                                                                <div class="fw-bold"><?php echo date('M j, Y', strtotime('-15 days')); ?></div>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <div class="text-muted">Cost</div>
                                                                <div class="fw-bold">KES 12,000</div>
                                                            </div>
                                                            <div class="col-md-3">
                                                                <div class="text-muted">Next Due</div>
                                                                <div class="fw-bold"><?php echo date('M j, Y', strtotime('+165 days')); ?></div>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <button class="btn btn-sm btn-outline-primary" onclick="viewMaintenance(2)">
                                                                    <i class="ri-eye-line"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="maintenance-item maintenance-overdue">
                                                        <div class="row align-items-center">
                                                            <div class="col-md-3">
                                                                <div class="fw-bold">Annual Inspection</div>
                                                                <small class="text-danger">Overdue</small>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <div class="text-muted">Last Done</div>
                                                                <div class="fw-bold"><?php echo date('M j, Y', strtotime('-395 days')); ?></div>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <div class="text-muted">Est. Cost</div>
                                                                <div class="fw-bold">KES 25,000</div>
                                                            </div>
                                                            <div class="col-md-3">
                                                                <div class="text-danger">Due Now</div>
                                                                <div class="fw-bold text-danger">Overdue by 30 days</div>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <button class="btn btn-sm btn-danger" onclick="scheduleMaintenanceUrgent(3)">
                                                                    <i class="ri-alarm-warning-line"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Maintenance Schedule Chart -->
                                                    <div class="mt-4">
                                                        <h6 class="text-muted mb-3">Upcoming Maintenance Schedule</h6>
                                                        <div class="chart-container" style="height: 200px;">
                                                            <canvas id="maintenanceChart"></canvas>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Driver Assignment Tab -->
                                        <div class="tab-pane fade" id="driver" role="tabpanel">
                                            <div class="row">
                                                <div class="col-xl-8">
                                                    <h6 class="text-muted mb-3">Driver Assignment History</h6>
                                                    
                                                    <!-- Current Assignment -->
                                                    <?php if ($vehicle['driver_first_name']): ?>
                                                    <div class="border rounded p-3 mb-3 bg-light">
                                                        <div class="row align-items-center">
                                                            <div class="col-md-2">
                                                                <div class="driver-avatar">
                                                                    <?php echo strtoupper(substr($vehicle['driver_first_name'], 0, 1) . substr($vehicle['driver_last_name'], 0, 1)); ?>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-4">
                                                                <div class="fw-bold"><?php echo $vehicle['driver_first_name'] . ' ' . $vehicle['driver_last_name']; ?></div>
                                                                <small class="text-muted">Current Driver</small>
                                                            </div>
                                                            <div class="col-md-3">
                                                                <div class="text-muted">Contact</div>
                                                                <div><?php echo $vehicle['driver_phone']; ?></div>
                                                            </div>
                                                            <div class="col-md-3">
                                                                <div class="text-muted">Assigned</div>
                                                                <div><?php echo date('M j, Y', strtotime($vehicle['driver_assigned_date'])); ?></div>
                                                            </div>
                                                        </div>
                                                        <div class="mt-2">
                                                            <button class="btn btn-sm btn-warning me-2" onclick="reassignDriver()">
                                                                <i class="ri-user-settings-line me-1"></i>Reassign
                                                            </button>
                                                            <button class="btn btn-sm btn-outline-danger" onclick="unassignDriver()">
                                                                <i class="ri-user-unfollow-line me-1"></i>Unassign
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <?php else: ?>
                                                    <div class="border rounded p-3 mb-3 text-center">
                                                        <i class="ri-user-add-line fs-2 text-muted"></i>
                                                        <p class="text-muted mt-2">No driver currently assigned to this vehicle</p>
                                                        <button class="btn btn-primary" onclick="assignDriver()">
                                                            <i class="ri-user-add-line me-1"></i>Assign Driver
                                                        </button>
                                                    </div>
                                                    <?php endif; ?>
                                                    
                                                    <!-- Assignment History -->
                                                    <h6 class="text-muted mb-3">Assignment History</h6>
                                                    <div class="border rounded p-3">
                                                        <div class="text-center py-3">
                                                            <i class="ri-history-line fs-2 text-muted"></i>
                                                            <p class="text-muted mt-2">Assignment history will appear here</p>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-xl-4">
                                                    <h6 class="text-muted mb-3">Available Drivers</h6>
                                                    <div class="border rounded p-3" style="max-height: 400px; overflow-y: auto;">
                                                        <?php while ($driver = $drivers_result->fetch_assoc()): ?>
                                                        <div class="border-bottom pb-2 mb-2">
                                                            <div class="d-flex align-items-center">
                                                                <div class="driver-avatar me-3" style="width: 40px; height: 40px; font-size: 0.9rem;">
                                                                    <?php echo strtoupper(substr($driver['first_name'], 0, 1) . substr($driver['last_name'], 0, 1)); ?>
                                                                </div>
                                                                <div class="flex-grow-1">
                                                                    <div class="fw-bold"><?php echo $driver['first_name'] . ' ' . $driver['last_name']; ?></div>
                                                                    <small class="text-muted"><?php echo $driver['driver_code']; ?></small><br>
                                                                    <small class="text-muted"><?php echo $driver['phone']; ?></small>
                                                                </div>
                                                                <button class="btn btn-sm btn-outline-primary" 
                                                                        onclick="assignSpecificDriver(<?php echo $driver['driver_id']; ?>)">
                                                                    <i class="ri-user-add-line"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                        <?php endwhile; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <!-- Edit Vehicle Modal -->
    <div class="modal fade" id="editVehicleModal" tabindex="-1" aria-labelledby="editVehicleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editVehicleModalLabel">
                        <i class="ri-edit-line me-2"></i>Edit Vehicle Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="editVehicleForm">
                    <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" 
                                       value="<?php echo $vehicle['vehicle_number']; ?>" required>
                            </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="TRUCK" <?php echo $vehicle['vehicle_type'] == 'TRUCK' ? 'selected' : ''; ?>>Truck</option>
                                    <option value="VAN" <?php echo $vehicle['vehicle_type'] == 'VAN' ? 'selected' : ''; ?>>Van</option>
                                    <option value="MOTORCYCLE" <?php echo $vehicle['vehicle_type'] == 'MOTORCYCLE' ? 'selected' : ''; ?>>Motorcycle</option>
                                    <option value="CAR" <?php echo $vehicle['vehicle_type'] == 'CAR' ? 'selected' : ''; ?>>Car</option>
                                    <option value="OTHER" <?php echo $vehicle['vehicle_type'] == 'OTHER' ? 'selected' : ''; ?>>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" 
                                       value="<?php echo $vehicle['make']; ?>">
                            </div>
                            
                            <div class="col-md-4">
                                <label for="model" class="form-label">Model</label>
                                <input type="text" class="form-control" id="model" name="model" 
                                       value="<?php echo $vehicle['model']; ?>">
                            </div>
                            
                            <div class="col-md-4">
                                <label for="year" class="form-label">Year</label>
                                <input type="number" class="form-control" id="year" name="year" 
                                       value="<?php echo $vehicle['year']; ?>" min="1900" max="<?php echo date('Y') + 1; ?>">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="capacity_weight" class="form-label">Weight Capacity (kg)</label>
                                <input type="number" class="form-control" id="capacity_weight" name="capacity_weight" 
                                       value="<?php echo $vehicle['capacity_weight']; ?>" step="0.1" min="0">
                            </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" 
                                       value="<?php echo $vehicle['capacity_volume']; ?>" step="0.1" min="0">
                            </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="PETROL" <?php echo $vehicle['fuel_type'] == 'PETROL' ? 'selected' : ''; ?>>Petrol</option>
                                    <option value="DIESEL" <?php echo $vehicle['fuel_type'] == 'DIESEL' ? 'selected' : ''; ?>>Diesel</option>
                                    <option value="ELECTRIC" <?php echo $vehicle['fuel_type'] == 'ELECTRIC' ? 'selected' : ''; ?>>Electric</option>
                                    <option value="HYBRID" <?php echo $vehicle['fuel_type'] == 'HYBRID' ? 'selected' : ''; ?>>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">
                                    <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>
                            </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" 
                                       value="<?php echo $vehicle['license_expiry']; ?>">
                            </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" 
                                       value="<?php echo $vehicle['insurance_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-primary">
                            <i class="ri-save-line me-1"></i>Save Changes
                        </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-add-line me-2"></i>Assign Driver
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="assignDriverForm">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="driver_select" class="form-label">Select Driver *</label>
                            <select class="form-select" id="driver_select" 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>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="ri-user-add-line me-1"></i>Assign Driver
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Maintenance Modal -->
    <div class="modal fade" id="addMaintenanceModal" tabindex="-1" aria-labelledby="addMaintenanceModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addMaintenanceModalLabel">
                        <i class="ri-tools-line me-2"></i>Add Maintenance Record
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="addMaintenanceForm">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="maintenance_type" class="form-label">Maintenance Type *</label>
                                <select class="form-select" id="maintenance_type" name="maintenance_type" required>
                                    <option value="">Select Type</option>
                                    <option value="ROUTINE">Routine Maintenance</option>
                                    <option value="REPAIR">Repair</option>
                                    <option value="INSPECTION">Inspection</option>
                                    <option value="EMERGENCY">Emergency Repair</option>
                                    <option value="UPGRADE">Upgrade</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="maintenance_date" class="form-label">Maintenance Date *</label>
                                <input type="date" class="form-control" id="maintenance_date" name="maintenance_date" 
                                       value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                            
                            <div class="col-12">
                                <label for="description" class="form-label">Description *</label>
                                <textarea class="form-control" id="description" name="description" rows="3" 
                                         placeholder="Describe the maintenance work performed..." required></textarea>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="cost" class="form-label">Cost (KES)</label>
                                <input type="number" class="form-control" id="cost" name="cost" 
                                       step="0.01" min="0" placeholder="0.00">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="performed_by" class="form-label">Performed By</label>
                                <input type="text" class="form-control" id="performed_by" name="performed_by" 
                                       placeholder="Mechanic/Service provider name">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="next_maintenance" class="form-label">Next Maintenance Due</label>
                                <input type="date" class="form-control" id="next_maintenance" name="next_maintenance">
                            </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-add-line me-1"></i>Add Record
                        </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>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
// Global vehicle ID for JavaScript functions
const vehicleId = <?php echo $vehicle_id; ?>;

$(document).ready(function() {
    // Initialize charts
    initializeUtilizationChart();
    initializeMaintenanceChart();
    
    // Form handlers
    $('#editVehicleForm').on('submit', handleEditVehicle);
    $('#assignDriverForm').on('submit', handleAssignDriver);
    $('#addMaintenanceForm').on('submit', handleAddMaintenance);
});

// Utilization Chart
function initializeUtilizationChart() {
    const ctx = document.getElementById('utilizationChart').getContext('2d');
    
    // Sample data - in real implementation, this would come from PHP
    const chartData = {
        labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        datasets: [{
            label: 'Trips Completed',
            data: [3, 2, 4, 2, 3, 1, 2],
            backgroundColor: 'rgba(102, 126, 234, 0.1)',
            borderColor: 'rgba(102, 126, 234, 1)',
            borderWidth: 2,
            fill: true,
            tension: 0.4
        }, {
            label: 'Weight Utilization (%)',
            data: [75, 60, 85, 70, 80, 45, 65],
            backgroundColor: 'rgba(16, 185, 129, 0.1)',
            borderColor: 'rgba(16, 185, 129, 1)',
            borderWidth: 2,
            fill: true,
            tension: 0.4,
            yAxisID: 'y1'
        }]
    };
    
    new Chart(ctx, {
        type: 'line',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                intersect: false,
                mode: 'index'
            },
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        padding: 20
                    }
                }
            },
            scales: {
                y: {
                    type: 'linear',
                    display: true,
                    position: 'left',
                    title: {
                        display: true,
                        text: 'Number of Trips'
                    }
                },
                y1: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: 'Utilization %'
                    },
                    grid: {
                        drawOnChartArea: false,
                    },
                    max: 100
                }
            }
        }
    });
}

// Maintenance Chart
function initializeMaintenanceChart() {
    const ctx = document.getElementById('maintenanceChart').getContext('2d');
    
    const chartData = {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        datasets: [{
            label: 'Maintenance Cost (KES)',
            data: [15000, 8500, 12000, 6500, 18000, 9200],
            backgroundColor: [
                'rgba(255, 99, 132, 0.8)',
                'rgba(54, 162, 235, 0.8)',
                'rgba(255, 205, 86, 0.8)',
                'rgba(75, 192, 192, 0.8)',
                'rgba(153, 102, 255, 0.8)',
                'rgba(255, 159, 64, 0.8)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 205, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    };
    
    new Chart(ctx, {
        type: 'bar',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Cost (KES)'
                    }
                }
            }
        }
    });
}

// Edit Vehicle Functions
function editVehicle() {
    $('#editVehicleModal').modal('show');
}

function handleEditVehicle(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('action', 'update_vehicle');
    
    Swal.fire({
        title: 'Updating Vehicle...',
        text: 'Please wait while we update the vehicle details.',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.ajax({
        url: 'vehicle_details.php?id=' + vehicleId,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    title: 'Success!',
                    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 updating the vehicle.',
                icon: 'error'
            });
        }
    });
}

// Driver Assignment Functions
function assignDriver() {
    $('#assignDriverModal').modal('show');
}

function reassignDriver() {
    $('#assignDriverModal').modal('show');
}

function unassignDriver() {
    Swal.fire({
        title: 'Unassign Driver',
        text: 'Are you sure you want to unassign the current driver from this vehicle?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Unassign',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            // Implement unassign functionality
            Swal.fire({
                title: 'Driver Unassigned',
                text: 'The driver has been successfully unassigned from this vehicle.',
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            }).then(() => {
                location.reload();
            });
        }
    });
}

function assignSpecificDriver(driverId) {
    $('#driver_select').val(driverId);
    $('#assignDriverModal').modal('show');
}

function handleAssignDriver(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: 'vehicle_details.php?id=' + vehicleId,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    title: 'Success!',
                    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'
            });
        }
    });
}

// Maintenance Functions
function addMaintenance() {
    $('#addMaintenanceModal').modal('show');
}

function handleAddMaintenance(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('action', 'add_maintenance');
    
    Swal.fire({
        title: 'Adding Maintenance Record...',
        text: 'Please wait while we add the maintenance record.',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.ajax({
        url: 'vehicle_details.php?id=' + vehicleId,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    title: 'Success!',
                    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 maintenance record.',
                icon: 'error'
            });
        }
    });
}

function viewMaintenance(maintenanceId) {
    Swal.fire({
        title: 'Maintenance Details',
        html: `
            <div class="text-start">
                <p><strong>Type:</strong> Oil Change</p>
                <p><strong>Date:</strong> ${new Date().toLocaleDateString()}</p>
                <p><strong>Cost:</strong> KES 8,500</p>
                <p><strong>Description:</strong> Regular engine oil change and filter replacement</p>
                <p><strong>Performed By:</strong> ABC Auto Services</p>
                <p><strong>Next Due:</strong> ${new Date(Date.now() + 30*24*60*60*1000).toLocaleDateString()}</p>
            </div>
        `,
        icon: 'info',
        confirmButtonText: 'Close'
    });
}

function scheduleMaintenanceUrgent(maintenanceId) {
    Swal.fire({
        title: 'Schedule Urgent Maintenance',
        html: `
            <div class="mb-3">
                <label class="form-label">Preferred Date:</label>
                <input type="date" class="form-control" id="urgentDate" value="${new Date().toISOString().split('T')[0]}">
            </div>
            <div class="mb-3">
                <label class="form-label">Service Provider:</label>
                <select class="form-select" id="serviceProvider">
                    <option value="">Select Provider</option>
                    <option value="ABC Auto Services">ABC Auto Services</option>
                    <option value="Quick Fix Garage">Quick Fix Garage</option>
                    <option value="Premium Motors">Premium Motors</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Priority:</label>
                <select class="form-select" id="priority">
                    <option value="HIGH">High</option>
                    <option value="URGENT" selected>Urgent</option>
                    <option value="CRITICAL">Critical</option>
                </select>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Schedule',
        preConfirm: () => {
            return {
                date: document.getElementById('urgentDate').value,
                provider: document.getElementById('serviceProvider').value,
                priority: document.getElementById('priority').value
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Maintenance Scheduled!',
                text: 'Urgent maintenance has been scheduled successfully.',
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            });
        }
    });
}

// Other Functions
function scheduleRun() {
    window.location.href = `schedule_run.php?vehicle_id=${vehicleId}`;
}

function viewTrip(runId) {
    window.open(`view_run.php?id=${runId}`, '_blank');
}

function generateReport() {
    Swal.fire({
        title: 'Generate Vehicle Report',
        html: `
            <div class="mb-3">
                <label class="form-label">Report Type:</label>
                <select class="form-select" id="reportType">
                    <option value="performance">Performance Report</option>
                    <option value="maintenance">Maintenance History</option>
                    <option value="utilization">Utilization Analysis</option>
                    <option value="cost">Cost Analysis</option>
                    <option value="complete">Complete Vehicle Report</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Date Range:</label>
                <div class="row">
                    <div class="col-6">
                        <input type="date" class="form-control" id="reportFromDate" value="${new Date(Date.now() - 30*24*60*60*1000).toISOString().split('T')[0]}">
                    </div>
                    <div class="col-6">
                        <input type="date" class="form-control" id="reportToDate" value="${new Date().toISOString().split('T')[0]}">
                    </div>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Format:</label>
                <select class="form-select" id="reportFormat">
                    <option value="pdf">PDF</option>
                    <option value="excel">Excel</option>
                    <option value="csv">CSV</option>
                </select>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Generate Report',
        preConfirm: () => {
            return {
                type: document.getElementById('reportType').value,
                fromDate: document.getElementById('reportFromDate').value,
                toDate: document.getElementById('reportToDate').value,
                format: document.getElementById('reportFormat').value
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { type, fromDate, toDate, format } = result.value;
            
            Swal.fire({
                title: 'Generating Report...',
                text: 'Please wait while we prepare your report.',
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                    setTimeout(() => {
                        Swal.close();
                        // Trigger download
                        const link = document.createElement('a');
                        link.href = `reports/vehicle_report.php?id=${vehicleId}&type=${type}&from=${fromDate}&to=${toDate}&format=${format}`;
                        link.download = `vehicle_${vehicleId}_${type}_report.${format}`;
                        link.click();
                        
                        Swal.fire({
                            title: 'Report Generated!',
                            text: 'Your report has been generated and downloaded.',
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false
                        });
                    }, 2000);
                }
            });
        }
    });
}

// Initialize tooltips and popovers
document.addEventListener('DOMContentLoaded', function () {
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});
</script>

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