<?php
// registration_management.php - نسخة كاملة مع تصحيح التخصصات ومشكلة تغيير الفصل
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

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

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

// ==================== SECURITY FUNCTIONS ====================

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

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

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

function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

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

$csrf_token = generateCSRFToken();

// ==================== INITIALIZE VARIABLES ====================
$selected_students = [];
$success_message = '';
$error_message = '';
$duplicate_students = [];
$students = [];

$filters_applied = isset($_GET['filter_applied']) && $_GET['filter_applied'] === '1';

if ($filters_applied) {
    $filter_college_id = isset($_GET['filter_college']) && $_GET['filter_college'] !== '' ? validateInt($_GET['filter_college']) : null;
    $filter_section_id = isset($_GET['filter_section']) && $_GET['filter_section'] !== '' ? validateInt($_GET['filter_section']) : null;
    $filter_program_id = isset($_GET['filter_program']) && $_GET['filter_program'] !== '' ? validateInt($_GET['filter_program']) : null;
    $filter_specialization_id = isset($_GET['filter_specialization']) && $_GET['filter_specialization'] !== '' ? validateInt($_GET['filter_specialization']) : null;
    $filter_batch_id = isset($_GET['filter_batch']) && $_GET['filter_batch'] !== '' ? validateInt($_GET['filter_batch']) : null;
    $search_query = validateString($_GET['search_query'] ?? '', 100);
} else {
    if (!$canAll && $scopeCollege !== null) {
        $filter_college_id = $scopeCollege;
    } else {
        $filter_college_id = null;
    }
    $filter_section_id = null;
    $filter_program_id = null;
    $filter_specialization_id = null;
    $filter_batch_id = null;
    $search_query = '';
}

// ==================== BUILD WHERE CLAUSE ====================
$where = " WHERE 1=1 ";
$types = ''; 
$params = [];

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

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

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

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

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

    if (!empty($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;
    }
}

// ==================== SECURE FUNCTIONS ====================

 function generateUniquePaymentReference($mysqli) {
    $unique = false;
    $max_attempts = 10;
    $attempts = 0;
    
    while (!$unique && $attempts < $max_attempts) {
        // Step 1: Get current year (last 2 digits) - e.g., '26' for 2026
        $year_prefix = date('y');  // This will automatically give '26' for year 2026
        
        // Step 2: Generate 14-digit random number (for total 16 digits: 2 + 14 = 16)
        $random_part = str_pad(mt_rand(1, 99999999999999), 14, '0', STR_PAD_LEFT);
        
        // Step 3: Combine to create 16-digit reference
        $reference = $year_prefix . $random_part;  // e.g., '26' + '12345678901234' = '2612345678901234'
        
        // Step 4: Check if this reference already exists in database
        $check_stmt = $mysqli->prepare("SELECT id FROM registrations WHERE payment_reference = ? AND deleted_at IS NULL");
        $check_stmt->bind_param("s", $reference);
        $check_stmt->execute();
        $existing = $check_stmt->get_result()->fetch_assoc();
        $check_stmt->close();
        
        // Step 5: If unique, return it; otherwise try again
        if (!$existing) {
            $unique = true;
            return $reference;
        }
        
        $attempts++;
    }
    
    // Step 6: Fallback if all attempts fail - also 16 digits
    return date('ymd') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT) . 
           str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT) . 
           str_pad(mt_rand(1, 99), 2, '0', STR_PAD_LEFT);
    // Example: '2603151234567890' (YYMMDD + 4-digit + 4-digit + 2-digit = 16 digits)
}
function checkExistingRegistrations($mysqli, $filters) {
    $where_conditions = [];
    $types = '';
    $params = [];
    
    if (!empty($filters['college_id']) && is_numeric($filters['college_id'])) {
        $where_conditions[] = "rc.college_id = ?";
        $types .= 'i';
        $params[] = (int)$filters['college_id'];
    }
    
    if (!empty($filters['section_id']) && is_numeric($filters['section_id'])) {
        $where_conditions[] = "rc.section_id = ?";
        $types .= 'i';
        $params[] = (int)$filters['section_id'];
    }
    
    if (!empty($filters['program_id']) && is_numeric($filters['program_id'])) {
        $where_conditions[] = "rc.program_id = ?";
        $types .= 'i';
        $params[] = (int)$filters['program_id'];
    }
    
    if (!empty($filters['specialization_id']) && is_numeric($filters['specialization_id'])) {
        $where_conditions[] = "rc.specialization_id = ?";
        $types .= 'i';
        $params[] = (int)$filters['specialization_id'];
    }
    
    if (!empty($filters['batch_id']) && is_numeric($filters['batch_id'])) {
        $where_conditions[] = "rc.batch_id = ?";
        $types .= 'i';
        $params[] = (int)$filters['batch_id'];
    }
    
    if (empty($where_conditions)) {
        return [];
    }
    
    $where_clause = implode(' AND ', $where_conditions);
    
    $sql = "
        SELECT 
            r.id, r.student_id, r.student_name, r.payment_reference,
            r.semester_id, r.study_fees, r.registration_fees, r.insurance_fees,
            r.payment_amount, r.due_amount, r.is_paid, r.start, r.end,
            r.created_at, r.updated_at,
            s.name as semester_name,
            c.name as college_name,
            sec.name as section_name,
            p.name as program_name,
            b.value as batch_name,
            sp.specialization_name_ar as specialization_name
        FROM registrations r
        INNER JOIN registration_constraints rc ON r.id = rc.registration_id
        INNER JOIN semesters s ON r.semester_id = s.id
        LEFT JOIN colleges c ON rc.college_id = c.id
        LEFT JOIN sections sec ON rc.section_id = sec.id
        LEFT JOIN programs p ON rc.program_id = p.id
        LEFT JOIN batches b ON rc.batch_id = b.id
        LEFT JOIN specializations sp ON rc.specialization_id = sp.specialization_id
        WHERE {$where_clause}
        AND r.deleted_at IS NULL
        ORDER BY r.created_at DESC
        LIMIT 350
    ";
    
    $stmt = $mysqli->prepare($sql);
    if ($types) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    return $result;
}

// ==================== GET LAST REGISTRATIONS ====================
$current_filters = [
    'college_id' => $filter_college_id,
    'section_id' => $filter_section_id,
    'program_id' => $filter_program_id,
    'specialization_id' => $filter_specialization_id,
    'batch_id' => $filter_batch_id
];

$last_registrations = $filters_applied ? checkExistingRegistrations($mysqli1, $current_filters) : [];

// ==================== HANDLE FORM SUBMISSION ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register_students'])) {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error_message = 'رمز الأمان غير صالح. الرجاء تحديث الصفحة والمحاولة مرة أخرى.';
    } else {
        $semester_id = validateInt($_POST['semester_id'] ?? 0);
        $start_date = validateString($_POST['start_date'] ?? '');
        $end_date = validateString($_POST['end_date'] ?? '');
        $student_ids = $_POST['student_ids'] ?? [];
        
        $start_date_valid = validateDate($start_date);
        $end_date_valid = validateDate($end_date);
        
        $valid_student_ids = [];
        if (is_array($student_ids)) {
            foreach ($student_ids as $id) {
                $clean_id = validateString($id, 50);
                if (!empty($clean_id)) {
                    $valid_student_ids[] = $clean_id;
                }
            }
        }
        
        if (empty($semester_id)) {
            $error_message = 'يرجى اختيار فصل دراسي';
        } elseif (!$start_date_valid) {
            $error_message = 'صيغة تاريخ البداية غير صالحة';
        } elseif (!$end_date_valid) {
            $error_message = 'صيغة تاريخ النهاية غير صالحة';
        } elseif (empty($valid_student_ids)) {
            $error_message = 'لم يتم اختيار أي طلاب صالحين للتسجيل';
        } else {
            $start_timestamp = date('Y-m-d H:i:s', strtotime($start_date));
            $end_timestamp = date('Y-m-d H:i:s', strtotime($end_date));
            
            if (strtotime($end_date) <= strtotime($start_date)) {
                $error_message = 'تاريخ النهاية يجب أن يكون بعد تاريخ البداية';
            } else {
                try {
                    $mysqli1->begin_transaction();
                    
                    $semester_stmt = $mysqli1->prepare("SELECT * FROM semesters WHERE id = ? AND deleted_at IS NULL");
                    $semester_stmt->bind_param("i", $semester_id);
                    $semester_stmt->execute();
                    $semester = $semester_stmt->get_result()->fetch_assoc();
                    $semester_stmt->close();
                    
                    if (!$semester) {
                        throw new Exception('الفصل الدراسي المحدد غير موجود');
                    }
                    
                    $registration_count = 0;
                    $duplicate_count = 0;
                    $duplicate_students = [];
                    $semester_name = $semester['name'] . ' (' . $semester['code'] . ')';
                    
                    foreach ($valid_student_ids as $student_id) {
                        $check_stmt = $mysqli1->prepare("
                            SELECT r.id, r.payment_reference, r.created_at, 
                                   r.study_fees, r.registration_fees, r.insurance_fees,
                                   r.payment_amount, r.is_paid, r.start, r.end,
                                   s.name as semester_name
                            FROM registrations r 
                            INNER JOIN semesters s ON r.semester_id = s.id
                            WHERE r.student_id = ? AND r.semester_id = ? AND r.deleted_at IS NULL
                        ");
                        $check_stmt->bind_param("si", $student_id, $semester_id);
                        $check_stmt->execute();
                        $existing_registration = $check_stmt->get_result()->fetch_assoc();
                        $check_stmt->close();
                        
                        if ($existing_registration) {
                            $duplicate_count++;
                            
                            $student_stmt = $mysqli1->prepare("SELECT student_name FROM students WHERE student_id = ?");
                            $student_stmt->bind_param("s", $student_id);
                            $student_stmt->execute();
                            $student_name_result = $student_stmt->get_result()->fetch_assoc();
                            $student_name = $student_name_result['student_name'] ?? $student_id;
                            $student_stmt->close();
                            
                            $duplicate_students[] = [
                                'student_id' => $student_id,
                                'student_name' => $student_name,
                                'payment_reference' => $existing_registration['payment_reference'],
                                'created_at' => $existing_registration['created_at'],
                                'is_paid' => $existing_registration['is_paid'],
                                'semester_name' => $existing_registration['semester_name']
                            ];
                            
                            continue;
                        }
                        
                        $student_stmt = $mysqli1->prepare("
                            SELECT student_id, student_name, college_id, section_id, program_id, 
                                   specialization_id, program_fees, registration_fees, insurance_fees 
                            FROM students 
                            WHERE student_id = ? AND deleted_at IS NULL
                        ");
                        $student_stmt->bind_param("s", $student_id);
                        $student_stmt->execute();
                        $student = $student_stmt->get_result()->fetch_assoc();
                        $student_stmt->close();

                        if (!$student) {
                            continue;
                        }

                        $payment_reference = generateUniquePaymentReference($mysqli1);

                        $study_fees = !empty($student['program_fees']) && is_numeric($student['program_fees']) ? floatval($student['program_fees']) : 0.00;
                        $registration_fees = !empty($student['registration_fees']) && is_numeric($student['registration_fees']) ? floatval($student['registration_fees']) : 0.00;
                        $insurance_fees = !empty($student['insurance_fees']) && is_numeric($student['insurance_fees']) ? floatval($student['insurance_fees']) : 0.00;
                        $total_fees = $study_fees + $registration_fees + $insurance_fees;

                        $insert_stmt = $mysqli1->prepare("
                            INSERT INTO registrations (
                                student_id, student_name, payment_reference, semester_id, 
                                study_fees, registration_fees, insurance_fees, payment_amount, 
                                due_amount, is_paid, fee_type_id, user_id, start, end, created_at, updated_at
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                        ");
                        
                        $is_paid = 0;
                        $fee_type_id = 1;
                        $due_amount = $total_fees;
                        
                        $insert_stmt->bind_param(
                            "sssiddddiiiiss", 
                            $student['student_id'],
                            $student['student_name'],
                            $payment_reference,
                            $semester_id,
                            $study_fees,
                            $registration_fees,
                            $insurance_fees,
                            $total_fees,
                            $due_amount,
                            $is_paid,
                            $fee_type_id,
                            $committeeId,
                            $start_timestamp,
                            $end_timestamp
                        );
                        
                        $insert_stmt->execute();
                        $registration_id = $insert_stmt->insert_id;
                        $insert_stmt->close();
                        
                        $table_check = $mysqli1->query("SHOW TABLES LIKE 'registration_constraints'");
                        
                        if ($table_check && $table_check->num_rows > 0) {
                            $constraint_stmt = $mysqli1->prepare("
                                INSERT INTO registration_constraints (
                                    registration_id, student_id, semester_id, college_id, 
                                    section_id, program_id, specialization_id, batch_id, created_at, updated_at
                                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                            ");
                            
                            $constraint_stmt->bind_param(
                                "isiisiii",
                                $registration_id,
                                $student['student_id'],
                                $semester_id,
                                $student['college_id'],
                                $student['section_id'],
                                $student['program_id'],
                                $student['specialization_id'],
                                $filter_batch_id
                            );
                            
                            $constraint_stmt->execute();
                            $constraint_stmt->close();
                        }
                        
                        $registration_count++;
                    }
                    
                    $mysqli1->commit();
                    
                    $success_message = "تم تسجيل {$registration_count} طالب بنجاح في الفصل الدراسي: <strong>{$semester_name}</strong>";
                    
                    if ($duplicate_count > 0) {
                        $success_message .= "<br><br><div class='alert alert-warning mb-0 mt-2'>";
                        $success_message .= "<strong><i class='fas fa-exclamation-triangle me-1'></i>تنبيه:</strong> تم تخطي {$duplicate_count} طالب مسجلين مسبقاً في هذا الفصل";
                        $success_message .= "<br><small class='text-muted'>لن يتم إنشاء تسجيلات جديدة لهؤلاء الطلاب</small>";
                        
                        $success_message .= "<div class='mt-2 p-2 bg-white bg-opacity-50 rounded'>";
                        $success_message .= "<strong>الطلاب المكررون:</strong>";
                        $success_message .= "<table class='table table-sm table-borderless mb-0 mt-2'>";
                        $success_message .= "<thead><tr><th>رقم الطالب</th><th>اسم الطالب</th><th>رقم المرجع</th><th>تاريخ التسجيل</th><th>الحالة</th></tr></thead><tbody>";
                        
                        foreach ($duplicate_students as $duplicate) {
                            $status_badge = $duplicate['is_paid'] == 1 ? 
                                '<span class="badge bg-success">مدفوع</span>' : 
                                '<span class="badge bg-warning">غير مدفوع</span>';
                            
                            $formatted_date = date('Y-m-d', strtotime($duplicate['created_at']));
                            
                            $success_message .= "<tr>";
                            $success_message .= "<td><code>" . htmlspecialchars($duplicate['student_id']) . "</code></td>";
                            $success_message .= "<td>" . htmlspecialchars($duplicate['student_name']) . "</td>";
                            $success_message .= "<td><small>" . htmlspecialchars($duplicate['payment_reference']) . "</small></td>";
                            $success_message .= "<td><small>{$formatted_date}</small></td>";
                            $success_message .= "<td>{$status_badge}</td>";
                            $success_message .= "</tr>";
                        }
                        
                        $success_message .= "</tbody></table>";
                        $success_message .= "</div></div>";
                    }
                    
                } catch (Exception $e) {
                    $mysqli1->rollback();
                    $error_message = "حدث خطأ أثناء التسجيل: " . $e->getMessage();
                    
                    error_log("Registration Error: " . $e->getMessage());
                    error_log("SQL Error: " . $mysqli1->error);
                }
            }
        }
    }
}

// ==================== GET FILTERED STUDENTS ====================
if ($filters_applied) {
    $sqlStudents = "
        SELECT 
            s.student_id, s.student_name, s.student_name_eng,
            s.college_id, s.section_id, s.program_id, s.specialization_id, s.batch_id,
            s.profile_completed, s.interview_status, s.medically_fit,
            s.program_fees, s.registration_fees, s.insurance_fees,
            c.name AS college_name,
            sec.name AS section_name,
            p.name AS program_name,
            sp.specialization_name_ar AS specialization_name,
            b.value AS batch_name,
            a.name AS admission_type,
            (SELECT COUNT(*) FROM registrations r WHERE r.student_id = s.student_id AND r.deleted_at IS NULL) as registration_count
        FROM students s
        LEFT JOIN colleges c ON s.college_id = c.id
        LEFT JOIN sections sec ON s.section_id = sec.id
        LEFT JOIN programs p ON s.program_id = p.id
        LEFT JOIN specializations sp ON s.specialization_id = sp.specialization_id
        LEFT JOIN batches b ON s.batch_id = b.id
        LEFT JOIN admissions a ON s.admission_id = a.id
        {$where}
        ORDER BY s.student_id DESC
        LIMIT 350
    ";

    $students_stmt = $mysqli1->prepare($sqlStudents);
    if ($types) {
        $students_stmt->bind_param($types, ...$params);
    }
    $students_stmt->execute();
    $students = $students_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $students_stmt->close();
} else {
    $students = [];
}

// ==================== GET FILTER OPTIONS ====================

$semesters_stmt = $mysqli1->prepare("SELECT id, name, code FROM semesters WHERE deleted_at IS NULL ORDER BY id DESC");
$semesters_stmt->execute();
$semesters = $semesters_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$semesters_stmt->close();

$colleges = [];
$colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
$colleges_stmt->execute();
$colleges_result = $colleges_stmt->get_result();
while ($row = $colleges_result->fetch_assoc()) {
    $colleges[] = $row;
}
$colleges_stmt->close();

$batches = [];
$batches_stmt = $mysqli1->prepare("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY id");
$batches_stmt->execute();
$batches_result = $batches_stmt->get_result();
while ($row = $batches_result->fetch_assoc()) {
    $batches[] = $row;
}
$batches_stmt->close();

// Get sections based on selected college
$sections = [];
if ($filter_college_id) {
    $sections_stmt = $mysqli1->prepare("SELECT id, name FROM sections WHERE parent = ? AND deleted_at IS NULL ORDER BY name");
    $sections_stmt->bind_param('i', $filter_college_id);
    $sections_stmt->execute();
    $sections_result = $sections_stmt->get_result();
    while ($row = $sections_result->fetch_assoc()) {
        $sections[] = $row;
    }
    $sections_stmt->close();
}

// Get all programs
$programs = [];
$programs_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
$programs_stmt->execute();
$programs_result = $programs_stmt->get_result();
while ($row = $programs_result->fetch_assoc()) {
    $programs[] = $row;
}
$programs_stmt->close();

// Get specializations based on selected section and program
$specializations = [];
if ($filter_section_id && $filter_program_id) {
    $spec_stmt = $mysqli1->prepare("
        SELECT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ");
    $spec_stmt->bind_param('ii', $filter_section_id, $filter_program_id);
    $spec_stmt->execute();
    $spec_result = $spec_stmt->get_result();
    while ($row = $spec_result->fetch_assoc()) {
        $specializations[] = $row;
    }
    $spec_stmt->close();
}

$last_semester = null;
if ($filters_applied && ($filter_college_id || $filter_section_id || $filter_program_id || $filter_specialization_id || $filter_batch_id)) {
    $where_conditions = [];
    $where_params = [];
    $where_types = "";
    
    if ($filter_college_id) {
        $where_conditions[] = "st.college_id = ?";
        $where_types .= "i";
        $where_params[] = $filter_college_id;
    }
    
    if ($filter_section_id) {
        $where_conditions[] = "st.section_id = ?";
        $where_types .= "i";
        $where_params[] = $filter_section_id;
    }
    
    if ($filter_program_id) {
        $where_conditions[] = "st.program_id = ?";
        $where_types .= "i";
        $where_params[] = $filter_program_id;
    }
    
    if ($filter_specialization_id) {
        $where_conditions[] = "st.specialization_id = ?";
        $where_types .= "i";
        $where_params[] = $filter_specialization_id;
    }
    
    if ($filter_batch_id) {
        $where_conditions[] = "st.batch_id = ?";
        $where_types .= "i";
        $where_params[] = $filter_batch_id;
    }
    
    $where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";
    
    $last_semester_sql = "
        SELECT s.id, s.name, s.code, MAX(r.created_at) as last_registration
        FROM semesters s
        INNER JOIN registrations r ON s.id = r.semester_id
        INNER JOIN students st ON r.student_id = st.student_id
        {$where_clause}
        AND r.deleted_at IS NULL
        GROUP BY s.id, s.name, s.code
        ORDER BY last_registration DESC
        LIMIT 1
    ";
    
    $last_semester_stmt = $mysqli1->prepare($last_semester_sql);
    if (!empty($where_params)) {
        $last_semester_stmt->bind_param($where_types, ...$where_params);
    }
    $last_semester_stmt->execute();
    $last_semester_result = $last_semester_stmt->get_result();
    $last_semester = $last_semester_result->fetch_assoc();
    $last_semester_stmt->close();
}

// Get selected filter names for display
$selected_college_name = '';
$selected_section_name = '';
$selected_program_name = '';
$selected_specialization_name = '';
$selected_batch_name = '';

if ($filter_college_id) {
    foreach ($colleges as $college) {
        if ($college['id'] == $filter_college_id) {
            $selected_college_name = $college['name'];
            break;
        }
    }
}

if ($filter_section_id) {
    foreach ($sections as $section) {
        if ($section['id'] == $filter_section_id) {
            $selected_section_name = $section['name'];
            break;
        }
    }
}

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

if ($filter_specialization_id) {
    foreach ($specializations as $spec) {
        if ($spec['specialization_id'] == $filter_specialization_id) {
            $selected_specialization_name = $spec['specialization_name_ar'];
            break;
        }
    }
}

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

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة التسجيلات - لوحة اللجنة</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* ==================== RESET & BASE STYLES ==================== */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body { 
            font-family: 'Cairo', sans-serif !important;
            background-color: #f8f9fa;
            padding-bottom: 30px;
            line-height: 1.6;
        }
        
        /* ==================== TYPOGRAPHY ==================== */
        h1 { font-size: 2.2rem; font-weight: 800; }
        h2 { font-size: 2rem; font-weight: 700; }
        h3 { font-size: 1.8rem; font-weight: 700; }
        h4 { font-size: 1.6rem; font-weight: 700; }
        h5 { font-size: 1.4rem; font-weight: 700; }
        h6 { font-size: 1.2rem; font-weight: 700; }
        
        p, li, .text-content { font-size: 1rem; }
        small { font-size: 0.9rem; }
        
        .form-label { 
            font-size: 1.1rem; 
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: #2c3e50;
        }
        
        .form-control, .form-select, .input-group-text, .btn {
            font-size: 1rem !important;
            padding: 0.6rem 1rem !important;
        }
        
        /* RTL dropdown arrow fix */
        .form-select {
            background-position: left 0.75rem center !important;
            padding-left: 2.25rem !important;
            padding-right: 0.75rem !important;
        }
        
        .input-group-text i {
            font-size: 1.1rem;
        }
        
        .table {
            font-size: 0.95rem;
        }
        
        .table th {
            font-size: 1rem;
            font-weight: 700;
            background-color: #f8f9fa;
        }
        
        .table td {
            font-size: 0.95rem;
            vertical-align: middle;
        }
        
        /* ==================== CARD STYLES ==================== */
        .card-arabic {
            border: 1px solid #e5e7eb;
            border-radius: 20px;
            background: #fff;
            box-shadow: 0 12px 28px rgba(0,0,0,.08);
            margin-bottom: 25px;
        }
        
        .filter-icon {
            width: 48px;
            height: 48px;
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.3rem;
            box-shadow: 0 4px 10px rgba(59, 130, 246, 0.3);
        }
        
        /* ==================== FILTER SUMMARY ==================== */
        .filter-summary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 16px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
        }
        
        .filter-summary h5 {
            font-size: 1.4rem;
            margin-bottom: 0;
        }
        
        .filter-summary-item {
            background: rgba(255, 255, 255, 0.15);
            border-radius: 10px;
            padding: 12px 18px;
            margin-bottom: 10px;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .filter-summary-label {
            font-size: 0.95rem;
            opacity: 0.9;
            margin-bottom: 5px;
        }
        
        .filter-summary-value {
            font-weight: 700;
            font-size: 1.2rem;
        }
        
        /* ==================== SEARCH SECTION ==================== */
        .search-section {
            background: linear-gradient(135deg, #f0f9ff, #e0f2fe);
            border: 1px solid #bae6fd;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 25px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
        }
        
        .search-section h6 {
            font-size: 1.2rem;
        }
        
        /* ==================== BADGES & TAGS ==================== */
        .badge {
            font-size: 0.85rem;
            padding: 0.4rem 0.7rem;
            font-weight: 500;
        }
        
        .badge-lg {
            font-size: 0.95rem;
            padding: 0.5rem 1rem;
        }
        
        .batch-badge {
            font-size: 0.85rem;
            padding: 0.35rem 0.65rem;
        }
        
        .fees-badge {
            font-size: 0.8rem;
            padding: 0.25rem 0.5rem;
        }
        
        .admission-badge {
            font-size: 0.85rem;
            padding: 0.3rem 0.8rem;
            background: linear-gradient(135deg, #059669, #047857);
            color: white;
            border-radius: 20px;
            display: inline-block;
            white-space: nowrap;
        }
        
        .filter-status {
            font-size: 0.95rem;
            padding: 0.4rem 0.8rem;
            border-radius: 30px;
        }
        
        .filter-status.applied {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
            border: none;
        }
        
        .filter-status.not-applied {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
            border: none;
        }
        
        /* ==================== CHECKBOX CELL ==================== */
        .checkbox-cell {
            width: 60px;
            text-align: center;
        }
        
        .checkbox-cell input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }
        
        /* ==================== DATE INPUTS ==================== */
        .date-inputs {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        /* ==================== WARNING ALERT ==================== */
        .warning-alert {
            border-right: 5px solid #f59e0b;
            background: linear-gradient(135deg, #fffbeb, #fef3c7);
        }
        
        /* ==================== AJAX LOADING ==================== */
        .ajax-loading {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            display: none;
            color: #3b82f6;
            font-size: 1.2rem;
        }
        
        /* ==================== FORM GROUP ==================== */
        .form-group {
            position: relative;
            margin-bottom: 1.2rem;
        }
        
        /* ==================== INFO MESSAGE ==================== */
        .info-message {
            background: linear-gradient(135deg, #e0f2fe, #bae6fd);
            border: 1px solid #7dd3fc;
            color: #0369a1;
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            font-size: 1rem;
        }
        
        /* ==================== REGISTRATION STATUS ==================== */
        .already-registered {
            background-color: #f8f9fa !important;
            opacity: 0.8;
        }
        
        .already-registered td {
            color: #6c757d !important;
        }
        
        .duplicate-indicator {
            font-size: 0.8rem;
            padding: 0.25rem 0.5rem;
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: white;
            border-radius: 20px;
            margin-right: 5px;
        }
        
        /* ==================== PRE-REGISTRATION CHECK ==================== */
        .pre-registration-check {
            background: linear-gradient(135deg, #f8fafc, #f1f5f9);
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 25px;
            border: 1px solid #e2e8f0;
        }
        
        .check-result {
            padding: 15px;
            border-radius: 12px;
            margin-top: 10px;
        }
        
        .check-result.has-duplicates {
            background: linear-gradient(135deg, #fffbeb, #fef3c7);
            border: 1px solid #fcd34d;
        }
        
        .check-result.no-duplicates {
            background: linear-gradient(135deg, #ecfdf5, #d1fae5);
            border: 1px solid #6ee7b7;
        }
        
        /* ==================== SPECIALIZATION ==================== */
        .bg-purple {
            background: linear-gradient(135deg, #8b5cf6, #7c3aed) !important;
            color: white;
            font-size: 0.85rem;
            padding: 0.4rem 0.7rem;
        }
        
        .spec-hint {
            font-size: 0.85rem;
            color: #64748b;
            margin-top: 0.3rem;
        }
        
        /* ==================== BUTTONS ==================== */
        .btn {
            font-size: 1rem;
            padding: 0.6rem 1.2rem;
            border-radius: 10px;
            font-weight: 600;
        }
        
        .btn i {
            font-size: 1.1rem;
            margin-left: 0.5rem;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            border: none;
        }
        
        .btn-success {
            background: linear-gradient(135deg, #10b981, #059669);
            border: none;
        }
        
        .btn-outline-primary {
            border: 2px solid #3b82f6;
            color: #3b82f6;
        }
        
        .btn-outline-secondary {
            border: 2px solid #6c757d;
            color: #6c757d;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 0.25rem rgba(59, 130, 246, 0.25);
        }
        
        select:disabled {
            background-color: #f1f5f9 !important;
            opacity: 0.8;
            cursor: not-allowed;
        }
        
        @media (max-width: 768px) {
            h3 { font-size: 1.5rem; }
            h5 { font-size: 1.2rem; }
            .table { font-size: 0.85rem; }
            .filter-summary-value { font-size: 1rem; }
            .checkbox-cell { width: 40px; }
            .checkbox-cell input[type="checkbox"] { width: 18px; height: 18px; }
        }
    </style>
</head>
<body>
    <div class="container py-4" dir="rtl">
        <!-- Header -->
        <div class="d-flex align-items-center justify-content-between mb-4">
            <div>
                <h3 class="mb-1 fw-bold">
                    <i class="fas fa-users-gear me-2 text-primary"></i>
                    إدارة تسجيلات الطلاب
                </h3>
                <p class="text-muted mb-0" style="font-size: 1.1rem;">
                    <i class="fas fa-arrow-left me-1"></i>
                    تسجيل الطلاب في الفصول الدراسية
                </p>
            </div>
            <div>
                <span class="filter-status <?= $filters_applied ? 'applied' : 'not-applied' ?> me-2">
                    <i class="fas fa-<?= $filters_applied ? 'check-circle' : 'exclamation-triangle' ?> me-1"></i>
                    <?= $filters_applied ? 'تم تطبيق التصفية' : 'لم يتم تطبيق أي تصفية' ?>
                </span>
                <a class="btn btn-outline-secondary" href="admin_dashboard.php">
                    <i class="fas fa-arrow-right me-2"></i>
                    العودة للوحة التحكم
                </a>
            </div>
        </div>

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

        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle fa-lg me-2"></i>
                <?= $success_message ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($error_message): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle fa-lg me-2"></i>
                <?= htmlspecialchars($error_message, ENT_QUOTES, 'UTF-8') ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Last Registrations Warning -->
        <?php if ($filters_applied && !empty($last_registrations)): ?>
            <div class="alert alert-warning alert-dismissible fade show warning-alert" role="alert">
                <div class="d-flex align-items-center">
                    <i class="fas fa-exclamation-triangle fa-2x me-3"></i>
                    <div>
                        <strong style="font-size: 1.1rem;">تنبيه: يوجد تسجيلات سابقة بنفس عوامل التصفية المحددة</strong>
                        <br>
                        <span style="font-size: 0.95rem;">تم العثور على <?= count($last_registrations) ?> تسجيل سابق. يرجى التأكد من عدم التكرار.</span>
                    </div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- ==================== FILTER CARD ==================== -->
        <div class="card card-arabic p-4 mb-4">
            <div class="d-flex align-items-center mb-4">
                <div class="filter-icon me-3">
                    <i class="fas fa-filter"></i>
                </div>
                <div>
                    <h5 class="fw-bold mb-1">فلتر الطلاب</h5>
                    <p class="text-muted mb-0" style="font-size: 1rem;">اختر معايير التصفية لعرض الطلاب المناسبين</p>
                </div>
                <div class="ms-auto">
                    <span class="badge bg-light text-dark border px-3 py-2" style="font-size: 0.95rem;">
                        <i class="fas fa-sliders-h me-1"></i>
                        <?= $filters_applied ? 'تصفية مطبقة' : 'في انتظار التطبيق' ?>
                    </span>
                </div>
            </div>
            
            <form method="get" class="row g-4" id="filterForm">
                <input type="hidden" name="filter_applied" value="1">
                
                <!-- الصف الأول: الكلية والدفعة -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label">
                                <i class="fas fa-university me-2 text-primary"></i>
                                الكلية
                            </label>
                            <select class="form-select" name="filter_college" id="filter_college">
                                <option value="">اختر الكلية</option>
                                <?php foreach ($colleges as $college): ?>
                                    <?php 
                                    if (!$canAll && $scopeCollege !== null && $college['id'] != $scopeCollege) {
                                        continue;
                                    }
                                    ?>
                                    <option value="<?= (int)$college['id'] ?>" <?= ($filter_college_id == $college['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label">
                                <i class="fas fa-calendar-alt me-2 text-primary"></i>
                                الدفعة
                            </label>
                            <select class="form-select" name="filter_batch" id="filter_batch">
                                <option value="">جميع الدفعات</option>
                                <?php foreach ($batches as $batch): ?>
                                    <option value="<?= (int)$batch['id'] ?>" <?= ($filter_batch_id == $batch['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($batch['value'], ENT_QUOTES, 'UTF-8') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
                
                <!-- الصف الثاني: القسم والبرنامج -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group position-relative">
                            <label class="form-label">
                                <i class="fas fa-layer-group me-2 text-primary"></i>
                                القسم
                            </label>
                            <select class="form-select" name="filter_section" id="filter_section" 
                                <?= !$filter_college_id ? 'disabled' : '' ?>>
                                <option value=""><?= $filter_college_id ? 'اختر القسم' : 'اختر الكلية أولاً' ?></option>
                                <?php if (!empty($sections)): ?>
                                    <?php foreach ($sections as $section): ?>
                                        <option value="<?= (int)$section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($section['name'], ENT_QUOTES, 'UTF-8') ?>
                                        </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                            <div class="ajax-loading" id="sectionLoading">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-group position-relative">
                            <label class="form-label">
                                <i class="fas fa-graduation-cap me-2 text-primary"></i>
                                البرنامج
                            </label>
                            <select class="form-select" name="filter_program" id="filter_program" 
                                <?= !$filter_college_id ? 'disabled' : '' ?>>
                                <option value=""><?= $filter_college_id ? 'اختر البرنامج' : 'اختر الكلية أولاً' ?></option>
                                <?php if (!empty($programs)): ?>
                                    <?php foreach ($programs as $program): ?>
                                        <option value="<?= (int)$program['id'] ?>" <?= ($filter_program_id == $program['id']) ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($program['name'], ENT_QUOTES, 'UTF-8') ?>
                                        </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                            <div class="ajax-loading" id="programLoading">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- الصف الثالث: التخصص والبحث -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group position-relative">
                            <label class="form-label">
                                <i class="fas fa-microscope me-2 text-primary"></i>
                                التخصص
                            </label>
                            <select class="form-select" name="filter_specialization" id="filter_specialization" disabled>
                                <option value="">اختر القسم والبرنامج أولاً</option>
                            </select>
                            <div class="ajax-loading" id="specLoading">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                            <small class="spec-hint d-block" id="specHint">
                                <i class="fas fa-info-circle me-1"></i>الرجاء اختيار القسم والبرنامج أولاً
                            </small>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label">
                                <i class="fas fa-search me-2 text-primary"></i>
                                بحث عن طالب
                            </label>
                            <div class="input-group">
                                <input type="text" 
                                       class="form-control" 
                                       name="search_query" 
                                       id="search_query"
                                       placeholder="ابحث برقم الطالب أو الاسم..."
                                       value="<?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?>">
                                <button type="button" class="btn btn-outline-secondary" onclick="clearSearch()" title="مسح البحث">
                                    <i class="fas fa-times"></i>
                                </button>
                                <span class="input-group-text">
                                    <i class="fas fa-search"></i>
                                </span>
                            </div>
                            <small class="text-muted d-block mt-1">رقم الطالب، الاسم (عربي أو إنجليزي)</small>
                        </div>
                    </div>
                </div>
                
                <!-- أزرار التحكم -->
                <div class="row mt-3">
                    <div class="col-12">
                        <div class="d-flex gap-3">
                            <button type="submit" class="btn btn-primary px-5 py-2">
                                <i class="fas fa-filter me-2"></i>
                                تطبيق التصفية
                            </button>
                            <a href="registration_management.php" class="btn btn-outline-secondary px-5 py-2">
                                <i class="fas fa-sync-alt me-2"></i>
                                إعادة تعيين
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <!-- ==================== FILTER SUMMARY SECTION ==================== -->
        <?php if ($filters_applied): ?>
        <div class="filter-summary mb-4">
            <div class="d-flex align-items-center justify-content-between mb-3">
                <h5 class="text-white mb-0">
                    <i class="fas fa-sliders-h me-2"></i>
                    ملخص التصفية المطبقة
                </h5>
                <span class="badge bg-white text-dark px-3 py-2" style="font-size: 1rem;">
                    <i class="fas fa-users me-1"></i>
                    عدد الطلاب: <?= count($students) ?>
                </span>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <?php if (!empty($search_query)): ?>
                    <div class="filter-summary-item">
                        <div class="filter-summary-label">
                            <i class="fas fa-search me-1"></i>
                            البحث
                        </div>
                        <div class="filter-summary-value">
                            "<?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?>"
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($selected_college_name)): ?>
                    <div class="filter-summary-item">
                        <div class="filter-summary-label">
                            <i class="fas fa-university me-1"></i>
                            الكلية
                        </div>
                        <div class="filter-summary-value">
                            <?= htmlspecialchars($selected_college_name, ENT_QUOTES, 'UTF-8') ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($selected_section_name)): ?>
                    <div class="filter-summary-item">
                        <div class="filter-summary-label">
                            <i class="fas fa-layer-group me-1"></i>
                            القسم
                        </div>
                        <div class="filter-summary-value">
                            <?= htmlspecialchars($selected_section_name, ENT_QUOTES, 'UTF-8') ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-6">
                    <?php if (!empty($selected_program_name)): ?>
                    <div class="filter-summary-item">
                        <div class="filter-summary-label">
                            <i class="fas fa-graduation-cap me-1"></i>
                            البرنامج
                        </div>
                        <div class="filter-summary-value">
                            <?= htmlspecialchars($selected_program_name, ENT_QUOTES, 'UTF-8') ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($selected_specialization_name)): ?>
                    <div class="filter-summary-item">
                        <div class="filter-summary-label">
                            <i class="fas fa-microscope me-1"></i>
                            التخصص
                        </div>
                        <div class="filter-summary-value">
                            <?= htmlspecialchars($selected_specialization_name, ENT_QUOTES, 'UTF-8') ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($selected_batch_name)): ?>
                    <div class="filter-summary-item">
                        <div class="filter-summary-label">
                            <i class="fas fa-calendar-alt me-1"></i>
                            الدفعة
                        </div>
                        <div class="filter-summary-value">
                            <?= htmlspecialchars($selected_batch_name, ENT_QUOTES, 'UTF-8') ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- ==================== SEARCH SECTION ==================== -->
        <?php if ($filters_applied && !empty($students)): ?>
        <div class="search-section mb-4">
            <div class="d-flex align-items-center mb-3">
                <i class="fas fa-search fa-lg text-primary me-2"></i>
                <h5 class="fw-bold mb-0">بحث في الجدول</h5>
            </div>
            <div class="row g-3 align-items-center">
                <div class="col-md-12">
                    <div class="input-group input-group-lg">
                        <input type="text" 
                               class="form-control form-control-lg" 
                               id="tableSearchInput"
                               placeholder="اكتب هنا للبحث في الجدول... (رقم الطالب، الاسم، الكلية، القسم، البرنامج)"
                               value="">
                        <button class="btn btn-outline-secondary" type="button" onclick="clearTableSearch()">
                            <i class="fas fa-times"></i>
                        </button>
                        <span class="input-group-text">
                            <i class="fas fa-search"></i>
                        </span>
                    </div>
                    <small class="text-muted mt-2 d-block">
                        <i class="fas fa-info-circle me-1"></i>
                        يمكنك البحث في جميع أعمدة الجدول
                    </small>
                </div>
            </div>
            
            <!-- Search stats -->
            <div id="searchStats" class="mt-3 p-2 bg-light rounded text-center" style="display: none; font-size: 1rem;">
                <i class="fas fa-chart-bar me-1 text-primary"></i>
                <span id="searchCount">0</span> نتيجة من أصل <span id="totalRows">0</span>
            </div>
        </div>
        <?php endif; ?>

        <!-- ==================== STUDENTS TABLE SECTION ==================== -->
        <?php if ($filters_applied && !empty($students)): ?>
        <div class="card card-arabic p-4">
            <!-- Registration Form -->
            <form method="post" id="registrationForm">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf_token, ENT_QUOTES, 'UTF-8') ?>">
                
                <div class="d-flex align-items-center mb-4">
                    <h5 class="fw-bold mb-0">
                        <i class="fas fa-user-graduate me-2 text-primary"></i>
                        تسجيل الطلاب في فصل دراسي
                    </h5>
                    <span class="badge bg-primary ms-3 px-3 py-2" style="font-size: 1rem;">
                        <i class="fas fa-users me-1"></i>
                        <?= count($students) ?> طالب متاح
                    </span>
                    <?php if (!empty($last_registrations)): ?>
                        <span class="badge bg-warning ms-2 px-3 py-2" style="font-size: 0.95rem;">
                            <i class="fas fa-exclamation-triangle me-1"></i>
                            يوجد تسجيلات سابقة
                        </span>
                    <?php endif; ?>
                </div>
                
                <!-- Pre-registration Duplicate Check -->
                <div class="pre-registration-check" id="preCheckSection">
                    <div class="d-flex align-items-center mb-3">
                        <i class="fas fa-search fa-lg me-2 text-primary"></i>
                        <h6 class="fw-bold mb-0">فحص مسبق للتسجيلات المكررة</h6>
                    </div>
                    <div class="row g-3 align-items-center">
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">اختر الفصل الدراسي:</label>
                            <select class="form-control" id="pre_check_semester" onchange="checkDuplicates()">
                                <option value="">-- اختر فصل دراسي --</option>
                                <?php foreach ($semesters as $semester): ?>
                                    <option value="<?= (int)$semester['id'] ?>">
                                        <?= htmlspecialchars($semester['name'], ENT_QUOTES, 'UTF-8') ?> (<?= htmlspecialchars($semester['code'], ENT_QUOTES, 'UTF-8') ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-8">
                            <div id="checkResult" class="check-result">
                                <div class="text-center text-muted py-3">
                                    <i class="fas fa-search fa-2x mb-2"></i>
                                    <p class="mb-0" style="font-size: 1rem;">الرجاء اختيار فصل دراسي للتحقق من التسجيلات المكررة</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Semester and Dates Section -->
                <div class="date-inputs mb-4">
                    <h6 class="fw-bold mb-3">
                        <i class="fas fa-calendar-alt me-2 text-primary"></i>
                        تفاصيل الفصل الدراسي
                    </h6>
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">الفصل الدراسي:</label>
                            <select class="form-control" name="semester_id" id="semester_id" required onchange="updateDuplicateCheck()">
                                <option value="">-- اختر الفصل الدراسي --</option>
                                <?php foreach ($semesters as $semester): ?>
                                    <option value="<?= (int)$semester['id'] ?>">
                                        <?= htmlspecialchars($semester['name'], ENT_QUOTES, 'UTF-8') ?> (<?= htmlspecialchars($semester['code'], ENT_QUOTES, 'UTF-8') ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">تاريخ البداية:</label>
                            <input type="date" class="form-control" name="start_date" required 
                                   min="<?= date('Y-m-d') ?>" value="<?= date('Y-m-d') ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">تاريخ النهاية:</label>
                            <input type="date" class="form-control" name="end_date" required 
                                   min="<?= date('Y-m-d', strtotime('+1 day')) ?>" 
                                   value="<?= date('Y-m-d', strtotime('+30 days')) ?>">
                        </div>
                    </div>
                </div>
                
                <!-- Action Buttons -->
                <div class="row g-3 align-items-end mb-4">
                    <div class="col-md-12">
                        <div class="d-flex gap-3">
                            <button type="button" class="btn btn-outline-primary" onclick="selectAllStudents()">
                                <i class="fas fa-check-square me-1"></i>
                                تحديد الكل
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="deselectAllStudents()">
                                <i class="fas fa-times-circle me-1"></i>
                                إلغاء الكل
                            </button>
                            <button type="submit" name="register_students" class="btn btn-success" id="submitBtn">
                                <i class="fas fa-user-plus me-1"></i>
                                تسجيل الطلاب المحددين
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Students Table -->
                <div class="table-responsive mt-4">
                    <table class="table table-striped table-hover student-table" id="studentsTable">
                        <thead>
                            <tr>
                                <th class="checkbox-cell">
                                    <input type="checkbox" id="selectAll" onchange="toggleAllStudents(this)">
                                </th>
                                <th>#</th>
                                <th>رقم الطالب</th>
                                <th>اسم الطالب</th>
                                <th>الكلية</th>
                                <th>القسم</th>
                                <th>البرنامج</th>
                                <th>التخصص</th>
                                <th>الدفعة</th>
                                <th>نوع القبول</th>
                                <th>الرسوم</th>
                                <th>التسجيلات</th>
                                <th>الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody id="studentsTableBody">
                            <?php 
                            $counter = 1; 
                            $selected_semester_id = isset($_POST['semester_id']) ? validateInt($_POST['semester_id']) : 0;
                            
                            $registered_students = [];
                            if ($selected_semester_id > 0) {
                                $reg_stmt = $mysqli1->prepare("
                                    SELECT student_id FROM registrations 
                                    WHERE semester_id = ? AND deleted_at IS NULL
                                ");
                                $reg_stmt->bind_param("i", $selected_semester_id);
                                $reg_stmt->execute();
                                $reg_result = $reg_stmt->get_result();
                                while ($row = $reg_result->fetch_assoc()) {
                                    $registered_students[] = $row['student_id'];
                                }
                                $reg_stmt->close();
                            }
                            ?>
                            
                            <?php foreach ($students as $student): ?>
                                <?php
                                $is_already_registered = in_array($student['student_id'], $registered_students);
                                
                                $study_fees = !empty($student['program_fees']) && is_numeric($student['program_fees']) ? floatval($student['program_fees']) : 0.00;
                                $registration_fees = !empty($student['registration_fees']) && is_numeric($student['registration_fees']) ? floatval($student['registration_fees']) : 0.00;
                                $insurance_fees = !empty($student['insurance_fees']) && is_numeric($student['insurance_fees']) ? floatval($student['insurance_fees']) : 0.00;
                                $total_fees = $study_fees + $registration_fees + $insurance_fees;
                                ?>
                                <tr class="<?= $is_already_registered ? 'already-registered' : '' ?>" 
                                    data-student-id="<?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?>">
                                    <td class="checkbox-cell">
                                        <input type="checkbox" 
                                               name="student_ids[]" 
                                               value="<?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?>" 
                                               class="student-checkbox"
                                               <?= $is_already_registered ? 'disabled' : '' ?>>
                                    </td>
                                    <td class="text-muted fw-bold"><?= $counter++ ?></td>
                                    <td>
                                        <code style="font-size: 0.95rem; background: #f1f5f9; padding: 0.2rem 0.4rem; border-radius: 4px;">
                                            <?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?>
                                        </code>
                                        <?php if ($is_already_registered): ?>
                                            <span class="duplicate-indicator" title="مسجل بالفعل">
                                                <i class="fas fa-exclamation-triangle"></i> مسجل
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?= htmlspecialchars($student['student_name'] ?: $student['student_name_eng'], ENT_QUOTES, 'UTF-8') ?>
                                    </td>
                                    <td><?= htmlspecialchars($student['college_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= htmlspecialchars($student['section_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= htmlspecialchars($student['program_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                    <td>
                                        <?php if (!empty($student['specialization_name'])): ?>
                                            <span class="badge bg-purple">
                                                <i class="fas fa-microscope me-1"></i>
                                                <?= htmlspecialchars($student['specialization_name'], ENT_QUOTES, 'UTF-8') ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="text-muted">—</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge bg-secondary batch-badge">
                                            <i class="fas fa-calendar-alt me-1"></i>
                                            <?= htmlspecialchars($student['batch_name'], ENT_QUOTES, 'UTF-8') ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="admission-badge">
                                            <i class="fas fa-tag me-1"></i>
                                            <?= !empty($student['admission_type']) ? htmlspecialchars($student['admission_type'], ENT_QUOTES, 'UTF-8') : 'غير محدد' ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="d-flex flex-column gap-1">
                                            <?php if ($total_fees > 0): ?>
                                                <span class="badge bg-primary fees-badge">
                                                    <i class="fas fa-calculator me-1"></i><?= number_format($total_fees, 2) ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted">—</span>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge <?= $student['registration_count'] > 0 ? 'bg-info' : 'bg-secondary' ?>">
                                            <i class="fas fa-clipboard-list me-1"></i>
                                            <?= $student['registration_count'] ?>
                                        </span>
                                    </td>
                                    <td>
                                        <a class="btn btn-sm btn-info" href="student_profile_admin.php?student_id=<?= urlencode($student['student_id']) ?>" 
                                           title="عرض ملف الطالب">
                                            <i class="fas fa-user-circle"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </form>
        </div>
        <?php elseif ($filters_applied && empty($students)): ?>
            <div class="card card-arabic p-5 text-center">
                <i class="fas fa-users fa-4x text-muted mb-3"></i>
                <h4 class="text-muted">لا يوجد طلاب</h4>
                <p class="text-muted mb-0" style="font-size: 1.1rem;">
                    <?php if (!empty($search_query)): ?>
                        لم يتم العثور على طلاب بناءً على عوامل التصفية والبحث: 
                        "<strong><?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?></strong>"
                    <?php else: ?>
                        لم يتم العثور على طلاب بناءً على عوامل التصفية المحددة
                    <?php endif; ?>
                </p>
            </div>
        <?php endif; ?>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // ==================== FUNCTIONS FOR LOADING DEPENDENT DROPDOWNS ====================

        // Load sections when college changes
        document.getElementById('filter_college').addEventListener('change', function() {
            const collegeId = this.value;
            
            if (collegeId) {
                loadSections(collegeId);
                loadPrograms(collegeId);
                disableSpecialization();
            } else {
                disableSectionAndProgram();
                disableSpecialization();
            }
        });

        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            const sectionLoading = document.getElementById('sectionLoading');
            
            sectionSelect.innerHTML = '<option value="">جاري تحميل الأقسام...</option>';
            sectionSelect.disabled = false;
            if (sectionLoading) sectionLoading.style.display = 'block';
            
            fetch(`ajax/get_sections.php?college_id=${encodeURIComponent(collegeId)}`)
                .then(response => response.json())
                .then(sections => {
                    sectionSelect.innerHTML = '<option value="">اختر القسم</option>';
                    
                    if (sections && sections.length > 0) {
                        sections.forEach(section => {
                            const option = document.createElement('option');
                            option.value = section.id;
                            option.textContent = section.name;
                            sectionSelect.appendChild(option);
                        });
                        sectionSelect.disabled = false;
                    } else {
                        sectionSelect.innerHTML = '<option value="">لا توجد أقسام</option>';
                    }
                    
                    if (sectionLoading) sectionLoading.style.display = 'none';
                    
                    const urlParams = new URLSearchParams(window.location.search);
                    const selectedSection = urlParams.get('filter_section');
                    if (selectedSection) {
                        sectionSelect.value = selectedSection;
                        const programSelect = document.getElementById('filter_program');
                        if (programSelect && programSelect.value) {
                            loadSpecializations(selectedSection, programSelect.value);
                        }
                    }
                })
                .catch(error => {
                    console.error('Error loading sections:', error);
                    sectionSelect.innerHTML = '<option value="">خطأ في تحميل الأقسام</option>';
                    sectionSelect.disabled = false;
                    if (sectionLoading) sectionLoading.style.display = 'none';
                });
        }

        function loadPrograms(collegeId) {
            const programSelect = document.getElementById('filter_program');
            const programLoading = document.getElementById('programLoading');
            
            programSelect.innerHTML = '<option value="">جاري تحميل البرامج...</option>';
            programSelect.disabled = false;
            if (programLoading) programLoading.style.display = 'block';
            
            fetch(`ajax/get_programs.php?college_id=${encodeURIComponent(collegeId)}`)
                .then(response => response.json())
                .then(programs => {
                    programSelect.innerHTML = '<option value="">اختر البرنامج</option>';
                    
                    if (programs && programs.length > 0) {
                        programs.forEach(program => {
                            const option = document.createElement('option');
                            option.value = program.id;
                            option.textContent = program.name;
                            programSelect.appendChild(option);
                        });
                        programSelect.disabled = false;
                    } else {
                        programSelect.innerHTML = '<option value="">لا توجد برامج</option>';
                    }
                    
                    if (programLoading) programLoading.style.display = 'none';
                    
                    const urlParams = new URLSearchParams(window.location.search);
                    const selectedProgram = urlParams.get('filter_program');
                    if (selectedProgram) {
                        programSelect.value = selectedProgram;
                        const sectionSelect = document.getElementById('filter_section');
                        if (sectionSelect && sectionSelect.value) {
                            loadSpecializations(sectionSelect.value, selectedProgram);
                        }
                    }
                })
                .catch(error => {
                    console.error('Error loading programs:', error);
                    programSelect.innerHTML = '<option value="">خطأ في تحميل البرامج</option>';
                    programSelect.disabled = false;
                    if (programLoading) programLoading.style.display = 'none';
                });
        }

        function disableSectionAndProgram() {
            const sectionSelect = document.getElementById('filter_section');
            const programSelect = document.getElementById('filter_program');
            
            if (sectionSelect) {
                sectionSelect.innerHTML = '<option value="">اختر الكلية أولاً</option>';
                sectionSelect.disabled = true;
            }
            
            if (programSelect) {
                programSelect.innerHTML = '<option value="">اختر الكلية أولاً</option>';
                programSelect.disabled = true;
            }
        }

        function disableSpecialization() {
            const specSelect = document.getElementById('filter_specialization');
            if (specSelect) {
                specSelect.innerHTML = '<option value="">اختر القسم والبرنامج أولاً</option>';
                specSelect.disabled = true;
            }
            
            const specHint = document.getElementById('specHint');
            if (specHint) {
                specHint.innerHTML = '<i class="fas fa-info-circle me-1"></i>الرجاء اختيار القسم والبرنامج أولاً';
            }
        }

        document.getElementById('filter_section').addEventListener('change', function() {
            const sectionId = this.value;
            const programId = document.getElementById('filter_program').value;
            
            if (sectionId && programId) {
                loadSpecializations(sectionId, programId);
            } else {
                disableSpecialization();
            }
        });

        document.getElementById('filter_program').addEventListener('change', function() {
            const programId = this.value;
            const sectionId = document.getElementById('filter_section').value;
            
            if (sectionId && programId) {
                loadSpecializations(sectionId, programId);
            } else {
                disableSpecialization();
            }
        });

        function loadSpecializations(sectionId, programId) {
            const specSelect = document.getElementById('filter_specialization');
            const specLoading = document.getElementById('specLoading');
            const specHint = document.getElementById('specHint');
            
            if (!sectionId || !programId) {
                disableSpecialization();
                return;
            }
            
            specSelect.innerHTML = '<option value="">جاري تحميل التخصصات...</option>';
            specSelect.disabled = false;
            if (specLoading) specLoading.style.display = 'block';
            if (specHint) specHint.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>جاري تحميل التخصصات...';
            
            console.log('Loading specializations for section:', sectionId, 'program:', programId);
            
            fetch(`ajax/get_specializations.php?section_id=${encodeURIComponent(sectionId)}&program_id=${encodeURIComponent(programId)}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(specializations => {
                    console.log('Specializations received:', specializations);
                    
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    
                    if (specializations && specializations.length > 0) {
                        specializations.forEach(spec => {
                            const option = document.createElement('option');
                            option.value = spec.specialization_id;
                            option.textContent = spec.specialization_name_ar;
                            specSelect.appendChild(option);
                        });
                        specSelect.disabled = false;
                        if (specHint) {
                            specHint.innerHTML = `<i class="fas fa-check-circle text-success me-1"></i>${specializations.length} تخصص متاح`;
                        }
                    } else {
                        specSelect.innerHTML = '<option value="">لا توجد تخصصات</option>';
                        specSelect.disabled = true;
                        if (specHint) {
                            specHint.innerHTML = '<i class="fas fa-exclamation-triangle text-warning me-1"></i>لا توجد تخصصات لهذا القسم والبرنامج';
                        }
                    }
                    
                    if (specLoading) specLoading.style.display = 'none';
                    
                    const urlParams = new URLSearchParams(window.location.search);
                    const selectedSpec = urlParams.get('filter_specialization');
                    if (selectedSpec && specializations && specializations.some(s => s.specialization_id == selectedSpec)) {
                        specSelect.value = selectedSpec;
                    }
                })
                .catch(error => {
                    console.error('Error loading specializations:', error);
                    specSelect.innerHTML = '<option value="">خطأ في تحميل التخصصات</option>';
                    specSelect.disabled = true;
                    if (specLoading) specLoading.style.display = 'none';
                    if (specHint) {
                        specHint.innerHTML = '<i class="fas fa-exclamation-circle text-danger me-1"></i>حدث خطأ في تحميل التخصصات';
                    }
                });
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Page loaded, initializing filters...');
            
            const collegeSelect = document.getElementById('filter_college');
            
            if (collegeSelect && collegeSelect.value) {
                console.log('College pre-selected:', collegeSelect.value);
                loadSections(collegeSelect.value);
                loadPrograms(collegeSelect.value);
                
                const sectionSelect = document.getElementById('filter_section');
                const programSelect = document.getElementById('filter_program');
                
                setTimeout(() => {
                    if (sectionSelect && sectionSelect.value && programSelect && programSelect.value) {
                        console.log('Section and program pre-selected, loading specializations...');
                        loadSpecializations(sectionSelect.value, programSelect.value);
                    }
                }, 1000);
            }
            
            const table = document.getElementById('studentsTable');
            if (table) {
                const rows = table.getElementsByTagName('tbody')[0]?.getElementsByTagName('tr').length || 0;
                const totalRows = document.getElementById('totalRows');
                if (totalRows) totalRows.textContent = rows;
            }
            
            <?php if (isset($_POST['semester_id']) && $_POST['semester_id'] > 0): ?>
            const semesterSelect = document.getElementById('semester_id');
            const preCheckSelect = document.getElementById('pre_check_semester');
            const semesterId = "<?= (int)$_POST['semester_id'] ?>";
            
            if (semesterSelect) {
                semesterSelect.value = semesterId;
            }
            
            if (preCheckSelect) {
                preCheckSelect.value = semesterId;
                setTimeout(checkDuplicates, 500);
            }
            <?php endif; ?>
        });

        // ==================== RESET STUDENT SELECTION WHEN SEMESTER CHANGES ====================

        document.getElementById('semester_id').addEventListener('change', function() {
            const newSemesterId = this.value;
            
            if (newSemesterId) {
                enableAllStudentCheckboxes();
                removeAlreadyRegisteredClass();
                checkDuplicatesForNewSemester(newSemesterId);
            } else {
                enableAllStudentCheckboxes();
                removeAlreadyRegisteredClass();
            }
        });

        function enableAllStudentCheckboxes() {
            const checkboxes = document.querySelectorAll('.student-checkbox:disabled');
            checkboxes.forEach(checkbox => {
                checkbox.disabled = false;
            });
        }

        function removeAlreadyRegisteredClass() {
            const rows = document.querySelectorAll('tr.already-registered');
            rows.forEach(row => {
                row.classList.remove('already-registered');
            });
        }

        function checkDuplicatesForNewSemester(semesterId) {
            if (!semesterId) return;
            
            const checkResult = document.getElementById('checkResult');
            const semesterSelect = document.getElementById('pre_check_semester');
            
            if (semesterSelect) {
                semesterSelect.value = semesterId;
            }
            
            if (checkResult) {
                checkResult.innerHTML = `
                    <div class="text-center py-3">
                        <div class="spinner-border text-primary me-2" role="status"></div>
                        <span style="font-size: 1rem;">جاري التحقق من التسجيلات المكررة للفصل الجديد...</span>
                    </div>
                `;
            }
            
            const studentIds = [];
            document.querySelectorAll('.student-checkbox').forEach(cb => {
                studentIds.push(cb.value);
            });
            
            const formData = new FormData();
            formData.append('action', 'check_duplicates');
            formData.append('semester_id', semesterId);
            formData.append('student_ids', JSON.stringify(studentIds));
            
            fetch('registration_ajax.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.duplicate_count > 0) {
                        data.duplicates.forEach(dup => {
                            const row = document.querySelector(`tr[data-student-id="${dup.student_id}"]`);
                            if (row) {
                                row.classList.add('already-registered');
                                const checkbox = row.querySelector('.student-checkbox');
                                if (checkbox) checkbox.disabled = true;
                            }
                        });
                        
                        checkResult.className = 'check-result has-duplicates';
                        let html = `
                            <div class="d-flex align-items-center mb-2">
                                <i class="fas fa-exclamation-triangle text-warning fa-lg me-2"></i>
                                <strong class="text-warning" style="font-size: 1.1rem;">تم العثور على ${data.duplicate_count} طالب مسجلين مسبقاً</strong>
                            </div>
                            <small class="text-muted">الفصل الدراسي: ${semesterSelect.options[semesterSelect.selectedIndex]?.text || ''}</small>
                        `;
                        checkResult.innerHTML = html;
                    } else {
                        checkResult.className = 'check-result no-duplicates';
                        checkResult.innerHTML = `
                            <div class="d-flex align-items-center mb-2">
                                <i class="fas fa-check-circle text-success fa-lg me-2"></i>
                                <strong class="text-success" style="font-size: 1.1rem;">لا يوجد تسجيلات مكررة</strong>
                            </div>
                            <small class="text-muted">الفصل الدراسي: ${semesterSelect.options[semesterSelect.selectedIndex]?.text || ''}</small>
                            <p class="mb-0 mt-2" style="font-size: 0.95rem;">جميع الطلاب المحددين غير مسجلين في هذا الفصل.</p>
                        `;
                    }
                } else {
                    checkResult.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            ${escapeHtml(data.message || 'حدث خطأ أثناء التحقق')}
                        </div>
                    `;
                }
            })
            .catch(error => {
                checkResult.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        حدث خطأ في الاتصال: ${escapeHtml(error.message)}
                    </div>
                `;
            });
        }

        // ==================== TABLE SEARCH FUNCTIONS ====================
        
        function filterTable() {
            const searchInput = document.getElementById('tableSearchInput');
            const filter = searchInput.value.toLowerCase();
            const table = document.getElementById('studentsTable');
            const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
            let visibleCount = 0;
            
            for (let i = 0; i < rows.length; i++) {
                const row = rows[i];
                let textContent = '';
                
                const cells = row.getElementsByTagName('td');
                for (let j = 1; j < cells.length; j++) {
                    textContent += cells[j].textContent.toLowerCase() + ' ';
                }
                
                if (textContent.includes(filter)) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            }
            
            const searchStats = document.getElementById('searchStats');
            const searchCount = document.getElementById('searchCount');
            const totalRows = document.getElementById('totalRows');
            
            if (filter !== '') {
                searchCount.textContent = visibleCount;
                totalRows.textContent = rows.length;
                searchStats.style.display = 'block';
            } else {
                searchStats.style.display = 'none';
            }
        }
        
        function clearTableSearch() {
            document.getElementById('tableSearchInput').value = '';
            filterTable();
        }
        
        function resetTableSearch() {
            clearTableSearch();
            
            const table = document.getElementById('studentsTable');
            const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
            
            for (let i = 0; i < rows.length; i++) {
                rows[i].style.display = '';
            }
        }
        
        let searchTimeout;
        document.getElementById('tableSearchInput')?.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(filterTable, 300);
        });
        
        // ==================== STUDENT SELECTION FUNCTIONS ====================
        
        function toggleAllStudents(selectAll) {
            const checkboxes = document.querySelectorAll('.student-checkbox:not(:disabled)');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
        }
        
        function selectAllStudents() {
            const checkboxes = document.querySelectorAll('.student-checkbox:not(:disabled)');
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
            });
            document.getElementById('selectAll').checked = true;
        }
        
        function deselectAllStudents() {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
            document.getElementById('selectAll').checked = false;
        }
        
        document.querySelectorAll('.student-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const enabledCheckboxes = document.querySelectorAll('.student-checkbox:not(:disabled)');
                const checkedCount = document.querySelectorAll('.student-checkbox:checked:not(:disabled)').length;
                document.getElementById('selectAll').checked = checkedCount === enabledCheckboxes.length;
            });
        });
        
        // ==================== FORM VALIDATION ====================
        
        document.getElementById('registrationForm')?.addEventListener('submit', function(e) {
            const selectedCheckboxes = document.querySelectorAll('.student-checkbox:checked:not(:disabled)');
            const selectedCount = selectedCheckboxes.length;
            const startDate = document.querySelector('input[name="start_date"]').value;
            const endDate = document.querySelector('input[name="end_date"]').value;
            const semesterSelect = document.getElementById('semester_id');
            const semesterName = semesterSelect.options[semesterSelect.selectedIndex]?.text || 'الفصل المحدد';
            
            if (selectedCount === 0) {
                e.preventDefault();
                alert('❌ يرجى اختيار طالب واحد على الأقل للتسجيل');
                return;
            }
            
            if (!semesterSelect.value) {
                e.preventDefault();
                alert('❌ يرجى اختيار الفصل الدراسي');
                return;
            }
            
            if (!startDate || !endDate) {
                e.preventDefault();
                alert('❌ يرجى تحديد تاريخي البداية والنهاية');
                return;
            }
            
            if (new Date(endDate) <= new Date(startDate)) {
                e.preventDefault();
                alert('❌ تاريخ النهاية يجب أن يكون بعد تاريخ البداية');
                return;
            }
            
            if (!confirm(`✅ تأكيد تسجيل ${selectedCount} طالب في ${semesterName}؟`)) {
                e.preventDefault();
            }
        });
        
        document.querySelector('input[name="start_date"]')?.addEventListener('change', function() {
            const startDate = this.value;
            const endDateInput = document.querySelector('input[name="end_date"]');
            
            if (startDate) {
                const minEndDate = new Date(startDate);
                minEndDate.setDate(minEndDate.getDate() + 1);
                endDateInput.min = minEndDate.toISOString().split('T')[0];
                
                if (endDateInput.value && new Date(endDateInput.value) <= new Date(startDate)) {
                    endDateInput.value = minEndDate.toISOString().split('T')[0];
                }
            }
        });
        
        // ==================== SEARCH FUNCTIONS ====================
        
        function clearSearch() {
            document.getElementById('search_query').value = '';
            document.getElementById('filterForm').submit();
        }
        
        document.getElementById('search_query')?.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                document.getElementById('filterForm').submit();
            }
        });
        
        // ==================== DUPLICATE CHECK FUNCTIONS ====================
        
        function checkDuplicates() {
            const semesterId = document.getElementById('pre_check_semester').value;
            const checkResult = document.getElementById('checkResult');
            
            if (!semesterId) {
                checkResult.innerHTML = `
                    <div class="text-center text-muted py-3">
                        <i class="fas fa-search fa-2x mb-2"></i>
                        <p class="mb-0" style="font-size: 1rem;">الرجاء اختيار فصل دراسي للتحقق من التسجيلات المكررة</p>
                    </div>
                `;
                return;
            }
            
            const semesterSelect = document.getElementById('pre_check_semester');
            const semesterName = semesterSelect.options[semesterSelect.selectedIndex].text;
            
            checkResult.innerHTML = `
                <div class="text-center py-3">
                    <div class="spinner-border text-primary me-2" role="status"></div>
                    <span style="font-size: 1rem;">جاري التحقق من التسجيلات المكررة...</span>
                </div>
            `;
            
            const studentIds = [];
            document.querySelectorAll('.student-checkbox').forEach(cb => {
                studentIds.push(cb.value);
            });
            
            const formData = new FormData();
            formData.append('action', 'check_duplicates');
            formData.append('semester_id', semesterId);
            formData.append('student_ids', JSON.stringify(studentIds));
            
            fetch('registration_ajax.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.duplicate_count > 0) {
                        checkResult.className = 'check-result has-duplicates';
                        let html = `
                            <div class="d-flex align-items-center mb-2">
                                <i class="fas fa-exclamation-triangle text-warning fa-lg me-2"></i>
                                <strong class="text-warning" style="font-size: 1.1rem;">تم العثور على ${data.duplicate_count} طالب مسجلين مسبقاً</strong>
                            </div>
                            <small class="text-muted">الفصل الدراسي: ${semesterName}</small>
                            <div class="mt-3">
                                <table class="table table-sm table-borderless mb-0">
                                    <thead>
                                        <tr>
                                            <th>رقم الطالب</th>
                                            <th>اسم الطالب</th>
                                            <th>رقم المرجع</th>
                                            <th>الحالة</th>
                                        </tr>
                                    </thead>
                                    <tbody>`;
                        
                        data.duplicates.forEach(dup => {
                            const statusBadge = dup.is_paid == 1 ? 
                                '<span class="badge bg-success">مدفوع</span>' : 
                                '<span class="badge bg-warning">غير مدفوع</span>';
                            
                            html += `
                                <tr>
                                    <td><code>${escapeHtml(dup.student_id)}</code></td>
                                    <td>${escapeHtml(dup.student_name)}</td>
                                    <td><small>${escapeHtml(dup.payment_reference)}</small></td>
                                    <td>${statusBadge}</td>
                                </tr>`;
                        });
                        
                        html += `</tbody></table></div>`;
                        
                        enableAllStudentCheckboxes();
                        removeAlreadyRegisteredClass();
                        
                        data.duplicates.forEach(dup => {
                            const row = document.querySelector(`tr[data-student-id="${dup.student_id}"]`);
                            if (row) {
                                row.classList.add('already-registered');
                                const checkbox = row.querySelector('.student-checkbox');
                                if (checkbox) checkbox.disabled = true;
                            }
                        });
                        
                        checkResult.innerHTML = html;
                    } else {
                        enableAllStudentCheckboxes();
                        removeAlreadyRegisteredClass();
                        
                        checkResult.className = 'check-result no-duplicates';
                        checkResult.innerHTML = `
                            <div class="d-flex align-items-center mb-2">
                                <i class="fas fa-check-circle text-success fa-lg me-2"></i>
                                <strong class="text-success" style="font-size: 1.1rem;">لا يوجد تسجيلات مكررة</strong>
                            </div>
                            <small class="text-muted">الفصل الدراسي: ${semesterName}</small>
                            <p class="mb-0 mt-2" style="font-size: 0.95rem;">جميع الطلاب المحددين غير مسجلين في هذا الفصل.</p>
                        `;
                    }
                } else {
                    checkResult.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            ${escapeHtml(data.message || 'حدث خطأ أثناء التحقق')}
                        </div>
                    `;
                }
            })
            .catch(error => {
                checkResult.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        حدث خطأ في الاتصال: ${escapeHtml(error.message)}
                    </div>
                `;
            });
        }
        
        function updateDuplicateCheck() {
            const semesterId = document.getElementById('semester_id').value;
            const preCheckSelect = document.getElementById('pre_check_semester');
            
            if (semesterId) {
                enableAllStudentCheckboxes();
                removeAlreadyRegisteredClass();
                
                for (let i = 0; i < preCheckSelect.options.length; i++) {
                    if (preCheckSelect.options[i].value === semesterId) {
                        preCheckSelect.value = semesterId;
                        break;
                    }
                }
                
                checkDuplicatesForNewSemester(semesterId);
            }
        }
        
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html>
<?php include 'footer.php'; ?>
