<?php
// registration.php - UPDATED WITH DUPLICATE PREVENTION AND LAST REGISTRATION CARDS
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);

// Initialize variables
$selected_students = [];
$success_message = '';
$error_message = '';

// Initialize students array
$students = [];

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

// Get filter parameters - only use them if filters were applied
if ($filters_applied) {
    $filter_college_id = $_GET['filter_college'] ?? null;
    $filter_section_id = $_GET['filter_section'] ?? null;
    $filter_program_id = $_GET['filter_program'] ?? null;
    $filter_batch_id = $_GET['filter_batch'] ?? null;
    $search_query = trim($_GET['search_query'] ?? '');
} else {
    // Don't apply filters by default
    $filter_college_id = null;
    $filter_section_id = null;
    $filter_program_id = null;
    $filter_batch_id = null;
    $search_query = '';
}

// Build WHERE clause for filtering students - NO CONSTRAINTS, ONLY FILTERS
$where = " WHERE 1=1 ";
$types = ''; 
$params = [];

// Apply scope restrictions only (no profile or interview constraints)
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;
    }

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

// Function to generate unique payment reference - UPDATED WITH YEAR PREFIX
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 (25 for 2025, 26 for 2026, etc.)
        $random_part = str_pad(mt_rand(1, 9999999999), 10, '0', STR_PAD_LEFT);
        $reference = $year_prefix . $random_part;
        
        // Check if reference already exists
        $check_stmt = $mysqli->prepare("SELECT id FROM registrations WHERE payment_reference = ?");
        $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);
}

// Function to check for existing registrations with same filters
function checkExistingRegistrations($mysqli, $filters) {
    $where_conditions = [];
    $types = '';
    $params = [];
    
    if (!empty($filters['college_id'])) {
        $where_conditions[] = "rc.college_id = ?";
        $types .= 'i';
        $params[] = $filters['college_id'];
    }
    
    if (!empty($filters['section_id'])) {
        $where_conditions[] = "rc.section_id = ?";
        $types .= 'i';
        $params[] = $filters['section_id'];
    }
    
    if (!empty($filters['program_id'])) {
        $where_conditions[] = "rc.program_id = ?";
        $types .= 'i';
        $params[] = $filters['program_id'];
    }
    
    if (!empty($filters['batch_id'])) {
        $where_conditions[] = "rc.batch_id = ?";
        $types .= 'i';
        $params[] = $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
        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
        WHERE {$where_clause}
        AND r.deleted_at IS NULL
        ORDER BY r.created_at DESC
        LIMIT 500
    ";
    
    $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 based on current filters
$current_filters = [
    'college_id' => $filter_college_id,
    'section_id' => $filter_section_id,
    'program_id' => $filter_program_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 for registration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register_students'])) {
    $semester_id = (int)($_POST['semester_id'] ?? 0);
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';
    $student_ids = $_POST['student_ids'] ?? [];
    
    // Validate dates
    if (empty($semester_id)) {
        $error_message = 'يرجى اختيار فصل دراسي';
    } elseif (empty($start_date)) {
        $error_message = 'يرجى تحديد تاريخ بداية التسجيل';
    } elseif (empty($end_date)) {
        $error_message = 'يرجى تحديد تاريخ نهاية التسجيل';
    } elseif (empty($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 = ?");
                $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;
                
                foreach ($student_ids as $student_id) {
                    // Check if student already registered for this semester
                    $check_stmt = $mysqli1->prepare("
                        SELECT id FROM registrations 
                        WHERE student_id = ? AND semester_id = ? AND 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++;
                        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, 
                               program_fees, registration_fees, insurance_fees 
                        FROM students 
                        WHERE student_id = ?
                    ");
                    $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 not empty and set to 0 if null/empty
                    // program_fees from students table becomes study_fees in registrations table
                    $study_fees = !empty($student['program_fees']) ? floatval($student['program_fees']) : 0.00;
                    $registration_fees = !empty($student['registration_fees']) ? floatval($student['registration_fees']) : 0.00;
                    $insurance_fees = !empty($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 and has the correct structure
                    $table_check = $mysqli1->query("
                        SHOW COLUMNS FROM registration_constraints LIKE 'registration_id'
                    ");
                    
                    if ($table_check->num_rows > 0) {
                        // Table exists with registration_id column
                        $constraint_stmt = $mysqli1->prepare("
                            INSERT INTO registration_constraints (
                                registration_id, student_id, semester_id, college_id, 
                                section_id, program_id, batch_id, created_at, updated_at
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                        ");
                        
                        // Get batch_id from student
                        $batch_stmt = $mysqli1->prepare("SELECT batch_id FROM students WHERE student_id = ?");
                        $batch_stmt->bind_param("s", $student_id);
                        $batch_stmt->execute();
                        $batch_result = $batch_stmt->get_result()->fetch_assoc();
                        $batch_id = $batch_result['batch_id'] ?? null;
                        $batch_stmt->close();
                        
                        $constraint_stmt->bind_param(
                            "isiisii",
                            $registration_id,
                            $student['student_id'],
                            $semester_id,
                            $student['college_id'],
                            $student['section_id'],
                            $student['program_id'],
                            $batch_id
                        );
                        
                        $constraint_stmt->execute();
                        $constraint_stmt->close();
                    } else {
                        // Table doesn't exist or doesn't have registration_id column
                        // Let's create the table if it doesn't exist
                        $create_table_sql = "
                            CREATE TABLE IF NOT EXISTS registration_constraints (
                                id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                                registration_id BIGINT UNSIGNED NOT NULL,
                                student_id VARCHAR(50) NOT NULL,
                                semester_id INT NOT NULL,
                                college_id INT,
                                section_id INT,
                                program_id INT,
                                batch_id INT,
                                created_at TIMESTAMP NULL DEFAULT NULL,
                                updated_at TIMESTAMP NULL DEFAULT NULL,
                                INDEX idx_registration_id (registration_id),
                                INDEX idx_student_id (student_id),
                                INDEX idx_semester_id (semester_id)
                            )
                        ";
                        $mysqli1->query($create_table_sql);
                        
                        // Now insert the constraint record
                        $constraint_stmt = $mysqli1->prepare("
                            INSERT INTO registration_constraints (
                                registration_id, student_id, semester_id, college_id, 
                                section_id, program_id, batch_id, created_at, updated_at
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                        ");
                        
                        // Get batch_id from student
                        $batch_stmt = $mysqli1->prepare("SELECT batch_id FROM students WHERE student_id = ?");
                        $batch_stmt->bind_param("s", $student_id);
                        $batch_stmt->execute();
                        $batch_result = $batch_stmt->get_result()->fetch_assoc();
                        $batch_id = $batch_result['batch_id'] ?? null;
                        $batch_stmt->close();
                        
                        $constraint_stmt->bind_param(
                            "isiisii",
                            $registration_id,
                            $student['student_id'],
                            $semester_id,
                            $student['college_id'],
                            $student['section_id'],
                            $student['program_id'],
                            $batch_id
                        );
                        
                        $constraint_stmt->execute();
                        $constraint_stmt->close();
                    }
                    
                    $registration_count++;
                }
                
                // Commit transaction
                $mysqli1->commit();
                
                $success_message = "تم تسجيل {$registration_count} طالب بنجاح في الفصل الدراسي المحدد";
                if ($duplicate_count > 0) {
                    $success_message .= " (تم تخطي {$duplicate_count} طالب لديهم تسجيلات سابقة في هذا الفصل)";
                }
                
            } 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 ONLY if filters were applied
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.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,
            b.value AS batch_name,
            (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 batches b ON s.batch_id = b.id
        {$where}
        ORDER BY s.student_id DESC
        LIMIT 500
    ";

    $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 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 filter options
$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();
}

$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();

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', 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;
        }
    </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>
                <?= $error_message ?>
                <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-3 col-md-6">
                            <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="<?= $college['id'] ?>" <?= (isset($_GET['filter_college']) && $_GET['filter_college'] == $college['id']) ? 'selected' : '' ?>>
                                                <?= e($college['name']) ?>
                                            </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-3 col-md-6">
                            <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' : '' ?>>
                                        <option value="">جميع الأقسام</option>
                                        <?php if ($filter_college_id && !empty($sections)): ?>
                                            <?php foreach ($sections as $section): ?>
                                                <option value="<?= $section['id'] ?>" <?= (isset($_GET['filter_section']) && $_GET['filter_section'] == $section['id']) ? 'selected' : '' ?>>
                                                    <?= e($section['name']) ?>
                                                </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-3 col-md-6">
                            <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">
                                        <option value="">جميع البرامج</option>
                                        <?php foreach ($programs as $program): ?>
                                            <option value="<?= $program['id'] ?>" <?= (isset($_GET['filter_program']) && $_GET['filter_program'] == $program['id']) ? 'selected' : '' ?>>
                                                <?= e($program['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-book"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Batch Filter -->
                        <div class="col-lg-3 col-md-6">
                            <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="<?= $batch['id'] ?>" <?= (isset($_GET['filter_batch']) && $_GET['filter_batch'] == $batch['id']) ? 'selected' : '' ?>>
                                                <?= e($batch['value']) ?>
                                            </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-12 mt-2">
                            <div class="search-input-group">
                                <div class="input-group input-group-sm">
                                    <input type="text" 
                                           class="form-control" 
                                           name="search_query" 
                                           id="search_query"
                                           placeholder="بحث برقم الطالب أو اسم الطالب..."
                                           value="<?= e($search_query) ?>"
                                           autocomplete="off">
                                    <span class="input-group-text bg-light">
                                        <i class="fas fa-search"></i>
                                    </span>
                                </div>
                                <button type="button" class="search-clear-btn" onclick="clearSearch()" title="مسح البحث">
                                    <i class="fas fa-times"></i>
                                </button>
                            </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">
                                    <i class="fas fa-sync-alt me-1"></i>
                                    إعادة تعيين
                                </a>
                                <?php if ($filters_applied): ?>
                                    <span class="badge bg-success align-self-center px-3 py-2">
                                        <i class="fas fa-check me-1"></i>
                                        تم تطبيق التصفية
                                        <?php if (!empty($search_query)): ?>
                                            <i class="fas fa-search ms-1"></i>
                                        <?php endif; ?>
                                    </span>
                                <?php endif; ?>
                            </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>
                                
                                <!-- Show search query if exists -->
                                <?php if (!empty($search_query)): ?>
                                    <div class="mb-2 p-2 bg-warning bg-opacity-10 rounded">
                                        <div class="fw-semibold text-warning mb-1">
                                            <i class="fas fa-search me-1"></i>
                                            نتيجة البحث
                                        </div>
                                        <div class="text-truncate">
                                            "<?= e($search_query) ?>"
                                        </div>
                                    </div>
                                <?php endif; ?>
                                
                                <!-- Show selected college and section -->
                                <?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 bg-primary bg-opacity-10 text-primary">
                                                <?= e($selected_college['name']) ?>
                                            </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 bg-success bg-opacity-10 text-success">
                                                <?= e($selected_section['name']) ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <!-- Last Semester with Enrollments -->
                                <?php
                                // Get last semester with enrollments based on current filters
                                if ($filters_applied && (isset($filter_college_id) || isset($filter_section_id) || isset($filter_program_id) || isset($filter_batch_id))) {
                                    $where_conditions = [];
                                    $where_params = [];
                                    
                                    if ($filter_college_id) {
                                        $where_conditions[] = "st.college_id = ?";
                                        $where_params[] = $filter_college_id;
                                    }
                                    
                                    if ($filter_section_id) {
                                        $where_conditions[] = "st.section_id = ?";
                                        $where_params[] = $filter_section_id;
                                    }
                                    
                                    if ($filter_program_id) {
                                        $where_conditions[] = "st.program_id = ?";
                                        $where_params[] = $filter_program_id;
                                    }
                                    
                                    if ($filter_batch_id) {
                                        $where_conditions[] = "st.batch_id = ?";
                                        $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)) {
                                        $param_types = str_repeat("i", count($where_params));
                                        $last_semester_stmt->bind_param($param_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();
                                }
                                ?>
                                
                                <?php if (isset($last_semester) && $last_semester): ?>
                                <div class="mb-2 p-2 bg-primary bg-opacity-10 rounded">
                                    <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><?= e($last_semester['name']) ?> (<?= e($last_semester['code']) ?>)</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">
            <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; ?>
                <?php if (!empty($search_query)): ?>
                    <span class="badge bg-info ms-2">
                        <i class="fas fa-search me-1"></i>
                        بحث: "<?= e($search_query) ?>"
                    </span>
                <?php endif; ?>
            </div>
            
            <form method="post" id="registrationForm">
                <!-- 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" required>
                                <option value="">-- اختر الفصل الدراسي --</option>
                                <?php foreach ($semesters as $semester): ?>
                                    <option value="<?= $semester['id'] ?>">
                                        <?= e($semester['name']) ?> (<?= e($semester['code']) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">تاريخ بداية التسجيل:</label>
                            <input type="date" class="form-control" name="start_date" required 
                                   min="<?= date('Y-m-d') ?>" value="<?= date('Y-m-d') ?>">
                            <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">
                                <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>
                            سيتم إنشاء رقم مرجعي فريد لكل تسجيل تلقائياً
                            <?php if (!empty($last_registrations)): ?>
                                <br>
                                <i class="fas fa-exclamation-triangle me-1 text-warning"></i>
                                <span class="text-warning">يوجد تسجيلات سابقة بنفس التصفية</span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Students Table -->
                <div class="table-responsive mt-4">
                    <table class="table table-striped student-table">
                       <!-- Updated thead section with serial number -->
<thead>
    <tr>
        <th class="checkbox-cell">
            <input type="checkbox" id="selectAll" onchange="toggleAllStudents(this)">
        </th>
        <th>#</th> <!-- Serial Number Column -->
        <th>رقم الطالب</th>
        <th>اسم الطالب</th>
        <th>الكلية</th>
        <th>القسم</th>
        <th>البرنامج</th>
        <th>الدفعة</th>
        <th>الرسوم</th>
        <th>التسجيلات السابقة</th>
        <th>الإجراءات</th> <!-- New Actions Column -->
    </tr>
</thead>

<!-- Updated tbody section with serial number -->
<tbody>
    <?php $counter = 1; ?>
    <?php foreach ($students as $student): ?>
        <?php
        // Calculate total fees for display
        $study_fees = !empty($student['program_fees']) ? floatval($student['program_fees']) : 0.00;
        $registration_fees = !empty($student['registration_fees']) ? floatval($student['registration_fees']) : 0.00;
        $insurance_fees = !empty($student['insurance_fees']) ? floatval($student['insurance_fees']) : 0.00;
        $total_fees = $study_fees + $registration_fees + $insurance_fees;
        ?>
        <tr>
            <td class="checkbox-cell">
                <input type="checkbox" name="student_ids[]" value="<?= e($student['student_id']) ?>" class="student-checkbox">
            </td>
            <td class="text-muted"><?= $counter++ ?></td> <!-- Serial Number -->
            <td><code><?= e($student['student_id']) ?></code></td>
            <td>
                <?= e($student['student_name']) ?>
                <?php if ($student['student_name_eng']): ?>
                    <br><small class="text-muted"><?= e($student['student_name_eng']) ?></small>
                <?php endif; ?>
            </td>
            <td><?= e($student['college_name']) ?></td>
            <td><?= e($student['section_name']) ?></td>
            <td><?= e($student['program_name']) ?></td>
            <td>
                <span class="badge bg-secondary batch-badge"><?= e($student['batch_name']) ?></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>
                <div class="d-flex align-items-center gap-2">
                    <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>
                    <?php if ($student['registration_count'] > 0): ?>
                        <a href="https://admission.tanob.edu.sd/student_profile.php?student_id=<?= urlencode($student['student_id']) ?>" 
                           class="btn btn-sm btn-outline-info" 
                           target="_blank"
                           title="عرض التفاصيل">
                            <i class="fas fa-external-link-alt"></i>
                        </a>
                    <?php else: ?>
                        <span class="btn btn-sm btn-outline-secondary disabled" title="لا توجد تسجيلات سابقة">
                            <i class="fas fa-external-link-alt"></i>
                        </span>
                    <?php endif; ?>
                </div>
            </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)): ?>
                        لم يتم العثور على طلاب بناءً على عوامل التصفية المحددة والبحث: "<?= e($search_query) ?>"
                    <?php else: ?>
                        لم يتم العثور على طلاب بناءً على عوامل التصفية المحددة
                    <?php endif; ?>
                </p>
                <?php if (!empty($search_query)): ?>
                    <div class="mt-3">
                        <a href="registration.php?filter_applied=1&filter_college=<?= e($filter_college_id) ?>&filter_section=<?= e($filter_section_id) ?>&filter_program=<?= e($filter_program_id) ?>&filter_batch=<?= e($filter_batch_id) ?>" 
                           class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-times me-1"></i>إلغاء البحث وعرض جميع الطلاب
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function toggleAllStudents(selectAll) {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
        }
        
        function selectAllStudents() {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            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 allChecked = document.querySelectorAll('.student-checkbox:checked').length === document.querySelectorAll('.student-checkbox').length;
                document.getElementById('selectAll').checked = allChecked;
            });
        });
        
        // Form submission confirmation and date validation
        document.getElementById('registrationForm')?.addEventListener('submit', function(e) {
            const selectedCount = document.querySelectorAll('.student-checkbox:checked').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' ?>;
            
            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;
            }
            
            let confirmationMessage = `هل أنت متأكد من تسجيل ${selectedCount} طالب في الفصل الدراسي المحدد؟`;
            
            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];
                }
            }
        });
        
        // Load sections when college changes - SIMPLE VERSION WITHOUT AJAX
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            const sectionLoading = document.getElementById('sectionLoading');
            
            // Reset section select
            sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
            
            if (!collegeId || collegeId === '') {
                sectionSelect.disabled = true;
                return;
            }
            
            // Show loading indicator
            sectionSelect.disabled = true;
            sectionLoading.style.display = 'block';
            
            // Instead of AJAX, we'll use a simple form submission to reload the page
            // Create a form and submit it
            const form = document.createElement('form');
            form.method = 'get';
            form.style.display = 'none';
            
            // Add college parameter
            const collegeInput = document.createElement('input');
            collegeInput.type = 'hidden';
            collegeInput.name = 'filter_college';
            collegeInput.value = collegeId;
            form.appendChild(collegeInput);
            
            // Add filter_applied parameter
            const appliedInput = document.createElement('input');
            appliedInput.type = 'hidden';
            appliedInput.name = 'filter_applied';
            appliedInput.value = '1';
            form.appendChild(appliedInput);
            
            // Add search query if exists
            const searchQuery = document.getElementById('search_query').value;
            if (searchQuery) {
                const searchInput = document.createElement('input');
                searchInput.type = 'hidden';
                searchInput.name = 'search_query';
                searchInput.value = searchQuery;
                form.appendChild(searchInput);
            }
            
            // Add current section if exists
            const currentSection = "<?= isset($_GET['filter_section']) ? $_GET['filter_section'] : '' ?>";
            if (currentSection) {
                const sectionInput = document.createElement('input');
                sectionInput.type = 'hidden';
                sectionInput.name = 'filter_section';
                sectionInput.value = currentSection;
                form.appendChild(sectionInput);
            }
            
            // Add current program if exists
            const currentProgram = "<?= isset($_GET['filter_program']) ? $_GET['filter_program'] : '' ?>";
            if (currentProgram) {
                const programInput = document.createElement('input');
                programInput.type = 'hidden';
                programInput.name = 'filter_program';
                programInput.value = currentProgram;
                form.appendChild(programInput);
            }
            
            // Add current batch if exists
            const currentBatch = "<?= isset($_GET['filter_batch']) ? $_GET['filter_batch'] : '' ?>";
            if (currentBatch) {
                const batchInput = document.createElement('input');
                batchInput.type = 'hidden';
                batchInput.name = 'filter_batch';
                batchInput.value = currentBatch;
                form.appendChild(batchInput);
            }
            
            document.body.appendChild(form);
            form.submit();
        }
        
        // Clear search field
        function clearSearch() {
            document.getElementById('search_query').value = '';
            // Submit the form to reload without search
            document.getElementById('filterForm').submit();
        }
        
        // Auto-submit search on Enter key
        document.getElementById('search_query')?.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                document.getElementById('filterForm').submit();
            }
        });
        
        // Show clear button when search field has value
        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';
            }
        });
        
        // Initialize clear button visibility
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('search_query');
            const clearBtn = document.querySelector('.search-clear-btn');
            if (searchInput && searchInput.value.trim() !== '') {
                clearBtn.style.display = 'block';
            }
        });
    </script>
</body>
</html>
