<?php
// registration_certificate_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'] ?? ''; // NEW: Program filter
$show_all = isset($_GET['show_all']) && $_GET['show_all'] === '1';
$search_query = trim($_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 !== '' && 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 program filter - CHECK STRUCTURE FIRST
// We'll handle this dynamically based on database structure

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 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)) {
    $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 - Check if programs table exists and get data
$programs = [];
$hasProgramsTable = false;
$hasProgramInStudents = 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 Students for Card Printing ---------- */
$students = [];
$student_count = 0;

if ($show_all || $college_id !== '' || $section_id !== '' || $batch_id !== '' || $program_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";
    }
    
    // Handle program filter
    $programWhere = "";
    $programTypes = "";
    $programParams = [];
    
    if ($program_id !== '' && is_numeric($program_id) && $hasProgramsTable) {
        if ($hasProgramInStudents) {
            $programWhere = " AND s.program_id = ? ";
        } elseif ($hasProgramInBatches) {
            $programWhere = " AND b.program_id = ? ";
        }
        
        if ($programWhere) {
            $programTypes = 'i';
            $programParams[] = (int)$program_id;
        }
    }
    
    $sqlStudents = $selectFields . $fromClause . $where . $programWhere . " ORDER BY s.student_id DESC LIMIT 1000";
    
    // Prepare and execute statement
    $stmt = $mysqli1->prepare($sqlStudents);
    
    if ($stmt) {
        // Bind all parameters
        $allParams = array_merge($params, $programParams);
        $allTypes = $types . $programTypes;
        
        if ($allTypes !== '') {
            $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
        $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
            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 1000
        ";
        
        $fallbackStmt = $mysqli1->prepare($fallbackSql);
        if ($types !== '') {
            $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);
    }
    .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; }
    .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;
    }
</style>

<div class="container py-4">
    <!-- 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">مرحباً، <?= e($committeeName ?: 'مسؤول الشهادات') ?></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>

    <!-- Database Structure Info -->
    <?php if (!$hasProgramsTable): ?>
    <div class="database-info">
        <h6><i class="fas fa-database me-2"></i>معلومات قاعدة البيانات:</h6>
        <p class="mb-0">
            جدول البرامج غير متوفر. فلتر البرنامج قد لا يعمل بشكل كامل.
            <?php if ($hasProgramInStudents): ?>
                <span class="badge bg-success ms-2"><i class="fas fa-check me-1"></i>برنامج موجود في جدول الطلاب</span>
            <?php elseif ($hasProgramInBatches): ?>
                <span class="badge bg-info ms-2"><i class="fas fa-check me-1"></i>برنامج موجود في جدول الدفعات</span>
            <?php else: ?>
                <span class="badge bg-warning ms-2"><i class="fas fa-exclamation-triangle me-1"></i>برنامج غير متوفر</span>
            <?php endif; ?>
        </p>
    </div>
    <?php endif; ?>

    <!-- 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="printRegistrationCertificates()">
                <i class="fas fa-print me-1"></i>طباعة شهادات القيد
            </button>
            <button type="button" class="btn btn-sm btn-outline-success" onclick="exportSelectedToExcel()">
                <i class="fas fa-file-excel me-1"></i>تصدير لـ Excel
            </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">
            <!-- 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" 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="<?= $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="<?= $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="<?= $batch['id'] ?>" <?= $batch_id == $batch['id'] ? 'selected' : '' ?>>
                            <?= e($batch['value']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Program Filter - Conditionally shown -->
            <?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">
                    <option value="">جميع البرامج</option>
                    <?php foreach ($programs as $program): ?>
                        <option value="<?= $program['id'] ?>" <?= $program_id == $program['id'] ? 'selected' : '' ?>>
                            <?= e($program['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <?php if (!$hasProgramsTable && ($hasProgramInStudents || $hasProgramInBatches)): ?>
                    <small class="text-muted"><i class="fas fa-exclamation-triangle me-1"></i>فلتر البرنامج محدود</small>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Search -->
            <div class="col-md-<?= ($hasProgramsTable || $hasProgramInStudents || $hasProgramInBatches) ? '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) ?>">
                </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">
                    <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">
                    <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="registration_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="printRegistrationCertificates()">
                            <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="printRegistrationCertificates()">
                    <i class="fas fa-print me-1"></i>طباعة الشهادات
                </button>
                <button type="button" class="btn btn-sm btn-outline-success" onclick="exportSelectedToExcel()">
                    <i class="fas fa-file-excel me-1"></i>تصدير المحدد
                </button>
            </div>
        </div>

        <!-- Quick Stats -->
        <?php if ($student_count > 0): ?>
        <?php
        // Get enrollment statistics
        $enrolled_count = 0;
        foreach ($students as $student) {
            // Check if student has registrations
            $reg_check = $mysqli1->prepare("SELECT MAX(semester_id) as max_semester FROM registrations WHERE student_id = ?");
            $reg_check->bind_param('s', $student['student_id']);
            $reg_check->execute();
            $reg_result = $reg_check->get_result()->fetch_assoc();
            $reg_check->close();
            
            if ($reg_result && $reg_result['max_semester']) {
                $enrolled_count++;
            }
        }
        ?>
        <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'] == 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">1000</h4>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Students List -->
        <div id="studentsContainer">
            <?php if ($student_count > 0): ?>
                <?php foreach ($students as $student): ?>
                    <?php
                    // Get enrollment data for this student
                    $reg_stmt = $mysqli1->prepare("SELECT MAX(semester_id) as max_semester FROM registrations WHERE student_id = ?");
                    $reg_stmt->bind_param('s', $student['student_id']);
                    $reg_stmt->execute();
                    $reg_result = $reg_stmt->get_result()->fetch_assoc();
                    $reg_stmt->close();
                    
                    $max_semester = $reg_result['max_semester'] ?? null;
                    $is_enrolled = !empty($max_semester);
                    ?>
                    <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']) ?>"
                         id="student-<?= e($student['student_id']) ?>">
                        <div class="row align-items-center">
                            <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;"
                                       data-student-name="<?= e($student['student_name']) ?>">
                            </div>
                            <div class="col-2">
                                <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-2">
                                <strong class="d-block"><?= e($student['student_name']) ?></strong>
                                <small class="text-muted d-block"><?= e($student['student_name_eng']) ?></small>
                                <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-2">
                                <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-2">
                                <span class="chip purple d-block mb-1"><?= e($student['section_name'] ?? 'غير محدد') ?></span>
                                <span class="chip orange d-block">دفعة <?= e($student['batch_name'] ?? 'غير محدد') ?></span>
                            </div>
                            <div class="col-2">
                                <div class="text-center">
                                    <?php if ($is_enrolled): ?>
                                        <span class="enrollment-status enrollment-registered">
                                            <i class="fas fa-check-circle me-1"></i> مسجل
                                        </span>
                                        <div class="mt-1">
                                            <span class="semester-badge">الفصل <?= e($max_semester) ?></span>
                                        </div>
                                    <?php else: ?>
                                        <span class="enrollment-status enrollment-not-registered">
                                            <i class="fas fa-exclamation-circle me-1"></i> غير مسجل
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="col-1 text-center">
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-info" 
                                            onclick="showEnrollmentReport('<?= e($student['student_id']) ?>')"
                                            title="تقرير القيد والتسجيل">
                                        <i class="fas fa-chart-bar"></i>
                                    </button>
                                    <button type="button" class="btn btn-outline-warning"
                                            onclick="printSingleCertificate('<?= e($student['student_id']) ?>')"
                                            title="طباعة شهادة فردية">
                                        <i class="fas fa-print"></i>
                                    </button>
                                </div>
                            </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-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">
                                <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>
    </div>
    <button class="btn btn-sm btn-light ms-2" onclick="printRegistrationCertificates()">
        <i class="fas fa-print me-1"></i>طباعة
    </button>
</div>

<!-- Enrollment Report Modal -->
<div class="modal fade" id="enrollmentReportModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-chart-bar me-2"></i>تقرير القيد والتسجيل</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="enrollmentReportContent">
                <!-- Content will be loaded via AJAX -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إغلاق</button>
                <button type="button" class="btn btn-primary" onclick="printEnrollmentReport()">
                    <i class="fas fa-print me-1"></i> طباعة
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Help Modal -->
<div class="modal fade" id="helpModal" tabindex="-1" aria-hidden="true">
    <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">
                <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>
                            <?php if ($hasProgramsTable || $hasProgramInStudents || $hasProgramInBatches): ?>
                            <li><strong>البرنامج:</strong> تصفية حسب البرنامج الدراسي</li>
                            <?php endif; ?>
                            <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>
                        </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>
// Student selection management
let selectedStudents = new Set();
let selectedStudentNames = new Map();

function updateSelection() {
    const checkboxes = document.querySelectorAll('.student-checkbox');
    selectedStudents.clear();
    selectedStudentNames.clear();
    
    checkboxes.forEach(checkbox => {
        if (checkbox.checked) {
            const studentId = checkbox.value;
            const studentName = checkbox.dataset.studentName;
            selectedStudents.add(studentId);
            selectedStudentNames.set(studentId, studentName);
            checkbox.closest('.student-card').classList.add('selected', 'print-selected');
        } else {
            const studentId = checkbox.value;
            selectedStudents.delete(studentId);
            selectedStudentNames.delete(studentId);
            checkbox.closest('.student-card').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 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 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');
}

// Print Registration Certificates
function printRegistrationCertificates() {
    if (selectedStudents.size === 0) {
        showToast('يرجى تحديد طلاب أولاً', 'warning');
        return;
    }
    
    const studentIds = Array.from(selectedStudents);
    
    // Show loading toast
    const loadingToast = showToast(`جاري تحضير ${studentIds.length} شهادة للطباعة...`, 'info', 0);
    
    // Open print page in new window
    const url = `print_registration_certificate.php?student_ids=${studentIds.join(',')}&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_registration_certificate.php?student_ids=${studentIds.join(',')}`;
        return;
    }
    
    // Success message
    setTimeout(() => {
        showToast(`تم فتح صفحة الطباعة بـ ${studentIds.length} شهادة`, 'success');
    }, 1000);
}

function printSingleCertificate(studentId) {
    // Show loading
    showToast('جاري تحضير الشهادة...', 'info');
    
    // Open single certificate
    const url = `print_registration_certificate.php?student_ids=${studentId}&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_registration_certificate.php?student_ids=${studentId}`;
    }
}

function exportSelectedToExcel() {
    if (selectedStudents.size === 0) {
        showToast('يرجى تحديد طلاب أولاً', 'warning');
        return;
    }
    
    const studentIds = Array.from(selectedStudents);
    exportEnrollmentReport(studentIds, 'selected');
}

function generateEnrollmentReport() {
    const allStudentIds = [];
    document.querySelectorAll('.student-checkbox').forEach(checkbox => {
        allStudentIds.push(checkbox.value);
    });
    
    if (allStudentIds.length === 0) {
        showToast('لا توجد بيانات للتصدير', 'warning');
        return;
    }
    
    exportEnrollmentReport(allStudentIds, 'all');
}

function exportEnrollmentReport(studentIds, type = 'all') {
    // Show loading
    showToast('جاري إنشاء التقرير...', 'info');
    
    // Prepare data
    const data = {
        student_ids: studentIds,
        filters: {
            college_id: '<?= $college_id ?>',
            section_id: '<?= $section_id ?>',
            batch_id: '<?= $batch_id ?>',
            program_id: '<?= $program_id ?>',
            search: '<?= e($search_query) ?>'
        }
    };
    
    // Send request to generate report
    fetch('ajax/generate_enrollment_report.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.blob();
    })
    .then(blob => {
        // Create download link
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        
        const fileName = type === 'selected' 
            ? `enrollment_report_selected_${studentIds.length}_students_${new Date().toISOString().slice(0,10)}.xlsx`
            : `enrollment_report_all_${studentIds.length}_students_${new Date().toISOString().slice(0,10)}.xlsx`;
        
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
        
        showToast(`تم تصدير تقرير ${studentIds.length} طالب بنجاح`, 'success');
    })
    .catch(error => {
        console.error('Error exporting report:', error);
        showToast('حدث خطأ أثناء تصدير التقرير', 'danger');
    });
}

function showEnrollmentReport(studentId) {
    // Show loading
    const modalContent = document.getElementById('enrollmentReportContent');
    modalContent.innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">جاري التحميل...</span>
            </div>
            <p class="mt-3">جاري تحميل بيانات القيد والتسجيل...</p>
        </div>
    `;
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('enrollmentReportModal'));
    modal.show();
    
    // Fetch enrollment data
    fetch(`ajax/get_enrollment_report.php?student_id=${studentId}`)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                modalContent.innerHTML = `
                    <div class="alert alert-danger">
                        <h6><i class="fas fa-exclamation-triangle me-2"></i>خطأ</h6>
                        <p>${data.error}</p>
                    </div>
                `;
                return;
            }
            
            // Format the report
            const reportHtml = `
                <div class="enrollment-report">
                    <div class="row mb-4">
                        <div class="col-md-12">
                            <div class="card border-primary">
                                <div class="card-header bg-primary text-white">
                                    <h6 class="mb-0"><i class="fas fa-user-graduate me-2"></i>معلومات الطالب</h6>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <table class="table table-sm">
                                                <tr>
                                                    <th width="40%">الرقم الجامعي:</th>
                                                    <td>${data.student_id || '—'}</td>
                                                </tr>
                                                <tr>
                                                    <th>اسم الطالب:</th>
                                                    <td>${data.student_name || '—'}</td>
                                                </tr>
                                                <tr>
                                                    <th>الاسم باللغة الإنجليزية:</th>
                                                    <td>${data.student_name_eng || '—'}</td>
                                                </tr>
                                                <tr>
                                                    <th>الجنس:</th>
                                                    <td>${data.gender === 'female' ? 'أنثى' : 'ذكر'}</td>
                                                </tr>
                                            </table>
                                        </div>
                                        <div class="col-md-6">
                                            <table class="table table-sm">
                                                <tr>
                                                    <th width="40%">الكليـة:</th>
                                                    <td>${data.college_name || '—'}</td>
                                                </tr>
                                                <tr>
                                                    <th>القسم/الشعبة:</th>
                                                    <td>${data.section_name || '—'}</td>
                                                </tr>
                                                <tr>
                                                    <th>الدفعة:</th>
                                                    <td>${data.batch_name || '—'}</td>
                                                </tr>
                                                ${data.program_name ? `
                                                <tr>
                                                    <th>البرنامج:</th>
                                                    <td>${data.program_name}</td>
                                                </tr>
                                                ` : ''}
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-md-12">
                            <div class="card border-success">
                                <div class="card-header bg-success text-white">
                                    <h6 class="mb-0"><i class="fas fa-clipboard-check me-2"></i>حالة القبول والتسجيل</h6>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <h6>حالة القبول:</h6>
                                            <div class="d-flex align-items-center gap-3">
                                                <span class="badge ${data.interview_status === 'accepted' ? 'bg-success' : 'bg-warning'}">
                                                    ${data.interview_status === 'accepted' ? '✓ مقبول' : 'قيد المراجعة'}
                                                </span>
                                                <span class="badge ${data.medically_fit ? 'bg-success' : 'bg-warning'}">
                                                    ${data.medically_fit ? '⚕️ لائق طبياً' : 'غير لائق'}
                                                </span>
                                                <span class="badge ${data.profile_completed ? 'bg-info' : 'bg-secondary'}">
                                                    ${data.profile_completed ? 'ملف مكتمل' : 'ملف غير مكتمل'}
                                                </span>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <h6>حالة التسجيل:</h6>
                                            ${data.registration_status === 'registered' ? `
                                                <div class="alert alert-success">
                                                    <div class="d-flex align-items-center">
                                                        <i class="fas fa-check-circle fa-2x me-3"></i>
                                                        <div>
                                                            <h6 class="mb-1">مسجل في الفصل الدراسي</h6>
                                                            <p class="mb-0">آخر فصل مسجل: <strong>الفصل ${data.max_semester}</strong></p>
                                                            ${data.registration_date ? `<small>تاريخ التسجيل: ${data.registration_date}</small>` : ''}
                                                        </div>
                                                    </div>
                                                </div>
                                            ` : `
                                                <div class="alert alert-warning">
                                                    <div class="d-flex align-items-center">
                                                        <i class="fas fa-exclamation-triangle fa-2x me-3"></i>
                                                        <div>
                                                            <h6 class="mb-1">غير مسجل</h6>
                                                            <p class="mb-0">لم يسجل الطالب في أي فصل دراسي بعد</p>
                                                        </div>
                                                    </div>
                                                </div>
                                            `}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    ${data.registration_details ? `
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card border-info">
                                <div class="card-header bg-info text-white">
                                    <h6 class="mb-0"><i class="fas fa-history me-2"></i>سجل التسجيلات</h6>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-sm">
                                            <thead>
                                                <tr>
                                                    <th>رقم الفصل</th>
                                                    <th>تاريخ التسجيل</th>
                                                    <th>الحالة</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                ${data.registration_details.map(reg => `
                                                    <tr>
                                                        <td>${reg.semester_id}</td>
                                                        <td>${reg.registration_date || '—'}</td>
                                                        <td><span class="badge bg-success">مسجل</span></td>
                                                    </tr>
                                                `).join('')}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    ` : ''}
                    
                    <div class="row mt-4">
                        <div class="col-md-12">
                            <div class="card border-secondary">
                                <div class="card-body text-center">
                                    <small class="text-muted">
                                        <i class="fas fa-info-circle me-1"></i>
                                        تم إنشاء التقرير في ${new Date().toLocaleString('ar-SA')}
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            modalContent.innerHTML = reportHtml;
        })
        .catch(error => {
            console.error('Error loading enrollment report:', error);
            modalContent.innerHTML = `
                <div class="alert alert-danger">
                    <h6><i class="fas fa-exclamation-triangle me-2"></i>خطأ في تحميل البيانات</h6>
                    <p>تعذر تحميل بيانات القيد والتسجيل. يرجى المحاولة مرة أخرى.</p>
                </div>
            `;
        });
}

function printEnrollmentReport() {
    const printContent = document.getElementById('enrollmentReportContent').innerHTML;
    const originalContent = document.body.innerHTML;
    
    document.body.innerHTML = `
        <!DOCTYPE html>
        <html dir="rtl" lang="ar">
        <head>
            <meta charset="UTF-8">
            <title>تقرير القيد والتسجيل</title>
            <style>
                body { font-family: 'Cairo', sans-serif; }
                .print-header { text-align: center; margin-bottom: 30px; }
                .print-header h2 { color: #2c3e50; }
                .print-footer { margin-top: 30px; text-align: center; color: #7f8c8d; }
                table { width: 100%; border-collapse: collapse; }
                th, td { border: 1px solid #ddd; padding: 8px; text-align: right; }
                th { background-color: #f2f2f2; }
                .alert { padding: 15px; border-radius: 4px; margin-bottom: 15px; }
                .alert-success { background-color: #d4edda; color: #155724; }
                .alert-warning { background-color: #fff3cd; color: #856404; }
                @media print {
                    .no-print { display: none; }
                }
            </style>
        </head>
        <body>
            <div class="print-header">
                <h2>تقرير القيد والتسجيل</h2>
                <p>جامعة - نظام القبول الإلكتروني</p>
            </div>
            ${printContent}
            <div class="print-footer">
                <p>تم الإنشاء: ${new Date().toLocaleString('ar-SA')}</p>
                <p>صفحة 1 من 1</p>
            </div>
        </body>
        </html>
    `;
    
    window.print();
    document.body.innerHTML = originalContent;
    
    // Re-initialize modal
    const modal = new bootstrap.Modal(document.getElementById('enrollmentReportModal'));
    modal.show();
}

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

function showToast(message, type = 'info', duration = 3000) {
    // Create toast element
    const toastId = 'toast-' + Date.now();
    const toastHtml = `
        <div id="${toastId}" class="toast align-items-center text-white bg-${type} 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>
    `;
    
    // Add to container
    const container = document.querySelector('.toast-container') || (() => {
        const div = document.createElement('div');
        div.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        document.body.appendChild(div);
        return 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();
    });
    
    // Return toast object for manual control
    return toast;
}

// 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();
    
    // Enable/disable section select based on college selection
    const collegeSelect = document.getElementById('collegeSelect');
    const sectionSelect = document.getElementById('sectionSelect');
    
    if (collegeSelect && sectionSelect) {
        collegeSelect.addEventListener('change', function() {
            sectionSelect.disabled = !this.value;
        });
        
        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');
            counter.style.display = 'none';
        }
        // Ctrl+P to print selected
        if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
            e.preventDefault();
            if (selectedStudents.size > 0) {
                printRegistrationCertificates();
            } else {
                showToast('يرجى تحديد طلاب للطباعة أولاً', 'warning');
            }
        }
    });
    
    // Add click handler for student cards
    document.addEventListener('click', function(e) {
        if (e.target.closest('.student-card') && !e.target.matches('input, button, a, i, .btn, .badge, .chip')) {
            const checkbox = e.target.closest('.student-card').querySelector('.student-checkbox');
            if (checkbox) {
                checkbox.checked = !checkbox.checked;
                updateSelection();
            }
        }
    });
    
    // Show welcome message for first time users
    if (!localStorage.getItem('registrationCertificateWelcomeShown')) {
        setTimeout(() => {
            showToast('مرحباً! يمكنك تحديد الطلاب وطباعة شهادات القيد بنقرة زر', 'info', 5000);
            localStorage.setItem('registrationCertificateWelcomeShown', 'true');
        }, 1500);
    }
    
    // Auto-load sections if college is selected
    if (collegeSelect && collegeSelect.value) {
        loadSectionsForCollege(collegeSelect.value);
    }
});

// Handle AJAX loading of sections based on college
function loadSectionsForCollege(collegeId) {
    const sectionSelect = document.getElementById('sectionSelect');
    
    if (!collegeId) {
        sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
        sectionSelect.disabled = true;
        return;
    }
    
    // Show loading
    sectionSelect.innerHTML = '<option value="">جاري التحميل...</option>';
    sectionSelect.disabled = false;
    
    // Fetch sections for this college
    fetch(`ajax/get_sections.php?college_id=${collegeId}`)
        .then(response => 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;
                sectionSelect.appendChild(option);
            });
            
            // Restore previously selected section if any
            const currentSectionId = '<?= $section_id ?>';
            if (currentSectionId) {
                sectionSelect.value = currentSectionId;
            }
        })
        .catch(error => {
            console.error('Error loading sections:', error);
            sectionSelect.innerHTML = '<option value="">خطأ في التحميل</option>';
        });
}

// Add event listener for college select
if (document.getElementById('collegeSelect')) {
    document.getElementById('collegeSelect').addEventListener('change', function() {
        loadSectionsForCollege(this.value);
    });
}

// Add print instructions when printing
window.addEventListener('beforeprint', function() {
    console.log('بدء عملية الطباعة...');
});

window.addEventListener('afterprint', function() {
    console.log('انتهت عملية الطباعة');
    showToast('تمت عملية الطباعة بنجاح', 'success');
});
</script>

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