<?php
// export_students.php - صفحة تصدير بيانات الطلاب


// ==================== حماية إضافية ====================
// منع الـ XSS
function sanitizeOutput($data) {
    return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}

// التحقق من أن الطلب آمن
function validateRequest() {
    // التحقق من الـ CSRF token
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
            die('طلب غير آمن');
        }
    }
    
    // منع الـ Clickjacking
    header('X-Frame-Options: DENY');
    
    // منع الـ XSS
    header('X-XSS-Protection: 1; mode=block');
    
    // منع الـ MIME type sniffing
    header('X-Content-Type-Options: nosniff');
}

// استدعاء دالة التحقق
validateRequest();


error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

$committeeId   = (int)($_SESSION['committee_id'] ?? 0);
$committeeName = (string)($_SESSION['committee_name'] ?? '');
$canAll        = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege  = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

$mysqli1->set_charset('utf8mb4');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// ==================== SECURITY FUNCTIONS ====================
function validateInt($value, $default = null) {
    if ($value === null || $value === '') return $default;
    $int = filter_var($value, FILTER_VALIDATE_INT);
    return $int !== false ? $int : $default;
}

function validateString($value, $max_length = 255) {
    if ($value === null) return '';
    $value = trim((string)$value);
    $value = preg_replace('/[\x00-\x1F\x7F]/u', '', $value);
    return substr($value, 0, $max_length);
}

function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

$csrf_token = generateCSRFToken();

// ==================== GET FILTERS FROM URL ====================
$filters_applied = isset($_GET['filter_applied']) && $_GET['filter_applied'] === '1';

if ($filters_applied) {
    $filter_college_id = isset($_GET['filter_college']) && $_GET['filter_college'] !== '' ? validateInt($_GET['filter_college']) : null;
    $filter_section_id = isset($_GET['filter_section']) && $_GET['filter_section'] !== '' ? validateInt($_GET['filter_section']) : null;
    $filter_program_id = isset($_GET['filter_program']) && $_GET['filter_program'] !== '' ? validateInt($_GET['filter_program']) : null;
    $filter_specialization_id = isset($_GET['filter_specialization']) && $_GET['filter_specialization'] !== '' ? validateInt($_GET['filter_specialization']) : null;
    $filter_batch_id = isset($_GET['filter_batch']) && $_GET['filter_batch'] !== '' ? validateInt($_GET['filter_batch']) : null;
    $search_query = validateString($_GET['search_query'] ?? '', 100);
    
    // حفظ الفلاتر في Session للتصدير
    $_SESSION['export_filters'] = [
        'college_id' => $filter_college_id,
        'section_id' => $filter_section_id,
        'program_id' => $filter_program_id,
        'specialization_id' => $filter_specialization_id,
        'batch_id' => $filter_batch_id,
        'search_query' => $search_query,
        'applied' => true
    ];
} else {
    if (!$canAll && $scopeCollege !== null) {
        $filter_college_id = $scopeCollege;
    } else {
        $filter_college_id = null;
    }
    $filter_section_id = null;
    $filter_program_id = null;
    $filter_specialization_id = null;
    $filter_batch_id = null;
    $search_query = '';
    
    // حفظ الفلاتر الافتراضية
    $_SESSION['export_filters'] = [
        'college_id' => $filter_college_id,
        'section_id' => $filter_section_id,
        'program_id' => $filter_program_id,
        'specialization_id' => $filter_specialization_id,
        'batch_id' => $filter_batch_id,
        'search_query' => $search_query,
        'applied' => $filters_applied
    ];
}

// ==================== GET FILTER OPTIONS FOR DISPLAY ====================
$colleges = [];
$colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
$colleges_stmt->execute();
$colleges_result = $colleges_stmt->get_result();
while ($row = $colleges_result->fetch_assoc()) {
    $colleges[] = $row;
}
$colleges_stmt->close();

$batches = [];
$batches_stmt = $mysqli1->prepare("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY id");
$batches_stmt->execute();
$batches_result = $batches_stmt->get_result();
while ($row = $batches_result->fetch_assoc()) {
    $batches[] = $row;
}
$batches_stmt->close();

// Get sections based on selected college
$sections = [];
if ($filter_college_id) {
    $sections_stmt = $mysqli1->prepare("SELECT id, name FROM sections WHERE parent = ? AND deleted_at IS NULL ORDER BY name");
    $sections_stmt->bind_param('i', $filter_college_id);
    $sections_stmt->execute();
    $sections_result = $sections_stmt->get_result();
    while ($row = $sections_result->fetch_assoc()) {
        $sections[] = $row;
    }
    $sections_stmt->close();
}

// Get all programs
$programs = [];
$programs_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
$programs_stmt->execute();
$programs_result = $programs_stmt->get_result();
while ($row = $programs_result->fetch_assoc()) {
    $programs[] = $row;
}
$programs_stmt->close();

// Get specializations based on selected section and program
$specializations = [];
if ($filter_section_id && $filter_program_id) {
    $spec_stmt = $mysqli1->prepare("
        SELECT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ");
    $spec_stmt->bind_param('ii', $filter_section_id, $filter_program_id);
    $spec_stmt->execute();
    $spec_result = $spec_stmt->get_result();
    while ($row = $spec_result->fetch_assoc()) {
        $specializations[] = $row;
    }
    $spec_stmt->close();
}

// Get selected filter names for display
$selected_college_name = '';
$selected_section_name = '';
$selected_program_name = '';
$selected_specialization_name = '';
$selected_batch_name = '';

if ($filter_college_id) {
    foreach ($colleges as $college) {
        if ($college['id'] == $filter_college_id) {
            $selected_college_name = $college['name'];
            break;
        }
    }
}

if ($filter_section_id) {
    foreach ($sections as $section) {
        if ($section['id'] == $filter_section_id) {
            $selected_section_name = $section['name'];
            break;
        }
    }
}

if ($filter_program_id) {
    foreach ($programs as $program) {
        if ($program['id'] == $filter_program_id) {
            $selected_program_name = $program['name'];
            break;
        }
    }
}

if ($filter_specialization_id) {
    foreach ($specializations as $spec) {
        if ($spec['specialization_id'] == $filter_specialization_id) {
            $selected_specialization_name = $spec['specialization_name_ar'];
            break;
        }
    }
}

if ($filter_batch_id) {
    foreach ($batches as $batch) {
        if ($batch['id'] == $filter_batch_id) {
            $selected_batch_name = $batch['value'];
            break;
        }
    }
}

// Get count of students to be exported
$student_count = 0;
$where = " WHERE 1=1 ";
$types = '';
$params = [];

if (!$canAll && $scopeCollege !== null) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i';
    $params[] = $scopeCollege;
} elseif (!$canAll && $scopeCollege === null) {
    $where .= " AND 1=0 ";
}

if ($filter_college_id && !empty($filter_college_id)) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i';
    $params[] = $filter_college_id;
}

if ($filter_section_id && !empty($filter_section_id)) {
    $where .= " AND s.section_id = ? ";
    $types .= 'i';
    $params[] = $filter_section_id;
}

if ($filter_program_id && !empty($filter_program_id)) {
    $where .= " AND s.program_id = ? ";
    $types .= 'i';
    $params[] = $filter_program_id;
}

if ($filter_specialization_id && !empty($filter_specialization_id)) {
    $where .= " AND s.specialization_id = ? ";
    $types .= 'i';
    $params[] = $filter_specialization_id;
}

if ($filter_batch_id && !empty($filter_batch_id)) {
    $where .= " AND s.batch_id = ? ";
    $types .= 'i';
    $params[] = $filter_batch_id;
}

if (!empty($search_query)) {
    $where .= " AND (s.student_id LIKE ? OR s.student_name LIKE ? OR s.student_name_eng LIKE ?) ";
    $types .= 'sss';
    $search_param = "%" . $search_query . "%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

$count_sql = "SELECT COUNT(*) as total FROM students s {$where}";
$count_stmt = $mysqli1->prepare($count_sql);
if ($types) {
    $count_stmt->bind_param($types, ...$params);
}
$count_stmt->execute();
$count_result = $count_stmt->get_result();
$student_count = $count_result->fetch_assoc()['total'];
$count_stmt->close();

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تصدير بيانات الطلاب - Excel</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body { 
            font-family: 'Cairo', sans-serif !important;
            background: linear-gradient(135deg,  #ffffff, #f8fafc);
            min-height: 100vh;
            padding: 40px 0;
        }
        
        .export-card {
            background: white;
            border-radius: 30px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
            overflow: hidden;
            margin: 20px auto;
            max-width: 1200px;
        }
        
        .export-header {
            background: linear-gradient(135deg, #059669 0%, #047857 100%);
            color: white;
            padding: 30px 40px;
        }
        
        .export-header h2 {
            font-size: 2rem;
            font-weight: 800;
            margin-bottom: 10px;
        }
        
        .export-header p {
            font-size: 1.1rem;
            opacity: 0.9;
            margin-bottom: 0;
        }
        
        .export-body {
            padding: 40px;
        }
        
        .filter-summary {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 30px;
            border: 1px solid #bbf7d0;
        }
        
        .filter-summary h5 {
            color: #166534;
            font-weight: 700;
            margin-bottom: 20px;
        }
        
        .filter-tag {
            background: white;
            border-radius: 12px;
            padding: 10px 15px;
            margin-bottom: 10px;
            border: 1px solid #86efac;
        }
        
        .filter-tag-label {
            font-size: 0.85rem;
            color: #166534;
            font-weight: 600;
            margin-bottom: 5px;
        }
        
        .filter-tag-value {
            font-size: 1.1rem;
            font-weight: 700;
            color: #064e3b;
        }
        
        .stats-box {
            background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
            border-radius: 20px;
            padding: 25px;
            text-align: center;
            margin-bottom: 30px;
        }
        
        .stats-number {
            font-size: 3rem;
            font-weight: 800;
            color: #1e40af;
            line-height: 1;
        }
        
        .stats-label {
            font-size: 1rem;
            color: #1e3a8a;
            margin-top: 10px;
        }
        
        .btn-export {
            background: linear-gradient(135deg, #059669 0%, #047857 100%);
            border: none;
            padding: 15px 40px;
            font-size: 1.2rem;
            font-weight: 700;
            border-radius: 50px;
            color: white;
            transition: all 0.3s ease;
        }
        
        .btn-export:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(5, 150, 105, 0.4);
            color: white;
        }
        
        .btn-export:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .btn-secondary-custom {
            background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
            border: none;
            padding: 15px 30px;
            font-size: 1rem;
            font-weight: 600;
            border-radius: 50px;
            color: white;
            transition: all 0.3s ease;
        }
        
        .btn-secondary-custom:hover {
            transform: translateY(-2px);
            color: white;
        }
        
        .info-box {
            background: #fef3c7;
            border: 1px solid #fde68a;
            border-radius: 16px;
            padding: 20px;
            margin-top: 30px;
        }
        
        .info-box i {
            color: #d97706;
            font-size: 1.5rem;
            margin-left: 15px;
        }
        
        .info-box-content {
            color: #92400e;
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            flex-direction: column;
        }
        
        .loading-spinner {
            width: 60px;
            height: 60px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #059669;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .loading-text {
            color: white;
            font-size: 1.2rem;
            margin-top: 20px;
            font-weight: 600;
        }
        
        .form-control, .form-select {
            font-size: 1rem;
            padding: 0.6rem 1rem;
            border-radius: 12px;
            border: 2px solid #e5e7eb;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #059669;
            box-shadow: 0 0 0 3px rgba(5, 150, 105, 0.1);
        }
        
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 8px;
        }
        
        @media (max-width: 768px) {
            .export-body {
                padding: 20px;
            }
            .stats-number {
                font-size: 2rem;
            }
            .btn-export {
                padding: 12px 25px;
                font-size: 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="container" dir="rtl">
        <div class="export-card">
            <div class="export-header">
                <div class="d-flex align-items-center justify-content-between">
                    <div>
                        <h2>
                            <i class="fas fa-file-excel me-3"></i>
                            تصدير بيانات الطلاب
                        </h2>
                        <p>قم بتصدير بيانات الطلاب إلى ملف Excel بناءً على عوامل التصفية المحددة</p>
                    </div>
                    <a href="registration_management.php" class="btn btn-secondary-custom">
                        <i class="fas fa-arrow-right me-2"></i>
                        العودة للتسجيل
                    </a>
                </div>
            </div>
            
            <div class="export-body">
                <!-- Filter Form -->
                <form id="exportForm" method="GET" action="export_students.php">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf_token, ENT_QUOTES, 'UTF-8') ?>">
                    
                    <div class="row g-4 mb-4">
                        <div class="col-md-6">
                            <label class="form-label">
                                <i class="fas fa-university text-success me-2"></i>
                                الكلية
                            </label>
                            <select class="form-select" name="filter_college" id="filter_college">
                                <option value="">جميع الكليات</option>
                                <?php foreach ($colleges as $college): ?>
                                    <?php 
                                    if (!$canAll && $scopeCollege !== null && $college['id'] != $scopeCollege) {
                                        continue;
                                    }
                                    ?>
                                    <option value="<?= (int)$college['id'] ?>" <?= ($filter_college_id == $college['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">
                                <i class="fas fa-calendar-alt text-success me-2"></i>
                                الدفعة
                            </label>
                            <select class="form-select" name="filter_batch" id="filter_batch">
                                <option value="">جميع الدفعات</option>
                                <?php foreach ($batches as $batch): ?>
                                    <option value="<?= (int)$batch['id'] ?>" <?= ($filter_batch_id == $batch['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($batch['value'], ENT_QUOTES, 'UTF-8') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">
                                <i class="fas fa-layer-group text-success me-2"></i>
                                القسم
                            </label>
                            <select class="form-select" name="filter_section" id="filter_section">
                                <option value="">جميع الأقسام</option>
                                <?php if (!empty($sections)): ?>
                                    <?php foreach ($sections as $section): ?>
                                        <option value="<?= (int)$section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($section['name'], ENT_QUOTES, 'UTF-8') ?>
                                        </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">
                                <i class="fas fa-graduation-cap text-success me-2"></i>
                                البرنامج
                            </label>
                            <select class="form-select" name="filter_program" id="filter_program">
                                <option value="">جميع البرامج</option>
                                <?php if (!empty($programs)): ?>
                                    <?php foreach ($programs as $program): ?>
                                        <option value="<?= (int)$program['id'] ?>" <?= ($filter_program_id == $program['id']) ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($program['name'], ENT_QUOTES, 'UTF-8') ?>
                                        </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">
                                <i class="fas fa-microscope text-success me-2"></i>
                                التخصص
                            </label>
                            <select class="form-select" name="filter_specialization" id="filter_specialization">
                                <option value="">جميع التخصصات</option>
                                <?php if (!empty($specializations)): ?>
                                    <?php foreach ($specializations as $spec): ?>
                                        <option value="<?= (int)$spec['specialization_id'] ?>" <?= ($filter_specialization_id == $spec['specialization_id']) ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($spec['specialization_name_ar'], ENT_QUOTES, 'UTF-8') ?>
                                        </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">
                                <i class="fas fa-search text-success me-2"></i>
                                بحث عن طالب
                            </label>
                            <input type="text" class="form-control" name="search_query" id="search_query"
                                   placeholder="ابحث برقم الطالب أو الاسم..."
                                   value="<?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?>">
                        </div>
                    </div>
                    
                    <div class="d-flex gap-3 mb-4">
                        <button type="submit" name="filter_applied" value="1" class="btn btn-secondary-custom">
                            <i class="fas fa-filter me-2"></i>
                            تطبيق التصفية
                        </button>
                        <button type="button" class="btn btn-secondary-custom" onclick="resetFilters()">
                            <i class="fas fa-sync-alt me-2"></i>
                            إعادة تعيين
                        </button>
                    </div>
                </form>
                
                <!-- Filter Summary -->
                <?php if ($filters_applied): ?>
                <div class="filter-summary">
                    <h5>
                        <i class="fas fa-sliders-h me-2"></i>
                        ملخص عوامل التصفية المطبقة
                    </h5>
                    <div class="row">
                        <div class="col-md-6">
                            <?php if (!empty($selected_college_name)): ?>
                            <div class="filter-tag">
                                <div class="filter-tag-label">الكلية</div>
                                <div class="filter-tag-value"><?= htmlspecialchars($selected_college_name, ENT_QUOTES, 'UTF-8') ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($selected_section_name)): ?>
                            <div class="filter-tag">
                                <div class="filter-tag-label">القسم</div>
                                <div class="filter-tag-value"><?= htmlspecialchars($selected_section_name, ENT_QUOTES, 'UTF-8') ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($selected_program_name)): ?>
                            <div class="filter-tag">
                                <div class="filter-tag-label">البرنامج</div>
                                <div class="filter-tag-value"><?= htmlspecialchars($selected_program_name, ENT_QUOTES, 'UTF-8') ?></div>
                            </div>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-6">
                            <?php if (!empty($selected_specialization_name)): ?>
                            <div class="filter-tag">
                                <div class="filter-tag-label">التخصص</div>
                                <div class="filter-tag-value"><?= htmlspecialchars($selected_specialization_name, ENT_QUOTES, 'UTF-8') ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($selected_batch_name)): ?>
                            <div class="filter-tag">
                                <div class="filter-tag-label">الدفعة</div>
                                <div class="filter-tag-value"><?= htmlspecialchars($selected_batch_name, ENT_QUOTES, 'UTF-8') ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($search_query)): ?>
                            <div class="filter-tag">
                                <div class="filter-tag-label">البحث</div>
                                <div class="filter-tag-value">"<?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?>"</div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Statistics -->
                <div class="stats-box">
                    <div class="stats-number" id="studentCount"><?= number_format($student_count) ?></div>
                    <div class="stats-label">
                        <i class="fas fa-users me-2"></i>
                        طالب سيتم تصديرهم
                    </div>
                </div>
                
                <!-- Export Button -->
                <div class="text-center">
                    <button type="button" class="btn btn-export" id="exportBtn" onclick="exportToExcel()" <?= $student_count == 0 ? 'disabled' : '' ?>>
                        <i class="fas fa-download me-2"></i>
                        تصدير إلى Excel
                    </button>
                </div>
                
                <!-- Info Box -->
                <div class="info-box d-flex align-items-start">
                    <i class="fas fa-info-circle"></i>
                    <div class="info-box-content">
                        <strong>معلومات التصدير:</strong><br>
                        • سيتم تصدير البيانات بتنسيق CSV<br>
                        • الأعمدة المصدرة: رقم الطالب، الاسم، الكلية، البرنامج، القسم، التخصص، الدفعة، نوع القبول<br>
                        • الحد الأقصى للتصدير: 10,000 طالب
                    </div>
                </div>
                <?php else: ?>
                <div class="stats-box">
                    <div class="stats-number">—</div>
                    <div class="stats-label">
                        <i class="fas fa-info-circle me-2"></i>
                        يرجى تطبيق التصفية أولاً
                    </div>
                </div>
                <div class="text-center">
                    <button type="button" class="btn btn-export" disabled>
                        <i class="fas fa-download me-2"></i>
                        يرجى تطبيق التصفية أولاً
                    </button>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-spinner"></div>
        <div class="loading-text">
            <i class="fas fa-file-excel me-2"></i>
            جاري تصدير البيانات...
        </div>
        <div class="loading-text mt-2" style="font-size: 0.9rem;">يرجى الانتظار</div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Load dependent dropdowns
        document.getElementById('filter_college').addEventListener('change', function() {
            const collegeId = this.value;
            if (collegeId) {
                loadSections(collegeId);
                loadPrograms(collegeId);
            } else {
                resetSectionAndProgram();
            }
        });
        
        function loadSections(collegeId) {
            fetch(`ajax/get_sections.php?college_id=${encodeURIComponent(collegeId)}`)
                .then(response => response.json())
                .then(sections => {
                    const sectionSelect = document.getElementById('filter_section');
                    sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
                    
                    if (sections && sections.length > 0) {
                        sections.forEach(section => {
                            const option = document.createElement('option');
                            option.value = section.id;
                            option.textContent = section.name;
                            sectionSelect.appendChild(option);
                        });
                    }
                })
                .catch(error => console.error('Error loading sections:', error));
        }
        
        function loadPrograms(collegeId) {
            fetch(`ajax/get_programs.php?college_id=${encodeURIComponent(collegeId)}`)
                .then(response => response.json())
                .then(programs => {
                    const programSelect = document.getElementById('filter_program');
                    programSelect.innerHTML = '<option value="">جميع البرامج</option>';
                    
                    if (programs && programs.length > 0) {
                        programs.forEach(program => {
                            const option = document.createElement('option');
                            option.value = program.id;
                            option.textContent = program.name;
                            programSelect.appendChild(option);
                        });
                    }
                })
                .catch(error => console.error('Error loading programs:', error));
        }
        
        function resetSectionAndProgram() {
            document.getElementById('filter_section').innerHTML = '<option value="">جميع الأقسام</option>';
            document.getElementById('filter_program').innerHTML = '<option value="">جميع البرامج</option>';
            document.getElementById('filter_specialization').innerHTML = '<option value="">جميع التخصصات</option>';
        }
        
        document.getElementById('filter_section').addEventListener('change', loadSpecializations);
        document.getElementById('filter_program').addEventListener('change', loadSpecializations);
        
        function loadSpecializations() {
            const sectionId = document.getElementById('filter_section').value;
            const programId = document.getElementById('filter_program').value;
            
            if (sectionId && programId) {
                fetch(`ajax/get_specializations.php?section_id=${encodeURIComponent(sectionId)}&program_id=${encodeURIComponent(programId)}`)
                    .then(response => response.json())
                    .then(specializations => {
                        const specSelect = document.getElementById('filter_specialization');
                        specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                        
                        if (specializations && specializations.length > 0) {
                            specializations.forEach(spec => {
                                const option = document.createElement('option');
                                option.value = spec.specialization_id;
                                option.textContent = spec.specialization_name_ar;
                                specSelect.appendChild(option);
                            });
                        }
                    })
                    .catch(error => console.error('Error loading specializations:', error));
            } else {
                document.getElementById('filter_specialization').innerHTML = '<option value="">جميع التخصصات</option>';
            }
        }
        
        function resetFilters() {
            window.location.href = 'export_students.php';
        }
        
        function exportToExcel() {
            // Show loading overlay
            document.getElementById('loadingOverlay').style.display = 'flex';
            
            // Send export request - filters are already in session
            fetch('export_students_csv.php', {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.blob();
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `students_export_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.csv`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                a.remove();
                document.getElementById('loadingOverlay').style.display = 'none';
            })
            .catch(error => {
                console.error('Export error:', error);
                document.getElementById('loadingOverlay').style.display = 'none';
                alert('حدث خطأ أثناء تصدير البيانات: ' + error.message);
            });
        }
        
        // Initial load of dependent dropdowns if college is selected
        document.addEventListener('DOMContentLoaded', function() {
            const collegeSelect = document.getElementById('filter_college');
            if (collegeSelect && collegeSelect.value) {
                loadSections(collegeSelect.value);
                loadPrograms(collegeSelect.value);
                
                const sectionSelect = document.getElementById('filter_section');
                const programSelect = document.getElementById('filter_program');
                if (sectionSelect.value && programSelect.value) {
                    loadSpecializations();
                }
            }
        });
    </script>
</body>
</html>
<?php include 'footer.php'; ?>
