<?php
// ============================================================
// 1. DATA FETCHING (Dynamic from Server File)
// ============================================================

$source_file = 'active_drivers_cache.json';

// Check if file exists to avoid errors
if (!file_exists($source_file)) {
    die('<div style="font-family:sans-serif; text-align:center; padding:50px; color:#dc2626;">
            <h1>⚠️ Error: Data File Not Found</h1>
            <p>Please ensure <strong>'.$source_file.'</strong> exists in the same directory.</p>
         </div>');
}

// Get content
$json_data = file_get_contents($source_file);
$data = json_decode($json_data, true);

if (!$data) {
    die('Error decoding JSON data.');
}

$drivers = $data['data'];
$last_updated = $data['last_updated'] ?? date('Y-m-d H:i:s');

// ============================================================
// 2. DATA PROCESSING (Logic Layer)
// ============================================================

$processed_drivers = [];
$stats = [
    'total' => 0,
    'elite' => 0,     // +50 hours
    'stable' => 0,    // +20 hours
    'experimental' => 0, // +5 hours
    'inactive' => 0
];

foreach ($drivers as $driver) {
    // Parse Active Time String (e.g., "293 ساعة و 48 دقيقة")
    $timeStr = $driver['active_time'] ?? "0 ساعة و 0 دقيقة";
    preg_match('/(\d+)\s*ساعة/', $timeStr, $hoursMatch);
    preg_match('/(\d+)\s*دقيقة/', $timeStr, $minsMatch);
    
    $hours = isset($hoursMatch[1]) ? (int)$hoursMatch[1] : 0;
    $mins = isset($minsMatch[1]) ? (int)$minsMatch[1] : 0;
    $totalMinutes = ($hours * 60) + $mins;

    // Categorize Driver
    $category = 'inactive';
    $catLabel = 'خامل';
    $catClass = 'cat-inactive';

    if ($totalMinutes >= 3000) { // 50 hours
        $category = 'elite';
        $catLabel = 'نخبة';
        $catClass = 'cat-elite';
        $stats['elite']++;
    } elseif ($totalMinutes >= 1200) { // 20 hours
        $category = 'stable';
        $catLabel = 'مستقر';
        $catClass = 'cat-stable';
        $stats['stable']++;
    } elseif ($totalMinutes >= 300) { // 5 hours
        $category = 'experimental';
        $catLabel = 'تجريبي';
        $catClass = 'cat-experimental';
        $stats['experimental']++;
    } else {
        $stats['inactive']++;
    }

    $driver['total_minutes'] = $totalMinutes;
    $driver['category_label'] = $catLabel;
    $driver['category_class'] = $catClass;
    $processed_drivers[] = $driver;
}

$stats['total'] = count($processed_drivers);

// Sort by Active Time (High to Low)
usort($processed_drivers, function($a, $b) {
    return $b['total_minutes'] <=> $a['total_minutes'];
});

?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>تقرير السائقين - Intaleq</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --color-elite: #d97706;
            --color-stable: #059669;
            --color-exp: #2563eb;
            --color-inactive: #dc2626;
        }
        body {
            font-family: 'Tajawal', sans-serif;
            background: #e5e7eb; /* Grey bg for screen */
            margin: 0;
            padding: 20px;
            color: #1f2937;
        }
        .page {
            background: white;
            max-width: 210mm; /* A4 Width */
            margin: 0 auto;
            padding: 20px 40px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            min-height: 297mm;
        }
        
        /* Header */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 2px solid #1f2937;
            padding-bottom: 20px;
            margin-bottom: 20px;
        }
        .header h1 { margin: 0; font-size: 24px; }
        .meta { font-size: 12px; color: #6b7280; }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
            margin-bottom: 30px;
        }
        .stat-box {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 15px;
            text-align: center;
        }
        .stat-value { font-size: 24px; font-weight: 800; display: block; }
        .stat-label { font-size: 12px; color: #6b7280; font-weight: bold; }

        /* Table */
        table { width: 100%; border-collapse: collapse; font-size: 12px; }
        th, td { border-bottom: 1px solid #e5e7eb; padding: 10px; text-align: right; }
        th { background-color: #f9fafb; font-weight: 800; color: #374151; border-top: 2px solid #374151; }
        tr:nth-child(even) { background-color: #fdfdfd; }
        
        /* Categories */
        .badge { padding: 2px 8px; border-radius: 4px; font-weight: bold; font-size: 10px; border: 1px solid; }
        .cat-elite { background: #fef3c7; color: var(--color-elite); border-color: #fcd34d; }
        .cat-stable { background: #d1fae5; color: var(--color-stable); border-color: #6ee7b7; }
        .cat-experimental { background: #dbeafe; color: var(--color-exp); border-color: #93c5fd; }
        .cat-inactive { background: #fee2e2; color: var(--color-inactive); border-color: #fca5a5; }

        /* Notes Column */
        .notes-col { width: 150px; border-left: 1px dashed #d1d5db; }

        /* Print Rules */
        @media print {
            body { background: white; padding: 0; }
            .page { box-shadow: none; max-width: 100%; padding: 0; margin: 0; }
            .no-print { display: none; }
            th { background-color: #f3f4f6 !important; -webkit-print-color-adjust: exact; }
            .badge { -webkit-print-color-adjust: exact; }
            tr { page-break-inside: avoid; }
        }
    </style>
</head>
<body>

    <div class="no-print" style="text-align: center; margin-bottom: 20px;">
        <button onclick="window.print()" style="padding: 10px 20px; background: #2563eb; color: white; border: none; border-radius: 5px; cursor: pointer; font-family: inherit; font-weight: bold; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
            🖨️ طباعة التقرير (PDF)
        </button>
        <button onclick="location.reload()" style="padding: 10px 20px; background: #4b5563; color: white; border: none; border-radius: 5px; cursor: pointer; font-family: inherit; margin-right: 10px;">
            🔄 تحديث البيانات
        </button>
    </div>

    <div class="page">
        <div class="header">
            <div>
                <h1>تقرير أداء السائقين</h1>
                <div class="meta">تاريخ الطباعة: <?php echo date('Y-m-d H:i'); ?></div>
            </div>
            <div style="text-align: left">
                <h2 style="margin:0; color: #2563eb;">Intaleq</h2>
                <div class="meta dir-ltr"><?php echo $last_updated; ?> :آخر تحديث بيانات</div>
            </div>
        </div>

        <div class="stats-grid">
            <div class="stat-box" style="border-bottom: 3px solid #374151;">
                <span class="stat-label">إجمالي السائقين</span>
                <span class="stat-value" style="color: #374151"><?php echo $stats['total']; ?></span>
            </div>
            <div class="stat-box" style="border-bottom: 3px solid var(--color-elite);">
                <span class="stat-label">النخبة (+50 ساعة)</span>
                <span class="stat-value" style="color: var(--color-elite)"><?php echo $stats['elite']; ?></span>
            </div>
            <div class="stat-box" style="border-bottom: 3px solid var(--color-stable);">
                <span class="stat-label">مستقرون (+20 ساعة)</span>
                <span class="stat-value" style="color: var(--color-stable)"><?php echo $stats['stable']; ?></span>
            </div>
            <div class="stat-box" style="border-bottom: 3px solid var(--color-inactive);">
                <span class="stat-label">يحتاجون متابعة</span>
                <span class="stat-value" style="color: var(--color-inactive)"><?php echo $stats['inactive']; ?></span>
            </div>
        </div>

        <table>
            <thead>
                <tr>
                    <th style="width: 5%">#</th>
                    <th style="width: 25%">اسم السائق</th>
                    <th style="width: 15%">رقم الهاتف</th>
                    <th style="width: 20%">ساعات النشاط</th>
                    <th style="width: 10%">الحالة</th>
                    <th style="width: 10%">تاريخ الانضمام</th>
                    <th class="notes-col">ملاحظات إدارية</th>
                </tr>
            </thead>
            <tbody>
                <?php $i = 1; foreach ($processed_drivers as $driver): ?>
                <tr>
                    <td><?php echo $i++; ?></td>
                    <td>
                        <strong><?php echo $driver['name_arabic'] ?? '---'; ?></strong>
                    </td>
                    <td style="direction: ltr; text-align: right; font-family: monospace;">
                        <?php echo $driver['phone']; ?>
                    </td>
                    <td>
                        <?php echo $driver['active_time']; ?>
                    </td>
                    <td>
                        <span class="badge <?php echo $driver['category_class']; ?>">
                            <?php echo $driver['category_label']; ?>
                        </span>
                    </td>
                    <td><?php echo isset($driver['created_at']) ? date('Y-m-d', strtotime($driver['created_at'])) : '-'; ?></td>
                    <td class="notes-col"></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

</body>
</html>