<?php
// card_printing_dashboard.php
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);

/* ---------- Filter Parameters ---------- */
$college_id = $_GET['college_id'] ?? '';
$section_id = $_GET['section_id'] ?? '';
$batch_id = $_GET['batch_id'] ?? '';
$program_id = $_GET['program_id'] ?? '';
$specialization_id = $_GET['specialization_id'] ?? ''; // NEW: Specialization filter
$show_all = isset($_GET['show_all']) && $_GET['show_all'] === '1';
$search_query = trim($_GET['search'] ?? '');

// Sanitize all inputs to prevent XSS
$college_id = htmlspecialchars($college_id, ENT_QUOTES, 'UTF-8');
$section_id = htmlspecialchars($section_id, ENT_QUOTES, 'UTF-8');
$batch_id = htmlspecialchars($batch_id, ENT_QUOTES, 'UTF-8');
$program_id = htmlspecialchars($program_id, ENT_QUOTES, 'UTF-8');
$specialization_id = htmlspecialchars($specialization_id, ENT_QUOTES, 'UTF-8');
$search_query = htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8');

/* ---------- 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 !== '' && is_numeric($college_id)) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i';
    $params[] = (int)$college_id;
}

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

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

// Apply search filter
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 Colleges, Sections, Batches, Programs, Specializations for Filters ---------- */
// Colleges
$colleges = [];
$college_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
$college_stmt->execute();
$colleges = $college_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$college_stmt->close();

// Sections - based on selected college
$sections = [];
if ($college_id && !empty($college_id) && is_numeric($college_id)) {
    $section_stmt = $mysqli1->prepare("SELECT id, name FROM sections WHERE parent = ? AND deleted_at IS NULL ORDER BY name");
    $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");
    $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");
$batch_stmt->execute();
$batches = $batch_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$batch_stmt->close();

// Programs
$programs = [];
$hasProgramsTable = false;
$hasProgramInStudents = false;
$hasProgramInBatches = false;

try {
    // Check if programs table exists
    $checkTable = $mysqli1->query("SHOW TABLES LIKE 'programs'");
    if ($checkTable->num_rows > 0) {
        $hasProgramsTable = true;
        $program_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
        $program_stmt->execute();
        $programs = $program_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $program_stmt->close();
    }
    
    // Check if program_id exists in students table
    $checkColumn = $mysqli1->query("SHOW COLUMNS FROM students LIKE 'program_id'");
    $hasProgramInStudents = $checkColumn->num_rows > 0;
    
    // Check if program_id exists in batches table
    $checkBatchColumn = $mysqli1->query("SHOW COLUMNS FROM batches LIKE 'program_id'");
    $hasProgramInBatches = $checkBatchColumn->num_rows > 0;
    
} catch (Exception $e) {
    // Ignore errors, just don't show program filter
    $hasProgramsTable = false;
}

/* ---------- Get Specializations for Filter ---------- */
$specializations = [];
$hasSpecializationsTable = false;
$hasSpecializationInStudents = false;

try {
    // Check if specializations table exists
    $checkSpecTable = $mysqli1->query("SHOW TABLES LIKE 'specializations'");
    if ($checkSpecTable->num_rows > 0) {
        $hasSpecializationsTable = true;
        
        // Get specializations based on selected section and program
        $specSql = "SELECT specialization_id, specialization_name_ar FROM specializations WHERE deleted_at IS NULL";
        $specTypes = "";
        $specParams = [];
        
        if ($section_id !== '' && is_numeric($section_id) && $section_id > 0) {
            $specSql .= " AND section_id = ?";
            $specTypes .= "i";
            $specParams[] = (int)$section_id;
        }
        
        if ($program_id !== '' && is_numeric($program_id) && $program_id > 0) {
            $specSql .= " AND program_id = ?";
            $specTypes .= "i";
            $specParams[] = (int)$program_id;
        }
        
        $specSql .= " ORDER BY specialization_name_ar";
        
        $spec_stmt = $mysqli1->prepare($specSql);
        if (!empty($specTypes)) {
            $spec_stmt->bind_param($specTypes, ...$specParams);
        }
        $spec_stmt->execute();
        $specializations = $spec_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $spec_stmt->close();
    }
    
    // Check if specialization_id exists in students table
    $checkSpecColumn = $mysqli1->query("SHOW COLUMNS FROM students LIKE 'specialization_id'");
    $hasSpecializationInStudents = $checkSpecColumn->num_rows > 0;
    
} catch (Exception $e) {
    error_log("Error checking specializations: " . $e->getMessage());
    $hasSpecializationsTable = false;
}

/* ---------- Get Students for Card Printing ---------- */
$students = [];
$student_count = 0;

if ($show_all || $college_id !== '' || $section_id !== '' || $batch_id !== '' || $program_id !== '' || $specialization_id !== '' || $search_query !== '') {
    // Build dynamic SQL based on available tables
    $selectFields = "
        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.interview_status,
            s.medically_fit,
            s.profile_completed,
            sec.name AS section_name,
            b.value AS batch_name,
            c.name AS college_name
    ";
    
    $fromClause = "
        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
    ";
    
    // Add program join if available
    if ($hasProgramInStudents) {
        $selectFields .= ", p.name AS program_name";
        $fromClause .= " LEFT JOIN programs p ON p.id = s.program_id";
    } elseif ($hasProgramInBatches) {
        $selectFields .= ", p.name AS program_name";
        $fromClause .= " LEFT JOIN programs p ON p.id = b.program_id";
    } else {
        $selectFields .= ", '' AS program_name";
    }
    
    // Add specialization join if available
    if ($hasSpecializationInStudents) {
        $selectFields .= ", spec.specialization_name_ar AS specialization_name";
        $fromClause .= " LEFT JOIN specializations spec ON spec.specialization_id = s.specialization_id";
    } else {
        $selectFields .= ", '' AS specialization_name";
    }
    
    // Handle program filter
    $programWhere = "";
    $programTypes = "";
    $programParams = [];
    
    if ($program_id !== '' && is_numeric($program_id) && $hasProgramsTable && (int)$program_id > 0) {
        if ($hasProgramInStudents) {
            $programWhere = " AND s.program_id = ? ";
        } elseif ($hasProgramInBatches) {
            $programWhere = " AND b.program_id = ? ";
        }
        
        if ($programWhere) {
            $programTypes = 'i';
            $programParams[] = (int)$program_id;
        }
    }
    
    // Handle specialization filter
    $specializationWhere = "";
    $specializationTypes = "";
    $specializationParams = [];
    
    if ($specialization_id !== '' && is_numeric($specialization_id) && $hasSpecializationsTable && (int)$specialization_id > 0) {
        if ($hasSpecializationInStudents) {
            $specializationWhere = " AND s.specialization_id = ? ";
            $specializationTypes = 'i';
            $specializationParams[] = (int)$specialization_id;
        }
    }
    
    // Combine all WHERE conditions
    $fullWhere = $where . $programWhere . $specializationWhere;
    
    // Prepare SQL with proper escaping
    $sqlStudents = $selectFields . $fromClause . $fullWhere . " ORDER BY s.student_id DESC LIMIT 400";
    
    // Prepare and execute statement
    $stmt = $mysqli1->prepare($sqlStudents);
    
    if ($stmt) {
        // Bind all parameters
        $allParams = array_merge($params, $programParams, $specializationParams);
        $allTypes = $types . $programTypes . $specializationTypes;
        
        if (!empty($allParams)) {
            $stmt->bind_param($allTypes, ...$allParams);
        }
        
        $stmt->execute();
        $students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $student_count = count($students);
        $stmt->close();
    } else {
        // Fallback query without program and specialization
        $fallbackSql = "
            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.interview_status,
                s.medically_fit,
                s.profile_completed,
                sec.name AS section_name,
                b.value AS batch_name,
                c.name AS college_name,
                '' AS program_name,
                '' 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
            $where
            ORDER BY s.student_id DESC
            LIMIT 400
        ";
        
        $fallbackStmt = $mysqli1->prepare($fallbackSql);
        if (!empty($params)) {
            $fallbackStmt->bind_param($types, ...$params);
        }
        $fallbackStmt->execute();
        $students = $fallbackStmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $student_count = count($students);
        $fallbackStmt->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);
    }
    .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.indigo { background: #c7d2fe; color: #3730a3; } /* New color for specialization */
    .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;
    }
    .print-section {
        position: sticky;
        bottom: 0;
        background: white;
        padding: 15px;
        border-top: 2px solid #e5e7eb;
        margin-top: 20px;
        box-shadow: 0 -5px 15px rgba(0,0,0,0.05);
    }
    .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;
    }
    .filter-help-text {
        font-size: 0.8rem;
        color: #6c757d;
        margin-top: 5px;
    }
</style>

<div class="container py-4" dir="rtl">
    <!-- Header -->
    <div class="d-flex align-items-center mb-4">
        <div>
            <h3 class="fw-bold mb-1">نظام طباعة البطاقات</h3>
            <p class="text-muted mb-0">طباعة بطاقات الطلاب المقبولين واللائقين طبياً</p>
        </div>
        <div class="ms-auto">
            <span class="chip orange">مرحباً، <?= e($committeeName ?: 'مسؤول الطباعة') ?></span>
            <a href="committee_dashboard.php" class="btn btn-sm btn-outline-secondary ms-2">لوحة التحكم</a>
        </div>
    </div>

    <!-- Database Structure Info -->
    <?php if (!$hasProgramsTable || !$hasSpecializationsTable): ?>
    <div class="database-info">
        <h6><i class="fas fa-database me-2"></i>معلومات قاعدة البيانات:</h6>
        <p class="mb-0">
            <?php if (!$hasProgramsTable): ?>
                <span class="badge bg-warning me-2">جدول البرامج غير متوفر</span>
            <?php endif; ?>
            <?php if (!$hasSpecializationsTable): ?>
                <span class="badge bg-warning me-2">جدول التخصصات غير متوفر</span>
            <?php endif; ?>
            <br>
            <small class="text-muted">
                <?php if ($hasSpecializationInStudents): ?>
                    <i class="fas fa-check-circle text-success me-1"></i>التخصص موجود في جدول الطلاب
                <?php else: ?>
                    <i class="fas fa-exclamation-triangle text-warning me-1"></i>التخصص غير موجود في جدول الطلاب
                <?php endif; ?>
            </small>
        </p>
    </div>
    <?php endif; ?>

    <!-- 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">
            <!-- College Filter -->
            <div class="col-md-3">
                <label class="form-label fw-semibold"><i class="fas fa-university me-1"></i> الكلية</label>
                <select name="college_id" class="form-select" id="collegeSelect">
                    <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' : '' ?>>
                            <?= e($college['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Section Filter -->
            <div class="col-md-3">
                <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" <?= !$college_id ? 'disabled' : '' ?>>
                    <option value="">جميع الأقسام</option>
                    <?php foreach ($sections as $section): ?>
                        <option value="<?= (int)$section['id'] ?>" <?= $section_id == $section['id'] ? 'selected' : '' ?>>
                            <?= e($section['name']) ?>
                        </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>

            <!-- Batch Filter -->
            <div class="col-md-3">
                <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' : '' ?>>
                            <?= e($batch['value']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Program Filter -->
            <?php if ($hasProgramsTable || $hasProgramInStudents || $hasProgramInBatches): ?>
            <div class="col-md-3">
                <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">
                    <option value="">جميع البرامج</option>
                    <?php foreach ($programs as $program): ?>
                        <option value="<?= (int)$program['id'] ?>" <?= $program_id == $program['id'] ? 'selected' : '' ?>>
                            <?= e($program['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <div class="filter-help-text">
                    <i class="fas fa-info-circle"></i> اختر القسم أولاً لعرض التخصصات
                </div>
            </div>
            <?php endif; ?>

            <!-- Specialization Filter - NEW -->
            <?php if ($hasSpecializationsTable || $hasSpecializationInStudents): ?>
            <div class="col-md-3">
                <label class="form-label fw-semibold"><i class="fas fa-certificate me-1"></i> التخصص</label>
                <select name="specialization_id" class="form-select" id="specializationSelect" <?= (!$section_id || !$program_id) ? 'disabled' : '' ?>>
                    <option value="">جميع التخصصات</option>
                    <?php foreach ($specializations as $specialization): ?>
                        <option value="<?= (int)$specialization['specialization_id'] ?>" <?= $specialization_id == $specialization['specialization_id'] ? 'selected' : '' ?>>
                            <?= e($specialization['specialization_name_ar']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <?php if (!$section_id || !$program_id): ?>
                    <small class="text-muted"><i class="fas fa-info-circle me-1"></i>الرجاء اختيار القسم والبرنامج أولاً</small>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Search -->
            <div class="col-md-<?= ($hasSpecializationsTable || $hasSpecializationInStudents) ? '6' : '9' ?>">
                <label class="form-label fw-semibold"><i class="fas fa-search me-1"></i> بحث</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="fas fa-user"></i></span>
                    <input type="text" name="search" class="form-control" placeholder="ابحث بالاسم أو رقم الطالب..." 
                           value="<?= e($search_query) ?>" maxlength="100">
                </div>
            </div>

            <!-- Status Filters -->
            <div class="col-md-3">
                <label class="form-label fw-semibold"><i class="fas fa-check-circle me-1"></i> حالة الطالب</label>
                <div class="d-flex gap-2 flex-wrap">
                    <span class="badge badge-accepted">✓ مقبول</span>
                    <span class="badge badge-medical">⚕️ لائق طبياً</span>
                </div>
                <small class="text-muted">(يتم عرض المقبولين واللائقين طبياً فقط)</small>
            </div>

            <!-- Action Buttons -->
            <div class="col-12">
                <div class="d-flex gap-2 flex-wrap">
                    <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="card_printing_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-info" onclick="showPrintHelp()">
                            <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 flex-wrap">
            <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 flex-wrap">
                <button type="button" class="btn btn-sm btn-outline-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-outline-success" onclick="exportSelectedStudents()">
                    <i class="fas fa-file-export me-1"></i>تصدير المحدد
                </button>
            </div>
        </div>

        <!-- Quick Stats -->
        <?php if ($student_count > 0): ?>
        <div class="row mb-4 g-3">
            <div class="col-md-3 col-6">
                <div class="card border-0 bg-light">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-1">طلاب مكتملي الملف</h6>
                        <h4 class="fw-bold text-primary">
                            <?= count(array_filter($students, function($s) { return $s['profile_completed'] == 1; })) ?>
                        </h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="card border-0 bg-light">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-1">ذكور</h6>
                        <h4 class="fw-bold text-info">
                            <?= count(array_filter($students, function($s) { return $s['gender'] == 'male'; })) ?>
                        </h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="card border-0 bg-light">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-1">إناث</h6>
                        <h4 class="fw-bold text-purple">
                            <?= count(array_filter($students, function($s) { return $s['gender'] == 'female'; })) ?>
                        </h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="card border-0 bg-light">
                    <div class="card-body text-center">
                        <h6 class="text-muted mb-1">حد العرض</h6>
                        <h4 class="fw-bold text-success">1000</h4>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Students List -->
      <!-- Students List -->
<div id="studentsContainer">
    <?php if ($student_count > 0): ?>
        <?php $counter = 1; // متغير العدادات ?>
        <?php foreach ($students as $student): ?>
            <div class="student-card" data-student-id="<?= e($student['student_id']) ?>" 
                 data-college-id="<?= e($student['college_id']) ?>"
                 data-section-id="<?= e($student['section_id']) ?>"
                 data-batch-id="<?= e($student['batch_id']) ?>">
                <div class="row align-items-center g-3">
                    <div class="col-1 text-center">
                        <!-- عمود التحديد -->
                        <input type="checkbox" class="form-check-input student-checkbox" 
                               value="<?= e($student['student_id']) ?>" 
                               style="transform: scale(1.2); cursor: pointer;">
                    </div>
                    
                    <!-- عمود الترقيم التسلسلي (جديد) -->
                    <div class="col-1 text-center">
                        <span class="badge bg-secondary rounded-pill fs-6"><?= $counter++ ?></span>
                    </div>
                    
                    <div class="col-md-2 col-6">
                        <strong class="d-block fs-6"><?= e($student['student_id']) ?></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>
                    </div>
                    <div class="col-md-2 col-6">
                        <strong class="d-block"><?= e($student['student_name']) ?></strong>
                       
                        <small class="d-block mt-1">
                            <i class="fas fa-<?= $student['gender'] === 'female' ? 'female' : 'male' ?> me-1"></i>
                            <?= e($student['gender'] === 'female' ? 'أنثى' : 'ذكر') ?>
                        </small>
                    </div>
                    <div class="col-md-2 col-6">
                        <span class="chip blue d-block mb-1"><?= e($student['college_name'] ?? '—') ?></span>
                        <?php if (!empty($student['program_name'])): ?>
                            <span class="chip teal d-block"><?= e($student['program_name']) ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-2 col-6">
                        <span class="chip purple d-block mb-1"><?= e($student['section_name'] ?? 'غير محدد') ?></span>
                        <?php if (!empty($student['specialization_name'])): ?>
                            <span class="chip indigo d-block"><?= e($student['specialization_name']) ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-1 col-6">
                        <span class="chip orange d-block mb-1">دفعة <?= e($student['batch_name'] ?? 'غير محدد') ?></span>
                        <div class="text-muted small">
                            <i class="fas fa-phone me-1"></i>
                            <?= e($student['phone_number'] ?? '—') ?>
                        </div>
                    </div>
                    <div class="col-md-1 col-6 text-center">
                      
                        <button type="button" class="btn btn-sm btn-outline-primary mt-1"
                                onclick="printSelectedCards('<?= e($student['student_id']) ?>')"
                                title="طباعة البطاقة">
                            <i class="fas fa-print"></i>
                        </button>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?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-75 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>

    <!-- Print Section -->
    <?php if ($student_count > 0): ?>
        <div class="print-section">
            <div class="dash-card">
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <h6 class="fw-bold mb-2"><i class="fas fa-print me-2"></i>خيارات الطباعة</h6>
                        <div class="d-flex align-items-center gap-3 flex-wrap">
                            <div>
                                <span class="badge bg-primary fs-6" id="selectedCount">0</span>
                                <span class="text-muted">طالب محدد</span>
                            </div>
                            <div>
                                <span class="badge bg-secondary fs-6"><?= $student_count ?></span>
                                <span class="text-muted">طالب في القائمة</span>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="printBothSides">
                                <label class="form-check-label" for="printBothSides">
                                    طباعة وجه وظهر معاً
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 text-md-end mt-3 mt-md-0">
                        <div class="d-flex gap-2 justify-content-md-end flex-wrap">
                            <button type="button" class="btn btn-success" onclick="printSelectedCards()" disabled id="printBtn">
                                <i class="fas fa-print me-2"></i>طباعة المحددة
                            </button>
                            <button type="button" class="btn btn-primary" onclick="printAllCards()">
                                <i class="fas fa-print me-2"></i>طباعة الكل
                            </button>
                            <button type="button" class="btn btn-info" onclick="printBackSide()">
                                <i class="fas fa-id-card me-2"></i>طباعة الخلفية
                            </button>
                            <button type="button" class="btn btn-warning" onclick="printTestPage()">
                                <i class="fas fa-vial me-2"></i>صفحة اختبار
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Print Settings -->
                <div class="row mt-3" id="printSettings" style="display: none;">
                    <div class="col-md-12">
                        <div class="card border-0 bg-light">
                            <div class="card-body">
                                <h6><i class="fas fa-cog me-2"></i>إعدادات الطباعة</h6>
                                <div class="row g-3">
                                    <div class="col-md-3">
                                        <label class="form-label">نوع الورق</label>
                                        <select class="form-select" id="paperType">
                                            <option value="cr80" selected>CR80 (54×85.6mm)</option>
                                            <option value="a4">A4</option>
                                            <option value="letter">Letter</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">عدد النسخ</label>
                                        <input type="number" class="form-control" id="copiesCount" value="1" min="1" max="10">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">التوجيه</label>
                                        <select class="form-select" id="printOrientation">
                                            <option value="portrait">عمودي</option>
                                            <option value="landscape">أفقي</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">الجودة</label>
                                        <select class="form-select" id="printQuality">
                                            <option value="draft">مسودة</option>
                                            <option value="normal" selected>عادية</option>
                                            <option value="high">عالية</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <?php else: ?>
        <!-- Welcome Message -->
        <div class="dash-card text-center py-5" dir="rtl">
            <div class="text-muted">
                <i class="fas fa-print fa-4x mb-4" style="color: #f39c12;"></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>
                                <li>سيتم عرض الطلاب المقبولين في المقابلة واللائقين طبياً فقط.</li>
                                <?php if ($hasSpecializationsTable): ?>
                                <li>يمكنك استخدام فلتر التخصص للبحث عن طلاب تخصص معين.</li>
                                <?php endif; ?>
                                <li>الحد الأقصى للعرض هو 400 طالب في كل عملية بحث.</li>
                                <li>يمكنك تحديد الطلاب بشكل فردي أو طباعة الجميع.</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Help Modal -->
<div class="modal fade" id="helpModal" tabindex="-1" aria-hidden="true" dir="rtl">
    <div class="modal-dialog modal-lg" >
        <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">
                <h6>🎯 كيفية الاستخدام:</h6>
                <ol>
                    <li>استخدم عوامل التصفية للبحث عن الطلاب المطلوبين</li>
                    <li>حدد الطلاب الذين تريد طباعة بطاقاتهم</li>
                    <li>اضغط على زر "طباعة المحددة" أو "طباعة الكل"</li>
                    <li>ستفتح نافذة جديدة تحتوي على البطاقات جاهزة للطباعة</li>
                </ol>
                
                <h6>🖨️ إعدادات الطباعة الموصى بها:</h6>
                <ul>
                    <li><strong>نوع الورق:</strong> CR80 (بطاقات بلاستيكية)</li>
                    <li><strong>الحجم:</strong> 54mm × 85.6mm</li>
                    <li><strong>الهوامش:</strong> بدون هوامش (Margin: None)</li>
                    <li><strong>التدرج:</strong> ملون (Color)</li>
                </ul>
                
                <h6>⚙️ الفلاتر المتاحة:</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="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">فهمت</button>
            </div>
        </div>
    </div>
</div>

<!-- Toast Container for Notifications -->
<div class="toast-container position-fixed bottom-0 end-0 p-3"></div>

<script>
// Student selection management
let selectedStudents = new Set();

function updateSelection() {
    const checkboxes = document.querySelectorAll('.student-checkbox');
    selectedStudents.clear();
    
    checkboxes.forEach(checkbox => {
        if (checkbox.checked) {
            selectedStudents.add(checkbox.value);
            checkbox.closest('.student-card').classList.add('selected');
        } else {
            checkbox.closest('.student-card').classList.remove('selected');
        }
    });
    
    // Update selected count
    const selectedCount = selectedStudents.size;
    const selectedCountElement = document.getElementById('selectedCount');
    if (selectedCountElement) {
        selectedCountElement.textContent = selectedCount;
    }
    
    // Enable/disable print button
    const printBtn = document.getElementById('printBtn');
    if (printBtn) {
        printBtn.disabled = selectedCount === 0;
        
        // Update print button text
        if (selectedCount > 0) {
            printBtn.innerHTML = `<i class="fas fa-print me-2"></i>طباعة المحددة (${selectedCount})`;
        } else {
            printBtn.innerHTML = `<i class="fas fa-print me-2"></i>طباعة المحددة`;
        }
    }
}

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');
}

function exportSelectedStudents() {
    if (selectedStudents.size === 0) {
        showToast('يرجى تحديد طلاب أولاً', 'warning');
        return;
    }
    
    const studentIds = Array.from(selectedStudents);
    let csvContent = "رقم الطالب,الاسم,الكلية,القسم,الدفعة,البرنامج,التخصص\n";
    
    studentIds.forEach(id => {
        const card = document.querySelector(`[data-student-id="${id}"]`);
        if (card) {
            const name = card.querySelector('strong').textContent;
            const college = card.querySelector('.chip.blue')?.textContent || '';
            const section = card.querySelector('.chip.purple')?.textContent || '';
            const batch = card.querySelector('.chip.orange')?.textContent || '';
            const program = card.querySelector('.chip.teal')?.textContent || '';
            const specialization = card.querySelector('.chip.indigo')?.textContent || '';
            
            // Escape commas in fields
            csvContent += `"${id}","${name.replace(/"/g, '""')}","${college.replace(/"/g, '""')}","${section.replace(/"/g, '""')}","${batch.replace(/"/g, '""')}","${program.replace(/"/g, '""')}","${specialization.replace(/"/g, '""')}"\n`;
        }
    });
    
    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); // Add BOM for Arabic
    const link = document.createElement("a");
    const url = URL.createObjectURL(blob);
    link.setAttribute("href", url);
    link.setAttribute("download", `students_${new Date().toISOString().slice(0,10)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    showToast(`تم تصدير ${selectedStudents.size} طالب`, 'success');
}

// Print functions
function printSelectedCards(singleStudentId = null) {
    let studentIds = [];
    
    if (singleStudentId) {
        studentIds = [singleStudentId];
    } else {
        if (selectedStudents.size === 0) {
            showToast('يرجى تحديد طلاب لطباعة بطاقاتهم.', 'warning');
            return;
        }
        studentIds = Array.from(selectedStudents);
    }
    
    printStudentCards(studentIds, singleStudentId ? 'single' : 'selected');
}

function printAllCards() {
    const studentIds = [];
    document.querySelectorAll('.student-checkbox').forEach(checkbox => {
        studentIds.push(checkbox.value);
    });
    
    if (studentIds.length === 0) {
        showToast('لا توجد بطاقات للطباعة.', 'warning');
        return;
    }
    
    printStudentCards(studentIds, 'all');
}

function printStudentCards(studentIds, type = 'selected') {
    // Get print settings
    const printBothSides = document.getElementById('printBothSides')?.checked || false;
    const paperType = document.getElementById('paperType')?.value || 'cr80';
    const copies = document.getElementById('copiesCount')?.value || 1;
    
    // Validate inputs
    if (!studentIds || studentIds.length === 0) {
        showToast('لا توجد بطاقات للطباعة', 'warning');
        return;
    }
    
    // Build print URL
    let printUrl = `card_print_page.php?students=${encodeURIComponent(studentIds.join(','))}`;
    printUrl += `&paper=${encodeURIComponent(paperType)}`;
    printUrl += `&copies=${encodeURIComponent(copies)}`;
    if (printBothSides) {
        printUrl += '&both_sides=1';
    }
    
    // Open print page in new window
    const printWindow = window.open(printUrl, '_blank');
    
    // Show success message
    const message = type === 'selected' 
        ? `سيتم فتح نافذة جديدة لطباعة ${studentIds.length} بطاقة طالب.`
        : `سيتم فتح نافذة جديدة لطباعة جميع البطاقات (${studentIds.length} بطاقة).`;
    
    showToast(message, 'info');
    
    // Auto-print after 2 seconds if in same domain
    setTimeout(() => {
        try {
            if (printWindow && !printWindow.closed) {
                printWindow.focus();
            }
        } catch (e) {
            // Cross-origin error, ignore
            console.log('Print window opened successfully');
        }
    }, 2000);
}

function printBackSide() {
    let studentIds = Array.from(selectedStudents);
    
    if (studentIds.length === 0) {
        // If no students selected, use all students
        document.querySelectorAll('.student-checkbox').forEach(checkbox => {
            studentIds.push(checkbox.value);
        });
    }
    
    if (studentIds.length === 0) {
        showToast('لا توجد بطاقات لطباعة الخلفية.', 'warning');
        return;
    }
    
    // Open back side page in new window
    const backSideUrl = `card_back_page.php?students=${encodeURIComponent(studentIds.join(','))}`;
    window.open(backSideUrl, '_blank');
    
    showToast(`سيتم فتح نافذة جديدة لطباعة ظهر ${studentIds.length} بطاقة.`, 'info');
}

function printTestPage() {
    // Open test page
    window.open('#', '_blank');
    showToast('تم فتح صفحة الاختبار للطباعة', 'info');
}

function previewCard(studentId) {
    if (!studentId) {
        showToast('رقم الطالب غير صحيح', 'error');
        return;
    }
    



    // Open preview in new window
    const previewUrl = `card_preview.php?student=${encodeURIComponent(studentIds.join(','))}`;
    window.open(previewUrl, '_blank', 'width=800,height=600');
    showToast('جاري فتح معاينة البطاقة...', 'info');
}

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

function showToast(message, type = 'info') {
    // Create toast element
    const toastId = 'toast-' + Date.now();
    const bgColor = type === 'success' ? 'bg-success' : (type === 'warning' ? 'bg-warning' : (type === 'error' ? 'bg-danger' : 'bg-info'));
    const textColor = type === 'warning' ? 'text-dark' : 'text-white';
    
    const toastHtml = `
        <div id="${toastId}" class="toast align-items-center ${bgColor} ${textColor} border-0" role="alert" aria-live="assertive" aria-atomic="true">
            <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" aria-label="Close"></button>
            </div>
        </div>
    `;
    
    // Add to container
    const container = document.querySelector('.toast-container');
    container.insertAdjacentHTML('beforeend', toastHtml);
    
    // Show toast
    const toastElement = document.getElementById(toastId);
    const toast = new bootstrap.Toast(toastElement, { delay: 3000 });
    toast.show();
    
    // Remove after hide
    toastElement.addEventListener('hidden.bs.toast', function () {
        toastElement.remove();
    });
}

// AJAX Functions for dynamic filters
function loadSections(collegeId) {
    if (!collegeId) {
        document.getElementById('sectionSelect').innerHTML = '<option value="">جميع الأقسام</option>';
        document.getElementById('sectionSelect').disabled = true;
        return;
    }
    
    const sectionSelect = document.getElementById('sectionSelect');
    sectionSelect.innerHTML = '<option value="">جاري التحميل...</option>';
    sectionSelect.disabled = false;
    
    fetch(`ajax/get_sections.php?college_id=${encodeURIComponent(collegeId)}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
            data.forEach(section => {
                const option = document.createElement('option');
                option.value = section.id;
                option.textContent = section.name;
                if (section.id == '<?= $section_id ?>') {
                    option.selected = true;
                }
                sectionSelect.appendChild(option);
            });
            
            // Trigger specialization load if section is selected
            if (sectionSelect.value) {
                loadSpecializations(sectionSelect.value, document.getElementById('programSelect')?.value);
            }
        })
        .catch(error => {
            console.error('Error loading sections:', error);
            sectionSelect.innerHTML = '<option value="">خطأ في التحميل</option>';
            showToast('فشل تحميل الأقسام', 'error');
        });
}

function loadSpecializations(sectionId, programId) {
    <?php if ($hasSpecializationsTable): ?>
    const specSelect = document.getElementById('specializationSelect');
    if (!specSelect) return;
    
    if (!sectionId || !programId) {
        specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
        specSelect.disabled = true;
        return;
    }
    
    specSelect.innerHTML = '<option value="">جاري تحميل التخصصات...</option>';
    specSelect.disabled = false;
    
    fetch(`ajax/get_specializations.php?section_id=${encodeURIComponent(sectionId)}&program_id=${encodeURIComponent(programId)}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
            data.forEach(spec => {
                const option = document.createElement('option');
                option.value = spec.specialization_id;
                option.textContent = spec.specialization_name_ar;
                if (spec.specialization_id == '<?= $specialization_id ?>') {
                    option.selected = true;
                }
                specSelect.appendChild(option);
            });
        })
        .catch(error => {
            console.error('Error loading specializations:', error);
            specSelect.innerHTML = '<option value="">خطأ في تحميل التخصصات</option>';
            showToast('فشل تحميل التخصصات', 'error');
        });
    <?php endif; ?>
}

// 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();
    
    // College change handler
    const collegeSelect = document.getElementById('collegeSelect');
    if (collegeSelect) {
        collegeSelect.addEventListener('change', function() {
            loadSections(this.value);
        });
    }
    
    // Section change handler
    const sectionSelect = document.getElementById('sectionSelect');
    const programSelect = document.getElementById('programSelect');
    
    if (sectionSelect && programSelect) {
        sectionSelect.addEventListener('change', function() {
            loadSpecializations(this.value, programSelect.value);
        });
        
        programSelect.addEventListener('change', function() {
            loadSpecializations(sectionSelect.value, this.value);
        });
    }
    
    // Show/hide print settings
    const printSettingsBtn = document.createElement('button');
    printSettingsBtn.className = 'btn btn-sm btn-outline-secondary ms-2';
    printSettingsBtn.innerHTML = '<i class="fas fa-cog"></i> إعدادات';
    printSettingsBtn.title = 'إعدادات الطباعة';
    printSettingsBtn.onclick = function() {
        const settings = document.getElementById('printSettings');
        if (settings) {
            settings.style.display = settings.style.display === 'none' ? 'block' : 'none';
        }
    };
    
    const printSection = document.querySelector('.print-section h6');
    if (printSection) {
        printSection.parentElement.appendChild(printSettingsBtn);
    }
    
    // Add keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        // Ctrl+A to select all
        if (e.ctrlKey && e.key === 'a' && !e.target.matches('input, textarea')) {
            e.preventDefault();
            selectAllStudents();
        }
        // Ctrl+D to deselect all
        if (e.ctrlKey && e.key === 'd' && !e.target.matches('input, textarea')) {
            e.preventDefault();
            deselectAllStudents();
        }
        // Ctrl+P to print selected
        if (e.ctrlKey && e.key === 'p' && !e.target.matches('input, textarea')) {
            e.preventDefault();
            printSelectedCards();
        }
        // Escape to deselect all
        if (e.key === 'Escape') {
            deselectAllStudents();
        }
    });
    
    // Add click handler for student cards (toggle selection)
    document.addEventListener('click', function(e) {
        const card = e.target.closest('.student-card');
        if (card && !e.target.matches('input, button, a, .btn')) {
            const checkbox = card.querySelector('.student-checkbox');
            if (checkbox) {
                checkbox.checked = !checkbox.checked;
                updateSelection();
            }
        }
    });
    
    // Show welcome message for first time users
    if (!localStorage.getItem('cardPrintingWelcomeShown')) {
        setTimeout(() => {
            showToast('مرحباً! يمكنك استخدام Ctrl+A لتحديد الكل وCtrl+P للطباعة السريعة', 'info');
            localStorage.setItem('cardPrintingWelcomeShown', 'true');
        }, 1000);
    }
    
    // Prevent double form submission
    const filterForm = document.getElementById('filterForm');
    if (filterForm) {
        filterForm.addEventListener('submit', function() {
            const submitBtn = this.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.disabled = true;
                setTimeout(() => {
                    submitBtn.disabled = false;
                }, 2000);
            }
        });
    }
});
</script>

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