<?php
// registration.php - UPDATED WITH DUPLICATE PREVENTION, LAST REGISTRATION CARDS, AND SECURITY IMPROVEMENTS
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 ====================

/**
 * Validate and sanitize integer input
 */
function validateInt($value, $default = null) {
    if ($value === null || $value === '') return $default;
    $int = filter_var($value, FILTER_VALIDATE_INT);
    return $int !== false ? $int : $default;
}

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

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

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

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

// Generate CSRF token for forms
$csrf_token = generateCSRFToken();

// ==================== INITIALIZE VARIABLES ====================
$selected_students = [];
$success_message = '';
$error_message = '';
$duplicate_students = []; // For duplicate registration warnings
$students = [];

// Check if filters were submitted
$filters_applied = isset($_GET['filter_applied']) && $_GET['filter_applied'] === '1';

// Get and validate filter parameters - SANITIZED
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 {
    // Don't apply filters by default
    $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 (SECURE) ====================
$where = " WHERE 1=1 ";
$types = ''; 
$params = [];

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

// Apply filters ONLY if they were applied by user
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;
    }
    
    // NEW: Add specialization filter
    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;
    }

    // Apply search query if provided
    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 ====================

/**
 * Generate unique payment reference with validation
 */
function generateUniquePaymentReference($mysqli) {
    $unique = false;
    $max_attempts = 10;
    $attempts = 0;
    
    while (!$unique && $attempts < $max_attempts) {
        // Generate random 12-digit number (year prefix + random part)
        $year_prefix = date('y'); // Gets last 2 digits of current year
        $random_part = str_pad(mt_rand(1, 9999999999), 10, '0', STR_PAD_LEFT);
        $reference = $year_prefix . $random_part;
        
        // Check if reference already exists using prepared statement
        $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();
        
        if (!$existing) {
            $unique = true;
            return $reference;
        }
        
        $attempts++;
    }
    
    // If we can't generate a unique reference after max attempts, use timestamp-based
    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);
}

/**
 * Check for existing registrations with same filters
 */
function checkExistingRegistrations($mysqli, $filters) {
    $where_conditions = [];
    $types = '';
    $params = [];
    
    // Validate and add filters
    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 []; // No filters provided
    }
    
    $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
];

// Only check for last registrations if filters were applied
$last_registrations = $filters_applied ? checkExistingRegistrations($mysqli1, $current_filters) : [];

// ==================== HANDLE FORM SUBMISSION (SECURE) ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register_students'])) {
    // Verify CSRF token
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error_message = 'رمز الأمان غير صالح. الرجاء تحديث الصفحة والمحاولة مرة أخرى.';
    } else {
        // Validate and sanitize inputs
        $semester_id = validateInt($_POST['semester_id'] ?? 0);
        $start_date = validateString($_POST['start_date'] ?? '');
        $end_date = validateString($_POST['end_date'] ?? '');
        $student_ids = $_POST['student_ids'] ?? [];
        
        // Validate dates format
        $start_date_valid = validateDate($start_date);
        $end_date_valid = validateDate($end_date);
        
        // Validate student IDs
        $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;
                }
            }
        }
        
        // Validate inputs
        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 {
            // Convert dates to MySQL format
            $start_timestamp = date('Y-m-d H:i:s', strtotime($start_date));
            $end_timestamp = date('Y-m-d H:i:s', strtotime($end_date));
            
            // Validate that end date is after start date
            if (strtotime($end_date) <= strtotime($start_date)) {
                $error_message = 'تاريخ النهاية يجب أن يكون بعد تاريخ البداية';
            } else {
                try {
                    // Begin transaction
                    $mysqli1->begin_transaction();
                    
                    // Get semester details
                    $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 = []; // Track duplicate students
                    
                    // Get semester name for error messages
                    $semester_name = $semester['name'] . ' (' . $semester['code'] . ')';
                    
                    foreach ($valid_student_ids as $student_id) {
                        // Check if student already registered for this semester
                        $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++;
                            
                            // Get student name for duplicate message
                            $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();
                            
                            // Add to duplicate students list
                            $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; // Skip if already registered
                        }
                        
                        // Get student details with fees
                        $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; // Skip if student not found
                        }

                        // Generate unique payment reference
                        $payment_reference = generateUniquePaymentReference($mysqli1);

                        // Get fees from student record, ensure they are numeric
                        $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 into registrations table with dates and payment reference
                        $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; // Not paid initially
                        $fee_type_id = 1; // Default fee type
                        $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();
                        
                        // Check if registration_constraints table exists
                        $table_check = $mysqli1->query("SHOW TABLES LIKE 'registration_constraints'");
                        
                        if ($table_check->num_rows > 0) {
                            // Insert into registration_constraints
                            $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 // Use the batch from filter or null
                            );
                            
                            $constraint_stmt->execute();
                            $constraint_stmt->close();
                        }
                        
                        $registration_count++;
                    }
                    
                    // Commit transaction
                    $mysqli1->commit();
                    
                    // Prepare success message
                    $success_message = "تم تسجيل {$registration_count} طالب بنجاح في الفصل الدراسي: <strong>{$semester_name}</strong>";
                    
                    // Add duplicate warning if any
                    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>";
                        
                        // Add detailed list of duplicates
                        $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) {
                    // Rollback transaction on error
                    $mysqli1->rollback();
                    $error_message = "حدث خطأ أثناء التسجيل: " . $e->getMessage();
                    
                    // Log detailed error for debugging
                    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 {
    // No students to show initially
    $students = [];
}

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

// Get semesters for dropdown
$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();

// Get colleges
$colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
$colleges_stmt->execute();
$colleges = $colleges_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$colleges_stmt->close();

// Get sections for the selected college
$sections = [];
if ($filter_college_id && !empty($filter_college_id)) {
    $sections_sql = "
        SELECT DISTINCT s.id, s.name, s.parent
        FROM sections s 
        WHERE s.parent = ? AND s.deleted_at IS NULL 
        ORDER BY s.name
    ";
    $sections_stmt = $mysqli1->prepare($sections_sql);
    $sections_stmt->bind_param("i", $filter_college_id);
    $sections_stmt->execute();
    $sections = $sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $sections_stmt->close();
}

// Get programs based on selected college and section
$programs = [];
if ($filter_college_id && !empty($filter_college_id)) {
    $programs_where = "p.deleted_at IS NULL";
    $programs_params = [];
    $programs_types = "";
    
    if ($filter_section_id && !empty($filter_section_id)) {
        $programs_where .= " AND st.section_id = ?";
        $programs_types .= "i";
        $programs_params[] = $filter_section_id;
    }
    
    $programs_where .= " AND st.college_id = ?";
    $programs_types .= "i";
    $programs_params[] = $filter_college_id;
    
    $programs_sql = "
        SELECT DISTINCT p.id, p.name 
        FROM programs p 
        INNER JOIN students st ON p.id = st.program_id 
        WHERE {$programs_where} 
        ORDER BY p.name
    ";
    
    $programs_stmt = $mysqli1->prepare($programs_sql);
    if ($programs_types) {
        $programs_stmt->bind_param($programs_types, ...$programs_params);
    }
    $programs_stmt->execute();
    $programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $programs_stmt->close();
} else {
    $programs_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
    $programs_stmt->execute();
    $programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $programs_stmt->close();
}

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

// Get batches
$batches_stmt = $mysqli1->prepare("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY id");
$batches_stmt->execute();
$batches = $batches_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$batches_stmt->close();

// Get last semester with enrollments based on current filters
$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();
}

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;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>
        body, h1,h2,h3,h4,h5,h6, p, a, button, label { 
            font-family: 'Cairo', system-ui, -apple-system, sans-serif !important; 
        }
        .card-arabic {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        .filter-icon {
            width: 40px;
            height: 40px;
            background: #3b82f6;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.1rem;
        }
        .student-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        .checkbox-cell {
            width: 50px;
            text-align: center;
        }
        .batch-badge {
            font-size: 0.75rem;
        }
        .registration-count {
            font-size: 0.8rem;
        }
        .status-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.4rem;
        }
        .date-inputs {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
        }
        .fees-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.4rem;
        }
        .registration-card {
            border-left: 4px solid #3b82f6;
            transition: all 0.3s ease;
        }
        .registration-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .paid-badge {
            background-color: #10b981;
        }
        .unpaid-badge {
            background-color: #ef4444;
        }
        .warning-alert {
            border-right: 4px solid #f59e0b;
        }
        .filter-status {
            font-size: 0.85rem;
            padding: 0.3rem 0.6rem;
            border-radius: 6px;
        }
        .filter-status.applied {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #a7f3d0;
        }
        .filter-status.not-applied {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
        }
        .info-message {
            background-color: #f0f9ff;
            border: 1px solid #bae6fd;
            color: #0369a1;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .ajax-loading {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            display: none;
        }
        .form-group {
            position: relative;
        }
        .search-input-group {
            position: relative;
        }
        .search-clear-btn {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #6c757d;
            cursor: pointer;
            display: none;
        }
        .search-input-group input:not(:placeholder-shown) + .search-clear-btn {
            display: block;
        }
        .admission-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.5rem;
            background-color: #067635;
            color: white;
        }
        .duplicate-warning {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
        }
        .already-registered {
            background-color: #f8f9fa !important;
            opacity: 0.7;
        }
        .already-registered td {
            color: #6c757d !important;
        }
        .duplicate-indicator {
            font-size: 0.7rem;
            padding: 0.2rem 0.4rem;
            background-color: #f59e0b;
            color: white;
            border-radius: 3px;
            margin-left: 5px;
        }
        .pre-registration-check {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .check-result {
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
        }
        .check-result.has-duplicates {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
        }
        .check-result.no-duplicates {
            background-color: #d1fae5;
            border: 1px solid #a7f3d0;
        }
        .bg-purple {
            background-color: #8b5cf6 !important;
        }
        .text-purple {
            color: #8b5cf6 !important;
        }
        .bg-opacity-10 {
            opacity: 0.1;
        }
        .spec-hint {
            font-size: 0.7rem;
            color: #6c757d;
            margin-top: 0.25rem;
        }
    </style>
</head>
<body>
    <div class="container py-4" dir="rtl">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4">
            <h3 class="mb-0 fw-bold">إدارة تسجيلات الطلاب</h3>
            <div class="ms-auto">
                <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="committee_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 me-2"></i>
                <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 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 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-lg me-3"></i>
                    <div>
                        <strong>تنبيه:</strong> يوجد تسجيلات سابقة بنفس عوامل التصفية المحددة
                        <br>
                        <small>تم العثور على <?= count($last_registrations) ?> تسجيل سابق. يرجى التأكد من عدم التكرار.</small>
                    </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="row align-items-center">
                <div class="col-md-8">
                    <div class="d-flex align-items-center mb-3">
                        <div class="filter-icon me-2">
                            <i class="fas fa-filter"></i>
                        </div>
                        <h6 class="fw-bold mb-0 text-dark">تصفية الطلاب</h6>
                        <div class="ms-3">
                            <span class="badge bg-light text-dark border">
                                <i class="fas fa-sliders-h me-1"></i>
                                <?= $filters_applied ? 'تصفية مطبقة' : 'في انتظار التطبيق' ?>
                            </span>
                        </div>
                    </div>
                    
                    <form method="get" class="row g-3 align-items-end" id="filterForm">
                        <!-- Hidden field to indicate filters were applied -->
                        <input type="hidden" name="filter_applied" value="1">
                        
                        <!-- College Filter -->
                        <div class="col-lg-2 col-md-4">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-university me-1"></i>
                                    الكلية
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_college" id="filter_college" onchange="loadSections(this.value)">
                                        <option value="">اختر الكلية</option>
                                        <?php foreach ($colleges as $college): ?>
                                            <?php 
                                            // Don't show college filter if user has scope restriction
                                            if (!$canAll && $scopeCollege !== null && $college['id'] != $scopeCollege) {
                                                continue;
                                            }
                                            ?>
                                            <option value="<?= (int)$college['id'] ?>" <?= ($filter_college_id == $college['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-building"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Section Filter (Dependent on College) -->
                        <div class="col-lg-2 col-md-4">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-layer-group me-1"></i>
                                    القسم
                                </label>
                                <div class="input-group input-group-sm position-relative">
                                    <select class="form-control border-end-0" name="filter_section" id="filter_section" <?= !$filter_college_id ? 'disabled' : '' ?> onchange="loadSpecializations()">
                                        <option value="">جميع الأقسام</option>
                                        <?php if ($filter_college_id && !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>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-building"></i>
                                    </span>
                                    <div class="ajax-loading" id="sectionLoading" style="display: none;">
                                        <i class="fas fa-spinner fa-spin"></i>
                                    </div>
                                </div>
                                <?php if (!$filter_college_id): ?>
                                    <small class="text-muted">الرجاء اختيار كلية أولاً</small>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Program Filter -->
                        <div class="col-lg-2 col-md-4">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-graduation-cap me-1"></i>
                                    البرنامج
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_program" id="filter_program" onchange="loadSpecializations()">
                                        <option value="">جميع البرامج</option>
                                        <?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; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-book"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- NEW: Specialization Filter -->
                        <div class="col-lg-2 col-md-4">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-microscope me-1"></i>
                                    التخصص
                                </label>
                                <div class="input-group input-group-sm position-relative">
                                    <select class="form-control border-end-0" name="filter_specialization" id="filter_specialization" <?= (!$filter_program_id || !$filter_section_id) ? 'disabled' : '' ?>>
                                        <option value="">جميع التخصصات</option>
                                        <?php if (!empty($specializations)): ?>
                                            <?php foreach ($specializations as $spec): ?>
                                                <option value="<?= (int)$spec['specialization_id'] ?>" <?= ($filter_specialization_id == $spec['specialization_id']) ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($spec['specialization_name_ar'], ENT_QUOTES, 'UTF-8') ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-microscope"></i>
                                    </span>
                                    <div class="ajax-loading" id="specLoading" style="display: none;">
                                        <i class="fas fa-spinner fa-spin"></i>
                                    </div>
                                </div>
                                <small class="spec-hint" id="specHint">
                                    <?php if (!$filter_program_id || !$filter_section_id): ?>
                                        الرجاء اختيار القسم والبرنامج أولاً
                                    <?php endif; ?>
                                </small>
                            </div>
                        </div>
                        
                        <!-- Batch Filter -->
                        <div class="col-lg-2 col-md-4">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-users me-1"></i>
                                    الدفعة
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="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>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Search Field -->
                        <div class="col-lg-2 col-md-4">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-search me-1"></i>
                                    بحث
                                </label>
                                <div class="search-input-group">
                                    <input type="text" 
                                           class="form-control form-control-sm" 
                                           name="search_query" 
                                           id="search_query"
                                           placeholder="رقم الطالب أو الاسم"
                                           value="<?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?>">
                                    <button type="button" class="search-clear-btn" onclick="clearSearch()" title="مسح البحث">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div class="col-12">
                            <div class="d-flex gap-2 pt-2">
                                <button type="submit" class="btn btn-primary btn-sm px-3">
                                    <i class="fas fa-filter me-1"></i>
                                    تطبيق التصفية
                                </button>
                                <a href="registration.php" class="btn btn-outline-secondary btn-sm px-3" title="إعادة تعيين">
                                    <i class="fas fa-sync-alt"></i>
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
                
                <!-- Filter Summary -->
                <div class="col-md-4">
                    <div class="bg-light rounded p-3 h-100">
                        <div class="d-flex align-items-center mb-2">
                            <i class="fas fa-info-circle me-2 <?= $filters_applied ? 'text-primary' : 'text-secondary' ?>"></i>
                            <span class="fw-semibold">ملخص التصفية</span>
                        </div>
                        <div class="small">
                            <?php if ($filters_applied): ?>
                                <div class="mb-1">عدد الطلاب: <strong><?= count($students) ?></strong></div>
                                
                                <?php if (!empty($search_query)): ?>
                                    <div class="mb-2 p-2 ">
                                        <div class="fw-semibold text-warning mb-1">
                                            <i class="fas fa-search me-1"></i>
                                            نتيجة البحث
                                        </div>
                                        <div class="text-truncate">
                                            "<?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?>"
                                        </div>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($filter_college_id): ?>
                                    <?php 
                                    $selected_college = null;
                                    foreach ($colleges as $college) {
                                        if ($college['id'] == $filter_college_id) {
                                            $selected_college = $college;
                                            break;
                                        }
                                    }
                                    ?>
                                    <?php if ($selected_college): ?>
                                        <div class="mb-1">
                                            <span class="fw-semibold">الكلية:</span>
                                            <span class="badge text-primary">
                                                <?= htmlspecialchars($selected_college['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <?php if ($filter_section_id && $filter_college_id && !empty($sections)): ?>
                                    <?php 
                                    $selected_section = null;
                                    foreach ($sections as $section) {
                                        if ($section['id'] == $filter_section_id) {
                                            $selected_section = $section;
                                            break;
                                        }
                                    }
                                    ?>
                                    <?php if ($selected_section): ?>
                                        <div class="mb-1">
                                            <span class="fw-semibold">القسم:</span>
                                            <span class="badge  text-success">
                                                <?= htmlspecialchars($selected_section['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <?php if ($filter_program_id): ?>
                                    <?php 
                                    $selected_program = null;
                                    foreach ($programs as $program) {
                                        if ($program['id'] == $filter_program_id) {
                                            $selected_program = $program;
                                            break;
                                        }
                                    }
                                    ?>
                                    <?php if ($selected_program): ?>
                                        <div class="mb-1">
                                            <span class="fw-semibold">البرنامج:</span>
                                            <span class="badge  text-info">
                                                <?= htmlspecialchars($selected_program['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <!-- NEW: Specialization Summary -->
                                <?php if ($filter_specialization_id && !empty($specializations)): ?>
                                    <?php 
                                    $selected_spec = null;
                                    foreach ($specializations as $spec) {
                                        if ($spec['specialization_id'] == $filter_specialization_id) {
                                            $selected_spec = $spec;
                                            break;
                                        }
                                    }
                                    ?>
                                    <?php if ($selected_spec): ?>
                                        <div class="mb-1">
                                            <span class="fw-semibold">التخصص:</span>
                                            <span class="badge text-purple">
                                                <?= htmlspecialchars($selected_spec['specialization_name_ar'], ENT_QUOTES, 'UTF-8') ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <?php if ($filter_batch_id): ?>
                                    <?php 
                                    $selected_batch = null;
                                    foreach ($batches as $batch) {
                                        if ($batch['id'] == $filter_batch_id) {
                                            $selected_batch = $batch;
                                            break;
                                        }
                                    }
                                    ?>
                                    <?php if ($selected_batch): ?>
                                        <div class="mb-1">
                                            <span class="fw-semibold">الدفعة:</span>
                                            <span class="badge   text-warning">
                                                <?= htmlspecialchars($selected_batch['value'], ENT_QUOTES, 'UTF-8') ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <?php if ($last_semester): ?>
                                    <div class="mb-2 p-2 ">
                                        <div class="fw-semibold text-primary mb-1">
                                            <i class="fas fa-calendar-check me-1"></i>
                                            آخر فصل دراسي مسجل
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <span><?= htmlspecialchars($last_semester['name'], ENT_QUOTES, 'UTF-8') ?> (<?= htmlspecialchars($last_semester['code'], ENT_QUOTES, 'UTF-8') ?>)</span>
                                            <small class="text-muted">
                                                <?= date('Y-m-d', strtotime($last_semester['last_registration'])) ?>
                                            </small>
                                        </div>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="mb-1">شروط التصفية:</div>
                                <ul class="small mb-0 ps-3">
                                    <li>جميع الطلاب</li>
                                    <li>بغض النظر عن حالة الملف</li>
                                    <li>بغض النظر عن حالة المقابلة</li>
                                    <li>بغض النظر عن الحالة الطبية</li>
                                    <?php if (!$canAll && $scopeCollege !== null): ?>
                                        <li>نطاق الكلية محدود</li>
                                    <?php endif; ?>
                                </ul>
                            <?php else: ?>
                                <div class="text-center py-3">
                                    <i class="fas fa-filter fa-2x text-muted mb-3"></i>
                                    <p class="text-muted mb-0">لم يتم تطبيق أي تصفية بعد</p>
                                    <p class="text-muted small">الرجاء اختيار عوامل التصفية ثم النقر على "تطبيق التصفية"</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Registration Form -->
        <?php if ($filters_applied && !empty($students)): ?>
        <div class="card card-arabic p-4 mb-4">
            <form method="post" id="registrationForm">
                <!-- CSRF Token -->
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf_token, ENT_QUOTES, 'UTF-8') ?>">
                
                <div class="d-flex align-items-center mb-3">
                    <h6 class="fw-bold mb-0">تسجيل الطلاب في فصل دراسي</h6>
                    <span class="badge bg-primary ms-2"><?= count($students) ?> طالب متاح</span>
                    <?php if (!empty($last_registrations)): ?>
                        <span class="badge bg-warning ms-2">
                            <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-2">
                        <i class="fas fa-search me-2 text-primary"></i>
                        <span class="fw-semibold">فحص مسبق للتسجيلات المكررة</span>
                    </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-lg mb-2"></i>
                                    <p class="mb-0">الرجاء اختيار فصل دراسي للتحقق من التسجيلات المكررة</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Semester and Dates Section -->
                <div class="date-inputs mb-4">
                    <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>
                            <small class="text-muted">سيتم منع التسجيل المكرر لنفس الفصل</small>
                        </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') ?>">
                            <small class="text-muted">تاريخ بداية فترة التسجيل</small>
                        </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')) ?>">
                            <small class="text-muted">تاريخ نهاية فترة التسجيل</small>
                        </div>
                    </div>
                </div>
                
                <!-- Action Buttons -->
                <div class="row g-3 align-items-end mb-3">
                    <div class="col-md-6">
                        <div class="d-flex gap-2">
                            <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 class="col-md-6 text-start">
                        <div class="text-muted small">
                            <i class="fas fa-info-circle me-1"></i>
                            سيتم إنشاء رقم مرجعي فريد لكل تسجيل تلقائياً
                        </div>
                    </div>
                </div>
                
                <!-- Students Table -->
                <div class="table-responsive mt-4">
                    <table class="table table-striped 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> <!-- NEW Column -->
                                <th>الدفعة</th>
                                <th>نوع القبول</th>
                                <th>الرسوم</th>
                                <th>التسجيلات السابقة</th>
                               <th>الإجراءات</th> <!-- New Actions Column -->

                            </tr>
                        </thead>
                        <tbody id="studentsTableBody">
                            <?php 
                            $counter = 1; 
                            $selected_semester_id = isset($_POST['semester_id']) ? validateInt($_POST['semester_id']) : 0;
                            
                            // Get all registered students for the selected semester if form was submitted
                            $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
                                // Check if student is already registered for selected semester
                                $is_already_registered = in_array($student['student_id'], $registered_students);
                                
                                // Calculate total fees for display
                                $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"><?= $counter++ ?></td>
                                    <td>
                                        <code><?= 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 bg">
                                                <?= 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"><?= htmlspecialchars($student['batch_name'], ENT_QUOTES, 'UTF-8') ?></span>
                                    </td>
                                    <td>
                                        <span class="admission-badge">
                                            <?= !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 ($study_fees > 0): ?>
                                                <span class="badge bg-info fees-badge" title="رسوم الدراسة">
                                                    <i class="fas fa-book me-1"></i><?= number_format($study_fees, 2) ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($registration_fees > 0): ?>
                                                <span class="badge bg-warning fees-badge" title="رسوم التسجيل">
                                                    <i class="fas fa-edit me-1"></i><?= number_format($registration_fees, 2) ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($insurance_fees > 0): ?>
                                                <span class="badge bg-success fees-badge" title="رسوم التأمين">
                                                    <i class="fas fa-shield-alt me-1"></i><?= number_format($insurance_fees, 2) ?>
                                                </span>
                                            <?php endif; ?>
                                            <span class="badge bg-primary fees-badge" title="المجموع">
                                                <i class="fas fa-calculator me-1"></i><?= number_format($total_fees, 2) ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="registration-count <?= $student['registration_count'] > 0 ? 'text-success' : 'text-muted' ?>">
                                            <i class="fas fa-clipboard-list me-1"></i>
                                            <?= $student['registration_count'] ?> تسجيل
                                        </span>
                                    </td>
                                     <td>
                <!-- Profile Button -->
                <a class="btn btn-sm btn-info" href="student_profile.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-3x text-muted mb-3"></i>
                <h5 class="text-muted">لا يوجد طلاب</h5>
                <p class="text-muted mb-0">
                    <?php if (!empty($search_query)): ?>
                        لم يتم العثور على طلاب بناءً على عوامل التصفية المحددة والبحث: "<?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?>"
                    <?php else: ?>
                        لم يتم العثور على طلاب بناءً على عوامل التصفية المحددة
                    <?php endif; ?>
                </p>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // ==================== 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;
        }
        
        // Update select all checkbox when individual checkboxes change
        document.querySelectorAll('.student-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const enabledCheckboxes = document.querySelectorAll('.student-checkbox:not(:disabled)');
                const allChecked = document.querySelectorAll('.student-checkbox:checked').length === enabledCheckboxes.length;
                document.getElementById('selectAll').checked = allChecked;
            });
        });
        
        // ==================== 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 hasPreviousRegistrations = <?= !empty($last_registrations) ? 'true' : 'false' ?>;
            const semesterSelect = document.getElementById('semester_id');
            const semesterName = semesterSelect.options[semesterSelect.selectedIndex]?.text || 'الفصل المحدد';
            
            if (selectedCount === 0) {
                e.preventDefault();
                alert('يرجى اختيار طالب واحد على الأقل للتسجيل');
                return;
            }
            
            if (!startDate || !endDate) {
                e.preventDefault();
                alert('يرجى تحديد تاريخي البداية والنهاية');
                return;
            }
            
            if (new Date(endDate) <= new Date(startDate)) {
                e.preventDefault();
                alert('تاريخ النهاية يجب أن يكون بعد تاريخ البداية');
                return;
            }
            
            // Check for disabled checkboxes (already registered students)
            const disabledChecked = document.querySelectorAll('.student-checkbox:checked:disabled').length;
            if (disabledChecked > 0) {
                e.preventDefault();
                alert(`تنبيه: ${disabledChecked} طالب مسجلين بالفعل في هذا الفصل ولن يتم تسجيلهم مرة أخرى. الرجاء إلغاء تحديدهم أو اختيار فصل دراسي مختلف.`);
                return;
            }
            
            let confirmationMessage = `هل أنت متأكد من تسجيل ${selectedCount} طالب في الفصل الدراسي: ${semesterName}؟\n\n`;
            confirmationMessage += `- تاريخ البداية: ${startDate}\n`;
            confirmationMessage += `- تاريخ النهاية: ${endDate}\n\n`;
            confirmationMessage += `ملاحظة: الطلاب المسجلين مسبقاً في هذا الفصل سيتم تخطيهم تلقائياً.`;
            
            if (hasPreviousRegistrations) {
                confirmationMessage += '\n\n⚠️ تنبيه إضافي: توجد تسجيلات سابقة بنفس عوامل التصفية.';
            }
            
            if (!confirm(confirmationMessage)) {
                e.preventDefault();
            }
        });
        
        // Set minimum end date based on start date
        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 current end date is before new min date, update it
                if (endDateInput.value && new Date(endDateInput.value) <= new Date(startDate)) {
                    endDateInput.value = minEndDate.toISOString().split('T')[0];
                }
            }
        });
        
        // ==================== FILTER FUNCTIONS ====================
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            const programSelect = document.getElementById('filter_program');
            const specSelect = document.getElementById('filter_specialization');
            const sectionLoading = document.getElementById('sectionLoading');
            const specHint = document.getElementById('specHint');
            
            // Reset dependent selects
            sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
            programSelect.innerHTML = '<option value="">جميع البرامج</option>';
            specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
            specHint.innerHTML = 'الرجاء اختيار القسم والبرنامج أولاً';
            
            if (!collegeId || collegeId === '') {
                sectionSelect.disabled = true;
                programSelect.disabled = true;
                specSelect.disabled = true;
                return;
            }
            
            // Show loading indicator
            sectionSelect.disabled = true;
            sectionLoading.style.display = 'block';
            
            // Create form to submit
            const form = document.createElement('form');
            form.method = 'get';
            form.style.display = 'none';
            
            // Add all current filter parameters
            const params = new URLSearchParams(window.location.search);
            
            // Update college parameter
            params.set('filter_college', collegeId);
            params.set('filter_applied', '1');
            
            // Remove dependent filters
            params.delete('filter_section');
            params.delete('filter_program');
            params.delete('filter_specialization');
            
            // Add each parameter to form
            for (let [key, value] of params.entries()) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = key;
                input.value = value;
                form.appendChild(input);
            }
            
            document.body.appendChild(form);
            form.submit();
        }
        
        function loadSpecializations() {
            const programId = document.getElementById('filter_program').value;
            const sectionId = document.getElementById('filter_section').value;
            const collegeId = document.getElementById('filter_college').value;
            const specSelect = document.getElementById('filter_specialization');
            const specLoading = document.getElementById('specLoading');
            const specHint = document.getElementById('specHint');
            
            // Reset specialization select
            specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
            
            if (!programId || !sectionId || !collegeId) {
                specSelect.disabled = true;
                specHint.innerHTML = 'الرجاء اختيار القسم والبرنامج أولاً';
                return;
            }
            
            // Show loading indicator
            specSelect.disabled = true;
            specLoading.style.display = 'block';
            specHint.innerHTML = 'جاري تحميل التخصصات...';
            
            // AJAX request to get specializations
            fetch(`ajax/get_specializations.php?section_id=${encodeURIComponent(sectionId)}&program_id=${encodeURIComponent(programId)}`)
                .then(response => response.json())
                .then(data => {
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    
                    if (data.length > 0) {
                        data.forEach(spec => {
                            const option = document.createElement('option');
                            option.value = spec.specialization_id;
                            option.textContent = spec.specialization_name_ar;
                            
                            // Check if this specialization was previously selected
                            const urlParams = new URLSearchParams(window.location.search);
                            const selectedSpec = urlParams.get('filter_specialization');
                            if (selectedSpec && selectedSpec == spec.specialization_id) {
                                option.selected = true;
                            }
                            
                            specSelect.appendChild(option);
                        });
                        specHint.innerHTML = `${data.length} تخصص متاح`;
                    } else {
                        specHint.innerHTML = 'لا توجد تخصصات متاحة لهذا القسم والبرنامج';
                    }
                    
                    specSelect.disabled = false;
                    specLoading.style.display = 'none';
                })
                .catch(error => {
                    console.error('Error loading specializations:', error);
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    specSelect.disabled = false;
                    specLoading.style.display = 'none';
                    specHint.innerHTML = 'حدث خطأ في تحميل التخصصات';
                });
        }
        
        // ==================== 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();
            }
        });
        
        document.getElementById('search_query')?.addEventListener('input', function() {
            const clearBtn = document.querySelector('.search-clear-btn');
            if (this.value.trim() !== '') {
                clearBtn.style.display = 'block';
            } else {
                clearBtn.style.display = 'none';
            }
        });
        
        // ==================== 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-lg mb-2"></i>
                        <p class="mb-0">الرجاء اختيار فصل دراسي للتحقق من التسجيلات المكررة</p>
                    </div>
                `;
                return;
            }
            
            // Get semester name
            const semesterSelect = document.getElementById('pre_check_semester');
            const semesterName = semesterSelect.options[semesterSelect.selectedIndex].text;
            
            // Show loading
            checkResult.innerHTML = `
                <div class="text-center py-3">
                    <div class="spinner-border spinner-border-sm text-primary me-2"></div>
                    <span>جاري التحقق من التسجيلات المكررة...</span>
                </div>
            `;
            
            // Get selected student IDs from checkboxes
            const studentIds = [];
            document.querySelectorAll('.student-checkbox').forEach(cb => {
                studentIds.push(cb.value);
            });
            
            // Send AJAX request to check duplicates
            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 me-2"></i>
                                <strong class="text-warning">تم العثور على ${data.duplicate_count} طالب مسجلين مسبقاً</strong>
                            </div>
                            <small class="text-muted">الفصل الدراسي: ${semesterName}</small>
                            <div class="mt-2">
                                <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>`;
                        
                        // Highlight rows in the table
                        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 {
                        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 me-2"></i>
                                <strong class="text-success">لا يوجد تسجيلات مكررة</strong>
                            </div>
                            <small class="text-muted">الفصل الدراسي: ${semesterName}</small>
                            <p class="mb-0 mt-2">جميع الطلاب المحددين غير مسجلين في هذا الفصل.</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) {
                // Set the same semester in pre-check dropdown
                for (let i = 0; i < preCheckSelect.options.length; i++) {
                    if (preCheckSelect.options[i].value === semesterId) {
                        preCheckSelect.value = semesterId;
                        break;
                    }
                }
                // Trigger duplicate check
                checkDuplicates();
            }
        }
        
        // Helper function to escape HTML
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize clear button visibility
            const searchInput = document.getElementById('search_query');
            const clearBtn = document.querySelector('.search-clear-btn');
            if (searchInput && searchInput.value.trim() !== '') {
                clearBtn.style.display = 'block';
            }
            
            // Trigger specialization load if program and section are selected
            <?php if ($filter_program_id && $filter_section_id && $filter_college_id): ?>
                // Simulate AJAX call to load specializations
                setTimeout(loadSpecializations, 500);
            <?php endif; ?>
            
            // Initialize duplicate check if semester is selected
            <?php if ($selected_semester_id > 0): ?>
                const semesterSelect = document.getElementById('semester_id');
                const preCheckSelect = document.getElementById('pre_check_semester');
                
                for (let i = 0; i < semesterSelect.options.length; i++) {
                    if (semesterSelect.options[i].value === "<?= $selected_semester_id ?>") {
                        semesterSelect.value = "<?= $selected_semester_id ?>";
                        break;
                    }
                }
                
                for (let i = 0; i < preCheckSelect.options.length; i++) {
                    if (preCheckSelect.options[i].value === "<?= $selected_semester_id ?>") {
                        preCheckSelect.value = "<?= $selected_semester_id ?>";
                        break;
                    }
                }
                
                setTimeout(checkDuplicates, 500);
            <?php endif; ?>
        });
    </script>
</body>
</html>