<?php
// exam_attendance.php - تقرير حضور الامتحان (نسخة محسنة بالكامل مع إضافة التخصص)
error_reporting(E_ALL);
ini_set('display_errors', 0); // إخفاء الأخطاء في الإنتاج
ini_set('log_errors', 1); // تسجيل الأخطاء في السجل
ini_set('error_log', __DIR__ . '/../logs/error.log'); // مسار سجل الأخطاء

require '../db.php';
require '../helpers.php';

// تفعيل التقرير الصارم للأخطاء في MySQL
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Check committee access (session is already started in header/db)
if (!isset($_SESSION['committee_id'])) {
    header('Location: ../login.php');
    exit;
}

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;
$userId        = (int)($_SESSION['user_id'] ?? 0);

// ===== دوال التحقق من صحة المدخلات =====
function validateInt($value, $default = null) {
    if ($value === null || $value === '') return $default;
    return filter_var($value, FILTER_VALIDATE_INT) !== false ? (int)$value : $default;
}

function validateString($value, $default = '', $maxLength = 191) {
    if ($value === null || $value === '') return $default;
    $value = trim((string)$value);
    $value = strip_tags($value);
    $value = preg_replace('/[<>"\']/', '', $value);
    $value = substr($value, 0, $maxLength);
    return $value === '' ? $default : $value;
}

function validateExamType($value, $default = 'midterm') {
    $allowed = ['midterm', 'final'];
    return in_array($value, $allowed, true) ? $value : $default;
}

function validateDate($value, $default = '') {
    if (empty($value)) return $default;
    $date = DateTime::createFromFormat('Y-m-d', $value);
    return $date && $date->format('Y-m-d') === $value ? $value : $default;
}

function validateTime($value, $default = '') {
    if (empty($value)) return $default;
    return preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $value) ? $value : $default;
}

// CSRF Protection
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

function verifyCSRF($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Initialize variables
$students = [];
$errors = [];
$warnings = [];
$success = [];

// Check if filters were submitted
$filters_applied = isset($_GET['filter_applied']) && $_GET['filter_applied'] === '1';

// Get filter parameters with validation - only use them if filters were applied
if ($filters_applied) {
    $filter_semester_id = isset($_GET['filter_semester']) ? validateInt($_GET['filter_semester']) : null;
    $filter_college_id = isset($_GET['filter_college']) ? validateInt($_GET['filter_college']) : null;
    $filter_section_id = isset($_GET['filter_section']) ? validateInt($_GET['filter_section']) : null;
    $filter_program_id = isset($_GET['filter_program']) ? validateInt($_GET['filter_program']) : null;
    $filter_specialization_id = isset($_GET['filter_specialization']) ? validateInt($_GET['filter_specialization']) : null;
    $filter_batch_id = isset($_GET['filter_batch']) ? validateInt($_GET['filter_batch']) : null;
    $filter_exam_type = isset($_GET['filter_exam_type']) ? validateExamType($_GET['filter_exam_type']) : 'midterm';
    
    // CSRF check for GET (optional but recommended for sensitive operations)
    if (isset($_GET['csrf']) && !verifyCSRF($_GET['csrf'])) {
        $errors[] = "رمز الجلسة غير صالح";
        error_log("CSRF violation in exam_attendance.php GET from user $userId");
        $filters_applied = false;
    }
} else {
    // Don't apply filters by default
    $filter_semester_id = null;
    $filter_college_id = null;
    $filter_section_id = null;
    $filter_program_id = null;
    $filter_specialization_id = null;
    $filter_batch_id = null;
    $filter_exam_type = 'midterm';
}

// Apply scope restrictions
if (!$canAll && $scopeCollege !== null) {
    // Auto-set the college filter if user has scope restriction
    if (!$filter_college_id) {
        $filter_college_id = $scopeCollege;
    } elseif ($filter_college_id != $scopeCollege) {
        // User trying to access other college - security violation
        $errors[] = "ليس لديك صلاحية للوصول إلى هذه الكلية";
        error_log("SECURITY VIOLATION: User $userId tried to access college $filter_college_id (scope: $scopeCollege)");
        $filter_college_id = $scopeCollege;
        $filters_applied = false;
    }
}

// Get semester name for display
$semester_name = '';
$semester_code = '';
if ($filter_semester_id) {
    try {
        $semester_sql = "SELECT name, code FROM semesters WHERE id = ? AND deleted_at IS NULL";
        $st_sem = $mysqli1->prepare($semester_sql);
        if (!$st_sem) {
            throw new Exception("Failed to prepare semester query");
        }
        $st_sem->bind_param("i", $filter_semester_id);
        $st_sem->execute();
        $semester_result = $st_sem->get_result();
        $semester_data = $semester_result->fetch_assoc();
        if ($semester_data) {
            $semester_name = $semester_data['name'];
            $semester_code = $semester_data['code'];
        }
        $st_sem->close();
    } catch (Exception $e) {
        error_log("Error fetching semester name: " . $e->getMessage());
        $warnings[] = "تعذر جلب اسم الفصل الدراسي";
    }
}

$semester_display = $semester_name . ($semester_code ? " ($semester_code)" : "");

// Build query to get students
if ($filters_applied) {
    try {
        $sql = "SELECT s.student_id, s.student_name, s.student_name_eng, 
                       sec.name as section_name, 
                       sp.specialization_name_ar as specialization_name,
                       b.value as batch_name,
                       p.name as program_name,
                       c.name as college_name
                FROM students s 
                LEFT JOIN sections sec ON sec.id = s.section_id AND sec.deleted_at IS NULL
                LEFT JOIN specializations sp ON sp.specialization_id = s.specialization_id AND sp.deleted_at IS NULL
                LEFT JOIN batches b ON b.id = s.batch_id AND b.deleted_at IS NULL
                LEFT JOIN programs p ON p.id = s.program_id AND p.deleted_at IS NULL
                LEFT JOIN colleges c ON c.id = s.college_id AND c.deleted_at IS NULL
                WHERE s.deleted_at IS NULL";

        $params = [];
        $types = '';

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

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

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

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

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

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

        $sql .= " ORDER BY s.student_name LIMIT 1000";

        $st = $mysqli1->prepare($sql);
        if (!$st) {
            throw new Exception("Failed to prepare student query: " . $mysqli1->error);
        }

        if ($types && !empty($params)) {
            $st->bind_param($types, ...$params);
        }
        $st->execute();
        $result = $st->get_result();
        $students = $result->fetch_all(MYSQLI_ASSOC);
        $st->close();
        
        // Log successful query
        error_log("User $userId retrieved " . count($students) . " students for exam attendance report");
        
        if (count($students) >= 1000) {
            $warnings[] = "تم عرض أول 1000 طالب فقط. الرجاء تضييق نطاق البحث للحصول على نتائج أكثر دقة.";
        }
        
    } catch (Exception $e) {
        error_log("Error fetching students: " . $e->getMessage());
        $errors[] = "حدث خطأ في جلب البيانات. الرجاء المحاولة لاحقاً.";
        $students = [];
    }
} else {
    $students = [];
}

// Get filter options with prepared statements
try {
    // Colleges with scope restriction
    $colleges_sql = "SELECT id, name FROM colleges WHERE deleted_at IS NULL";
    $colleges_params = [];
    $colleges_types = "";
    
    if (!$canAll && $scopeCollege !== null) {
        $colleges_sql .= " AND id = ?";
        $colleges_types .= "i";
        $colleges_params[] = $scopeCollege;
    }
    
    $colleges_sql .= " ORDER BY name";
    
    $colleges_stmt = $mysqli1->prepare($colleges_sql);
    if (!$colleges_stmt) {
        throw new Exception("Failed to prepare colleges query");
    }
    if (!empty($colleges_params)) {
        $colleges_stmt->bind_param($colleges_types, ...$colleges_params);
    }
    $colleges_stmt->execute();
    $colleges = $colleges_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $colleges_stmt->close();

    // Get sections for the selected college
    $sections = [];
    if ($filter_college_id && !empty($filter_college_id)) {
        $sections_sql = "
            SELECT DISTINCT s.id, s.name, s.parent
            FROM sections s 
            WHERE s.parent = ? AND s.deleted_at IS NULL 
            ORDER BY s.name
        ";
        $sections_stmt = $mysqli1->prepare($sections_sql);
        if (!$sections_stmt) {
            throw new Exception("Failed to prepare sections query");
        }
        $sections_stmt->bind_param("i", $filter_college_id);
        $sections_stmt->execute();
        $sections = $sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $sections_stmt->close();
    }

    // Get programs based on selected college and section
    $programs = [];
    if ($filter_college_id && !empty($filter_college_id)) {
        $programs_where = ["p.deleted_at IS NULL"];
        $programs_params = [];
        $programs_types = "";
        
        if ($filter_section_id && !empty($filter_section_id)) {
            $programs_where[] = "st.section_id = ?";
            $programs_types .= "i";
            $programs_params[] = $filter_section_id;
        }
        
        $programs_where[] = "st.college_id = ?";
        $programs_types .= "i";
        $programs_params[] = $filter_college_id;
        
        $programs_sql = "
            SELECT DISTINCT p.id, p.name 
            FROM programs p 
            INNER JOIN students st ON p.id = st.program_id 
            WHERE " . implode(" AND ", $programs_where) . " 
            ORDER BY p.name
        ";
        
        $programs_stmt = $mysqli1->prepare($programs_sql);
        if (!$programs_stmt) {
            throw new Exception("Failed to prepare programs query");
        }
        if ($programs_types) {
            $programs_stmt->bind_param($programs_types, ...$programs_params);
        }
        $programs_stmt->execute();
        $programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $programs_stmt->close();
    } else {
        $programs_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
        if (!$programs_stmt) {
            throw new Exception("Failed to prepare programs query");
        }
        $programs_stmt->execute();
        $programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $programs_stmt->close();
    }

    // Get specializations based on selected section and program
    $specializations = [];
    if ($filter_section_id && !empty($filter_section_id) && $filter_program_id && !empty($filter_program_id)) {
        $specializations_sql = "
            SELECT specialization_id, specialization_name_ar 
            FROM specializations 
            WHERE section_id = ? AND program_id = ? AND deleted_at IS NULL 
            ORDER BY specialization_name_ar
        ";
        $specializations_stmt = $mysqli1->prepare($specializations_sql);
        if ($specializations_stmt) {
            $specializations_stmt->bind_param("ii", $filter_section_id, $filter_program_id);
            $specializations_stmt->execute();
            $specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $specializations_stmt->close();
        }
    }

    // Batches
    $batches_stmt = $mysqli1->prepare("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY id DESC");
    if (!$batches_stmt) {
        throw new Exception("Failed to prepare batches query");
    }
    $batches_stmt->execute();
    $batches = $batches_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $batches_stmt->close();

    // Semesters
    $semesters_stmt = $mysqli1->prepare("SELECT id, name, code FROM semesters WHERE deleted_at IS NULL ORDER BY id DESC");
    if (!$semesters_stmt) {
        throw new Exception("Failed to prepare semesters query");
    }
    $semesters_stmt->execute();
    $semesters = $semesters_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $semesters_stmt->close();
    
} catch (Exception $e) {
    error_log("Error fetching filter options: " . $e->getMessage());
    $errors[] = "حدث خطأ في تحميل البيانات. الرجاء المحاولة لاحقاً.";
    $colleges = $sections = $programs = $specializations = $batches = $semesters = [];
}

// Get filter names for display
$college_name = "";
if ($filter_college_id) {
    foreach ($colleges as $college) {
        if ($college['id'] == $filter_college_id) {
            $college_name = $college['name'];
            break;
        }
    }
}

$section_name = "";
if ($filter_section_id && !empty($sections)) {
    foreach ($sections as $section) {
        if ($section['id'] == $filter_section_id) {
            $section_name = $section['name'];
            break;
        }
    }
}

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

$specialization_name = "";
if ($filter_specialization_id && !empty($specializations)) {
    foreach ($specializations as $spec) {
        if ($spec['specialization_id'] == $filter_specialization_id) {
            $specialization_name = $spec['specialization_name_ar'];
            break;
        }
    }
}

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

// Generate CSRF token for forms
$csrf_token = $_SESSION['csrf_token'];

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>تقرير حضور الامتحان</title>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://cdnjs.cloudflare.com https://code.jquery.com https://cdn.jsdelivr.net 'unsafe-inline'; style-src 'self' https://fonts.googleapis.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net 'unsafe-inline'; font-src 'self' https://fonts.gstatic.com https://cdnjs.cloudflare.com; img-src 'self' data:;">
    
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;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" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js" integrity="sha512-rP1IpZR5hXJqDcX6RFsWQN5B15t0Yp15hqB3RrJjU2pW6BVV+V3F5G4GID+LGPL+tgZ5O6K9qL+uE0ztF0xTqw==" crossorigin="anonymous" referrerpolicy="no-referrer">
    
    <style>
        body, h1,h2,h3,h4,h5,h6, p, a, button, label { 
            font-family: 'Cairo', sans-serif !important; 
        }
        .card-arabic {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        .filter-icon {
            width: 40px;
            height: 40px;
            background: #3b82f6;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.1rem;
        }
        .filter-status {
            font-size: 0.85rem;
            padding: 0.3rem 0.6rem;
            border-radius: 6px;
        }
        .filter-status.applied {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #a7f3d0;
        }
        .filter-status.not-applied {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
        }
        .info-message {
            background-color: #f0f9ff;
            border: 1px solid #bae6fd;
            color: #0369a1;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .error-message {
            background-color: #fee2e2;
            border: 1px solid #f87171;
            color: #991b1b;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .warning-message {
            background-color: #fef3c7;
            border: 1px solid #fbbf24;
            color: #92400e;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .success-message {
            background-color: #d1fae5;
            border: 1px solid #a7f3d0;
            color: #065f46;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .summary-card {
            background: white;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.06);
            border: 1px solid #e0e0e0;
            text-align: center;
            transition: transform 0.2s ease;
        }
        .summary-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .summary-card .number {
            font-size: 2rem;
            font-weight: 800;
            margin-bottom: 5px;
            color: #3b82f6;
        }
        .summary-card .label {
            font-size: 0.9rem;
            color: #6c757d;
        }
        .student-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        .badge-custom {
            padding: 5px 10px;
            border-radius: 20px;
            font-weight: 500;
        }
        .form-select, .form-control {
            border-radius: 8px;
            border: 1px solid #ced4da;
        }
        .form-select:focus, .form-control:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 0.2rem rgba(59, 130, 246, 0.25);
        }
        .form-control.is-invalid {
            border-color: #dc3545;
            background-image: none;
        }
        .btn-primary {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            border: none;
            border-radius: 8px;
            padding: 8px 20px;
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #2563eb, #1d4ed8);
        }
        .table-responsive {
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.06);
        }
        .chip {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        .chip.success { background: #d4edda; color: #155724; }
        .chip.info { background: #d1ecf1; color: #0c5460; }
        .chip.warning { background: #fff3cd; color: #856404; }
        .chip.primary { background: #dbeafe; color: #1e3a8a; }
        .chip.secondary { background: #e9ecef; color: #495057; }
        .chip.blue { background: #d0ebff; color: #0c63e4; border: 1px solid #a5d8ff; }
        .chip.green { background: #d3f9d8; color: #2b8a3e; border: 1px solid #b2f2bb; }
        .chip.red { background: #ffe3e3; color: #c92a2a; border: 1px solid #ffc9c9; }
        .chip.purple { background: #f3e8ff; color: #7e22ce; border: 1px solid #e9d5ff; }
        
        /* Print styles */
        @media print {
            body { 
                font-size: 12px !important; 
                direction: rtl;
                padding: 0;
                margin: 0;
            }
            
            .no-print { 
                display: none !important; 
            }
            
            .print-only { 
                display: block !important; 
            }
            
            .print-header {
                text-align: center;
                margin-bottom: 20px;
                padding-bottom: 15px;
            }
            
            .print-info {
                font-size: 11px;
                color: #666;
                margin-bottom: 10px;
            }
            
            .print-table {
                width: 100%;
                border-collapse: collapse;
                font-size: 10px;
            }
            
            .print-table th {
                background-color: #f0f0f0 !important;
                border: 1px solid #000 !important;
                padding: 6px 4px !important;
                font-weight: bold !important;
                text-align: center !important;
            }
            
            .print-table td {
                border: 1px solid #000 !important;
                padding: 5px 4px !important;
                text-align: center !important;
            }
            
            .print-table .text-right {
                text-align: right !important;
                padding-right: 10px !important;
            }
            
            .print-footer {
                margin-top: 20px;
                padding-top: 10px;
                border-top: 1px solid #000;
                font-size: 10px;
                text-align: center;
                color: #666;
            }
            
            /* Hide all elements except print content */
            body > *:not(.print-container) {
                display: none !important;
            }
        }
        
        .print-container {
            display: none;
        }
        
        .banner-img {
            max-width: 100%;
            height: auto;
            margin-bottom: 15px;
        }
        
        .student-name-cell {
            text-align: right !important;
            direction: rtl !important;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            padding-right: 15px !important;
        }
        
        .filter-summary {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            border: 1px solid #e9ecef;
        }
        
        .filter-summary-item {
            margin-bottom: 8px;
        }
        
        .filter-summary-label {
            font-size: 0.85rem;
            color: #6c757d;
            margin-left: 5px;
        }
        
        .filter-summary-value {
            font-size: 0.9rem;
            font-weight: 600;
            color: #212529;
        }
        
        .export-options {
            background: white;
            border-radius: 12px;
            padding: 15px;
            border: 1px solid #e5e7eb;
            margin-bottom: 20px;
        }
        
        .btn-export {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s ease;
            border: none;
            cursor: pointer;
        }
        
        .btn-export-excel {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
        }
        
        .btn-export-excel:hover:not(:disabled) {
            background: linear-gradient(135deg, #059669, #047857);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
        }
        
        .btn-export-pdf {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
        }
        
        .btn-export-pdf:hover:not(:disabled) {
            background: linear-gradient(135deg, #dc2626, #b91c1c);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
        }
        
        .btn-export:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        @media (max-width: 768px) {
            .d-flex {
                flex-direction: column;
                gap: 10px;
            }
            
            .ms-auto {
                margin-right: 0 !important;
            }
            
            .export-options .d-flex {
                flex-direction: column;
            }
            
            .btn-export {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container py-4" dir="rtl">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4 no-print">
            <h3 class="mb-0 fw-bold">
                <i class="fas fa-file-alt ms-2 text-primary"></i>
                تقرير حضور الامتحان
            </h3>
            <div class="ms-auto d-flex align-items-center">
                <span class="filter-status <?= $filters_applied ? 'applied' : 'not-applied' ?> me-2">
                    <i class="fas fa-<?= $filters_applied ? 'check-circle' : 'exclamation-triangle' ?> me-1"></i>
                    <?= $filters_applied ? 'تم تطبيق التصفية' : 'لم يتم تطبيق أي تصفية' ?>
                </span>
                <a class="btn btn-outline-secondary" href="../committee_dashboard.php">
                    <i class="fas fa-arrow-right me-2"></i>العودة للوحة التحكم
                </a>
            </div>
        </div>

        <!-- Error Messages -->
        <?php if (!empty($errors)): ?>
            <div class="error-message no-print">
                <i class="fas fa-exclamation-circle me-2 fa-lg"></i>
                <div>
                    <?php foreach ($errors as $error): ?>
                        <p class="mb-0 <?= $index > 0 ? 'mt-2' : '' ?>"><?= e($error) ?></p>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- Warning Messages -->
        <?php if (!empty($warnings)): ?>
            <div class="warning-message no-print">
                <i class="fas fa-exclamation-triangle me-2 fa-lg"></i>
                <div>
                    <?php foreach ($warnings as $warning): ?>
                        <p class="mb-0 <?= $index > 0 ? 'mt-2' : '' ?>"><?= e($warning) ?></p>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <?php if (!$filters_applied && empty($errors)): ?>
            <div class="info-message no-print">
                <i class="fas fa-info-circle me-2 fa-lg"></i>
                <strong>تنبيه:</strong> لم يتم تطبيق أي تصفية. الرجاء اختيار عوامل التصفية ثم النقر على "تطبيق التصفية" لعرض الطلاب.
            </div>
        <?php endif; ?>

        <!-- Filter Card -->
        <div class="card card-arabic p-4 mb-4 no-print">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="d-flex align-items-center mb-3">
                        <div class="filter-icon me-2">
                            <i class="fas fa-filter"></i>
                        </div>
                        <h6 class="fw-bold mb-0 text-dark">تصفية الطلاب لحضور الامتحان</h6>
                        <div class="ms-3">
                            <span class="badge bg-light text-dark border">
                                <i class="fas fa-sliders-h me-1"></i>
                                <?= $filters_applied ? 'تصفية مطبقة' : 'في انتظار التطبيق' ?>
                            </span>
                        </div>
                    </div>
                    
                    <form method="get" class="row g-3 align-items-end" id="filterForm">
                        <!-- CSRF Token for security -->
                        <input type="hidden" name="csrf" value="<?= e($csrf_token) ?>">
                        
                        <!-- Hidden field to indicate filters were applied -->
                        <input type="hidden" name="filter_applied" value="1">
                        
                        <!-- College Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-university me-1"></i>
                                    الكلية
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_college" id="filter_college" onchange="loadSections(this.value)">
                                        <option value="">اختر الكلية</option>
                                        <?php foreach ($colleges as $college): ?>
                                            <?php 
                                            // Don't show college filter if user has scope restriction
                                            if (!$canAll && $scopeCollege !== null && $college['id'] != $scopeCollege) {
                                                continue;
                                            }
                                            ?>
                                            <option value="<?= (int)$college['id'] ?>" <?= ($filter_college_id == $college['id']) ? 'selected' : '' ?>>
                                                <?= e($college['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-building"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Section Filter (Dependent on College) -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-layer-group me-1"></i>
                                    القسم
                                </label>
                                <div class="input-group input-group-sm position-relative">
                                    <select class="form-control border-end-0" name="filter_section" id="filter_section" <?= !$filter_college_id ? 'disabled' : '' ?> onchange="loadPrograms()">
                                        <option value="">جميع الأقسام</option>
                                        <?php if ($filter_college_id && !empty($sections)): ?>
                                            <?php foreach ($sections as $section): ?>
                                                <option value="<?= (int)$section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                                    <?= e($section['name']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-building"></i>
                                    </span>
                                </div>
                                <?php if (!$filter_college_id): ?>
                                    <small class="text-muted">الرجاء اختيار كلية أولاً</small>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Program Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-graduation-cap me-1"></i>
                                    البرنامج
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_program" id="filter_program" onchange="loadSpecializations()">
                                        <option value="">جميع البرامج</option>
                                        <?php foreach ($programs as $program): ?>
                                            <option value="<?= (int)$program['id'] ?>" <?= ($filter_program_id == $program['id']) ? 'selected' : '' ?>>
                                                <?= e($program['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-book"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Specialization Filter (NEW) -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-microscope me-1"></i>
                                    التخصص
                                </label>
                                <div class="input-group input-group-sm position-relative">
                                    <select class="form-control border-end-0" name="filter_specialization" id="filter_specialization" <?= (!$filter_program_id || !$filter_section_id) ? 'disabled' : '' ?>>
                                        <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' : '' ?>>
                                                    <?= e($spec['specialization_name_ar']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-microscope"></i>
                                    </span>
                                    <div class="ajax-loading" id="specLoading" style="display: none;">
                                        <i class="fas fa-spinner fa-spin"></i>
                                    </div>
                                </div>
                                <small class="text-muted" id="specHint">
                                    <?php if (!$filter_program_id || !$filter_section_id): ?>
                                        الرجاء اختيار القسم والبرنامج أولاً
                                    <?php endif; ?>
                                </small>
                            </div>
                        </div>
                        
                        <!-- Batch Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-users me-1"></i>
                                    الدفعة
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_batch">
                                        <option value="">جميع الدفعات</option>
                                        <?php foreach ($batches as $batch): ?>
                                            <option value="<?= (int)$batch['id'] ?>" <?= ($filter_batch_id == $batch['id']) ? 'selected' : '' ?>>
                                                <?= e($batch['value']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Semester Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-calendar-alt me-1"></i>
                                    الفصل الدراسي
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_semester">
                                        <option value="">جميع الفصول</option>
                                        <?php foreach ($semesters as $semester): ?>
                                            <option value="<?= (int)$semester['id'] ?>" <?= ($filter_semester_id == $semester['id']) ? 'selected' : '' ?>>
                                                <?= e($semester['name'] . ' (' . $semester['code'] . ')') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-calendar"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Exam Type Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-file-alt me-1"></i>
                                    نوع الامتحان
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_exam_type">
                                        <option value="midterm" <?= ($filter_exam_type == 'midterm') ? 'selected' : '' ?>>منتصف الفصل</option>
                                        <option value="final" <?= ($filter_exam_type == 'final') ? 'selected' : '' ?>>نهاية الفصل</option>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-file-alt"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div class="col-12">
                            <div class="d-flex gap-2 pt-2">
                                <button type="submit" class="btn btn-primary btn-sm px-3">
                                    <i class="fas fa-filter me-1"></i>
                                    تطبيق التصفية
                                </button>
                                <a href="exam_attendance.php" class="btn btn-outline-secondary btn-sm px-3">
                                    <i class="fas fa-sync-alt me-1"></i>
                                    إعادة تعيين
                                </a>
                                <?php if ($filters_applied): ?>
                                    <span class="badge bg-success align-self-center px-3 py-2">
                                        <i class="fas fa-check me-1"></i>
                                        تم تطبيق التصفية
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                </div>
                
                <!-- Filter Summary -->
                <div class="col-md-4">
                    <div class="filter-summary h-100">
                        <div class="d-flex align-items-center mb-3">
                            <i class="fas fa-info-circle me-2 <?= $filters_applied ? 'text-primary' : 'text-secondary' ?> fa-lg"></i>
                            <span class="fw-semibold">ملخص التصفية</span>
                        </div>
                        
                        <?php if ($filters_applied): ?>
                            <div class="filter-summary-item">
                                <span class="filter-summary-label">عدد الطلاب:</span>
                                <span class="filter-summary-value badge bg-info"><?= number_format(count($students)) ?></span>
                            </div>
                            
                            <div class="filter-summary-item">
                                <span class="filter-summary-label">نوع الامتحان:</span>
                                <span class="filter-summary-value chip <?= $filter_exam_type == 'midterm' ? 'primary' : 'red' ?>">
                                    <?= $filter_exam_type == 'midterm' ? 'منتصف الفصل' : 'نهاية الفصل' ?>
                                </span>
                            </div>
                            
                            <?php if ($filter_semester_id && $semester_display): ?>
                                <div class="filter-summary-item">
                                    <span class="filter-summary-label">الفصل الدراسي:</span>
                                    <span class="filter-summary-value chip secondary"><?= e($semester_display) ?></span>
                                </div>
                            <?php endif; ?>
                            
                            <?php if ($filter_college_id && $college_name): ?>
                                <div class="filter-summary-item">
                                    <span class="filter-summary-label">الكلية:</span>
                                    <span class="filter-summary-value chip info"><?= e($college_name) ?></span>
                                </div>
                            <?php endif; ?>
                            
                            <?php if ($filter_section_id && $section_name): ?>
                                <div class="filter-summary-item">
                                    <span class="filter-summary-label">القسم:</span>
                                    <span class="filter-summary-value chip success"><?= e($section_name) ?></span>
                                </div>
                            <?php endif; ?>
                            
                            <?php if ($filter_program_id && $program_name): ?>
                                <div class="filter-summary-item">
                                    <span class="filter-summary-label">البرنامج:</span>
                                    <span class="filter-summary-value chip warning"><?= e($program_name) ?></span>
                                </div>
                            <?php endif; ?>
                            
                            <!-- NEW: Specialization Summary -->
                            <?php if ($filter_specialization_id && $specialization_name): ?>
                                <div class="filter-summary-item">
                                    <span class="filter-summary-label">التخصص:</span>
                                    <span class="filter-summary-value chip purple"><?= e($specialization_name) ?></span>
                                </div>
                            <?php endif; ?>
                            
                            <?php if ($filter_batch_id && $batch_name): ?>
                                <div class="filter-summary-item">
                                    <span class="filter-summary-label">الدفعة:</span>
                                    <span class="filter-summary-value chip secondary"><?= e($batch_name) ?></span>
                                </div>
                            <?php endif; ?>
                            
                            <?php if (count($students) >= 1000): ?>
                                <div class="filter-summary-item mt-2">
                                    <span class="chip red">
                                        <i class="fas fa-exclamation-triangle me-1"></i>
                                        تم عرض أول 1000 طالب فقط
                                    </span>
                                </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <div class="text-center py-3">
                                <i class="fas fa-filter fa-2x text-muted mb-2"></i>
                                <p class="text-muted small mb-0">لم يتم تطبيق أي تصفية بعد</p>
                                <p class="text-muted small">الرجاء اختيار عوامل التصفية</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Report Content -->
        <?php if ($filters_applied): ?>
            <!-- Exam Information Card -->
            <div class="card card-arabic p-4 mb-4 no-print">
                <div class="d-flex align-items-center mb-3">
                    <div class="filter-icon me-2" style="background: #10b981;">
                        <i class="fas fa-info-circle"></i>
                    </div>
                    <h6 class="fw-bold mb-0 text-dark">معلومات الامتحان</h6>
                </div>
                
                <form id="examInfoForm" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label fw-semibold text-muted mb-2">
                            <i class="fas fa-door-open me-1"></i>
                            اسم القاعة
                        </label>
                        <div class="input-group input-group-sm">
                            <input type="text" class="form-control border-end-0" id="room_name" placeholder="أدخل اسم القاعة" maxlength="100">
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-building"></i>
                            </span>
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label fw-semibold text-muted mb-2">
                            <i class="fas fa-book me-1"></i>
                            اسم المادة
                        </label>
                        <div class="input-group input-group-sm">
                            <input type="text" class="form-control border-end-0" id="exam_name" placeholder="أدخل اسم المادة" maxlength="100">
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-book-open"></i>
                            </span>
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label fw-semibold text-muted mb-2">
                            <i class="fas fa-calendar-day me-1"></i>
                            تاريخ الامتحان
                        </label>
                        <div class="input-group input-group-sm">
                            <input type="date" class="form-control border-end-0" id="exam_date">
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-calendar"></i>
                            </span>
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label fw-semibold text-muted mb-2">
                            <i class="fas fa-clock me-1"></i>
                            وقت الامتحان
                        </label>
                        <div class="input-group input-group-sm">
                            <input type="time" class="form-control border-end-0" id="exam_time">
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-clock"></i>
                            </span>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Summary Cards -->
            <div class="row mb-4 no-print">
                <div class="col-md-3">
                    <div class="summary-card">
                        <div class="number"><?= number_format(count($students)) ?></div>
                        <div class="label">إجمالي الطلاب</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="summary-card">
                        <div class="number text-success">
                            <?= number_format(count($students) * 4) ?>
                        </div>
                        <div class="label">الحقول المطلوبة</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="summary-card">
                        <div class="number text-warning">
                            <?= number_format(count($students)) ?>
                        </div>
                        <div class="label">توقيعات مطلوبة</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="summary-card">
                        <div class="number" style="font-size: 1.5rem;">
                            <?= $filter_exam_type == 'midterm' ? 'منتصف الفصل' : 'نهاية الفصل' ?>
                        </div>
                        <div class="label">نوع الامتحان</div>
                    </div>
                </div>
            </div>

            <!-- Export and Print Options -->
            <div class="export-options mb-4 no-print">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="text-muted">
                            <i class="fas fa-info-circle me-1"></i>
                            آخر تحديث: <?= date('Y-m-d H:i:s') ?>
                            <?php if ($program_name): ?>
                                | <i class="fas fa-graduation-cap me-1"></i>
                                <?= e($program_name) ?>
                            <?php endif; ?>
                            <?php if ($specialization_name): ?>
                                | <i class="fas fa-microscope me-1"></i>
                                <?= e($specialization_name) ?>
                            <?php endif; ?>
                            <?php if ($semester_display): ?>
                                | <i class="fas fa-calendar-alt me-1"></i>
                                <?= e($semester_display) ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn-export btn-export-excel" onclick="exportToExcel()" <?= empty($students) ? 'disabled' : '' ?>>
                            <i class="fas fa-file-excel me-1"></i>
                            تصدير إكسل
                        </button>
                        <button class="btn-export btn-export-pdf" onclick="printReportPDF()" <?= empty($students) ? 'disabled' : '' ?>>
                            <i class="fas fa-print me-1"></i>
                            طباعة PDF
                        </button>
                    </div>
                </div>
            </div>

            <!-- Students Table -->
            <div class="card card-arabic p-4">
                <div class="d-flex align-items-center mb-3">
                    <h6 class="fw-bold mb-0">
                        <i class="fas fa-file-signature me-2 text-info"></i>
                        سجل حضور الامتحان
                        <span class="chip <?= $filter_exam_type == 'midterm' ? 'primary' : 'red' ?> ms-2">
                            <i class="fas fa-file-alt me-1"></i>
                            <?= $filter_exam_type == 'midterm' ? 'منتصف الفصل' : 'نهاية الفصل' ?>
                        </span>
                        <?php if ($program_name): ?>
                            <span class="chip warning ms-2">
                                <i class="fas fa-graduation-cap me-1"></i>
                                <?= e($program_name) ?>
                            </span>
                        <?php endif; ?>
                        <?php if ($specialization_name): ?>
                            <span class="chip purple ms-2">
                                <i class="fas fa-microscope me-1"></i>
                                <?= e($specialization_name) ?>
                            </span>
                        <?php endif; ?>
                    </h6>
                    <div class="ms-auto">
                        <span class="badge bg-info">
                            <i class="fas fa-users me-1"></i>
                            <?= number_format(count($students)) ?> طالب
                        </span>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-striped student-table" id="studentsTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>رقم الطالب</th>
                                <th>اسم الطالب</th>
                                <th>التخصص</th>
                                <th class="text-center">الحضور</th>
                                <th class="text-center">درجة الامتحان </th>
                                <th class="text-center">المجموع</th>
                                <th class="text-center">توقيع الطالب</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($students)): ?>
                                <tr>
                                    <td colspan="8" class="text-center text-muted py-4">
                                        <i class="fas fa-info-circle me-2"></i>
                                        لا توجد بيانات للعرض بناءً على عوامل التصفية المحددة
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($students as $index => $student): ?>
                                    <tr>
                                        <td class="fw-bold"><?= $index + 1 ?></td>
                                        <td>
                                            <code><?= e($student['student_id']) ?></code>
                                        </td>
                                        <td class="text-right student-name-cell">
                                            <?= e($student['student_name'] ?: $student['student_name_eng']) ?>
                                        </td>
                                        <td>
                                            <?php if (!empty($student['specialization_name'])): ?>
                                                <span class="chip purple">
                                                    <i class="fas fa-microscope me-1"></i>
                                                    <?= e($student['specialization_name']) ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted">—</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center" style="height: 45px; background-color: #f8f9fa; vertical-align: middle;">
                                            <!-- Empty for grade -->
                                        </td>
                                        <td class="text-center" style="height: 45px; background-color: #f8f9fa; vertical-align: middle;">
                                            <!-- Empty for midterm remarks -->
                                        </td>
                                        <td class="text-center" style="height: 45px; background-color: #f8f9fa; vertical-align: middle;">
                                            <!-- Empty for final remarks -->
                                        </td>
                                        <td class="text-center" style="height: 45px; background-color: #f8f9fa; vertical-align: middle;">
                                            <!-- Empty for signature -->
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                    
                    <?php if (count($students) >= 1000): ?>
                        <div class="alert alert-warning mt-3 mb-0">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            تم عرض أول 1000 طالب فقط. الرجاء تضييق نطاق البحث للحصول على نتائج أكثر دقة.
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
        
        <!-- Hidden Print Container -->
      <!-- Hidden Print Container - بدون هيدر مكرر -->
<div class="print-container" id="printContainer">
    <!-- تم إزالة .print-header من هنا لأنه سيتم إضافته في الدالة -->
    <table class="print-table" id="printTable">
        <thead>
            <tr>
                <th width="4%">#</th>
                <th width="12%">رقم الطالب</th>
                <th width="20%">اسم الطالب</th>
                <th width="8%">توقيع الطالب</th>
                <th width="8%">الحضور</th>
                <th width="8%">تمارين</th>
                <th width="8%">عملي</th>
                <th width="8%">نصف فترة</th>
                <th width="8%">نهائي</th>
                <th width="8%">المجموع</th>
                <th width="8%">التقدير</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($students)): ?>
                <tr>
                    <td colspan="12" class="text-center">
                        لا توجد بيانات للعرض
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($students as $index => $student): ?>
                    <tr>
                        <td><?= $index + 1 ?></td>
                        <td><?= e($student['student_id']) ?></td>
                        <td class="text-right">
                            <?= e($student['student_name'] ?: $student['student_name_eng']) ?>
                        </td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>
    </div>

    <!-- Load Scripts with SRI hashes for security -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js" integrity="sha512-rP1IpZR5hXJqDcX6RFsWQN5B15t0Yp15hqB3RrJjU2pW6BVV+V3F5G4GID+LGPL+tgZ5O6K9qL+uE0ztF0xTqw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
    <script>
        // Secure JavaScript with CSP compliance
        (function() {
            'use strict';
            
            // Check if XLSX is loaded
            function isXLSXLoaded() {
                return typeof XLSX !== 'undefined';
            }
            
            // Load XLSX with fallback
            if (!isXLSXLoaded()) {
                const script = document.createElement('script');
                script.src = 'https://cdn.sheetjs.com/xlsx-0.19.2/package/dist/xlsx.full.min.js';
                script.onload = function() {
                    console.log('XLSX loaded successfully');
                };
                script.onerror = function() {
                    console.error('Failed to load XLSX');
                };
                document.head.appendChild(script);
            }
            
            // Auto-submit on college change
            window.loadSections = function(collegeId) {
                const sectionSelect = document.getElementById('filter_section');
                const programSelect = document.getElementById('filter_program');
                const specSelect = document.getElementById('filter_specialization');
                
                if (!collegeId || collegeId === '') {
                    if (sectionSelect) sectionSelect.disabled = true;
                    return;
                }
                
                // Create a form and submit it to reload the page
                const form = document.createElement('form');
                form.method = 'get';
                form.style.display = 'none';
                
                // Add CSRF token
                const csrfInput = document.createElement('input');
                csrfInput.type = 'hidden';
                csrfInput.name = 'csrf';
                csrfInput.value = '<?= e($csrf_token) ?>';
                form.appendChild(csrfInput);
                
                // Add current exam type
                const currentExamType = "<?= e($filter_exam_type) ?>";
                if (currentExamType) {
                    const examTypeInput = document.createElement('input');
                    examTypeInput.type = 'hidden';
                    examTypeInput.name = 'filter_exam_type';
                    examTypeInput.value = currentExamType;
                    form.appendChild(examTypeInput);
                }
                
                // Add current semester
                const currentSemester = "<?= (int)$filter_semester_id ?>";
                if (currentSemester) {
                    const semesterInput = document.createElement('input');
                    semesterInput.type = 'hidden';
                    semesterInput.name = 'filter_semester';
                    semesterInput.value = currentSemester;
                    form.appendChild(semesterInput);
                }
                
                // Add college parameter
                const collegeInput = document.createElement('input');
                collegeInput.type = 'hidden';
                collegeInput.name = 'filter_college';
                collegeInput.value = collegeId;
                form.appendChild(collegeInput);
                
                // Add filter_applied parameter
                const appliedInput = document.createElement('input');
                appliedInput.type = 'hidden';
                appliedInput.name = 'filter_applied';
                appliedInput.value = '1';
                form.appendChild(appliedInput);
                
                // Add current section if exists
                const currentSection = "<?= (int)$filter_section_id ?>";
                if (currentSection) {
                    const sectionInput = document.createElement('input');
                    sectionInput.type = 'hidden';
                    sectionInput.name = 'filter_section';
                    sectionInput.value = currentSection;
                    form.appendChild(sectionInput);
                }
                
                // Add current program if exists
                const currentProgram = "<?= (int)$filter_program_id ?>";
                if (currentProgram) {
                    const programInput = document.createElement('input');
                    programInput.type = 'hidden';
                    programInput.name = 'filter_program';
                    programInput.value = currentProgram;
                    form.appendChild(programInput);
                }
                
                // Add current specialization if exists
                const currentSpec = "<?= (int)$filter_specialization_id ?>";
                if (currentSpec) {
                    const specInput = document.createElement('input');
                    specInput.type = 'hidden';
                    specInput.name = 'filter_specialization';
                    specInput.value = currentSpec;
                    form.appendChild(specInput);
                }
                
                // Add current batch if exists
                const currentBatch = "<?= (int)$filter_batch_id ?>";
                if (currentBatch) {
                    const batchInput = document.createElement('input');
                    batchInput.type = 'hidden';
                    batchInput.name = 'filter_batch';
                    batchInput.value = currentBatch;
                    form.appendChild(batchInput);
                }
                
                document.body.appendChild(form);
                form.submit();
            };
            
            // Load programs when section changes
            window.loadPrograms = function() {
                const collegeId = document.getElementById('filter_college').value;
                const sectionId = document.getElementById('filter_section').value;
                const programSelect = document.getElementById('filter_program');
                const specSelect = document.getElementById('filter_specialization');
                const specHint = document.getElementById('specHint');
                
                // Reset program and specialization selects
                programSelect.innerHTML = '<option value="">جميع البرامج</option>';
                specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                specSelect.disabled = true;
                specHint.innerHTML = 'الرجاء اختيار القسم والبرنامج أولاً';
                
                if (!collegeId || !sectionId) {
                    programSelect.disabled = true;
                    return;
                }
                
                // Create a form and submit it to reload the page with section filter
                const form = document.createElement('form');
                form.method = 'get';
                form.style.display = 'none';
                
                // Add CSRF token
                const csrfInput = document.createElement('input');
                csrfInput.type = 'hidden';
                csrfInput.name = 'csrf';
                csrfInput.value = '<?= e($csrf_token) ?>';
                form.appendChild(csrfInput);
                
                // Add all current parameters
                const urlParams = new URLSearchParams(window.location.search);
                
                // Update section parameter
                urlParams.set('filter_section', sectionId);
                urlParams.set('filter_applied', '1');
                
                // Remove dependent filters
                urlParams.delete('filter_program');
                urlParams.delete('filter_specialization');
                
                // Add each parameter to form
                for (let [key, value] of urlParams.entries()) {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = key;
                    input.value = value;
                    form.appendChild(input);
                }
                
                document.body.appendChild(form);
                form.submit();
            };
            
            // Load specializations based on program and section using AJAX
            window.loadSpecializations = function() {
                const programId = document.getElementById('filter_program').value;
                const sectionId = document.getElementById('filter_section').value;
                const collegeId = document.getElementById('filter_college').value;
                const specSelect = document.getElementById('filter_specialization');
                const specLoading = document.getElementById('specLoading');
                const specHint = document.getElementById('specHint');
                
                // Reset specialization select
                specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                
                if (!programId || !sectionId || !collegeId) {
                    specSelect.disabled = true;
                    specHint.innerHTML = 'الرجاء اختيار القسم والبرنامج أولاً';
                    return;
                }
                
                // Show loading indicator
                specSelect.disabled = true;
                specLoading.style.display = 'block';
                specHint.innerHTML = 'جاري تحميل التخصصات...';
                
                // AJAX request to get specializations
                fetch(`../ajax/get_specializations.php?section_id=${encodeURIComponent(sectionId)}&program_id=${encodeURIComponent(programId)}`)
                    .then(response => response.json())
                    .then(data => {
                        specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                        
                        if (data.length > 0) {
                            data.forEach(spec => {
                                const option = document.createElement('option');
                                option.value = spec.specialization_id;
                                option.textContent = spec.specialization_name_ar;
                                
                                // Check if this specialization was previously selected
                                const urlParams = new URLSearchParams(window.location.search);
                                const selectedSpec = urlParams.get('filter_specialization');
                                if (selectedSpec && selectedSpec == spec.specialization_id) {
                                    option.selected = true;
                                }
                                
                                specSelect.appendChild(option);
                            });
                            specHint.innerHTML = `${data.length} تخصص متاح`;
                        } else {
                            specHint.innerHTML = 'لا توجد تخصصات متاحة لهذا القسم والبرنامج';
                        }
                        
                        specSelect.disabled = false;
                        specLoading.style.display = 'none';
                    })
                    .catch(error => {
                        console.error('Error loading specializations:', error);
                        specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                        specSelect.disabled = false;
                        specLoading.style.display = 'none';
                        specHint.innerHTML = 'حدث خطأ في تحميل التخصصات';
                    });
            };
            
            // Export to Excel function
            window.exportToExcel = function() {
                if (<?= (int)empty($students) ?>) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'تنبيه',
                        text: 'لا توجد بيانات للتصدير',
                        confirmButtonText: 'حسناً',
                        confirmButtonColor: '#3b82f6'
                    });
                    return;
                }
                
                // Show loading
                Swal.fire({
                    title: 'جاري التصدير...',
                    text: 'الرجاء الانتظار',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                try {
                    // التحقق من وجود المكتبة
                    if (!isXLSXLoaded()) {
                        throw new Error('مكتبة Excel غير محملة');
                    }
                    
                    // Get exam information with sanitization
                    const roomName = sanitizeInput(document.getElementById('room_name')?.value) || 'غير محدد';
                    const examName = sanitizeInput(document.getElementById('exam_name')?.value) || 'غير محدد';
                    const examDate = document.getElementById('exam_date')?.value || 'غير محدد';
                    const examTime = document.getElementById('exam_time')?.value || 'غير محدد';
                    const examType = "<?= $filter_exam_type == 'midterm' ? 'منتصف الفصل' : 'نهاية الفصل' ?>";
                    const semesterName = "<?= e($semester_display) ?>";
                    
                    // Get the table
                    const table = document.getElementById('studentsTable');
                    
                    if (!table) {
                        throw new Error('الجدول غير موجود');
                    }
                    
                    // Prepare data array for Excel
                    const data = [];
                    
                    // Add header information
                    data.push(['سجل حضور الامتحان - ' + examType]);
                    data.push(['اسم القاعة: ' + roomName + ' | اسم المادة: ' + examName]);
                    data.push(['تاريخ الامتحان: ' + examDate + ' | وقت الامتحان: ' + examTime]);
                    data.push(['الفصل الدراسي: ' + semesterName]);
                    data.push([]); // Empty row
                    
                    // Get table headers
                    const headers = [];
                    const headerCells = table.querySelectorAll('thead th');
                    headerCells.forEach(cell => {
                        headers.push(cell.textContent.trim());
                    });
                    data.push(headers);
                    
                    // Get table rows
                    let rowCount = 0;
                    const rows = table.querySelectorAll('tbody tr');
                    rows.forEach(row => {
                        const rowData = [];
                        const cells = row.querySelectorAll('td');
                        cells.forEach(cell => {
                            // Remove any inner HTML and get clean text
                            rowData.push(cell.textContent.trim());
                        });
                        if (rowData.length > 0 && rowData[0] !== '') {
                            data.push(rowData);
                            rowCount++;
                        }
                    });
                    
                    if (rowCount === 0) {
                        throw new Error('لا توجد بيانات في الجدول');
                    }
                    
                    // Create worksheet
                    const wb = XLSX.utils.book_new();
                    const ws = XLSX.utils.aoa_to_sheet(data);
                    
                    // Set column widths
                    const wscols = [
                        {wch: 5},   // #
                        {wch: 15},  // Student ID
                        {wch: 30},  // Student Name
                        {wch: 20},  // Specialization
                        {wch: 12},  // Grade
                        {wch: 15},  // Year Work
                        {wch: 12},  // Total
                        {wch: 15},  // Signature
                    ];
                    ws['!cols'] = wscols;
                    
                    // Add worksheet to workbook
                    XLSX.utils.book_append_sheet(wb, ws, "سجل حضور الامتحان");
                    
                    // Generate filename
                    let filename = "سجل_حضور_الامتحان";
                    <?php if ($program_name): ?>
                        filename += "_" + sanitizeFilename("<?= e($program_name) ?>");
                    <?php endif; ?>
                    <?php if ($specialization_name): ?>
                        filename += "_" + sanitizeFilename("<?= e($specialization_name) ?>");
                    <?php endif; ?>
                    <?php if ($semester_display): ?>
                        filename += "_" + sanitizeFilename("<?= e($semester_display) ?>");
                    <?php endif; ?>
                    filename += "_<?= date('Y-m-d') ?>.xlsx";
                    
                    // Close loading
                    Swal.close();
                    
                    // Save the file
                    XLSX.writeFile(wb, filename);
                    
                    // Show success message
                    Swal.fire({
                        icon: 'success',
                        title: 'تم التصدير',
                        text: 'تم تصدير ' + rowCount + ' طالب بنجاح',
                        timer: 2000,
                        showConfirmButton: false
                    });
                    
                } catch (error) {
                    console.error('Excel export error:', error);
                    
                    // Close loading
                    Swal.close();
                    
                    // Show user-friendly error message
                    Swal.fire({
                        icon: 'error',
                        title: 'خطأ في التصدير',
                        text: error.message || 'حدث خطأ في تصدير البيانات',
                        confirmButtonText: 'حسناً',
                        confirmButtonColor: '#ef4444'
                    });
                    
                    // Try alternative export method
                    setTimeout(() => {
                        exportToCSV();
                    }, 500);
                }
            };
            
            // Alternative CSV export method
            window.exportToCSV = function() {
                try {
                    const table = document.getElementById('studentsTable');
                    if (!table) return;
                    
                    let csv = [];
                    
                    // Add headers
                    const headers = [];
                    table.querySelectorAll('thead th').forEach(th => {
                        headers.push('"' + th.textContent.trim() + '"');
                    });
                    csv.push(headers.join(','));
                    
                    // Add rows
                    let rowCount = 0;
                    table.querySelectorAll('tbody tr').forEach(tr => {
                        const row = [];
                        tr.querySelectorAll('td').forEach(td => {
                            row.push('"' + td.textContent.trim().replace(/"/g, '""') + '"');
                        });
                        if (row.length > 0 && row[0] !== '""') {
                            csv.push(row.join(','));
                            rowCount++;
                        }
                    });
                    
                    if (rowCount === 0) {
                        Swal.fire({
                            icon: 'warning',
                            title: 'تنبيه',
                            text: 'لا توجد بيانات في الجدول',
                            confirmButtonText: 'حسناً'
                        });
                        return;
                    }
                    
                    // Create download link
                    const blob = new Blob(["\uFEFF" + csv.join('\n')], { type: 'text/csv;charset=utf-8;' });
                    const link = document.createElement('a');
                    const url = URL.createObjectURL(blob);
                    link.href = url;
                    link.setAttribute('download', 'export.csv');
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    URL.revokeObjectURL(url);
                    
                    Swal.fire({
                        icon: 'info',
                        title: 'تم التصدير بصيغة CSV',
                        text: 'تم تصدير ' + rowCount + ' طالب بصيغة CSV',
                        confirmButtonText: 'حسناً',
                        confirmButtonColor: '#3b82f6'
                    });
                } catch (e) {
                    console.error('CSV export error:', e);
                    Swal.fire({
                        icon: 'error',
                        title: 'خطأ',
                        text: 'فشل تصدير البيانات',
                        confirmButtonText: 'حسناً'
                    });
                }
            };
            
            // PDF Print function
          // PDF Print function with banner - نسخة مصححة (بدون تكرار الهيدر)
window.printReportPDF = function() {
    if (<?= (int)empty($students) ?>) {
        Swal.fire({
            icon: 'warning',
            title: 'تنبيه',
            text: 'لا توجد بيانات للطباعة',
            confirmButtonText: 'حسناً'
        });
        return;
    }
    
    try {
        // Get exam information
        const roomName = sanitizeInput(document.getElementById('room_name')?.value) || 'غير محدد';
        const examName = sanitizeInput(document.getElementById('exam_name')?.value) || 'غير محدد';
        const examDate = document.getElementById('exam_date')?.value || 'غير محدد';
        const examTime = document.getElementById('exam_time')?.value || 'غير محدد';
        const examType = "<?= $filter_exam_type == 'midterm' ? 'منتصف الفصل' : 'نهاية الفصل' ?>";
        const semesterName = "<?= e($semester_display) ?>";
        
        // Create a new window for printing
        const printWindow = window.open('', '_blank', 'width=1200,height=800');
        
        if (!printWindow) {
            Swal.fire({
                icon: 'error',
                title: 'خطأ',
                text: 'الرجاء السماح بالنوافذ المنبثقة',
                confirmButtonText: 'حسناً'
            });
            return;
        }
        
        // Get the print container HTML (الجدول فقط بدون الهيدر)
        const printContainer = document.getElementById('printContainer').innerHTML;
        
        // Create exam info (هذا هو الهيدر الخاص بالطباعة)
        const printInfo = `
            <div class="print-header">
                <img src="../img/banar3.jpg" alt="Banner" class="banner-img" onerror="this.style.display='none'">
                <h2>تقرير حضور الامتحان</h2>
                <div class="print-info">
                    نوع الامتحان: ${examType}<br>
                    الفصل الدراسي: ${semesterName}<br>
                    اسم القاعة: ${roomName} | اسم المادة: ${examName}<br>
                    تاريخ الامتحان: ${examDate} | وقت الامتحان: ${examTime}<br>
                    <?php if ($college_name): ?>الكلية: <?= e($college_name) ?><br><?php endif; ?>
                    <?php if ($section_name): ?>القسم: <?= e($section_name) ?><br><?php endif; ?>
                    <?php if ($program_name): ?>البرنامج: <?= e($program_name) ?><br><?php endif; ?>
                    <?php if ($specialization_name): ?>التخصص: <?= e($specialization_name) ?><br><?php endif; ?>
                </div>
            </div>
        `;
        
        // Create the print content - مع إزالة الهيدر المكرر من printContainer
        const fullContent = `
            <!DOCTYPE html>
            <html dir="rtl">
            <head>
                <meta charset="UTF-8">
                <title>تقرير حضور الامتحان</title>
                <style>
                    @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap');
                    
                    * {
                        font-family: 'Cairo', sans-serif !important;
                        box-sizing: border-box;
                    }
                    
                    body {
                        margin: 0;
                        padding: 15mm;
                        direction: rtl;
                        background: white;
                        font-size: 12px;
                    }
                    
                    .print-header {
                        text-align: center;
                        margin-bottom: 20px;
                        padding-bottom: 10px;
                    }
                    
                    .banner-img {
                        max-width: 100%;
                        height: auto;
                        margin-bottom: 15px;
                    }
                    
                    .print-header h2 {
                        font-size: 20px;
                        margin: 5px 0;
                        font-weight: bold;
                        color: #000;
                    }
                    
                    .print-info {
                        font-size: 11px;
                        color: #666;
                        margin-top: 10px;
                        line-height: 1.6;
                        text-align: center;
                    }
                    
                    .print-table {
                        width: 100%;
                        border-collapse: collapse;
                        font-size: 10px;
                        margin-top: 15px;
                    }
                    
                    .print-table th {
                        background-color: #f0f0f0;
                        border: 1px solid #000;
                        padding: 8px 5px;
                        font-weight: bold;
                        text-align: center;
                        font-size: 11px;
                    }
                    
                    .print-table td {
                        border: 1px solid #000;
                        padding: 6px 5px;
                        text-align: center;
                    }
                    
                    .print-table .text-right {
                        text-align: right;
                        padding-right: 10px;
                    }
                    
                    .print-footer {
                        margin-top: 20px;
                        padding-top: 10px;
                        border-top: 1px solid #666;
                        font-size: 10px;
                        text-align: center;
                        color: #666;
                        line-height: 1.6;
                    }
                    
                    /* إخفاء أي عناصر زائدة من printContainer */
                    .print-container .print-header {
                        display: none !important;
                    }
                    
                    @media print {
                        @page {
                            size: A4 landscape;
                            margin: 15mm;
                        }
                        
                        body { 
                            margin: 0;
                            padding: 0;
                        }
                        
                        .print-table {
                            font-size: 9px;
                        }
                        
                        .print-table th, 
                        .print-table td {
                            padding: 5px 3px;
                        }
                        
                        /* إخفاء أي عناصر زائدة عند الطباعة */
                        .print-container .print-header {
                            display: none !important;
                        }
                    }
                </style>
            </head>
            <body>
                <!-- هذا هو الهيدر الرئيسي (مرة واحدة فقط) -->
                ${printInfo}
                
                <!-- هذا هو الجدول من printContainer (بدون الهيدر المكرر) -->
                <div class="print-container">
                    ${printContainer}
                </div>
                
                <div class="print-footer">
                    تم إنشاء التقرير تلقائياً من نظام إدارة القبول والتسجيل<br>
                    الصفحة 1 من 1
                </div>
            </body>
            </html>
        `;
        
        printWindow.document.write(fullContent);
        printWindow.document.close();
        
        // Trigger print after content is loaded
        printWindow.onload = function() {
            setTimeout(function() {
                printWindow.focus();
                printWindow.print();
            }, 500);
        };
        
    } catch (error) {
        console.error('Print error:', error);
        Swal.fire({
            icon: 'error',
            title: 'خطأ في الطباعة',
            text: 'حدث خطأ في طباعة التقرير',
            confirmButtonText: 'حسناً'
        });
    }
};
            
            // Helper function to sanitize input
            function sanitizeInput(input) {
                if (!input) return '';
                return input.replace(/[<>"']/g, '');
            }
            
            // Helper function to sanitize filename
            function sanitizeFilename(filename) {
                return filename.replace(/[<>:"/\\|?*]+/g, '_').replace(/\s+/g, '_');
            }
            
            // Initialize when page loads
            document.addEventListener('DOMContentLoaded', function() {
                const collegeSelect = document.getElementById('filter_college');
                const sectionSelect = document.getElementById('filter_section');
                const programSelect = document.getElementById('filter_program');
                
                // Enable/disable section select based on college selection
                if (collegeSelect && sectionSelect) {
                    sectionSelect.disabled = !collegeSelect.value;
                }
                
                // Load saved exam info from localStorage (with sanitization)
                try {
                    const savedRoom = localStorage.getItem('exam_room');
                    const savedExam = localStorage.getItem('exam_name');
                    const savedDate = localStorage.getItem('exam_date');
                    const savedTime = localStorage.getItem('exam_time');
                    
                    if (savedRoom) document.getElementById('room_name').value = sanitizeInput(savedRoom);
                    if (savedExam) document.getElementById('exam_name').value = sanitizeInput(savedExam);
                    if (savedDate) document.getElementById('exam_date').value = savedDate;
                    if (savedTime) document.getElementById('exam_time').value = savedTime;
                } catch (e) {
                    console.error('Error loading from localStorage:', e);
                }
                
                // Save exam info when they change (with sanitization)
                document.getElementById('room_name')?.addEventListener('input', function() {
                    try {
                        localStorage.setItem('exam_room', sanitizeInput(this.value));
                    } catch (e) {}
                });
                
                document.getElementById('exam_name')?.addEventListener('input', function() {
                    try {
                        localStorage.setItem('exam_name', sanitizeInput(this.value));
                    } catch (e) {}
                });
                
                document.getElementById('exam_date')?.addEventListener('input', function() {
                    try {
                        localStorage.setItem('exam_date', this.value);
                    } catch (e) {}
                });
                
                document.getElementById('exam_time')?.addEventListener('input', function() {
                    try {
                        localStorage.setItem('exam_time', this.value);
                    } catch (e) {}
                });
                
                // Trigger specialization load if program and section are selected
                <?php if ($filter_program_id && $filter_program_id > 0 && $filter_section_id && $filter_section_id > 0 && $filter_college_id && $filter_college_id > 0): ?>
                    loadSpecializations();
                <?php endif; ?>
            });
        })();
    </script>
</body>
</html>
