<?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: 20px;
        padding: 25px;
        background: #fff;
        box-shadow: 0 12px 32px rgba(0,0,0,.08);
        margin-bottom: 25px;
        transition: transform 0.3s ease;
    }
    .dash-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 20px 40px rgba(0,0,0,.12);
    }
    .filter-card {
        background: linear-gradient(135deg, #ffffff, #f8f9fa);
        border: 1px solid #e0e0e0;
    }
    .btn-primary { 
        background: linear-gradient(135deg, #f59e0b, #d97706);
        border: none;
        font-weight: 700;
        padding: 12px 24px;
        border-radius: 12px;
        transition: all 0.3s ease;
    }
    .btn-primary:hover {
        background: linear-gradient(135deg, #d97706, #b45309);
        transform: translateY(-2px) scale(1.02);
        box-shadow: 0 8px 20px rgba(245, 158, 11, 0.3);
    }
    .btn-success { 
        background: linear-gradient(135deg, #10b981, #059669);
        border: none;
        font-weight: 700;
        padding: 12px 24px;
        border-radius: 12px;
        transition: all 0.3s ease;
    }
    .btn-success:hover {
        background: linear-gradient(135deg, #059669, #047857);
        transform: translateY(-2px) scale(1.02);
        box-shadow: 0 8px 20px rgba(16, 185, 129, 0.3);
    }
    .btn-info {
        background: linear-gradient(135deg, #3b82f6, #2563eb);
        border: none;
        font-weight: 700;
        padding: 12px 24px;
        border-radius: 12px;
        transition: all 0.3s ease;
    }
    .btn-info:hover {
        background: linear-gradient(135deg, #2563eb, #1d4ed8);
        transform: translateY(-2px) scale(1.02);
        box-shadow: 0 8px 20px rgba(59, 130, 246, 0.3);
    }
    .btn-warning {
        background: linear-gradient(135deg, #f59e0b, #d97706);
        border: none;
        font-weight: 700;
        padding: 12px 24px;
        border-radius: 12px;
        transition: all 0.3s ease;
        color: white;
    }
    .btn-warning:hover {
        background: linear-gradient(135deg, #d97706, #b45309);
        transform: translateY(-2px) scale(1.02);
        box-shadow: 0 8px 20px rgba(245, 158, 11, 0.3);
        color: white;
    }
    
    /* بطاقات الطلاب الجديدة */
    .student-card {
        border: 1px solid #e5e7eb;
        border-radius: 20px;
        padding: 25px;
        margin-bottom: 20px;
        background: linear-gradient(135deg, #ffffff, #fafafa);
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;
        overflow: hidden;
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.05);
    }
    
    .student-card::before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 6px;
        height: 100%;
        background: linear-gradient(to bottom, #f59e0b, #f97316);
        border-radius: 0 20px 20px 0;
        z-index: 1;
    }
    
    .student-card:hover {
        border-color: #f59e0b;
        box-shadow: 0 20px 45px rgba(245, 158, 11, 0.15);
        transform: translateY(-8px);
        background: linear-gradient(135deg, #ffffff, #fff7ed);
    }
    
    .student-card.selected {
        border-color: #10b981;
        background: linear-gradient(135deg, #f0fdf4, #dcfce7);
        animation: selectPulse 2s infinite;
    }
    
    .student-card.print-selected {
        border-color: #f59e0b;
        background: linear-gradient(135deg, #fffbeb, #fed7aa);
        box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.2);
    }
    
    @keyframes selectPulse {
        0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4); }
        70% { box-shadow: 0 0 0 15px rgba(16, 185, 129, 0); }
        100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
    }
    
    /* تحسين البطاقات الداخلية */
    .student-info-header {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 2px dashed #e5e7eb;
    }
    
    .student-avatar {
        width: 70px;
        height: 70px;
        border-radius: 50%;
        background: linear-gradient(135deg, #f59e0b, #f97316);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 28px;
        font-weight: bold;
        margin-left: 20px;
        box-shadow: 0 8px 20px rgba(245, 158, 11, 0.3);
    }
    
    .student-id-badge {
        background: linear-gradient(135deg, #3b82f6, #2563eb);
        color: white;
        padding: 8px 16px;
        border-radius: 12px;
        font-weight: 700;
        font-size: 1.1rem;
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
    }
    
    /* رقائق المعلومات */
    .info-chip {
        display: inline-flex;
        align-items: center;
        padding: 8px 16px;
        border-radius: 12px;
        font-size: 0.9rem;
        font-weight: 600;
        margin: 5px;
        transition: all 0.3s ease;
    }
    
    .info-chip:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    
    .chip-blue { 
        background: linear-gradient(135deg, #dbeafe, #bfdbfe); 
        color: #1e40af; 
        border: 1px solid #93c5fd;
    }
    .chip-purple { 
        background: linear-gradient(135deg, #e9d5ff, #d8b4fe); 
        color: #7e22ce; 
        border: 1px solid #c084fc;
    }
    .chip-orange { 
        background: linear-gradient(135deg, #fed7aa, #fdba74); 
        color: #9a3412; 
        border: 1px solid #fb923c;
    }
    .chip-green { 
        background: linear-gradient(135deg, #d1fae5, #a7f3d0); 
        color: #065f46; 
        border: 1px solid #6ee7b7;
    }
    .chip-teal { 
        background: linear-gradient(135deg, #99f6e4, #5eead4); 
        color: #115e59; 
        border: 1px solid #2dd4bf;
    }
    .chip-yellow { 
        background: linear-gradient(135deg, #fef3c7, #fde68a); 
        color: #92400e; 
        border: 1px solid #fcd34d;
    }
    .chip-pink { 
        background: linear-gradient(135deg, #fce7f3, #fbcfe8); 
        color: #9d174d; 
        border: 1px solid #f9a8d4;
    }
    
    /* حالة التسجيل */
    .enrollment-status-card {
        padding: 15px;
        border-radius: 16px;
        text-align: center;
        transition: all 0.3s ease;
    }
    
    .enrollment-status-card:hover {
        transform: scale(1.05);
    }
    
    .enrollment-registered {
        background: linear-gradient(135deg, #d1fae5, #a7f3d0);
        border: 2px solid #10b981;
        color: #065f46;
    }
    
    .enrollment-not-registered {
        background: linear-gradient(135deg, #fef3c7, #fde68a);
        border: 2px solid #f59e0b;
        color: #92400e;
    }
    
    .semester-badge {
        background: linear-gradient(135deg, #8b5cf6, #7c3aed);
        color: white;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 0.9rem;
        font-weight: 700;
        display: inline-block;
        margin-top: 8px;
        box-shadow: 0 4px 12px rgba(139, 92, 246, 0.3);
    }
    
    /* أزرار البطاقة */
    .student-actions {
        display: flex;
        gap: 10px;
        justify-content: center;
        margin-top: 15px;
    }
    
    .action-btn {
        width: 45px;
        height: 45px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none;
        transition: all 0.3s ease;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    
    .action-btn:hover {
        transform: translateY(-3px) scale(1.1);
        box-shadow: 0 8px 20px rgba(0,0,0,0.15);
    }
    
    .action-btn-info {
        background: linear-gradient(135deg, #3b82f6, #2563eb);
        color: white;
    }
    
    .action-btn-warning {
        background: linear-gradient(135deg, #f59e0b, #d97706);
        color: white;
    }
    
    /* محدد الاختيار */
    .selection-checkbox {
        width: 24px;
        height: 24px;
        border-radius: 8px;
        cursor: pointer;
        border: 2px solid #d1d5db;
        position: relative;
        transition: all 0.3s ease;
    }
    
    .selection-checkbox:checked {
        background: #10b981;
        border-color: #10b981;
    }
    
    .selection-checkbox:checked::after {
        content: '✓';
        position: absolute;
        color: white;
        font-weight: bold;
        font-size: 16px;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    
    /* تحسين الفلاتر */
    .form-select, .form-control {
        border-radius: 12px;
        border: 1px solid #d1d5db;
        padding: 12px;
        transition: all 0.3s ease;
        background: white;
    }
    
    .form-select:focus, .form-control:focus {
        border-color: #f59e0b;
        box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.15);
        transform: translateY(-2px);
    }
    
    /* شارة العداد */
    .selection-counter {
        position: fixed;
        bottom: 30px;
        right: 30px;
        background: linear-gradient(135deg, #f59e0b, #d97706);
        color: white;
        padding: 20px 25px;
        border-radius: 16px;
        box-shadow: 0 15px 35px rgba(245, 158, 11, 0.3);
        z-index: 1000;
        display: none;
        align-items: center;
        gap: 15px;
        animation: slideIn 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
    }
    
    @keyframes slideIn {
        from { 
            transform: translateY(100px) scale(0.8); 
            opacity: 0; 
        }
        to { 
            transform: translateY(0) scale(1); 
            opacity: 1; 
        }
    }
    
    .print-badge {
        background: linear-gradient(135deg, #f59e0b, #d97706);
        color: white;
        padding: 8px 20px;
        border-radius: 20px;
        font-size: 0.95rem;
        font-weight: 700;
        display: inline-flex;
        align-items: center;
        gap: 10px;
        margin-left: 10px;
        box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
        transition: all 0.3s ease;
    }
    
    .print-badge:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(245, 158, 11, 0.4);
    }
    
    /* رأس البطاقة */
    .student-name {
        font-size: 1.4rem;
        font-weight: 800;
        color: #1f2937;
        margin-bottom: 5px;
        background: linear-gradient(135deg, #1f2937, #374151);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    .student-name-en {
        font-size: 1.1rem;
        color: #6b7280;
        font-weight: 600;
    }
    
    /* الأيقونات */
    .icon-circle {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 10px;
        background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
        color: #6b7280;
    }
    
    /* تأثيرات إضافية */
    .stats-card {
        border-radius: 16px;
        padding: 20px;
        text-align: center;
        transition: all 0.3s ease;
        background: linear-gradient(135deg, #ffffff, #f9fafb);
        border: 1px solid #e5e7eb;
    }
    
    .stats-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 15px 30px rgba(0,0,0,0.1);
    }
    
    .stats-number {
        font-size: 2.5rem;
        font-weight: 800;
        margin-bottom: 5px;
    }
    
    /* شبكة البطاقات */
    .student-card-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
        gap: 20px;
    }
    
    /* تحسين الاستجابة */
    @media (max-width: 768px) {
        .student-card-grid {
            grid-template-columns: 1fr;
        }
        
        .student-card {
            padding: 20px;
        }
        
        .student-avatar {
            width: 60px;
            height: 60px;
            font-size: 24px;
        }
    }
    
    /* تأثير الضوء */
    .glow-effect {
        position: relative;
    }
    
    .glow-effect::after {
        content: '';
        position: absolute;
        top: -2px;
        left: -2px;
        right: -2px;
        bottom: -2px;
        background: linear-gradient(45deg, #f59e0b, #fbbf24, #f59e0b);
        border-radius: 22px;
        z-index: -1;
        opacity: 0;
        transition: opacity 0.3s ease;
    }
    
    .glow-effect.selected::after {
        opacity: 0.3;
    }
</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="info-chip chip-orange">
                <i class="fas fa-user-tie me-2"></i>مرحباً، <?= e($committeeName ?: 'مسؤول الشهادات') ?>
            </span>
            <a href="committee_dashboard.php" class="btn 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-3">
            <span class="fw-bold text-primary fs-5"><i class="fas fa-bolt me-2"></i>أدوات سريعة:</span>
            <button type="button" class="btn btn-primary" onclick="selectAllStudents()">
                <i class="fas fa-check-square me-2"></i>تحديد الكل
            </button>
            <button type="button" class="btn btn-outline-secondary" onclick="deselectAllStudents()">
                <i class="fas fa-times-circle me-2"></i>إلغاء الكل
            </button>
            <button type="button" class="btn btn-warning" onclick="printRegistrationCertificates()">
                <i class="fas fa-print me-2"></i>طباعة شهادات القيد
            </button>
            <button type="button" class="btn btn-outline-success" onclick="exportSelectedToExcel()">
                <i class="fas fa-file-excel me-2"></i>تصدير لـ Excel
            </button>
            <button type="button" class="btn btn-outline-info" onclick="showReportHelp()">
                <i class="fas fa-question-circle me-2"></i>مساعدة
            </button>
            <div class="ms-auto">
                <span id="selectedCountBadge" class="print-badge" style="display: none;">
                    <i class="fas fa-users me-2"></i>
                    <span id="selectedCount">0</span> طالب محدد
                </span>
            </div>
        </div>
    </div>

    <!-- Filters Card -->
    <div class="dash-card filter-card">
        <h5 class="fw-bold mb-4"><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-2"></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-2"></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-2"></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-2"></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-2"></i> بحث سريع</label>
                <div class="input-group">
                    <span class="input-group-text bg-warning text-white"><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-2"></i> حالة الطالب</label>
                <div class="d-flex gap-2">
                    <span class="info-chip chip-green">✓ مقبول</span>
                    <span class="info-chip chip-teal">⚕️ لائق طبياً</span>
                </div>
                <small class="text-muted">(يتم عرض المقبولين واللائقين طبياً فقط)</small>
            </div>

            <!-- Action Buttons -->
            <div class="col-12">
                <div class="d-flex gap-3 align-items-center">
                    <button type="submit" name="show_all" value="1" class="btn btn-primary">
                        <i class="fas fa-eye me-2"></i> عرض الطلاب
                    </button>
                    <button type="submit" class="btn btn-outline-primary">
                        <i class="fas fa-sync-alt me-2"></i> تطبيق التصفية
                    </button>
                    <a href="registration_certificate_dashboard.php" class="btn btn-outline-danger">
                        <i class="fas fa-times me-2"></i> مسح الكل
                    </a>
                    <div class="ms-auto">
                        <button type="button" class="btn btn-warning" onclick="printRegistrationCertificates()">
                            <i class="fas fa-id-card me-2"></i> طباعة شهادات القيد
                        </button>
                        <button type="button" class="btn btn-outline-info" onclick="showReportHelp()">
                            <i class="fas fa-question-circle me-2"></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-4">
            <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-3">
                <button type="button" class="btn btn-primary" onclick="selectAllStudents()">
                    <i class="fas fa-check-square me-2"></i>تحديد الكل
                </button>
                <button type="button" class="btn btn-outline-secondary" onclick="deselectAllStudents()">
                    <i class="fas fa-times-circle me-2"></i>إلغاء الكل
                </button>
                <button type="button" class="btn btn-warning" onclick="printRegistrationCertificates()">
                    <i class="fas fa-print me-2"></i>طباعة الشهادات
                </button>
                <button type="button" class="btn btn-outline-success" onclick="exportSelectedToExcel()">
                    <i class="fas fa-file-excel me-2"></i>تصدير المحدد
                </button>
            </div>
        </div>

        <!-- Quick Stats -->
        <?php if ($student_count > 0): ?>
        <?php
        // Get enrollment statistics
        $enrolled_count = 0;
        $completed_profiles = 0;
        $male_count = 0;
        $female_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++;
            }
            
            if ($student['profile_completed'] == 1) {
                $completed_profiles++;
            }
            
            if ($student['gender'] === 'male') {
                $male_count++;
            } elseif ($student['gender'] === 'female') {
                $female_count++;
            }
        }
        ?>
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-number text-success"><?= $enrolled_count ?></div>
                    <h6 class="text-muted mb-1"><i class="fas fa-user-graduate me-2"></i>طلاب مسجلين</h6>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-number text-warning"><?= $student_count - $enrolled_count ?></div>
                    <h6 class="text-muted mb-1"><i class="fas fa-user-clock me-2"></i>طلاب غير مسجلين</h6>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-number text-info"><?= $completed_profiles ?></div>
                    <h6 class="text-muted mb-1"><i class="fas fa-file-check me-2"></i>ملفات مكتملة</h6>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-number text-primary"><?= number_format($student_count) ?></div>
                    <h6 class="text-muted mb-1"><i class="fas fa-users me-2"></i>إجمالي الطلاب</h6>
                </div>
            </div>
        </div>
        
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-number" style="color: #3b82f6;"><?= $male_count ?></div>
                    <h6 class="text-muted mb-1"><i class="fas fa-male me-2"></i>ذكور</h6>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-number" style="color: #ec4899;"><?= $female_count ?></div>
                    <h6 class="text-muted mb-1"><i class="fas fa-female me-2"></i>إناث</h6>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-number" style="color: #8b5cf6;"><?= count(array_unique(array_column($students, 'college_id'))) ?></div>
                    <h6 class="text-muted mb-1"><i class="fas fa-university me-2"></i>كليات</h6>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-number" style="color: #10b981;"><?= count(array_unique(array_column($students, 'section_id'))) ?></div>
                    <h6 class="text-muted mb-1"><i class="fas fa-layer-group me-2"></i>أقسام</h6>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Students List - Grid Layout -->
        <div class="student-card-grid" 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);
                    
                    // Get first letter for avatar
                    $first_letter = mb_substr($student['student_name'], 0, 1, 'UTF-8');
                    
                    // Determine gender icon
                    $gender_icon = $student['gender'] === 'female' ? 'fa-female' : 'fa-male';
                    $gender_color = $student['gender'] === 'female' ? '#ec4899' : '#3b82f6';
                    ?>
                    
                    <div class="student-card glow-effect" 
                         data-student-id="<?= e($student['student_id']) ?>" 
                         id="student-<?= e($student['student_id']) ?>">
                        
                        <!-- Header Section -->
                        <div class="student-info-header">
                            <div class="student-avatar" style="background: linear-gradient(135deg, <?= $gender_color ?>, <?= $student['gender'] === 'female' ? '#db2777' : '#2563eb' ?>);">
                                <?= $first_letter ?>
                            </div>
                            <div class="flex-grow-1">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <div class="student-name"><?= e($student['student_name']) ?></div>
                                        <div class="student-name-en"><?= e($student['student_name_eng']) ?></div>
                                    </div>
                                    <span class="student-id-badge">#<?= e($student['student_id']) ?></span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Info Chips Section -->
                        <div class="mb-4">
                            <div class="d-flex flex-wrap gap-2 mb-3">
                                <span class="info-chip chip-blue">
                                    <i class="fas fa-university me-2"></i>
                                    <?= e($student['college_name'] ?? '—') ?>
                                </span>
                                <span class="info-chip chip-purple">
                                    <i class="fas fa-layer-group me-2"></i>
                                    <?= e($student['section_name'] ?? 'غير محدد') ?>
                                </span>
                                <span class="info-chip chip-orange">
                                    <i class="fas fa-users me-2"></i>
                                    دفعة <?= e($student['batch_name'] ?? 'غير محدد') ?>
                                </span>
                            </div>
                            
                            <?php if (!empty($student['program_name'])): ?>
                            <div class="mb-2">
                                <span class="info-chip chip-teal">
                                    <i class="fas fa-graduation-cap me-2"></i>
                                    <?= e($student['program_name']) ?>
                                </span>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Status Section -->
                        <div class="row mb-3">
                            <div class="col-6">
                                <div class="d-flex flex-column gap-2">
                                    <span class="info-chip chip-green">
                                        <i class="fas fa-check-circle me-2"></i> مقبول
                                    </span>
                                    <span class="info-chip chip-teal">
                                        <i class="fas fa-heartbeat me-2"></i> لائق طبياً
                                    </span>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="enrollment-status-card <?= $is_enrolled ? 'enrollment-registered' : 'enrollment-not-registered' ?>">
                                    <?php if ($is_enrolled): ?>
                                        <div>
                                            <i class="fas fa-check-circle fa-2x mb-2"></i>
                                            <div class="fw-bold">مسجل</div>
                                            <span class="semester-badge">الفصل <?= e($max_semester) ?></span>
                                        </div>
                                    <?php else: ?>
                                        <div>
                                            <i class="fas fa-exclamation-circle fa-2x mb-2"></i>
                                            <div class="fw-bold">غير مسجل</div>
                                            <small>لم يسجل بعد</small>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex align-items-center">
                                <input type="checkbox" 
                                       class="selection-checkbox student-checkbox" 
                                       value="<?= e($student['student_id']) ?>" 
                                       data-student-name="<?= e($student['student_name']) ?>">
                                <label class="ms-2 mb-0 fw-semibold" style="cursor: pointer;">
                                    تحديد للطباعة
                                </label>
                            </div>
                            
                            <div class="student-actions">
                                <button type="button" class="action-btn action-btn-info" 
                                        onclick="showEnrollmentReport('<?= e($student['student_id']) ?>')"
                                        title="تقرير القيد والتسجيل">
                                    <i class="fas fa-chart-bar"></i>
                                </button>
                                <button type="button" class="action-btn action-btn-warning"
                                        onclick="printSingleCertificate('<?= 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-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-2x"></i>
    <div>
        <strong id="counterNumber" class="fs-4">0</strong> طالب محدد
        <small class="d-block mt-1" id="counterNames"></small>
    </div>
    <button class="btn btn-sm btn-light ms-3" onclick="printRegistrationCertificates()" style="border-radius: 12px;">
        <i class="fas fa-print me-2"></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);
            
            // Add selected class to card
            const card = checkbox.closest('.student-card');
            card.classList.add('selected', 'print-selected');
            card.classList.remove('glow-effect');
        } else {
            const studentId = checkbox.value;
            selectedStudents.delete(studentId);
            selectedStudentNames.delete(studentId);
            
            // Remove selected class from card
            const card = checkbox.closest('.student-card');
            card.classList.remove('selected', 'print-selected');
            card.classList.add('glow-effect');
        }
    });
    
    // 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');
    let count = 0;
    
    checkboxes.forEach(checkbox => {
        if (!checkbox.checked) {
            checkbox.checked = true;
            count++;
        }
    });
    
    updateSelection();
    
    if (count > 0) {
        showToast(`تم تحديد ${count} طالب إضافي`, 'success');
    } else {
        showToast('جميع الطلاب محددون بالفعل', 'info');
    }
}

function deselectAllStudents() {
    const checkboxes = document.querySelectorAll('.student-checkbox');
    let count = 0;
    
    checkboxes.forEach(checkbox => {
        if (checkbox.checked) {
            checkbox.checked = false;
            count++;
        }
    });
    
    updateSelection();
    
    if (count > 0) {
        showToast(`تم إلغاء تحديد ${count} طالب`, 'info');
    } else {
        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');
        loadingToast.hide();
    }, 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) {
        const card = e.target.closest('.student-card');
        if (card && !e.target.matches('input, button, a, i, .btn, .badge, .info-chip, .action-btn, .student-actions *')) {
            const checkbox = card.querySelector('.student-checkbox');
            if (checkbox) {
                checkbox.checked = !checkbox.checked;
                updateSelection();
                
                // Add click animation
                card.style.transform = 'scale(0.98)';
                setTimeout(() => {
                    card.style.transform = '';
                }, 200);
            }
        }
    });
    
    // 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);
    }
    
    // Add hover effects to info chips
    document.querySelectorAll('.info-chip').forEach(chip => {
        chip.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-2px)';
        });
        
        chip.addEventListener('mouseleave', function() {
            this.style.transform = '';
        });
    });
});

// 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'; ?>
