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

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

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

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

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

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

// Handle AJAX requests
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'add_driver':
            $driver_code = trim($_POST['driver_code']);
            $first_name = trim($_POST['first_name']);
            $last_name = trim($_POST['last_name']);
            $email = trim($_POST['email']);
            $phone = trim($_POST['phone']);
            $license_number = trim($_POST['license_number']);
            $license_expiry = $_POST['license_expiry'];
            $address = trim($_POST['address']);
            $emergency_contact_name = trim($_POST['emergency_contact_name']);
            $emergency_contact_phone = trim($_POST['emergency_contact_phone']);
            $hire_date = $_POST['hire_date'];
            $status = $_POST['status'];
            
            // Check for duplicate driver code
            $check_sql = "SELECT driver_id FROM drivers WHERE driver_code = ?";
            $stmt_check = $conn->prepare($check_sql);
            $stmt_check->bind_param("s", $driver_code);
            $stmt_check->execute();
            
            if ($stmt_check->get_result()->num_rows > 0) {
                echo json_encode(['success' => false, 'message' => 'Driver code already exists']);
                break;
            }
            
            // Check for duplicate license number
            $check_license_sql = "SELECT driver_id FROM drivers WHERE license_number = ?";
            $stmt_check_license = $conn->prepare($check_license_sql);
            $stmt_check_license->bind_param("s", $license_number);
            $stmt_check_license->execute();
            
            if ($stmt_check_license->get_result()->num_rows > 0) {
                echo json_encode(['success' => false, 'message' => 'License number already exists']);
                break;
            }
            
            $insert_sql = "INSERT INTO drivers (driver_code, first_name, last_name, email, phone, 
                          license_number, license_expiry, address, emergency_contact_name, 
                          emergency_contact_phone, hire_date, status) 
                          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("ssssssssssss", $driver_code, $first_name, $last_name, $email, $phone,
                             $license_number, $license_expiry, $address, $emergency_contact_name,
                             $emergency_contact_phone, $hire_date, $status);
            
            if ($stmt->execute()) {
                $driver_id = $conn->insert_id;
                
                // Log activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                           VALUES (?, 'CREATE', 'drivers', ?, ?)";
                $stmt_log = $conn->prepare($log_sql);
                $details = json_encode(['driver_code' => $driver_code, 'name' => $first_name . ' ' . $last_name]);
                $stmt_log->bind_param("iss", $user_id, $driver_id, $details);
                $stmt_log->execute();
                
                echo json_encode(['success' => true, 'message' => 'Driver added successfully', 'driver_id' => $driver_id]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to add driver']);
            }
            break;
            
        case 'update_driver':
            $driver_id = intval($_POST['driver_id']);
            $driver_code = trim($_POST['driver_code']);
            $first_name = trim($_POST['first_name']);
            $last_name = trim($_POST['last_name']);
            $email = trim($_POST['email']);
            $phone = trim($_POST['phone']);
            $license_number = trim($_POST['license_number']);
            $license_expiry = $_POST['license_expiry'];
            $address = trim($_POST['address']);
            $emergency_contact_name = trim($_POST['emergency_contact_name']);
            $emergency_contact_phone = trim($_POST['emergency_contact_phone']);
            $hire_date = $_POST['hire_date'];
            $status = $_POST['status'];
            
            $update_sql = "UPDATE drivers SET driver_code = ?, first_name = ?, last_name = ?, 
                          email = ?, phone = ?, license_number = ?, license_expiry = ?, 
                          address = ?, emergency_contact_name = ?, emergency_contact_phone = ?, 
                          hire_date = ?, status = ?, updated_at = NOW() 
                          WHERE driver_id = ?";
            
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("ssssssssssssi", $driver_code, $first_name, $last_name, $email, $phone,
                             $license_number, $license_expiry, $address, $emergency_contact_name,
                             $emergency_contact_phone, $hire_date, $status, $driver_id);
            
            if ($stmt->execute()) {
                // Log activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                           VALUES (?, 'UPDATE', 'drivers', ?, ?)";
                $stmt_log = $conn->prepare($log_sql);
                $details = json_encode(['driver_code' => $driver_code, 'status' => $status]);
                $stmt_log->bind_param("iss", $user_id, $driver_id, $details);
                $stmt_log->execute();
                
                echo json_encode(['success' => true, 'message' => 'Driver updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update driver']);
            }
            break;
            
        case 'delete_driver':
            $driver_id = intval($_POST['driver_id']);
            
            // Check if driver is assigned to any active vehicles
            $check_sql = "SELECT COUNT(*) as count FROM vehicle_assignments 
                         WHERE driver_id = ? AND is_active = 1";
            $stmt_check = $conn->prepare($check_sql);
            $stmt_check->bind_param("i", $driver_id);
            $stmt_check->execute();
            $active_assignments = $stmt_check->get_result()->fetch_assoc()['count'];
            
            if ($active_assignments > 0) {
                echo json_encode(['success' => false, 'message' => 'Cannot delete driver with active vehicle assignments']);
                break;
            }
            
            $delete_sql = "DELETE FROM drivers WHERE driver_id = ?";
            $stmt = $conn->prepare($delete_sql);
            $stmt->bind_param("i", $driver_id);
            
            if ($stmt->execute()) {
                // Log activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, old_values) 
                           VALUES (?, 'DELETE', 'drivers', ?, 'driver_deleted')";
                $stmt_log = $conn->prepare($log_sql);
                $stmt_log->bind_param("ii", $user_id, $driver_id);
                $stmt_log->execute();
                
                echo json_encode(['success' => true, 'message' => 'Driver deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to delete driver']);
            }
            break;
            
        case 'get_driver':
            $driver_id = intval($_POST['driver_id']);
            
            $sql = "SELECT * FROM drivers WHERE driver_id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $driver_id);
            $stmt->execute();
            $driver = $stmt->get_result()->fetch_assoc();
            
            if ($driver) {
                echo json_encode(['success' => true, 'driver' => $driver]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Driver not found']);
            }
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit();
}

// Filter parameters
$status_filter = $_GET['status'] ?? '';
$license_filter = $_GET['license_status'] ?? '';
$search = $_GET['search'] ?? '';

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

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

if ($license_filter == 'expired') {
    $where_conditions[] = "d.license_expiry <= CURDATE()";
} elseif ($license_filter == 'expiring') {
    $where_conditions[] = "d.license_expiry > CURDATE() AND d.license_expiry <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)";
}

if ($search) {
    $where_conditions[] = "(d.driver_code LIKE ? OR d.first_name LIKE ? OR d.last_name LIKE ? OR d.phone LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $param_types .= 'ssss';
}

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

// Get drivers with vehicle assignment details
$sql_drivers = "
    SELECT 
        d.*,
        va.vehicle_id,
        v.vehicle_number,
        v.vehicle_type,
        va.assigned_date,
        COUNT(sr.run_id) as total_runs,
        COUNT(CASE WHEN sr.status IN ('SCHEDULED', 'IN_PROGRESS') THEN 1 END) as active_runs,
        CASE 
            WHEN d.license_expiry <= CURDATE() THEN 'EXPIRED'
            WHEN d.license_expiry <= DATE_ADD(CURDATE(), INTERVAL 30 DAY) THEN 'EXPIRING'
            ELSE 'VALID'
        END as license_status,
        DATEDIFF(d.license_expiry, CURDATE()) as days_to_expiry
    FROM drivers d
    LEFT JOIN vehicle_assignments va ON d.driver_id = va.driver_id AND va.is_active = 1
    LEFT JOIN vehicles v ON va.vehicle_id = v.vehicle_id
    LEFT JOIN scheduled_runs sr ON va.vehicle_id = sr.vehicle_id AND sr.driver_id = d.driver_id
    $where_clause
    GROUP BY d.driver_id, d.driver_code, d.first_name, d.last_name, d.email, d.phone,
             d.license_number, d.license_expiry, d.address, d.emergency_contact_name,
             d.emergency_contact_phone, d.hire_date, d.status, d.created_at, d.updated_at,
             va.vehicle_id, v.vehicle_number, v.vehicle_type, va.assigned_date
    ORDER BY d.first_name, d.last_name";

$stmt_drivers = $conn->prepare($sql_drivers);
if (!empty($params)) {
    $stmt_drivers->bind_param($param_types, ...$params);
}
$stmt_drivers->execute();
$drivers_result = $stmt_drivers->get_result();

// Get summary statistics
$sql_summary = "
    SELECT 
        COUNT(*) as total_drivers,
        COUNT(CASE WHEN d.status = 'ACTIVE' THEN 1 END) as active_drivers,
        COUNT(CASE WHEN d.status = 'SUSPENDED' THEN 1 END) as suspended_drivers,
        COUNT(CASE WHEN d.status = 'INACTIVE' THEN 1 END) as inactive_drivers,
        COUNT(CASE WHEN va.vehicle_id IS NOT NULL THEN 1 END) as assigned_drivers,
        COUNT(CASE WHEN d.license_expiry <= CURDATE() THEN 1 END) as expired_licenses,
        COUNT(CASE WHEN d.license_expiry > CURDATE() AND d.license_expiry <= DATE_ADD(CURDATE(), INTERVAL 30 DAY) THEN 1 END) as expiring_licenses
    FROM drivers d
    LEFT JOIN vehicle_assignments va ON d.driver_id = va.driver_id AND va.is_active = 1
    $where_clause";

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

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Driver Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .driver-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
        }
        
        .driver-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
        }
        
        .summary-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            transform: translate(30px, -30px);
        }
        
        .summary-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .summary-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .status-badge {
            padding: 0.35rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-active { background: #d1e7dd; color: #0a3622; }
        .status-suspended { background: #fff3cd; color: #664d03; }
        .status-inactive { background: #f8d7da; color: #58151c; }
        
        .license-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 8px;
            font-size: 0.7rem;
            font-weight: 600;
        }
        
        .license-valid { background: #d1e7dd; color: #0a3622; }
        .license-expiring { background: #fff3cd; color: #664d03; animation: pulse 2s infinite; }
        .license-expired { background: #f8d7da; color: #58151c; animation: pulse 2s infinite; }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.6; }
            100% { opacity: 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.2rem;
        }
        
        .vehicle-info {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 0.5rem;
            margin-top: 0.5rem;
        }
        
        .contact-info {
            display: flex;
            flex-direction: column;
            gap: 0.25rem;
        }
        
        .contact-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.875rem;
        }
        
        .action-btn {
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            font-size: 0.75rem;
            margin: 0.1rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-view { background: #e3f2fd; color: #1976d2; }
        .btn-edit { background: #fff3e0; color: #ef6c00; }
        .btn-assign { background: #e8f5e8; color: #2e7d32; }
        .btn-delete { background: #ffebee; color: #c62828; }
        
        .action-btn:hover {
            transform: scale(1.05);
        }
        
        .filter-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e9ecef;
        }
        
        .add-driver-btn {
            background: linear-gradient(45deg, #28a745, #20c997);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(40,167,69,0.3);
        }
        
        .add-driver-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(40,167,69,0.4);
            color: white;
        }
        
        .emergency-contact {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 0.5rem;
            margin-top: 0.5rem;
        }
        
        .performance-stats {
            display: flex;
            gap: 1rem;
            margin-top: 0.5rem;
        }
        
        .stat-item {
            text-align: center;
            flex: 1;
        }
        
        .stat-value {
            font-weight: 700;
            font-size: 1.1rem;
            color: #495057;
        }
        
        .stat-label {
            font-size: 0.75rem;
            color: #6c757d;
            text-transform: uppercase;
        }
        
        @media (max-width: 768px) {
            .summary-card {
                margin-bottom: 1rem;
            }
            
            .summary-value {
                font-size: 1.5rem;
            }
            
            .table-responsive {
                font-size: 0.875rem;
            }
            
            .performance-stats {
                flex-direction: column;
                gap: 0.5rem;
            }
        }
    </style>
</head>

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

                    <!-- Summary Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-2 col-md-4">
                            <div class="summary-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                <div class="summary-value"><?php echo number_format($summary['total_drivers']); ?></div>
                                <div class="summary-label">Total Drivers</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4">
                            <div class="summary-card" style="background: linear-gradient(135deg, #36d1dc 0%, #5b86e5 100%);">
                                <div class="summary-value"><?php echo number_format($summary['active_drivers']); ?></div>
                                <div class="summary-label">Active</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4">
                            <div class="summary-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                <div class="summary-value"><?php echo number_format($summary['assigned_drivers']); ?></div>
                                <div class="summary-label">Assigned</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4">
                            <div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                <div class="summary-value"><?php echo number_format($summary['suspended_drivers']); ?></div>
                                <div class="summary-label">Suspended</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4">
                            <div class="summary-card" style="background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);">
                                <div class="summary-value"><?php echo number_format($summary['expired_licenses']); ?></div>
                                <div class="summary-label">Expired Licenses</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4">
                            <div class="summary-card" style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);">
                                <div class="summary-value"><?php echo number_format($summary['expiring_licenses']); ?></div>
                                <div class="summary-label">Expiring Soon</div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions and Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="driver-card">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-6">
                                            <button class="btn add-driver-btn me-2" onclick="showAddDriverModal()">
                                                <i class="ri-user-add-line me-1"></i>Add Driver
                                            </button>
                                            <button class="btn btn-outline-success me-2" onclick="exportDrivers()">
                                                <i class="ri-download-line me-1"></i>Export
                                            </button>
                                            <button class="btn btn-outline-info me-2" onclick="driverPerformance()">
                                                <i class="ri-bar-chart-line me-1"></i>Performance
                                            </button>
                                            <button class="btn btn-outline-warning" onclick="licenseReminders()">
                                                <i class="ri-notification-line me-1"></i>License Alerts
                                            </button>
                                        </div>
                                        <div class="col-md-6 text-end">
                                            <button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#filterSection">
                                                <i class="ri-filter-3-line me-1"></i>Filters
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="collapse" id="filterSection">
                        <div class="filter-section">
                            <form method="GET" class="row g-3">
                                <div class="col-md-2">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" name="status" id="status">
                                        <option value="">All Status</option>
                                        <option value="ACTIVE" <?php echo $status_filter == 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                        <option value="SUSPENDED" <?php echo $status_filter == 'SUSPENDED' ? 'selected' : ''; ?>>Suspended</option>
                                        <option value="INACTIVE" <?php echo $status_filter == 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="license_status" class="form-label">License Status</label>
                                    <select class="form-select" name="license_status" id="license_status">
                                        <option value="">All Licenses</option>
                                        <option value="expired" <?php echo $license_filter == 'expired' ? 'selected' : ''; ?>>Expired</option>
                                        <option value="expiring" <?php echo $license_filter == 'expiring' ? 'selected' : ''; ?>>Expiring Soon</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="search" class="form-label">Search</label>
                                    <input type="text" class="form-control" name="search" id="search" 
                                           placeholder="Driver code, name, phone..." value="<?php echo htmlspecialchars($search); ?>">
                                </div>
                                
                                <div class="col-md-2">
                                    <label class="form-label">&nbsp;</label>
                                    <button type="submit" class="btn btn-primary d-block w-100">
                                        <i class="ri-search-line me-1"></i>Search
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Drivers Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="driver-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-steering-line me-2"></i>Driver List
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover" id="driversTable">
                                            <thead>
                                                <tr>
                                                    <th>Driver</th>
                                                    <th>Contact</th>
                                                    <th>License</th>
                                                    <th>Vehicle</th>
                                                    <th>Status</th>
                                                    <th>Performance</th>
                                                    <th>Emergency</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($driver = $drivers_result->fetch_assoc()): ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="driver-avatar me-3">
                                                                <?php echo strtoupper(substr($driver['first_name'], 0, 1) . substr($driver['last_name'], 0, 1)); ?>
                                                            </div>
                                                            <div>
                                                                <div class="fw-bold"><?php echo $driver['first_name'] . ' ' . $driver['last_name']; ?></div>
                                                                <small class="text-muted"><?php echo $driver['driver_code']; ?></small>
                                                                <?php if ($driver['hire_date']): ?>
                                                                <small class="d-block text-muted">
                                                                    Since: <?php echo date('M Y', strtotime($driver['hire_date'])); ?>
                                                                </small>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="contact-info">
                                                            <div class="contact-item">
                                                                <i class="ri-phone-line text-muted"></i>
                                                                <?php echo $driver['phone']; ?>
                                                            </div>
                                                            <?php if ($driver['email']): ?>
                                                            <div class="contact-item">
                                                                <i class="ri-mail-line text-muted"></i>
                                                                <?php echo $driver['email']; ?>
                                                            </div>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <div class="fw-bold"><?php echo $driver['license_number']; ?></div>
                                                            <span class="license-badge license-<?php echo strtolower($driver['license_status']); ?>">
                                                                <?php echo ucfirst(strtolower($driver['license_status'])); ?>
                                                            </span>
                                                            <small class="d-block text-muted">
                                                                Expires: <?php echo date('M j, Y', strtotime($driver['license_expiry'])); ?>
                                                                <?php if ($driver['days_to_expiry'] < 30 && $driver['days_to_expiry'] >= 0): ?>
                                                                <span class="text-warning">(<?php echo $driver['days_to_expiry']; ?> days)</span>
                                                                <?php elseif ($driver['days_to_expiry'] < 0): ?>
                                                                <span class="text-danger">(<?php echo abs($driver['days_to_expiry']); ?> days overdue)</span>
                                                                <?php endif; ?>
                                                            </small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <?php if ($driver['vehicle_number']): ?>
                                                        <div class="vehicle-info">
                                                            <div class="fw-bold"><?php echo $driver['vehicle_number']; ?></div>
                                                            <small class="text-muted">
                                                                <?php echo ucfirst(strtolower($driver['vehicle_type'])); ?>
                                                            </small>
                                                            <small class="d-block text-muted">
                                                                Since: <?php echo date('M j, Y', strtotime($driver['assigned_date'])); ?>
                                                            </small>
                                                        </div>
                                                        <?php else: ?>
                                                        <span class="text-muted">
                                                            <i class="ri-car-line"></i> Unassigned
                                                        </span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <span class="status-badge status-<?php echo strtolower($driver['status']); ?>">
                                                            <?php echo ucfirst(strtolower($driver['status'])); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="performance-stats">
                                                            <div class="stat-item">
                                                                <div class="stat-value"><?php echo $driver['total_runs']; ?></div>
                                                                <div class="stat-label">Total Runs</div>
                                                            </div>
                                                            <div class="stat-item">
                                                                <div class="stat-value"><?php echo $driver['active_runs']; ?></div>
                                                                <div class="stat-label">Active</div>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <?php if ($driver['emergency_contact_name']): ?>
                                                        <div class="emergency-contact">
                                                            <div class="fw-bold"><?php echo $driver['emergency_contact_name']; ?></div>
                                                            <small><?php echo $driver['emergency_contact_phone']; ?></small>
                                                        </div>
                                                        <?php else: ?>
                                                        <span class="text-muted">Not provided</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group" role="group">
                                                            <button class="action-btn btn-view" onclick="viewDriver(<?php echo $driver['driver_id']; ?>)" 
                                                                    title="View Profile">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-edit" onclick="editDriver(<?php echo $driver['driver_id']; ?>)" 
                                                                    title="Edit Driver">
                                                                <i class="ri-edit-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-assign" onclick="assignVehicle(<?php echo $driver['driver_id']; ?>)" 
                                                                    title="Assign Vehicle">
                                                                <i class="ri-car-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-delete" onclick="deleteDriver(<?php echo $driver['driver_id']; ?>)" 
                                                                    title="Delete Driver">
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <!-- Add/Edit Driver Modal -->
    <div class="modal fade" id="driverModal" tabindex="-1" aria-labelledby="driverModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="driverModalLabel">
                        <i class="ri-user-add-line me-2"></i>Add Driver
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="driverForm">
                    <input type="hidden" id="driver_id" name="driver_id">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="driver_code" class="form-label">Driver Code *</label>
                                <input type="text" class="form-control" id="driver_code" name="driver_code" 
                                       placeholder="DRV001" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="status" class="form-label">Status *</label>
                                <select class="form-select" id="driver_status" name="status" required>
                                    <option value="ACTIVE">Active</option>
                                    <option value="SUSPENDED">Suspended</option>
                                    <option value="INACTIVE">Inactive</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="first_name" class="form-label">First Name *</label>
                                <input type="text" class="form-control" id="first_name" name="first_name" 
                                       placeholder="John" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="last_name" class="form-label">Last Name *</label>
                                <input type="text" class="form-control" id="last_name" name="last_name" 
                                       placeholder="Doe" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="email" class="form-label">Email</label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       placeholder="john.doe@example.com">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="phone" class="form-label">Phone *</label>
                                <input type="tel" class="form-control" id="phone" name="phone" 
                                       placeholder="+254700000000" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="license_number" class="form-label">License Number *</label>
                                <input type="text" class="form-control" id="license_number" name="license_number" 
                                       placeholder="DL123456789" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="license_expiry" class="form-label">License Expiry *</label>
                                <input type="date" class="form-control" id="license_expiry" name="license_expiry" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="hire_date" class="form-label">Hire Date</label>
                                <input type="date" class="form-control" id="hire_date" name="hire_date" 
                                       value="<?php echo date('Y-m-d'); ?>">
                            </div>
                            
                            <div class="col-12">
                                <label for="address" class="form-label">Address</label>
                                <textarea class="form-control" id="address" name="address" rows="2" 
                                         placeholder="Full address..."></textarea>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="emergency_contact_name" class="form-label">Emergency Contact Name</label>
                                <input type="text" class="form-control" id="emergency_contact_name" name="emergency_contact_name" 
                                       placeholder="Jane Doe">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="emergency_contact_phone" class="form-label">Emergency Contact Phone</label>
                                <input type="tel" class="form-control" id="emergency_contact_phone" name="emergency_contact_phone" 
                                       placeholder="+254700000000">
                            </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-save-line me-1"></i>Save Driver
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

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

    // Driver Form Handler
    $('#driverForm').on('submit', function(e) {
        e.preventDefault();
        
        const isEdit = $('#driver_id').val() !== '';
        const action = isEdit ? 'update_driver' : 'add_driver';
        
        const formData = new FormData(this);
        formData.append('action', action);
        
        // Show loading
        Swal.fire({
            title: isEdit ? 'Updating Driver...' : 'Adding Driver...',
            text: 'Please wait while we process your request.',
            icon: 'info',
            allowOutsideClick: false,
            showConfirmButton: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        $.ajax({
            url: 'drivers.php',
            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 processing your request.',
                    icon: 'error'
                });
            }
        });
    });
});

// Global Functions
window.showAddDriverModal = function() {
    $('#driverModalLabel').html('<i class="ri-user-add-line me-2"></i>Add Driver');
    $('#driverForm')[0].reset();
    $('#driver_id').val('');
    $('#hire_date').val(new Date().toISOString().split('T')[0]);
    $('#driverModal').modal('show');
};

window.viewDriver = function(driverId) {
    window.open(`view_driver.php?id=${driverId}`, '_blank');
};

window.editDriver = function(driverId) {
    $.ajax({
        url: 'drivers.php',
        method: 'POST',
        data: {
            action: 'get_driver',
            driver_id: driverId
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                const driver = response.driver;
                
                $('#driverModalLabel').html('<i class="ri-edit-line me-2"></i>Edit Driver');
                $('#driver_id').val(driver.driver_id);
                $('#driver_code').val(driver.driver_code);
                $('#first_name').val(driver.first_name);
                $('#last_name').val(driver.last_name);
                $('#email').val(driver.email);
                $('#phone').val(driver.phone);
                $('#license_number').val(driver.license_number);
                $('#license_expiry').val(driver.license_expiry);
                $('#address').val(driver.address);
                $('#emergency_contact_name').val(driver.emergency_contact_name);
                $('#emergency_contact_phone').val(driver.emergency_contact_phone);
                $('#hire_date').val(driver.hire_date);
                $('#driver_status').val(driver.status);
                
                $('#driverModal').modal('show');
            } else {
                Swal.fire({
                    title: 'Error',
                    text: response.message,
                    icon: 'error'
                });
            }
        },
        error: function() {
            Swal.fire({
                title: 'Error',
                text: 'Failed to load driver details.',
                icon: 'error'
            });
        }
    });
};

window.assignVehicle = function(driverId) {
    Swal.fire({
        title: 'Assign Vehicle',
        html: `
            <div class="mb-3">
                <label class="form-label">Select Vehicle:</label>
                <select class="form-select" id="vehicleSelect">
                    <option value="">Loading vehicles...</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Assignment Date:</label>
                <input type="date" class="form-control" id="assignmentDate" value="${new Date().toISOString().split('T')[0]}">
            </div>
            <div class="mb-3">
                <label class="form-label">Notes:</label>
                <textarea class="form-control" id="assignmentNotes" rows="3" placeholder="Assignment notes..."></textarea>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Assign Vehicle',
        didOpen: () => {
            // Load available vehicles
            fetch('get_available_vehicles.php')
                .then(response => response.json())
                .then(vehicles => {
                    const select = document.getElementById('vehicleSelect');
                    select.innerHTML = '<option value="">Select Vehicle</option>';
                    vehicles.forEach(vehicle => {
                        select.innerHTML += `<option value="${vehicle.vehicle_id}">${vehicle.vehicle_number} (${vehicle.vehicle_type})</option>`;
                    });
                });
        },
        preConfirm: () => {
            const vehicleId = document.getElementById('vehicleSelect').value;
            const assignmentDate = document.getElementById('assignmentDate').value;
            const notes = document.getElementById('assignmentNotes').value;
            
            if (!vehicleId) {
                Swal.showValidationMessage('Please select a vehicle');
                return false;
            }
            
            return { vehicleId, assignmentDate, notes };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Success!',
                text: 'Vehicle has been assigned to the driver.',
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            }).then(() => {
                location.reload();
            });
        }
    });
};

window.deleteDriver = function(driverId) {
    Swal.fire({
        title: 'Delete Driver',
        text: 'Are you sure you want to delete this driver? This action cannot be undone.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Delete',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#d33'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'drivers.php',
                method: 'POST',
                data: {
                    action: 'delete_driver',
                    driver_id: driverId
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: 'Deleted!',
                            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: 'Failed to delete driver.',
                        icon: 'error'
                    });
                }
            });
        }
    });
};

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

window.driverPerformance = function() {
    window.location.href = 'driver_performance.php';
};

window.licenseReminders = function() {
    Swal.fire({
        title: 'License Expiry Alerts',
        html: `
            <div class="mb-3">
                <label class="form-label">Send Reminders To:</label>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="expiredLicenses" checked>
                    <label class="form-check-label" for="expiredLicenses">Drivers with Expired Licenses</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="expiringLicenses" checked>
                    <label class="form-check-label" for="expiringLicenses">Licenses Expiring in 30 Days</label>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Reminder Method:</label>
                <select class="form-select" id="reminderMethod">
                    <option value="email">Email</option>
                    <option value="sms">SMS</option>
                    <option value="both">Both Email & SMS</option>
                </select>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Send Reminders',
        preConfirm: () => {
            return {
                expired: document.getElementById('expiredLicenses').checked,
                expiring: document.getElementById('expiringLicenses').checked,
                method: document.getElementById('reminderMethod').value
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Sending Reminders...',
                text: 'Please wait while we send license expiry reminders.',
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                    setTimeout(() => {
                        Swal.fire({
                            title: 'Reminders Sent!',
                            text: 'License expiry reminders have been sent to drivers.',
                            icon: 'success',
                            timer: 3000,
                            showConfirmButton: false
                        });
                    }, 3000);
                }
            });
        }
    });
};
</script>

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