<?php
// medical_certificate_dashboard.php - نسخة محسنة بالكامل مع فلتر التخصص وحماية SQL Injection
error_reporting(E_ALL);
ini_set('display_errors', 1);

require 'db.php';
require 'helpers.php';
require_committee(); // Using same authentication as committee

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

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

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

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

function validateSearchQuery($value) {
    if ($value === null) return '';
    $value = trim((string)$value);
    // Allow only alphanumeric, spaces, and basic punctuation for search
    $value = preg_replace('/[^\p{L}\p{N}\s\-_\.]/u', '', $value);
    return substr($value, 0, 100);
}

// Generate CSRF token for forms
if (!function_exists('csrf_token')) {
    function csrf_token() {
        return $_SESSION['csrf'] = $_SESSION['csrf'] ?? bin2hex(random_bytes(32));
    }
}
$csrf_token = csrf_token();

// ==================== FILTER PARAMETERS (SANITIZED) ====================
$college_id = isset($_GET['college_id']) && $_GET['college_id'] !== '' ? validateInt($_GET['college_id']) : null;
$section_id = isset($_GET['section_id']) && $_GET['section_id'] !== '' ? validateInt($_GET['section_id']) : null;
$batch_id = isset($_GET['batch_id']) && $_GET['batch_id'] !== '' ? validateInt($_GET['batch_id']) : null;
$program_id = isset($_GET['program_id']) && $_GET['program_id'] !== '' ? validateInt($_GET['program_id']) : null;
$specialization_id = isset($_GET['specialization_id']) && $_GET['specialization_id'] !== '' ? validateInt($_GET['specialization_id']) : null;
$show_all = isset($_GET['show_all']) && $_GET['show_all'] === '1';
$search_query = isset($_GET['search']) ? validateSearchQuery($_GET['search']) : '';

// ==================== SCOPE WHERE - For single college system ====================
$where = " WHERE 1=1 ";
$types = ''; 
$params = [];

if (!$canAll && $scopeCollege !== null) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i'; 
    $params[] = $scopeCollege;
    // Auto-set the college filter if user has scope restriction
    if (!$college_id) {
        $college_id = $scopeCollege;
    }
} elseif (!$canAll && $scopeCollege === null) {
    $where .= " AND 1=0 ";
}

// Apply college filter
if ($college_id !== null) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i';
    $params[] = $college_id;
}

// Apply section filter
if ($section_id !== null) {
    $where .= " AND s.section_id = ? ";
    $types .= 'i';
    $params[] = $section_id;
}

// Apply batch filter
if ($batch_id !== null) {
    $where .= " AND s.batch_id = ? ";
    $types .= 'i';
    $params[] = $batch_id;
}

// Apply program filter
if ($program_id !== null) {
    $where .= " AND s.program_id = ? ";
    $types .= 'i';
    $params[] = $program_id;
}

// Apply specialization filter
if ($specialization_id !== null) {
    $where .= " AND s.specialization_id = ? ";
    $types .= 'i';
    $params[] = $specialization_id;
}

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

// Only show accepted students for card printing
$where .= " AND s.interview_status = 'accepted' AND s.medically_fit = 1 ";

// ==================== GET FILTER OPTIONS (SECURE) ====================

// Colleges
$colleges = [];
$college_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
if ($college_stmt) {
    $college_stmt->execute();
    $colleges = $college_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $college_stmt->close();
}

// Sections - based on selected college
$sections = [];
if ($college_id) {
    $section_stmt = $mysqli1->prepare("SELECT id, name FROM sections WHERE parent = ? AND deleted_at IS NULL ORDER BY name");
    if ($section_stmt) {
        $section_stmt->bind_param('i', $college_id);
        $section_stmt->execute();
        $sections = $section_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $section_stmt->close();
    }
} else {
    // Get all sections if no college selected
    $section_stmt = $mysqli1->prepare("SELECT id, name FROM sections WHERE deleted_at IS NULL ORDER BY name");
    if ($section_stmt) {
        $section_stmt->execute();
        $sections = $section_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $section_stmt->close();
    }
}

// Batches
$batches = [];
$batch_stmt = $mysqli1->prepare("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY value DESC");
if ($batch_stmt) {
    $batch_stmt->execute();
    $batches = $batch_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $batch_stmt->close();
}

// Programs
$programs = [];
$program_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
if ($program_stmt) {
    $program_stmt->execute();
    $programs = $program_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $program_stmt->close();
}

// Get specializations based on selected program and section
$specializations = [];
if ($program_id && $section_id) {
    $spec_stmt = $mysqli1->prepare("
        SELECT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE program_id = ? AND section_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ");
    if ($spec_stmt) {
        $spec_stmt->bind_param('ii', $program_id, $section_id);
        $spec_stmt->execute();
        $specializations = $spec_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $spec_stmt->close();
    }
} elseif ($program_id) {
    // Get specializations by program only
    $spec_stmt = $mysqli1->prepare("
        SELECT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ");
    if ($spec_stmt) {
        $spec_stmt->bind_param('i', $program_id);
        $spec_stmt->execute();
        $specializations = $spec_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $spec_stmt->close();
    }
} elseif ($section_id) {
    // Get specializations by section only
    $spec_stmt = $mysqli1->prepare("
        SELECT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ");
    if ($spec_stmt) {
        $spec_stmt->bind_param('i', $section_id);
        $spec_stmt->execute();
        $specializations = $spec_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $spec_stmt->close();
    }
}

// ==================== GET STUDENTS FOR CARD PRINTING (SECURE) ====================
$students = [];
$student_count = 0;

if ($show_all || $college_id || $section_id || $batch_id || $program_id || $specialization_id || $search_query !== '') {
    // Build the query with all joins
    $sqlStudents = "
        SELECT 
            s.student_id, 
            s.student_name, 
            s.student_name_eng,
            s.gender,
            s.national_id,
            s.phone_number,
            s.email,
            s.college_id,
            s.section_id,
            s.batch_id,
            s.program_id,
            s.specialization_id,
            s.interview_status,
            s.medically_fit,
            s.profile_completed,
            sec.name AS section_name,
            b.value AS batch_name,
            c.name AS college_name,
            p.name AS program_name,
            sp.specialization_name_ar AS specialization_name
        FROM students s
        LEFT JOIN sections sec ON sec.id = s.section_id
        LEFT JOIN batches b ON b.id = s.batch_id
        LEFT JOIN colleges c ON c.id = s.college_id
        LEFT JOIN programs p ON p.id = s.program_id
        LEFT JOIN specializations sp ON sp.specialization_id = s.specialization_id
        {$where}
        ORDER BY s.student_id DESC
        LIMIT 350
    ";
    
    // Prepare and execute statement
    $stmt = $mysqli1->prepare($sqlStudents);
    
    if ($stmt) {
        if ($types !== '') {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $student_count = count($students);
        $stmt->close();
    }
}

// ==================== GET ENROLLMENT STATUS FOR STUDENTS ====================
$enrolled_count = 0;
$student_enrollment = [];

if ($student_count > 0) {
    // Get enrollment data for all students in one query (more efficient)
    $student_ids = array_column($students, 'student_id');
    $placeholders = implode(',', array_fill(0, count($student_ids), '?'));
    $enroll_types = str_repeat('s', count($student_ids));
    
    $enroll_stmt = $mysqli1->prepare("
        SELECT student_id, MAX(semester_id) as max_semester 
        FROM registrations 
        WHERE student_id IN ({$placeholders}) 
        GROUP BY student_id
    ");
    
    if ($enroll_stmt) {
        $enroll_stmt->bind_param($enroll_types, ...$student_ids);
        $enroll_stmt->execute();
        $enroll_result = $enroll_stmt->get_result();
        while ($row = $enroll_result->fetch_assoc()) {
            $student_enrollment[$row['student_id']] = $row['max_semester'];
            $enrolled_count++;
        }
        $enroll_stmt->close();
    }
}

// ==================== UI ====================
include 'header.php';
?>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

<style>
    body, h1,h2,h3,h4,h5,h6, p, a, button, label { 
        font-family: 'Cairo', sans-serif !important; 
    }
    .dash-card {
        border: 1px solid #e5e7eb;
        border-radius: 16px;
        padding: 20px;
        background: #fff;
        box-shadow: 0 10px 24px rgba(0,0,0,.06);
        margin-bottom: 20px;
    }
    .filter-card {
        background: linear-gradient(135deg, #f8f9fa, #e9ecef);
    }
    .btn-primary { 
        background: linear-gradient(135deg, #f39c12, #e67e22);
        border: none;
        font-weight: 600;
    }
    .btn-primary:hover {
        background: linear-gradient(135deg, #e67e22, #f39c12);
        transform: translateY(-1px);
    }
    .btn-success { 
        background: linear-gradient(135deg, #27ae60, #2ecc71);
        border: none;
        font-weight: 600;
    }
    .btn-success:hover {
        background: linear-gradient(135deg, #2ecc71, #27ae60);
        transform: translateY(-1px);
    }
    .btn-info {
        background: linear-gradient(135deg, #2596be, #2596be);
        border: none;
        font-weight: 600;
    }
    .btn-info:hover {
        background: linear-gradient(135deg, #2596be, #2596be);
        transform: translateY(-1px);
    }
    .btn-warning {
        background: linear-gradient(135deg, #f59e0b, #d97706);
        border: none;
        font-weight: 600;
        color: white;
    }
    .btn-warning:hover {
        background: linear-gradient(135deg, #d97706, #f59e0b);
        transform: translateY(-1px);
        color: white;
    }
    .chip {
        display: inline-block;
        padding: 0.2rem 0.5rem;
        border-radius: 999px;
        font-size: 0.85rem;
        font-weight: 600;
    }
    .chip.green { background: #d1fae5; color: #065f46; }
    .chip.blue { background: #dbeafe; color: #1e3a8a; }
    .chip.purple { background: #e9d5ff; color: #7e22ce; }
    .chip.orange { background: #fed7aa; color: #9a3412; }
    .chip.red { background: #fecaca; color: #991b1b; }
    .chip.teal { background: #99f6e4; color: #115e59; }
    .chip.yellow { background: #fef3c7; color: #92400e; }
    .chip.specialization { background: #f3e8ff; color: #6b21a8; }
    .student-card {
        border: 2px solid #e5e7eb;
        border-radius: 12px;
        padding: 15px;
        margin-bottom: 15px;
        background: white;
        transition: all 0.3s ease;
    }
    .student-card:hover {
        border-color: #f39c12;
        box-shadow: 0 5px 15px rgba(243, 156, 18, 0.1);
    }
    .student-card.selected {
        border-color: #27ae60;
        background: #f0f9ff;
    }
    .student-card.print-selected {
        border-color: #f59e0b;
        background: #fff7ed;
        animation: pulse 2s infinite;
    }
    @keyframes pulse {
        0% { box-shadow: 0 0 0 0 rgba(245, 158, 11, 0.4); }
        70% { box-shadow: 0 0 0 10px rgba(245, 158, 11, 0); }
        100% { box-shadow: 0 0 0 0 rgba(245, 158, 11, 0); }
    }
    .form-select, .form-control {
        border-radius: 10px;
        border: 1px solid #d1d5db;
        padding: 10px;
    }
    .form-select:focus, .form-control:focus {
        border-color: #f39c12;
        box-shadow: 0 0 0 0.2rem rgba(243, 156, 18, 0.25);
    }
    .status-badge {
        font-size: 0.75rem;
        padding: 0.2rem 0.5rem;
        border-radius: 4px;
    }
    .badge-accepted { background: #d1fae5; color: #065f46; }
    .badge-medical { background: #dbeafe; color: #1e3a8a; }
    .badge-pending { background: #fef3c7; color: #92400e; }
    .badge-rejected { background: #fecaca; color: #991b1b; }
    .filter-row {
        margin-bottom: 15px;
    }
    .student-info-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 10px;
    }
    .database-info {
        background: #e8f4fd;
        border-left: 4px solid #2596be;
        padding: 10px;
        border-radius: 8px;
        margin-bottom: 15px;
    }
    .enrollment-status {
        padding: 8px 12px;
        border-radius: 8px;
        font-weight: 600;
        display: inline-block;
    }
    .enrollment-registered { background: #d1fae5; color: #065f46; }
    .enrollment-not-registered { background: #fef3c7; color: #92400e; }
    .semester-badge {
        background: #6366f1;
        color: white;
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 600;
    }
    .selection-counter {
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: linear-gradient(135deg, #f59e0b, #d97706);
        color: white;
        padding: 15px 20px;
        border-radius: 12px;
        box-shadow: 0 8px 25px rgba(245, 158, 11, 0.3);
        z-index: 1000;
        display: none;
        align-items: center;
        gap: 10px;
        animation: slideIn 0.3s ease;
    }
    @keyframes slideIn {
        from { transform: translateY(100px); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
    }
    .print-badge {
        background: linear-gradient(135deg, #f59e0b, #d97706);
        color: white;
        padding: 5px 15px;
        border-radius: 20px;
        font-size: 0.9rem;
        font-weight: 600;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        margin-left: 10px;
    }
    .action-buttons {
        position: sticky;
        top: 10px;
        background: white;
        padding: 15px;
        border-radius: 12px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        z-index: 100;
        margin-bottom: 20px;
    }
    .toast-container {
        z-index: 2000;
    }
    .serial-number {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        padding: 2px 8px;
        border-radius: 20px;
        font-size: 0.75rem;
        font-weight: 600;
        display: inline-block;
    }
    .student-index {
        background: #f3f4f6;
        border-radius: 50%;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        color: #4b5563;
    }
</style>

<div class="container py-4" dir="rtl">
    <!-- CSRF Token -->
    <input type="hidden" id="csrf_token" value="<?= htmlspecialchars($csrf_token, ENT_QUOTES, 'UTF-8') ?>">
    
    <!-- Header -->
    <div class="d-flex align-items-center mb-4">
        <div>
            <h3 class="fw-bold mb-1"><i class="fas fa-id-card me-2" style="color: #f59e0b;"></i>نظام شهادات الأرانيك المرضية</h3>
            <p class="text-muted mb-0">إدارة وطباعة الأرانيك الطبية للطلاب المقبولين واللائقين طبياً</p>
        </div>
        <div class="ms-auto">
            <span class="chip orange">مرحباً، <?= htmlspecialchars($committeeName ?: 'مسؤول الشهادات', ENT_QUOTES, 'UTF-8') ?></span>
            <a href="committee_dashboard.php" class="btn btn-sm btn-outline-secondary ms-2">
                <i class="fas fa-home me-1"></i>لوحة التحكم
            </a>
        </div>
    </div>

    <!-- Action Buttons (Sticky) -->
    <div class="action-buttons">
        <div class="d-flex flex-wrap align-items-center gap-2">
            <span class="fw-bold text-primary"><i class="fas fa-bolt me-2"></i>أدوات سريعة:</span>
            <button type="button" class="btn btn-sm btn-primary" onclick="selectAllStudents()">
                <i class="fas fa-check-square me-1"></i>تحديد الكل
            </button>
            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="deselectAllStudents()">
                <i class="fas fa-times-circle me-1"></i>إلغاء الكل
            </button>
            <button type="button" class="btn btn-sm btn-warning" onclick="printMedicalCertificates()">
                <i class="fas fa-print me-1"></i>طباعة الأرانيك المرضية
            </button>
            <button type="button" class="btn btn-sm btn-outline-info" onclick="showReportHelp()">
                <i class="fas fa-question-circle me-1"></i>مساعدة
            </button>
            <div class="ms-auto">
                <span id="selectedCountBadge" class="print-badge" style="display: none;">
                    <i class="fas fa-users me-1"></i>
                    <span id="selectedCount">0</span> طالب محدد
                </span>
            </div>
        </div>
    </div>

    <!-- Filters Card -->
    <div class="dash-card filter-card">
        <h5 class="fw-bold mb-3"><i class="fas fa-filter me-2"></i>تصفية الطلاب</h5>
        
        <form method="get" class="row g-3" id="filterForm">
            <!-- CSRF Token for form -->
            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf_token, ENT_QUOTES, 'UTF-8') ?>">
            
            <!-- College Filter -->
            <div class="col-md-2">
                <label class="form-label fw-semibold"><i class="fas fa-university me-1"></i> الكلية</label>
                <select name="college_id" class="form-select" id="collegeSelect" onchange="this.form.submit()">
                    <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'] ?>" <?= $college_id == $college['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Section Filter -->
            <div class="col-md-2">
                <label class="form-label fw-semibold"><i class="fas fa-layer-group me-1"></i> القسم/الشعبة</label>
                <select name="section_id" class="form-select" id="sectionSelect" onchange="this.form.submit()" <?= !$college_id ? 'disabled' : '' ?>>
                    <option value="">جميع الأقسام</option>
                    <?php foreach ($sections as $section): ?>
                        <option value="<?= (int)$section['id'] ?>" <?= $section_id == $section['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($section['name'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <?php if (!$college_id): ?>
                    <small class="text-muted"><i class="fas fa-info-circle me-1"></i>الرجاء اختيار كلية أولاً</small>
                <?php endif; ?>
            </div>

            <!-- Program Filter -->
            <div class="col-md-2">
                <label class="form-label fw-semibold"><i class="fas fa-graduation-cap me-1"></i> البرنامج</label>
                <select name="program_id" class="form-select" id="programSelect" onchange="this.form.submit()">
                    <option value="">جميع البرامج</option>
                    <?php foreach ($programs as $program): ?>
                        <option value="<?= (int)$program['id'] ?>" <?= $program_id == $program['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($program['name'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Specialization Filter -->
            <div class="col-md-2">
                <label class="form-label fw-semibold"><i class="fas fa-microscope me-1"></i> التخصص</label>
                <select name="specialization_id" class="form-select" id="specializationSelect" <?= (!$program_id && !$section_id) ? 'disabled' : '' ?>>
                    <option value="">جميع التخصصات</option>
                    <?php foreach ($specializations as $spec): ?>
                        <option value="<?= (int)$spec['specialization_id'] ?>" <?= $specialization_id == $spec['specialization_id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($spec['specialization_name_ar'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <small class="text-muted spec-hint" id="specHint">
                    <?php if (!$program_id && !$section_id): ?>
                        الرجاء اختيار البرنامج أو القسم أولاً
                    <?php endif; ?>
                </small>
            </div>

            <!-- Batch Filter -->
            <div class="col-md-2">
                <label class="form-label fw-semibold"><i class="fas fa-users me-1"></i> الدفعة</label>
                <select name="batch_id" class="form-select">
                    <option value="">جميع الدفعات</option>
                    <?php foreach ($batches as $batch): ?>
                        <option value="<?= (int)$batch['id'] ?>" <?= $batch_id == $batch['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($batch['value'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Search -->
            <div class="col-md-2">
                <label class="form-label fw-semibold"><i class="fas fa-search me-1"></i> بحث سريع</label>
                <input type="text" name="search" class="form-control" placeholder="ابحث بالاسم أو رقم الطالب..." 
                       value="<?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?>">
            </div>

            <!-- Status Filters -->
            <div class="col-12">
                <div class="d-flex gap-2">
                    <span class="badge badge-accepted">✓ مقبول</span>
                    <span class="badge badge-medical">⚕️ لائق طبياً</span>
                    <span class="text-muted me-2">(يتم عرض المقبولين واللائقين طبياً فقط)</span>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="col-12">
                <div class="d-flex gap-2">
                    <button type="submit" name="show_all" value="1" class="btn btn-primary">
                        <i class="fas fa-eye me-1"></i> عرض الطلاب
                    </button>
                    <button type="submit" class="btn btn-outline-primary">
                        <i class="fas fa-sync-alt me-1"></i> تطبيق التصفية
                    </button>
                    <a href="medical_certificate_dashboard.php" class="btn btn-outline-danger">
                        <i class="fas fa-times me-1"></i> مسح الكل
                    </a>
                    <div class="ms-auto">
                        <button type="button" class="btn btn-outline-warning" onclick="printMedicalCertificates()">
                            <i class="fas fa-id-card me-1"></i> طباعة الأرانيك المرضية
                        </button>
                        <button type="button" class="btn btn-outline-info" onclick="showReportHelp()">
                            <i class="fas fa-question-circle me-1"></i> مساعدة
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- Results Summary -->
    <?php if ($show_all || $student_count > 0): ?>
    <div class="dash-card">
        <div class="d-flex align-items-center justify-content-between mb-3">
            <h5 class="fw-bold mb-0">
                <i class="fas fa-list me-2"></i>نتائج البحث 
                <span class="badge bg-primary fs-6"><?= number_format($student_count) ?> طالب</span>
            </h5>
            <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-primary" onclick="selectAllStudents()">
                    <i class="fas fa-check-square me-1"></i>تحديد الكل
                </button>
                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="deselectAllStudents()">
                    <i class="fas fa-times-circle me-1"></i>إلغاء الكل
                </button>
                <button type="button" class="btn btn-sm btn-warning" onclick="printMedicalCertificates()">
                    <i class="fas fa-print me-1"></i>طباعة الأرانيك
                </button>
            </div>
        </div>

        <!-- Quick Stats -->
        <?php if ($student_count > 0): ?>
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card border-0 bg-light">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-1"><i class="fas fa-user-graduate me-1"></i>طلاب مسجلين</h6>
                        <h4 class="fw-bold text-success"><?= $enrolled_count ?></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 bg-light">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-1"><i class="fas fa-user-clock me-1"></i>طلاب غير مسجلين</h6>
                        <h4 class="fw-bold text-warning"><?= $student_count - $enrolled_count ?></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 bg-light">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-1"><i class="fas fa-file-check me-1"></i>ملفات مكتملة</h6>
                        <h4 class="fw-bold text-info">
                            <?= count(array_filter($students, function($s) { return ($s['profile_completed'] ?? 0) == 1; })) ?>
                        </h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 bg-light">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-1"><i class="fas fa-chart-line me-1"></i>حد العرض</h6>
                        <h4 class="fw-bold text-primary">350</h4>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Students List with Serial Numbers -->
        <div id="studentsContainer">
            <?php if ($student_count > 0): ?>
                <?php $counter = 1; // Initialize counter ?>
                <?php foreach ($students as $student): ?>
                    <?php
                    $is_enrolled = isset($student_enrollment[$student['student_id']]);
                    $max_semester = $is_enrolled ? $student_enrollment[$student['student_id']] : null;
                    ?>
                    <div class="student-card" data-student-id="<?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?>" 
                         data-college-id="<?= htmlspecialchars($student['college_id'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                         data-section-id="<?= htmlspecialchars($student['section_id'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                         data-batch-id="<?= htmlspecialchars($student['batch_id'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                         data-program-id="<?= htmlspecialchars($student['program_id'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                         data-specialization-id="<?= htmlspecialchars($student['specialization_id'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                         id="student-<?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?>">
                        <div class="row align-items-center">
                            <!-- Serial Number Column -->
                            <div class="col-1 text-center">
                                <div class="student-index" title="الرقم التسلسلي">
                                    <?= $counter ?>
                                </div>
                            </div>
                            
                            <!-- Checkbox Column -->
                            <div class="col-1 text-center">
                                <input type="checkbox" class="form-check-input student-checkbox" 
                                       value="<?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?>" 
                                       style="transform: scale(1.2); cursor: pointer;"
                                       data-student-name="<?= htmlspecialchars($student['student_name'], ENT_QUOTES, 'UTF-8') ?>"
                                       data-serial="<?= $counter ?>">
                            </div>
                            
                            <!-- Student ID Column -->
                            <div class="col-2">
                                <strong class="d-block fs-6"><?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?></strong>
                                <small class="text-muted d-block">رقم الطالب</small>
                                <div class="mt-1">
                                    <span class="status-badge badge-accepted">مقبول</span>
                                    <span class="status-badge badge-medical">لائق</span>
                                </div>
                                <!-- Serial number badge for mobile -->
                                <span class="serial-number d-md-none mt-1">
                                    <i class="fas fa-hashtag"></i> <?= $counter ?>
                                </span>
                            </div>
                            
                            <!-- Student Name Column -->
                            <div class="col-2">
                                <strong class="d-block"><?= htmlspecialchars($student['student_name'], ENT_QUOTES, 'UTF-8') ?></strong>
                                <small class="text-muted d-block"><?= htmlspecialchars($student['student_name_eng'] ?? '', ENT_QUOTES, 'UTF-8') ?></small>
                            </div>
                            
                            <!-- College/Program Column -->
                            <div class="col-2">
                                <span class="chip blue d-block mb-1"><?= htmlspecialchars($student['college_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?></span>
                                <?php if (!empty($student['program_name'])): ?>
                                    <span class="chip teal d-block"><?= htmlspecialchars($student['program_name'], ENT_QUOTES, 'UTF-8') ?></span>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Section/Specialization/Batch Column -->
                            <div class="col-2">
                                <span class="chip purple d-block mb-1"><?= htmlspecialchars($student['section_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8') ?></span>
                                <?php if (!empty($student['specialization_name'])): ?>
                                    <span class="chip specialization d-block mb-1">📚 <?= htmlspecialchars($student['specialization_name'], ENT_QUOTES, 'UTF-8') ?></span>
                                <?php endif; ?>
                                <span class="chip orange d-block">دفعة <?= htmlspecialchars($student['batch_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8') ?></span>
                            </div>
                            
                            <!-- Enrollment Status Column -->
                            <div class="col-1">
                                <div class="text-center">
                                    <?php if ($is_enrolled): ?>
                                        <span class="enrollment-status enrollment-registered" title="مسجل">
                                            <i class="fas fa-check-circle"></i>
                                        </span>
                                        <div class="mt-1">
                                            <span class="semester-badge">الفصل <?= htmlspecialchars($max_semester, ENT_QUOTES, 'UTF-8') ?></span>
                                        </div>
                                    <?php else: ?>
                                        <span class="enrollment-status enrollment-not-registered" title="غير مسجل">
                                            <i class="fas fa-exclamation-circle"></i>
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Actions Column -->
                            <div class="col-1 text-center">
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-warning"
                                            onclick="printSingleCertificate('<?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?>')"
                                            title="طباعة شهادة فردية">
                                        <i class="fas fa-print"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Mobile view compact info -->
                        <div class="row d-md-none mt-2 pt-2 border-top">
                            <div class="col-12">
                                <small class="text-muted">
                                    <span class="chip blue"><?= htmlspecialchars($student['college_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?></span>
                                    <span class="chip purple"><?= htmlspecialchars($student['section_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?></span>
                                    <?php if (!empty($student['specialization_name'])): ?>
                                        <span class="chip specialization">📚 <?= htmlspecialchars($student['specialization_name'], ENT_QUOTES, 'UTF-8') ?></span>
                                    <?php endif; ?>
                                    <span class="chip orange">دفعة <?= htmlspecialchars($student['batch_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?></span>
                                </small>
                            </div>
                        </div>
                    </div>
                    <?php $counter++; ?>
                <?php endforeach; ?>
                
                <!-- Display total count with serial range -->
                <div class="alert alert-info mt-3">
                    <i class="fas fa-info-circle me-2"></i>
                    عرض الطلاب من <strong>#1</strong> إلى <strong>#<?= $student_count ?></strong> 
                    (إجمالي <?= $student_count ?> طالب)
                </div>
                
            <?php else: ?>
                <div class="text-center py-5">
                    <div class="text-muted">
                        <i class="fas fa-search fa-3x mb-3" style="color: #95a5a6;"></i>
                        <h5>لا توجد نتائج</h5>
                        <p class="mb-3">لم يتم العثور على طلاب مطابقين لمعايير البحث.</p>
                        <div class="alert alert-warning w-50 mx-auto">
                            <h6><i class="fas fa-exclamation-triangle me-2"></i>ملاحظة</h6>
                            <p class="mb-0">يتم عرض الطلاب المقبولين في المقابلة واللائقين طبياً فقط.</p>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <?php else: ?>
        <!-- Welcome Message -->
        <div class="dash-card text-center py-5">
            <div class="text-muted">
                <i class="fas fa-id-card fa-4x mb-4" style="color: #f59e0b;"></i>
                <h4>مرحباً في نظام شهادات الأرانيك المرضية</h4>
                <p class="mb-3">استخدم عوامل التصفية للعثور على الطلاب وطباعة الأرانيك المرضية الاحترافية.</p>
                <div class="row justify-content-center">
                    <div class="col-md-8">
                        <div class="alert alert-info">
                            <h6><i class="fas fa-lightbulb me-2"></i>💡 ماذا يمكنك أن تفعل؟</h6>
                            <ul class="text-start mb-0 text-center">
                                <li><strong>طباعة الأرانيك المرضية:</strong> بتصميم احترافي نصف A4</li>
                                <li><strong>عرض تقارير التسجيل:</strong> تفاصيل كاملة عن حالة قيد كل طالب</li>
                                <li><strong>تصدير البيانات:</strong> لبرنامج Excel للاحتفاظ بالسجلات</li>
                                <li><strong>فلترة متقدمة:</strong> البحث حسب الكلية، القسم، الدفعة، البرنامج، التخصص</li>
                                <li><strong>اختيار متعدد:</strong> تحديد عدة طلاب للطباعة الجماعية</li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="mt-4">
                    <button class="btn btn-warning btn-lg" onclick="showReportHelp()">
                        <i class="fas fa-play-circle me-2"></i>ابدأ الآن - تعرف على الميزات
                    </button>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Selection Counter -->
<div class="selection-counter" id="selectionCounter">
    <i class="fas fa-users fa-lg"></i>
    <div>
        <strong id="counterNumber">0</strong> طالب محدد
        <small class="d-block" id="counterNames"></small>
        <small class="d-block text-white-50" id="counterSerials"></small>
    </div>
    <button class="btn btn-sm btn-light ms-2" onclick="printMedicalCertificates()">
        <i class="fas fa-print me-1"></i>طباعة
    </button>
</div>

<!-- Help Modal -->
<div class="modal fade" id="helpModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg" dir="rtl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-question-circle me-2"></i>دليل الاستخدام - نظام الأرانيك المرضية</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6><i class="fas fa-print text-warning me-2"></i>طباعة الأرانيك</h6>
                        <ol>
                            <li>حدد الطلاب المراد طباعة أرانيكهم</li>
                            <li>انقر على زر "طباعة الأرانيك المرضية"</li>
                            <li>ستفتح نافذة جديدة بصفحة الطباعة</li>
                            <li>استخدم Ctrl+P للطباعة أو انقر على زر الطباعة</li>
                            <li>تأكد من استخدام ورق A4</li>
                        </ol>
                        
                        <h6><i class="fas fa-filter text-primary me-2"></i>التصفية</h6>
                        <ul>
                            <li><strong>الكلية:</strong> تصفية حسب الكلية</li>
                            <li><strong>القسم:</strong> تصفية حسب القسم/الشعبة</li>
                            <li><strong>البرنامج:</strong> تصفية حسب البرنامج الدراسي</li>
                            <li><strong>التخصص:</strong> تصفية حسب التخصص</li>
                            <li><strong>الدفعة:</strong> تصفية حسب سنة الدفعة</li>
                            <li><strong>البحث:</strong> بحث بالاسم أو رقم الطالب</li>
                        </ul>
                    </div>
                    
                    <div class="col-md-6">
                        <h6><i class="fas fa-id-card text-success me-2"></i>محتوى الأرنيكة</h6>
                        <p>تحتوي الأرنيكة على:</p>
                        <ul>
                            <li>رقم الطالب (مميز)</li>
                            <li>اسم الطالب (عربي وإنجليزي)</li>
                            <li>الكليـة والقسم والبرنامج</li>
                            <li>التخصص (إذا وجد)</li>
                            <li>الدفعة وسنة البدء</li>
                            <li>آخر فصل دراسي مسجل</li>
                            <li>حالة القبول واللياقة الطبية</li>
                            <li>رقم تسلسلي وتاريخ الإنشاء</li>
                        </ul>
                        
                        <h6><i class="fas fa-keyboard text-info me-2"></i>اختصارات لوحة المفاتيح</h6>
                        <ul>
                            <li><kbd>Ctrl + A</kbd> تحديد جميع الطلاب</li>
                            <li><kbd>Ctrl + D</kbd> إلغاء تحديد الكل</li>
                            <li><kbd>Esc</kbd> إخفاء عداد التحديد</li>
                            <li><kbd>Ctrl + P</kbd> طباعة مباشرة</li>
                        </ul>
                    </div>
                </div>
                
                <div class="alert alert-warning mt-3">
                    <h6><i class="fas fa-exclamation-triangle me-2"></i>ملاحظات هامة:</h6>
                    <ul class="mb-0">
                        <li>يتم طباعة أرنيكة لكل طالب على صفحة منفصلة</li>
                        <li>تأكد من توفر حبر الطابعة قبل البدء</li>
                        <li>يمكنك طباعة أرنيكة فردية عن طريق الزر بجانب كل طالب</li>
                        <li>الأرنيكة مصممة بحجم نصف A4 (148×210 ملم)</li>
                    </ul>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">
                    <i class="fas fa-check me-1"></i> فهمت
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// CSRF Token for AJAX requests
const csrfToken = document.getElementById('csrf_token').value;

// Student selection management
let selectedStudents = new Set();
let selectedStudentNames = new Map();
let selectedStudentSerials = new Map();

function updateSelection() {
    const checkboxes = document.querySelectorAll('.student-checkbox');
    selectedStudents.clear();
    selectedStudentNames.clear();
    selectedStudentSerials.clear();
    
    checkboxes.forEach(checkbox => {
        if (checkbox.checked) {
            const studentId = checkbox.value;
            const studentName = checkbox.dataset.studentName;
            const serial = checkbox.dataset.serial;
            
            selectedStudents.add(studentId);
            selectedStudentNames.set(studentId, studentName);
            if (serial) selectedStudentSerials.set(studentId, serial);
            
            const studentCard = checkbox.closest('.student-card');
            if (studentCard) {
                studentCard.classList.add('selected', 'print-selected');
            }
        } else {
            const studentId = checkbox.value;
            selectedStudents.delete(studentId);
            selectedStudentNames.delete(studentId);
            selectedStudentSerials.delete(studentId);
            
            const studentCard = checkbox.closest('.student-card');
            if (studentCard) {
                studentCard.classList.remove('selected', 'print-selected');
            }
        }
    });
    
    // Update UI
    updateSelectionUI();
}

function updateSelectionUI() {
    const selectedCount = selectedStudents.size;
    const counterElement = document.getElementById('selectionCounter');
    const counterNumber = document.getElementById('counterNumber');
    const counterNames = document.getElementById('counterNames');
    const counterSerials = document.getElementById('counterSerials');
    const selectedCountBadge = document.getElementById('selectedCountBadge');
    const selectedCountSpan = document.getElementById('selectedCount');
    
    if (selectedCount > 0) {
        counterNumber.textContent = selectedCount;
        selectedCountSpan.textContent = selectedCount;
        
        // Show student names (first 3)
        const names = Array.from(selectedStudentNames.values()).slice(0, 3);
        counterNames.textContent = names.join('، ');
        if (selectedCount > 3) {
            counterNames.textContent += ` ... +${selectedCount - 3}`;
        }
        
        // Show serial numbers range
        if (selectedStudentSerials.size > 0) {
            const serials = Array.from(selectedStudentSerials.values()).map(s => parseInt(s)).sort((a,b) => a-b);
            if (serials.length > 0) {
                const minSerial = serials[0];
                const maxSerial = serials[serials.length - 1];
                if (minSerial === maxSerial) {
                    counterSerials.textContent = `الرقم التسلسلي: ${minSerial}`;
                } else {
                    counterSerials.textContent = `الأرقام التسلسلية: ${minSerial} - ${maxSerial}`;
                }
            }
        }
        
        // Show counter
        counterElement.style.display = 'flex';
        selectedCountBadge.style.display = 'inline-flex';
        
        // Show toast for bulk selection
        if (selectedCount > 10) {
            showToast(`تم تحديد ${selectedCount} طالب جاهزين للطباعة`, 'success', 2000);
        }
    } else {
        counterElement.style.display = 'none';
        selectedCountBadge.style.display = 'none';
    }
}

function selectAllStudents() {
    const checkboxes = document.querySelectorAll('.student-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = true;
    });
    updateSelection();
    showToast('تم تحديد جميع الطلاب للطباعة', 'success');
}

function deselectAllStudents() {
    const checkboxes = document.querySelectorAll('.student-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = false;
    });
    updateSelection();
    showToast('تم إلغاء تحديد جميع الطلاب', 'info');
}

// Load specializations dynamically when program or section changes
function loadSpecializations() {
    const programId = document.getElementById('programSelect').value;
    const sectionId = document.getElementById('sectionSelect').value;
    const specSelect = document.getElementById('specializationSelect');
    const specHint = document.getElementById('specHint');
    
    if (!programId && !sectionId) {
        specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
        specSelect.disabled = true;
        specHint.innerHTML = 'الرجاء اختيار البرنامج أو القسم أولاً';
        return;
    }
    
    // Show loading
    specSelect.innerHTML = '<option value="">جاري التحميل...</option>';
    specSelect.disabled = false;
    specHint.innerHTML = 'جاري تحميل التخصصات...';
    
    // Build URL with available parameters
    let url = 'ajax/get_specializations.php?';
    if (programId) url += `program_id=${encodeURIComponent(programId)}&`;
    if (sectionId) url += `section_id=${encodeURIComponent(sectionId)}&`;
    url += `csrf=${encodeURIComponent(csrfToken)}`;
    
    // Fetch specializations
    fetch(url)
        .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('specialization_id');
                    if (selectedSpec && selectedSpec == spec.specialization_id) {
                        option.selected = true;
                    }
                    
                    specSelect.appendChild(option);
                });
                specHint.innerHTML = `${data.length} تخصص متاح`;
            } else {
                specHint.innerHTML = 'لا توجد تخصصات متاحة';
            }
        })
        .catch(error => {
            console.error('Error loading specializations:', error);
            specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
            specHint.innerHTML = 'حدث خطأ في تحميل التخصصات';
        });
}

// Print Medical Certificates
function printMedicalCertificates() {
    if (selectedStudents.size === 0) {
        showToast('يرجى تحديد طلاب أولاً', 'warning');
        return;
    }
    
    const studentIds = Array.from(selectedStudents);
    
    // Show loading toast
    showToast(`جاري تحضير ${studentIds.length} أرنيكة للطباعة...`, 'info', 0);
    
    // Open print page in new window with CSRF token
    const url = `print_medical_certificate.php?student_ids=${encodeURIComponent(studentIds.join(','))}&csrf=${encodeURIComponent(csrfToken)}&auto_print=1`;
    const printWindow = window.open(url, '_blank', 'width=1000,height=700,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes');
    
    // Check if window opened successfully
    if (!printWindow) {
        showToast('تم حظر النافذة المنبثقة. يرجى السماح بالنوافذ المنبثقة.', 'warning');
        // Fallback: open in same window
        window.location.href = `print_medical_certificate.php?student_ids=${encodeURIComponent(studentIds.join(','))}&csrf=${encodeURIComponent(csrfToken)}`;
        return;
    }
    
    // Success message
    setTimeout(() => {
        showToast(`تم فتح صفحة الطباعة بـ ${studentIds.length} أرنيكة`, 'success');
    }, 1000);
}

function printSingleCertificate(studentId) {
    // Show loading
    showToast('جاري تحضير الأرنيكة...', 'info');
    
    // Open single certificate with CSRF token
    const url = `print_medical_certificate.php?student_ids=${encodeURIComponent(studentId)}&csrf=${encodeURIComponent(csrfToken)}&auto_print=1`;
    const printWindow = window.open(url, '_blank', 'width=1000,height=700,toolbar=no,location=no,status=no,menubar=no');
    
    if (!printWindow) {
        showToast('تم حظر النافذة المنبثقة. يرجى السماح بالنوافذ المنبثقة.', 'warning');
        window.location.href = `print_medical_certificate.php?student_ids=${encodeURIComponent(studentId)}&csrf=${encodeURIComponent(csrfToken)}`;
    }
}

function showReportHelp() {
    const modal = new bootstrap.Modal(document.getElementById('helpModal'));
    modal.show();
}

function showToast(message, type = 'info', duration = 3000) {
    // Create toast container if not exists
    let container = document.querySelector('.toast-container');
    if (!container) {
        container = document.createElement('div');
        container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        document.body.appendChild(container);
    }
    
    // Create toast element
    const toastId = 'toast-' + Date.now();
    const bgClass = type === 'success' ? 'bg-success' : 
                   type === 'warning' ? 'bg-warning' : 
                   type === 'danger' ? 'bg-danger' : 'bg-info';
    
    const toastHtml = `
        <div id="${toastId}" class="toast align-items-center text-white ${bgClass} border-0" role="alert">
            <div class="d-flex">
                <div class="toast-body">
                    ${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        </div>
    `;
    
    container.innerHTML += toastHtml;
    
    // Show toast
    const toastElement = document.getElementById(toastId);
    const toast = new bootstrap.Toast(toastElement, { delay: duration });
    toast.show();
    
    // Remove after hide
    toastElement.addEventListener('hidden.bs.toast', function () {
        toastElement.remove();
    });
}

// Initialize event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Add event listeners to checkboxes
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('student-checkbox')) {
            updateSelection();
        }
    });
    
    // Initialize selection state
    updateSelection();
    
    // Add event listeners for dynamic specialization loading
    const programSelect = document.getElementById('programSelect');
    const sectionSelect = document.getElementById('sectionSelect');
    
    if (programSelect) {
        programSelect.addEventListener('change', loadSpecializations);
    }
    
    if (sectionSelect) {
        sectionSelect.addEventListener('change', loadSpecializations);
    }
    
    // Enable/disable section select based on college selection
    const collegeSelect = document.getElementById('collegeSelect');
    
    if (collegeSelect && sectionSelect) {
        if (!collegeSelect.value) {
            sectionSelect.disabled = true;
        }
    }
    
    // Add keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        // Ctrl+A to select all
        if (e.ctrlKey && e.key === 'a') {
            e.preventDefault();
            selectAllStudents();
        }
        // Ctrl+D to deselect all
        if (e.ctrlKey && e.key === 'd') {
            e.preventDefault();
            deselectAllStudents();
        }
        // Escape to hide counter
        if (e.key === 'Escape') {
            const counter = document.getElementById('selectionCounter');
            if (counter) counter.style.display = 'none';
        }
        // Ctrl+P to print selected
        if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
            e.preventDefault();
            if (selectedStudents.size > 0) {
                printMedicalCertificates();
            } else {
                showToast('يرجى تحديد طلاب للطباعة أولاً', 'warning');
            }
        }
    });
    
    // Add click handler for student cards
    document.addEventListener('click', function(e) {
        const studentCard = e.target.closest('.student-card');
        if (studentCard && !e.target.matches('input, button, a, i, .btn, .badge, .chip')) {
            const checkbox = studentCard.querySelector('.student-checkbox');
            if (checkbox) {
                checkbox.checked = !checkbox.checked;
                updateSelection();
            }
        }
    });
    
    // Show welcome message for first time users
    if (!localStorage.getItem('medicalCertificateWelcomeShown')) {
        setTimeout(() => {
            showToast('مرحباً! يمكنك تحديد الطلاب وطباعة الأرانيك المرضية بنقرة زر', 'info', 5000);
            localStorage.setItem('medicalCertificateWelcomeShown', 'true');
        }, 1500);
    }
    
    // Load specializations if program or section is selected
    if ((programSelect && programSelect.value) || (sectionSelect && sectionSelect.value)) {
        loadSpecializations();
    }
});
</script>

<?php include 'footer.php'; ?>
