<?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();
}

// Filter parameters
$period_filter = $_GET['period'] ?? '30';
$driver_filter = $_GET['driver'] ?? '';
$status_filter = $_GET['status'] ?? '';
$vehicle_filter = $_GET['vehicle'] ?? '';

// Calculate date range based on period
$date_from = date('Y-m-d', strtotime("-$period_filter days"));
$date_to = date('Y-m-d');

// Build WHERE clause for filters
$where_conditions = ["sr.created_at >= '$date_from'", "sr.created_at <= '$date_to 23:59:59'"];
$params = [];
$param_types = '';

if ($driver_filter) {
    $where_conditions[] = "d.driver_id = ?";
    $params[] = intval($driver_filter);
    $param_types .= 'i';
}

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

if ($vehicle_filter) {
    $where_conditions[] = "v.vehicle_id = ?";
    $params[] = intval($vehicle_filter);
    $param_types .= 'i';
}

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

// Get comprehensive driver performance data
$sql_driver_performance = "
    SELECT 
        d.driver_id,
        d.driver_code,
        d.first_name,
        d.last_name,
        d.phone,
        d.email,
        d.status,
        d.hire_date,
        d.license_number,
        d.license_expiry,
        v.vehicle_number,
        v.vehicle_type,
        va.assigned_date,
        
        -- Performance Metrics
        COUNT(DISTINCT sr.run_id) as total_runs,
        COUNT(DISTINCT CASE WHEN sr.status = 'COMPLETED' THEN sr.run_id END) as completed_runs,
        COUNT(DISTINCT CASE WHEN sr.status = 'CANCELLED' THEN sr.run_id END) as cancelled_runs,
        COUNT(DISTINCT CASE WHEN sr.status = 'DELAYED' THEN sr.run_id END) as delayed_runs,
        
        -- Time Performance
        AVG(CASE 
            WHEN sr.status = 'COMPLETED' AND sr.scheduled_departure IS NOT NULL AND sr.actual_departure IS NOT NULL 
            THEN TIMESTAMPDIFF(MINUTE, sr.scheduled_departure, sr.actual_departure) 
        END) as avg_departure_delay_minutes,
        
        AVG(CASE 
            WHEN sr.status = 'COMPLETED' AND sr.scheduled_arrival IS NOT NULL AND sr.actual_arrival IS NOT NULL 
            THEN TIMESTAMPDIFF(MINUTE, sr.scheduled_arrival, sr.actual_arrival) 
        END) as avg_arrival_delay_minutes,
        
        AVG(CASE 
            WHEN sr.status = 'COMPLETED' AND sr.actual_departure IS NOT NULL AND sr.actual_arrival IS NOT NULL 
            THEN TIMESTAMPDIFF(HOUR, sr.actual_departure, sr.actual_arrival) 
        END) as avg_trip_duration_hours,
        
        -- Cargo Performance
        SUM(CASE WHEN sr.status = 'COMPLETED' THEN sr.capacity_used_weight ELSE 0 END) as total_weight_transported,
        AVG(CASE WHEN sr.status = 'COMPLETED' THEN sr.capacity_used_weight ELSE 0 END) as avg_weight_per_run,
        SUM(CASE WHEN sr.status = 'COMPLETED' THEN sr.capacity_used_pieces ELSE 0 END) as total_pieces_transported,
        
        -- Route Performance
        COUNT(DISTINCT r.route_id) as unique_routes_covered,
        SUM(CASE WHEN sr.status = 'COMPLETED' THEN r.distance_km ELSE 0 END) as total_distance_covered,
        
        -- Calculated Performance Indicators
        CASE 
            WHEN COUNT(DISTINCT sr.run_id) > 0 
            THEN (COUNT(DISTINCT CASE WHEN sr.status = 'COMPLETED' THEN sr.run_id END) / COUNT(DISTINCT sr.run_id)) * 100 
            ELSE 0 
        END as completion_rate,
        
        CASE 
            WHEN COUNT(DISTINCT sr.run_id) > 0 
            THEN (COUNT(DISTINCT CASE WHEN sr.status = 'CANCELLED' THEN sr.run_id END) / COUNT(DISTINCT sr.run_id)) * 100 
            ELSE 0 
        END as cancellation_rate,
        
        -- Safety & Efficiency Score (calculated from multiple factors)
        CASE 
            WHEN COUNT(DISTINCT sr.run_id) > 0 THEN
                GREATEST(0, LEAST(100, 
                    (COUNT(DISTINCT CASE WHEN sr.status = 'COMPLETED' THEN sr.run_id END) / COUNT(DISTINCT sr.run_id)) * 40 +  -- 40% completion rate
                    GREATEST(0, (100 - COALESCE(AVG(CASE 
                        WHEN sr.status = 'COMPLETED' AND sr.scheduled_departure IS NOT NULL AND sr.actual_departure IS NOT NULL 
                        THEN ABS(TIMESTAMPDIFF(MINUTE, sr.scheduled_departure, sr.actual_departure)) 
                    END), 0) / 10)) * 30 +  -- 30% punctuality
                    LEAST(100, COALESCE(AVG(CASE WHEN sr.status = 'COMPLETED' THEN sr.capacity_used_weight ELSE 0 END), 0) / 1000 * 30) * 30  -- 30% efficiency
                ))
            ELSE 0 
        END as performance_score
        
    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 d.driver_id = sr.driver_id
    LEFT JOIN routes r ON sr.route_id = r.route_id
    $where_clause
    GROUP BY d.driver_id, d.driver_code, d.first_name, d.last_name, d.phone, d.email, 
             d.status, d.hire_date, d.license_number, d.license_expiry,
             v.vehicle_number, v.vehicle_type, va.assigned_date
    HAVING total_runs > 0 OR d.status = 'ACTIVE'
    ORDER BY performance_score DESC, completion_rate DESC";

$stmt_performance = $conn->prepare($sql_driver_performance);
if (!empty($params)) {
    $stmt_performance->bind_param($param_types, ...$params);
}
$stmt_performance->execute();
$performance_result = $stmt_performance->get_result();

// Get summary statistics
$sql_summary = "
    SELECT 
        COUNT(DISTINCT d.driver_id) as total_drivers,
        COUNT(DISTINCT CASE WHEN d.status = 'ACTIVE' THEN d.driver_id END) as active_drivers,
        COUNT(DISTINCT CASE WHEN sr.status = 'COMPLETED' THEN sr.run_id END) as total_completed_runs,
        AVG(CASE 
            WHEN sr.status = 'COMPLETED' AND sr.scheduled_departure IS NOT NULL AND sr.actual_departure IS NOT NULL 
            THEN TIMESTAMPDIFF(MINUTE, sr.scheduled_departure, sr.actual_departure) 
        END) as avg_departure_delay,
        SUM(CASE WHEN sr.status = 'COMPLETED' THEN sr.capacity_used_weight ELSE 0 END) as total_cargo_moved,
        COUNT(DISTINCT CASE WHEN d.license_expiry <= DATE_ADD(CURDATE(), INTERVAL 30 DAY) THEN d.driver_id END) as licenses_expiring
    FROM drivers d
    LEFT JOIN scheduled_runs sr ON d.driver_id = sr.driver_id
    $where_clause";

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

// Get drivers list for filter dropdown
$sql_drivers = "SELECT driver_id, driver_code, first_name, last_name, status 
                FROM drivers ORDER BY first_name, last_name";
$drivers_result = $conn->query($sql_drivers);

// Get vehicles list for filter dropdown
$sql_vehicles = "SELECT vehicle_id, vehicle_number, vehicle_type 
                 FROM vehicles ORDER BY vehicle_number";
$vehicles_result = $conn->query($sql_vehicles);

// Get top performers for the period
$sql_top_performers = "
    SELECT 
        d.driver_code,
        d.first_name,
        d.last_name,
        COUNT(DISTINCT CASE WHEN sr.status = 'COMPLETED' THEN sr.run_id END) as completed_runs,
        (COUNT(DISTINCT CASE WHEN sr.status = 'COMPLETED' THEN sr.run_id END) / COUNT(DISTINCT sr.run_id)) * 100 as success_rate,
        SUM(CASE WHEN sr.status = 'COMPLETED' THEN sr.capacity_used_weight ELSE 0 END) as total_weight
    FROM drivers d
    LEFT JOIN scheduled_runs sr ON d.driver_id = sr.driver_id
    $where_clause
    GROUP BY d.driver_id, d.driver_code, d.first_name, d.last_name
    HAVING completed_runs > 0
    ORDER BY success_rate DESC, completed_runs DESC
    LIMIT 5";

$stmt_top = $conn->prepare($sql_top_performers);
if (!empty($params)) {
    $stmt_top->bind_param($param_types, ...$params);
}
$stmt_top->execute();
$top_performers_result = $stmt_top->get_result();

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Driver Performance Dashboard')); ?>
    <?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">
    
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        .performance-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;
        }
        
        .performance-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
            margin-bottom: 1.5rem;
        }
        
        .summary-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            transform: translate(30px, -30px);
        }
        
        .summary-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .summary-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .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: 1rem;
        }
        
        .performance-score {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 0.875rem;
            color: white;
        }
        
        .score-excellent { background: linear-gradient(45deg, #28a745, #20c997); }
        .score-good { background: linear-gradient(45deg, #20c997, #17a2b8); }
        .score-average { background: linear-gradient(45deg, #ffc107, #fd7e14); }
        .score-poor { background: linear-gradient(45deg, #fd7e14, #dc3545); }
        
        .metric-indicator {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 0.75rem;
            margin: 0.5rem 0;
        }
        
        .metric-value {
            font-size: 1.25rem;
            font-weight: 700;
            color: #2c3e50;
        }
        
        .metric-label {
            font-size: 0.75rem;
            color: #6c757d;
            text-transform: uppercase;
        }
        
        .performance-bar {
            height: 6px;
            background: #e9ecef;
            border-radius: 3px;
            overflow: hidden;
            margin-top: 0.5rem;
        }
        
        .performance-fill {
            height: 100%;
            transition: width 0.3s ease;
        }
        
        .fill-excellent { background: linear-gradient(90deg, #28a745, #20c997); }
        .fill-good { background: linear-gradient(90deg, #20c997, #17a2b8); }
        .fill-average { background: linear-gradient(90deg, #ffc107, #fd7e14); }
        .fill-poor { background: linear-gradient(90deg, #fd7e14, #dc3545); }
        
        .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-inactive { background: #f8d7da; color: #58151c; }
        .status-suspended { background: #fff3cd; color: #664d03; }
        
        .license-warning {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 6px;
            padding: 0.5rem;
            margin-top: 0.5rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .license-expired {
            background: #f8d7da;
            border-color: #f5c6cb;
        }
        
        .filter-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e9ecef;
        }
        
        .top-performer {
            background: linear-gradient(45deg, #ffd700, #ffed4e);
            color: #664d03;
            border-radius: 8px;
            padding: 1rem;
            margin: 0.5rem 0;
        }
        
        .chart-container {
            position: relative;
            height: 300px;
            margin: 1rem 0;
        }
        
        @media (max-width: 768px) {
            .summary-card {
                margin-bottom: 1rem;
            }
            
            .summary-value {
                font-size: 1.5rem;
            }
            
            .table-responsive {
                font-size: 0.875rem;
            }
            
            .driver-avatar {
                width: 40px;
                height: 40px;
                font-size: 0.875rem;
            }
            
            .performance-score {
                width: 50px;
                height: 50px;
                font-size: 0.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-user-star-line me-2"></i>Driver Performance Dashboard</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"><a href="drivers.php">Drivers</a></li>
                                        <li class="breadcrumb-item active">Performance</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                <div class="summary-value"><?php echo number_format($summary['total_drivers']); ?></div>
                                <div class="summary-label">Total Drivers</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                <div class="summary-value"><?php echo number_format($summary['active_drivers']); ?></div>
                                <div class="summary-label">Active Drivers</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                <div class="summary-value"><?php echo number_format($summary['total_completed_runs']); ?></div>
                                <div class="summary-label">Completed Runs (<?php echo $period_filter; ?>d)</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                                <div class="summary-value"><?php echo number_format($summary['total_cargo_moved'] / 1000, 1); ?>T</div>
                                <div class="summary-label">Cargo Transported</div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="row">
                        <div class="col-12">
                            <div class="performance-card">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-8">
                                            <form method="GET" class="row g-3">
                                                <div class="col-md-2">
                                                    <label for="period" class="form-label">Period</label>
                                                    <select class="form-select" name="period" id="period">
                                                        <option value="7" <?php echo $period_filter == '7' ? 'selected' : ''; ?>>Last 7 days</option>
                                                        <option value="30" <?php echo $period_filter == '30' ? 'selected' : ''; ?>>Last 30 days</option>
                                                        <option value="90" <?php echo $period_filter == '90' ? 'selected' : ''; ?>>Last 90 days</option>
                                                        <option value="365" <?php echo $period_filter == '365' ? 'selected' : ''; ?>>Last year</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-3">
                                                    <label for="driver" class="form-label">Driver</label>
                                                    <select class="form-select" name="driver" id="driver">
                                                        <option value="">All Drivers</option>
                                                        <?php 
                                                        $drivers_result->data_seek(0);
                                                        while ($driver = $drivers_result->fetch_assoc()): 
                                                        ?>
                                                        <option value="<?php echo $driver['driver_id']; ?>" <?php echo $driver_filter == $driver['driver_id'] ? 'selected' : ''; ?>>
                                                            <?php echo $driver['first_name'] . ' ' . $driver['last_name'] . ' (' . $driver['driver_code'] . ')'; ?>
                                                        </option>
                                                        <?php endwhile; ?>
                                                    </select>
                                                </div>
                                                
                                                <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="INACTIVE" <?php echo $status_filter == 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                                        <option value="SUSPENDED" <?php echo $status_filter == 'SUSPENDED' ? 'selected' : ''; ?>>Suspended</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-3">
                                                    <label for="vehicle" class="form-label">Vehicle</label>
                                                    <select class="form-select" name="vehicle" id="vehicle">
                                                        <option value="">All Vehicles</option>
                                                        <?php 
                                                        $vehicles_result->data_seek(0);
                                                        while ($vehicle = $vehicles_result->fetch_assoc()): 
                                                        ?>
                                                        <option value="<?php echo $vehicle['vehicle_id']; ?>" <?php echo $vehicle_filter == $vehicle['vehicle_id'] ? 'selected' : ''; ?>>
                                                            <?php echo $vehicle['vehicle_number'] . ' (' . $vehicle['vehicle_type'] . ')'; ?>
                                                        </option>
                                                        <?php endwhile; ?>
                                                    </select>
                                                </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>Filter
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                        <div class="col-md-4 text-end">
                                            <button class="btn btn-outline-success me-2" onclick="exportPerformance()">
                                                <i class="ri-download-line me-1"></i>Export Report
                                            </button>
                                            <button class="btn btn-outline-info" onclick="performanceAnalytics()">
                                                <i class="ri-bar-chart-line me-1"></i>Analytics
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Top Performers and Charts -->
                    <div class="row">
                        <div class="col-xl-8">
                            <div class="performance-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-user-star-line me-2"></i>Driver Performance Overview
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover" id="performanceTable">
                                            <thead>
                                                <tr>
                                                    <th>Driver</th>
                                                    <th>Vehicle</th>
                                                    <th>Performance Score</th>
                                                    <th>Runs</th>
                                                    <th>Success Rate</th>
                                                    <th>Cargo Moved</th>
                                                    <th>Avg Delay</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($driver = $performance_result->fetch_assoc()): ?>
                                                <?php
                                                    $score = floatval($driver['performance_score']);
                                                    $score_class = 'score-excellent';
                                                    if ($score < 80) $score_class = 'score-good';
                                                    if ($score < 60) $score_class = 'score-average';
                                                    if ($score < 40) $score_class = 'score-poor';
                                                    
                                                    $license_warning = $driver['license_expiry'] && 
                                                        strtotime($driver['license_expiry']) <= strtotime('+30 days');
                                                    $license_expired = $driver['license_expiry'] && 
                                                        strtotime($driver['license_expiry']) <= time();
                                                ?>
                                                <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 ($license_warning || $license_expired): ?>
                                                                <div class="license-warning <?php echo $license_expired ? 'license-expired' : ''; ?>">
                                                                    <i class="ri-alert-line"></i>
                                                                    <span>License <?php echo $license_expired ? 'Expired' : 'Expiring Soon'; ?></span>
                                                                </div>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <?php if ($driver['vehicle_number']): ?>
                                                        <div>
                                                            <strong><?php echo $driver['vehicle_number']; ?></strong>
                                                            <div class="text-muted small"><?php echo $driver['vehicle_type']; ?></div>
                                                            <small class="text-muted">Since: <?php echo date('M j, Y', strtotime($driver['assigned_date'])); ?></small>
                                                        </div>
                                                        <?php else: ?>
                                                        <span class="text-muted">No Vehicle</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="performance-score <?php echo $score_class; ?>">
                                                            <?php echo number_format($score, 0); ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="metric-indicator">
                                                            <div class="metric-value"><?php echo $driver['total_runs']; ?></div>
                                                            <div class="metric-label">Total</div>
                                                            <div class="performance-bar">
                                                                <div class="performance-fill fill-excellent" style="width: <?php echo min(100, ($driver['completed_runs'] / max(1, $driver['total_runs'])) * 100); ?>%"></div>
                                                            </div>
                                                            <small class="text-muted"><?php echo $driver['completed_runs']; ?> completed</small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="metric-indicator">
                                                            <div class="metric-value"><?php echo number_format($driver['completion_rate'], 1); ?>%</div>
                                                            <div class="metric-label">Success Rate</div>
                                                            <div class="performance-bar">
                                                                <?php 
                                                                $rate = floatval($driver['completion_rate']);
                                                                $fill_class = 'fill-excellent';
                                                                if ($rate < 90) $fill_class = 'fill-good';
                                                                if ($rate < 75) $fill_class = 'fill-average';
                                                                if ($rate < 60) $fill_class = 'fill-poor';
                                                                ?>
                                                                <div class="performance-fill <?php echo $fill_class; ?>" style="width: <?php echo $rate; ?>%"></div>
                                                            </div>
                                                            <?php if ($driver['cancelled_runs'] > 0): ?>
                                                            <small class="text-danger"><?php echo $driver['cancelled_runs']; ?> cancelled</small>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="metric-indicator">
                                                            <div class="metric-value"><?php echo number_format($driver['total_weight_transported'] / 1000, 1); ?>T</div>
                                                            <div class="metric-label">Total Weight</div>
                                                            <small class="text-muted">
                                                                Avg: <?php echo number_format($driver['avg_weight_per_run'], 0); ?>kg/run
                                                            </small>
                                                            <?php if ($driver['total_pieces_transported'] > 0): ?>
                                                            <div class="mt-1">
                                                                <small class="text-muted"><?php echo number_format($driver['total_pieces_transported']); ?> pieces</small>
                                                            </div>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        $avg_delay = floatval($driver['avg_departure_delay_minutes']);
                                                        $delay_class = 'text-success';
                                                        if ($avg_delay > 15) $delay_class = 'text-warning';
                                                        if ($avg_delay > 30) $delay_class = 'text-danger';
                                                        ?>
                                                        <div class="metric-indicator">
                                                            <div class="metric-value <?php echo $delay_class; ?>">
                                                                <?php echo $avg_delay > 0 ? '+' : ''; ?><?php echo number_format($avg_delay, 0); ?>m
                                                            </div>
                                                            <div class="metric-label">Departure</div>
                                                            <?php if ($driver['avg_arrival_delay_minutes']): ?>
                                                            <small class="text-muted">
                                                                Arrival: <?php echo number_format($driver['avg_arrival_delay_minutes'], 0); ?>m
                                                            </small>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="status-badge status-<?php echo strtolower($driver['status']); ?>">
                                                            <?php echo $driver['status']; ?>
                                                        </span>
                                                        <?php if ($driver['total_distance_covered'] > 0): ?>
                                                        <div class="mt-1">
                                                            <small class="text-muted">
                                                                <?php echo number_format($driver['total_distance_covered'], 0); ?>km covered
                                                            </small>
                                                        </div>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-4">
                            <div class="performance-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-trophy-line me-2"></i>Top Performers (<?php echo $period_filter; ?> days)
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <?php if ($top_performers_result->num_rows > 0): ?>
                                    <?php $rank = 1; ?>
                                    <?php while ($performer = $top_performers_result->fetch_assoc()): ?>
                                    <div class="top-performer <?php echo $rank == 1 ? 'bg-warning' : ($rank <= 3 ? 'bg-light' : ''); ?>">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <div class="fw-bold">
                                                    <i class="ri-medal-line me-1"></i>
                                                    #<?php echo $rank; ?> <?php echo $performer['first_name'] . ' ' . $performer['last_name']; ?>
                                                </div>
                                                <small><?php echo $performer['driver_code']; ?></small>
                                            </div>
                                            <div class="text-end">
                                                <div class="fw-bold"><?php echo number_format($performer['success_rate'], 1); ?>%</div>
                                                <small><?php echo $performer['completed_runs']; ?> runs</small>
                                            </div>
                                        </div>
                                        <div class="mt-2">
                                            <small class="text-muted">
                                                Cargo: <?php echo number_format($performer['total_weight'] / 1000, 1); ?>T
                                            </small>
                                        </div>
                                    </div>
                                    <?php $rank++; ?>
                                    <?php endwhile; ?>
                                    <?php else: ?>
                                    <div class="text-center text-muted py-4">
                                        <i class="ri-user-line fs-1"></i>
                                        <p class="mt-2">No performance data available for the selected period</p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Performance Chart -->
                            <div class="performance-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-bar-chart-line me-2"></i>Performance Distribution
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container">
                                        <canvas id="performanceChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Additional Analytics -->
                    <div class="row">
                        <div class="col-xl-6">
                            <div class="performance-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-time-line me-2"></i>Punctuality Analysis
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container">
                                        <canvas id="punctualityChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-6">
                            <div class="performance-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-truck-line me-2"></i>Cargo Efficiency
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container">
                                        <canvas id="cargoChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </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
    $('#performanceTable').DataTable({
        responsive: true,
        pageLength: 25,
        order: [[2, 'desc']], // Sort by performance score
        columnDefs: [
            { targets: [2], className: 'text-center' },
            { targets: [4, 5], className: 'text-end' }
        ],
        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'
            }
        ]
    });

    // Initialize Charts
    initializePerformanceChart();
    initializePunctualityChart();
    initializeCargoChart();
});

function initializePerformanceChart() {
    const ctx = document.getElementById('performanceChart').getContext('2d');
    
    // Sample data - in real implementation, this would come from PHP
    const data = {
        labels: ['Excellent (80-100)', 'Good (60-79)', 'Average (40-59)', 'Poor (0-39)'],
        datasets: [{
            data: [<?php 
            // Count drivers by performance score ranges
            $performance_result->data_seek(0);
            $excellent = $good = $average = $poor = 0;
            while ($driver = $performance_result->fetch_assoc()) {
                $score = floatval($driver['performance_score']);
                if ($score >= 80) $excellent++;
                elseif ($score >= 60) $good++;
                elseif ($score >= 40) $average++;
                else $poor++;
            }
            echo "$excellent, $good, $average, $poor";
            ?>],
            backgroundColor: [
                'rgba(40, 167, 69, 0.8)',
                'rgba(32, 201, 151, 0.8)', 
                'rgba(255, 193, 7, 0.8)',
                'rgba(220, 53, 69, 0.8)'
            ],
            borderColor: [
                'rgba(40, 167, 69, 1)',
                'rgba(32, 201, 151, 1)',
                'rgba(255, 193, 7, 1)', 
                'rgba(220, 53, 69, 1)'
            ],
            borderWidth: 2
        }]
    };

    new Chart(ctx, {
        type: 'doughnut',
        data: data,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return context.label + ': ' + context.parsed + ' drivers';
                        }
                    }
                }
            }
        }
    });
}

function initializePunctualityChart() {
    const ctx = document.getElementById('punctualityChart').getContext('2d');
    
    const data = {
        labels: ['On Time', 'Early', 'Late (< 15m)', 'Late (15-30m)', 'Late (> 30m)'],
        datasets: [{
            label: 'Departures',
            data: [45, 15, 25, 10, 5], // Sample data
            backgroundColor: 'rgba(54, 162, 235, 0.6)',
            borderColor: 'rgba(54, 162, 235, 1)',
            borderWidth: 1
        }]
    };

    new Chart(ctx, {
        type: 'bar',
        data: data,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Number of Runs'
                    }
                },
                x: {
                    title: {
                        display: true,
                        text: 'Punctuality Category'
                    }
                }
            }
        }
    });
}

function initializeCargoChart() {
    const ctx = document.getElementById('cargoChart').getContext('2d');
    
    const data = {
        labels: ['< 1T', '1-2T', '2-3T', '3-4T', '> 4T'],
        datasets: [{
            label: 'Average Load per Run',
            data: [20, 35, 30, 10, 5], // Sample data
            backgroundColor: [
                'rgba(255, 99, 132, 0.6)',
                'rgba(54, 162, 235, 0.6)',
                'rgba(255, 205, 86, 0.6)',
                'rgba(75, 192, 192, 0.6)',
                'rgba(153, 102, 255, 0.6)'
            ],
            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)'
            ],
            borderWidth: 1
        }]
    };

    new Chart(ctx, {
        type: 'bar',
        data: data,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Percentage of Drivers'
                    }
                },
                x: {
                    title: {
                        display: true,
                        text: 'Load Capacity Range'
                    }
                }
            }
        }
    });
}

// Global Functions
window.exportPerformance = function() {
    Swal.fire({
        title: 'Export Performance Report',
        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="includeCharts" checked>
                    <label class="form-check-label" for="includeCharts">Performance Charts</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includeDetails" checked>
                    <label class="form-check-label" for="includeDetails">Detailed Metrics</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includeRecommendations">
                    <label class="form-check-label" for="includeRecommendations">Improvement Recommendations</label>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Export',
        preConfirm: () => {
            return {
                format: document.getElementById('exportFormat').value,
                includeCharts: document.getElementById('includeCharts').checked,
                includeDetails: document.getElementById('includeDetails').checked,
                includeRecommendations: document.getElementById('includeRecommendations').checked
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Generating Report...',
                text: 'Please wait while we prepare your performance report.',
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                    setTimeout(() => {
                        Swal.close();
                        // Trigger download
                        const link = document.createElement('a');
                        link.href = `exports/driver_performance_export.php?format=${result.value.format}&period=<?php echo $period_filter; ?>&charts=${result.value.includeCharts}&details=${result.value.includeDetails}&recommendations=${result.value.includeRecommendations}`;
                        link.download = `driver_performance_${new Date().toISOString().split('T')[0]}.${result.value.format}`;
                        link.click();
                    }, 2000);
                }
            });
        }
    });
};

window.performanceAnalytics = function() {
    window.location.href = 'driver_analytics.php';
};
</script>

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