<?php
// stop_registration.php - PAGE TO STOP REGISTRATION BY SETTING END DATE
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
$success_message = '';
$error_message = '';

// 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;
    $filter_semester_id = $_GET['filter_semester'] ?? null;
    $filter_payment_status = $_GET['filter_payment_status'] ?? null;
    $filter_active_only = isset($_GET['filter_active_only']) ? 1 : 0;
    $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;
    $filter_semester_id = null;
    $filter_payment_status = null;
    $filter_active_only = 0;
    $search_query = '';
}

// Initialize registrations array
$registrations = [];

// Handle form submission for stopping registration (setting end date)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['stop_registrations'])) {
    $registration_ids = $_POST['registration_ids'] ?? [];
    $end_date = $_POST['end_date'] ?? '';
    $end_time = $_POST['end_time'] ?? '23:59:59';
    
    if (empty($registration_ids)) {
        $error_message = 'لم يتم اختيار أي تسجيل لإيقاف التسجيل';
    } elseif (empty($end_date)) {
        $error_message = 'يرجى تحديد تاريخ النهاية';
    } else {
        try {
            // Validate date format and ensure it's not in the past
            $end_datetime = $end_date . ' ' . $end_time . ':00';
            $end_timestamp = strtotime($end_datetime);
            $now_timestamp = time();
            
            if ($end_timestamp <= $now_timestamp) {
                $error_message = 'تاريخ النهاية يجب أن يكون في المستقبل';
                throw new Exception('End date must be in the future');
            }
            
            // Begin transaction
            $mysqli1->begin_transaction();
            
            $updated_count = 0;
            
            foreach ($registration_ids as $reg_id) {
                // Check if registration exists and is not deleted
                $check_stmt = $mysqli1->prepare("
                    SELECT id, student_id, semester_id, end 
                    FROM registrations 
                    WHERE id = ? AND deleted_at IS NULL
                ");
                $check_stmt->bind_param("i", $reg_id);
                $check_stmt->execute();
                $registration = $check_stmt->get_result()->fetch_assoc();
                $check_stmt->close();
                
                if (!$registration) {
                    continue; // Skip if registration not found
                }
                
                // Update the end date of the registration
                $update_stmt = $mysqli1->prepare("
                    UPDATE registrations 
                    SET end = ?, updated_at = NOW()
                    WHERE id = ? AND deleted_at IS NULL
                ");
                $update_stmt->bind_param("si", $end_datetime, $reg_id);
                
                if ($update_stmt->execute()) {
                    $updated_count++;
                }
                $update_stmt->close();
            }
            
            // Commit transaction
            $mysqli1->commit();
            
            $success_message = "تم تحديث تاريخ نهاية التسجيل لـ {$updated_count} تسجيل/تسجيلات بنجاح";
            
        } catch (Exception $e) {
            // Rollback transaction on error
            $mysqli1->rollback();
            $error_message = "حدث خطأ أثناء تحديث تاريخ النهاية: " . $e->getMessage();
            
            // Log detailed error for debugging
            error_log("Stop Registration Error: " . $e->getMessage());
            error_log("SQL Error: " . ($mysqli1->error ?? 'No SQL error'));
        }
    }
}

// Get filtered registrations ONLY if filters were applied
if ($filters_applied) {
    // Build WHERE clause for filtering registrations
    $where = " WHERE r.deleted_at IS NULL AND r.start IS NOT NULL ";
    $types = ''; 
    $params = [];
    
    // Apply scope restrictions
    if (!$canAll && $scopeCollege !== null) {
        $where .= " AND st.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 st.college_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_college_id;
        }
        
        if ($filter_section_id && !empty($filter_section_id)) {
            $where .= " AND st.section_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_section_id;
        }
        
        if ($filter_program_id && !empty($filter_program_id)) {
            $where .= " AND st.program_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_program_id;
        }
        
        if ($filter_batch_id && !empty($filter_batch_id)) {
            $where .= " AND st.batch_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_batch_id;
        }
        
        if ($filter_semester_id && !empty($filter_semester_id)) {
            $where .= " AND r.semester_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_semester_id;
        }
        
        if ($filter_payment_status && !empty($filter_payment_status)) {
            if ($filter_payment_status === 'paid') {
                $where .= " AND r.is_paid = 1 ";
            } elseif ($filter_payment_status === 'unpaid') {
                $where .= " AND r.is_paid = 0 ";
            }
        }
        
        // Filter active registrations only (end date in future)
        if ($filter_active_only) {
            $where .= " AND r.end > NOW() ";
        }
        
        // Apply search query if provided
        if (!empty($search_query)) {
            $where .= " AND (r.student_id LIKE ? OR r.student_name LIKE ?) ";
            $types .= 'ss';
            $search_param = "%" . $search_query . "%";
            $params[] = $search_param;
            $params[] = $search_param;
        }
    }
    
    // Query to get registrations with end dates
    $sqlRegistrations = "
        SELECT 
            r.id, 
            r.student_id, 
            r.student_name,
            r.semester_id,
            r.is_paid,
            r.created_at,
            r.start,
            r.end,
            s.name as semester_name, 
            s.code as semester_code,
            c.name as college_name,
            sec.name as section_name,
            p.name as program_name,
            b.value as batch_name,
            CASE 
                WHEN r.end IS NULL THEN 'مفتوح'
                WHEN r.end > NOW() THEN 'نشط'
                WHEN r.end <= NOW() THEN 'منتهي'
            END as status,
            CASE 
                WHEN r.end IS NULL THEN 'open'
                WHEN r.end > NOW() THEN 'active'
                WHEN r.end <= NOW() THEN 'expired'
            END as status_class,
            TIMESTAMPDIFF(HOUR, NOW(), r.end) as hours_remaining,
            TIMESTAMPDIFF(DAY, NOW(), r.end) as days_remaining
        FROM registrations r
        INNER JOIN students st ON r.student_id = st.student_id
        INNER JOIN semesters s ON r.semester_id = s.id
        LEFT JOIN colleges c ON st.college_id = c.id
        LEFT JOIN sections sec ON st.section_id = sec.id
        LEFT JOIN programs p ON st.program_id = p.id
        LEFT JOIN batches b ON st.batch_id = b.id
        {$where}
        ORDER BY 
            CASE 
                WHEN r.end IS NULL THEN 0
                WHEN r.end > NOW() THEN 1
                ELSE 2
            END,
            r.end ASC,
            r.created_at DESC
        LIMIT 500
    ";
    
    $reg_stmt = $mysqli1->prepare($sqlRegistrations);
    if ($types) {
        $reg_stmt->bind_param($types, ...$params);
    }
    $reg_stmt->execute();
    $registrations = $reg_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $reg_stmt->close();
} else {
    // No registrations to show initially
    $registrations = [];
}

// Get semesters for filter 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', 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: #ef4444;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.1rem;
        }
        .stop-icon {
            width: 40px;
            height: 40px;
            background: #dc3545;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.1rem;
        }
        .registration-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            font-size: 0.85rem;
        }
        .registration-table td {
            font-size: 0.85rem;
            vertical-align: middle;
        }
        .checkbox-cell {
            width: 50px;
            text-align: center;
        }
        .warning-alert {
            border-right: 4px solid #dc3545;
        }
        .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;
        }
        .danger-zone {
            background-color: #fef2f2;
            border: 2px solid #fecaca;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .status-badge {
            font-size: 0.7rem;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-weight: 600;
            display: inline-block;
        }
        .status-active {
            background-color: #10b981;
            color: white;
        }
        .status-expired {
            background-color: #6b7280;
            color: white;
        }
        .status-open {
            background-color: #3b82f6;
            color: white;
        }
        .date-picker-group {
            background-color: #fff;
            border-radius: 8px;
        }
        .end-date-input {
            border: 2px solid #dc3545;
            border-radius: 8px !important;
            padding: 0.6rem 1rem !important;
            font-size: 0.95rem !important;
        }
        .end-date-input:focus {
            border-color: #b91c1c;
            box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
        }
        .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;
        }
        .compact-table {
            font-size: 0.8rem;
        }
        .compact-table th, .compact-table td {
            padding: 0.5rem;
        }
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        .filter-row {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            margin-bottom: 15px;
        }
        .filter-group {
            flex: 1;
            min-width: 150px;
        }
        .search-row {
            margin-top: 10px;
            margin-bottom: 15px;
        }
        .time-remaining {
            font-size: 0.7rem;
            color: #6c757d;
        }
        .expiry-warning {
            background-color: #fff3cd;
        }
        .badge-end-date {
            background-color: #dc3545;
            color: white;
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
        }
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
        }
        .quick-action-btn {
            transition: all 0.3s ease;
        }
        .quick-action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container py-4" dir="rtl">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4">
            <div class="stop-icon me-3">
                <i class="fas fa-stop-circle"></i>
            </div>
            <h3 class="mb-0 fw-bold text-danger">
                <i class="fas fa-calendar-times me-2"></i>إيقاف التسجيل - تحديد تاريخ النهاية
            </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="admin_dashboard.php">
                    <i class="fas fa-arrow-right me-2"></i>العودة للوحة التحكم
                </a>
            </div>
        </div>

        <?php if (!$filters_applied): ?>
            <div class="info-message">
                <i class="fas fa-info-circle 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; ?>

        <!-- Warning Alert -->
        <div class="alert alert-danger alert-dismissible fade show warning-alert" role="alert">
            <div class="d-flex align-items-center">
                <i class="fas fa-exclamation-circle fa-lg me-3"></i>
                <div>
                    <strong class="text-dark">تحذير هام:</strong> يمكنك إيقاف التسجيل للطلاب بتحديد تاريخ نهاية جديد
                    <br>
                    <small class="text-muted">سيتم تحديث تاريخ النهاية للتسجيلات المحددة. الطلاب لن يتمكنوا من التسجيل بعد التاريخ المحدد.</small>
                </div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>

        <!-- Filter Card -->
        <div class="card card-arabic p-4 mb-4">
            <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" id="filterForm">
                <!-- Hidden field to indicate filters were applied -->
                <input type="hidden" name="filter_applied" value="1">
                
                <!-- Filter Row 1: All filters in one row -->
                <div class="filter-row">
                    <!-- College Filter -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <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>
                    
                    <!-- Section Filter -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <i class="fas fa-layer-group me-1"></i>
                            القسم
                        </label>
                        <div class="input-group input-group-sm">
                            <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>
                    </div>
                    
                    <!-- Program Filter -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <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>
                    
                    <!-- Batch Filter -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <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>
                    
                    <!-- Semester Filter -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <i class="fas fa-calendar-alt me-1"></i>
                            الفصل الدراسي
                        </label>
                        <div class="input-group input-group-sm">
                            <select class="form-control border-end-0" name="filter_semester" id="filter_semester">
                                <option value="">جميع الفصول</option>
                                <?php foreach ($semesters as $semester): ?>
                                    <option value="<?= $semester['id'] ?>" <?= (isset($_GET['filter_semester']) && $_GET['filter_semester'] == $semester['id']) ? 'selected' : '' ?>>
                                        <?= e($semester['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-calendar"></i>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Payment Status Filter -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <i class="fas fa-money-bill-wave me-1"></i>
                            حالة الدفع
                        </label>
                        <div class="input-group input-group-sm">
                            <select class="form-control border-end-0" name="filter_payment_status">
                                <option value="">جميع الحالات</option>
                                <option value="paid" <?= (isset($_GET['filter_payment_status']) && $_GET['filter_payment_status'] == 'paid') ? 'selected' : '' ?>>
                                    مدفوعة
                                </option>
                                <option value="unpaid" <?= (isset($_GET['filter_payment_status']) && $_GET['filter_payment_status'] == 'unpaid') ? 'selected' : '' ?>>
                                    غير مدفوعة
                                </option>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-credit-card"></i>
                            </span>
                        </div>
                    </div>
                </div>
                
                <!-- Filter Row 2: Additional filters -->
                <div class="filter-row mt-2">
                    <!-- Active Only Filter -->
                    <div class="filter-group d-flex align-items-center">
                        <div class="form-check">
                            <input type="checkbox" 
                                   class="form-check-input" 
                                   name="filter_active_only" 
                                   id="filter_active_only" 
                                   value="1"
                                   <?= $filter_active_only ? 'checked' : '' ?>>
                            <label class="form-check-label fw-semibold text-muted small" for="filter_active_only">
                                <i class="fas fa-bolt me-1"></i>
                                التسجيلات النشطة فقط (تاريخ نهاية في المستقبل)
                            </label>
                        </div>
                    </div>
                </div>
                
                <!-- Search Row -->
                <div class="search-row">
                    <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="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="stop_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>
            </form>
        </div>

        <!-- Stop Registration Form -->
        <?php if ($filters_applied && !empty($registrations)): ?>
        <div class="card card-arabic p-4 mb-4">
            <div class="d-flex align-items-center mb-3">
                <h6 class="fw-bold mb-0 text-danger">
                    <i class="fas fa-calendar-times me-2"></i>إيقاف التسجيل - تحديد تاريخ النهاية
                </h6>
                <span class="badge bg-danger ms-2"><?= count($registrations) ?> تسجيل متاح</span>
                <?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>
            
            <!-- Date Picker Card -->
            <div class="card mb-4 border-danger">
                <div class="card-header bg-danger text-white py-2">
                    <i class="fas fa-clock me-2"></i>
                    تحديد تاريخ النهاية الجديد للتسجيلات المحددة
                </div>
                <div class="card-body">
                    <div class="row align-items-end">
                        <div class="col-md-5">
                            <label class="form-label fw-bold">
                                <i class="fas fa-calendar-alt me-1 text-danger"></i>
                                تاريخ النهاية
                            </label>
                            <div class="input-group">
                                <input type="date" 
                                       name="end_date" 
                                       id="end_date" 
                                       form="stopRegistrationForm"
                                       class="form-control end-date-input"
                                       min="<?= date('Y-m-d', strtotime('+1 day')) ?>"
                                       value="<?= date('Y-m-d', strtotime('+7 days')) ?>"
                                       required>
                                <span class="input-group-text bg-light">
                                    <i class="fas fa-calendar"></i>
                                </span>
                            </div>
                            <div class="form-text text-muted mt-1">
                                <i class="fas fa-info-circle me-1"></i>
                                يجب أن يكون التاريخ في المستقبل
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold">
                                <i class="fas fa-clock me-1 text-danger"></i>
                                الوقت
                            </label>
                            <div class="input-group">
                                <input type="time" 
                                       name="end_time" 
                                       id="end_time" 
                                       form="stopRegistrationForm"
                                       class="form-control"
                                       value="23:59">
                                <span class="input-group-text bg-light">
                                    <i class="fas fa-clock"></i>
                                </span>
                            </div>
                            <div class="form-text text-muted mt-1">
                                <i class="fas fa-info-circle me-1"></i>
                                الوقت بصيغة 24 ساعة
                            </div>
                        </div>
                        <div class="col-md-3">
                            <button type="submit" 
                                    name="stop_registrations" 
                                    form="stopRegistrationForm"
                                    class="btn btn-danger w-100 py-2 quick-action-btn">
                                <i class="fas fa-stop-circle me-1"></i>
                                إيقاف التسجيل
                            </button>
                            <div class="form-text text-muted mt-1 text-center">
                                <i class="fas fa-check-circle me-1"></i>
                                للتسجيلات المحددة فقط
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <form method="post" id="stopRegistrationForm">
                <!-- Action Buttons -->
                <div class="row g-3 align-items-end mb-3">
                    <div class="col-md-8">
                        <div class="d-flex gap-2 flex-wrap">
                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="selectAllRegistrations()">
                                <i class="fas fa-check-square me-1"></i>تحديد الكل
                            </button>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="deselectAllRegistrations()">
                                <i class="fas fa-times-circle me-1"></i>إلغاء الكل
                            </button>
                            <button type="button" class="btn btn-outline-success btn-sm" onclick="selectActiveOnly()">
                                <i class="fas fa-bolt me-1"></i>تحديد النشط فقط
                            </button>
                            <button type="button" class="btn btn-outline-warning btn-sm" onclick="selectExpiringSoon()">
                                <i class="fas fa-hourglass-half me-1"></i>تنتهي خلال 3 أيام
                            </button>
                            <button type="button" class="btn btn-outline-info btn-sm" onclick="selectNoEndDate()">
                                <i class="fas fa-infinity me-1"></i>بدون تاريخ نهاية
                            </button>
                        </div>
                    </div>
                    <div class="col-md-4 text-start">
                        <div class="text-muted small bg-light p-2 rounded">
                            <i class="fas fa-info-circle me-1"></i>
                            <span id="selectedCount">0</span> تسجيل/تسجيلات محددة
                        </div>
                    </div>
                </div>
                
                <!-- Registrations Table -->
                <div class="table-responsive mt-4">
                    <table class="table table-striped registration-table compact-table">
                        <thead>
                            <tr>
                                <th class="checkbox-cell">
                                    <input type="checkbox" id="selectAll" onchange="toggleAllRegistrations(this)">
                                </th>
                                <th>#</th>
                                <th>رقم الطالب</th>
                                <th>اسم الطالب</th>
                                <th>الكلية</th>
                                <th>البرنامج</th>
                                <th>الفصل الدراسي</th>
                                <th>تاريخ البداية</th>
                                <th>تاريخ النهاية الحالي</th>
                                <th>الحالة</th>
                                <th>الوقت المتبقي</th>
                                <th>الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $counter = 1; ?>
                            <?php foreach ($registrations as $reg): ?>
                                <?php
                                // Status styling
                                $status_class = '';
                                $status_text = $reg['status'] ?? 'غير معروف';
                                
                                if ($reg['status_class'] === 'active') {
                                    $status_class = 'status-active';
                                } elseif ($reg['status_class'] === 'expired') {
                                    $status_class = 'status-expired';
                                } elseif ($reg['status_class'] === 'open') {
                                    $status_class = 'status-open';
                                }
                                
                                // Format dates
                                $start_date = $reg['start'] ? date('Y-m-d H:i', strtotime($reg['start'])) : 'غير محدد';
                                $end_date = $reg['end'] ? date('Y-m-d H:i', strtotime($reg['end'])) : 'مفتوح';
                                
                                // Payment status
                                $payment_status = ($reg['is_paid'] == 1) ? 'مدفوعة' : 'غير مدفوعة';
                                $payment_class = ($reg['is_paid'] == 1) ? 'paid-status' : 'unpaid-status';
                                
                                // Time remaining warning
                                $is_expiring_soon = ($reg['days_remaining'] !== null && $reg['days_remaining'] <= 3 && $reg['status_class'] === 'active');
                                $row_class = $is_expiring_soon ? 'expiry-warning' : '';
                                ?>
                                <tr class="<?= $row_class ?>">
                                    <td class="checkbox-cell">
                                        <input type="checkbox" 
                                               name="registration_ids[]" 
                                               value="<?= e($reg['id']) ?>" 
                                               class="registration-checkbox"
                                               data-status="<?= $reg['status_class'] ?>"
                                               data-end="<?= $reg['end'] ?>"
                                               onchange="updateSelectedCount()">
                                    </td>
                                    <td class="text-muted"><?= $counter++ ?></td>
                                    <td><code><?= e($reg['student_id']) ?></code></td>
                                    <td><?= e($reg['student_name']) ?></td>
                                    <td><?= e($reg['college_name'] ?? 'غير محدد') ?></td>
                                    <td><?= e($reg['program_name'] ?? 'غير محدد') ?></td>
                                    <td>
                                        <span class="badge bg-primary" style="font-size: 0.7rem;">
                                            <?= e($reg['semester_name']) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <i class="fas fa-play-circle text-success me-1"></i>
                                        <?= $start_date ?>
                                    </td>
                                    <td>
                                        <?php if ($reg['end']): ?>
                                            <span class="badge-end-date">
                                                <i class="fas fa-stop-circle me-1"></i>
                                                <?= date('Y-m-d H:i', strtotime($reg['end'])) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-info">
                                                <i class="fas fa-infinity me-1"></i>
                                                مفتوح
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="status-badge <?= $status_class ?>">
                                            <?= $status_text ?>
                                        </span>
                                        <?php if ($reg['is_paid'] == 1): ?>
                                            <span class="badge bg-success mt-1" style="font-size: 0.65rem;">
                                                <i class="fas fa-check-circle"></i> مدفوع
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-warning mt-1" style="font-size: 0.65rem;">
                                                <i class="fas fa-exclamation-circle"></i> غير مدفوع
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($reg['status_class'] === 'active'): ?>
                                            <span class="time-remaining">
                                                <i class="fas fa-hourglass-half me-1"></i>
                                                <?php if ($reg['days_remaining'] > 0): ?>
                                                    <?= $reg['days_remaining'] ?> يوم
                                                <?php else: ?>
                                                    <?= $reg['hours_remaining'] ?> ساعة
                                                <?php endif ?>
                                            </span>
                                            <?php if ($is_expiring_soon): ?>
                                                <i class="fas fa-exclamation-triangle text-warning ms-1" title="تنتهي قريباً"></i>
                                            <?php endif; ?>
                                        <?php elseif ($reg['status_class'] === 'expired'): ?>
                                            <span class="text-muted">
                                                <i class="fas fa-check-circle me-1"></i>
                                                منتهي
                                            </span>
                                        <?php elseif ($reg['status_class'] === 'open'): ?>
                                            <span class="text-info">
                                                <i class="fas fa-infinity me-1"></i>
                                                مفتوح
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="action-buttons">
                                            <!-- Profile Button -->
                                            <a class="btn btn-sm btn-info" href="student_profile.php?student_id=<?= urlencode($reg['student_id']) ?>" 
                                               title="عرض ملف الطالب">
                                                <i class="fas fa-user-circle"></i>
                                            </a>
                                            <!-- Quick Set End Date -->
                                            <button type="button" class="btn btn-sm btn-danger" 
                                                    onclick="quickSetEndDate(<?= $reg['id'] ?>, '<?= e($reg['student_name']) ?> (<?= e($reg['student_id']) ?>)')"
                                                    title="تعيين تاريخ نهاية سريع">
                                                <i class="fas fa-stop-circle"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </form>
            
            <!-- Quick Stats -->
            <div class="row mt-4">
                <div class="col-md-3">
                    <div class="border rounded p-3 bg-light">
                        <div class="small text-muted">إجمالي التسجيلات</div>
                        <div class="h5 mb-0 fw-bold"><?= count($registrations) ?></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="border rounded p-3 bg-light">
                        <div class="small text-muted">تسجيلات نشطة</div>
                        <div class="h5 mb-0 fw-bold text-success">
                            <?= count(array_filter($registrations, function($r) { return $r['status_class'] === 'active'; })) ?>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="border rounded p-3 bg-light">
                        <div class="small text-muted">بدون تاريخ نهاية</div>
                        <div class="h5 mb-0 fw-bold text-info">
                            <?= count(array_filter($registrations, function($r) { return $r['status_class'] === 'open'; })) ?>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="border rounded p-3 bg-light">
                        <div class="small text-muted">تنتهي خلال 3 أيام</div>
                        <div class="h5 mb-0 fw-bold text-warning">
                            <?= count(array_filter($registrations, function($r) { 
                                return $r['status_class'] === 'active' && $r['days_remaining'] <= 3; 
                            })) ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php elseif ($filters_applied && empty($registrations)): ?>
            <div class="card card-arabic p-5 text-center">
                <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                <i class="fas fa-user-slash fa-2x 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>
                <div class="mt-4">
                    <a href="registrations.php" class="btn btn-primary">
                        <i class="fas fa-plus-circle me-1"></i>
                        عرض جميع التسجيلات
                    </a>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Quick Set End Date Modal -->
    <div class="modal fade" id="quickEndDateModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">
                        <i class="fas fa-stop-circle me-2"></i>
                        تعيين تاريخ نهاية سريع
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" id="quickEndDateForm">
                    <div class="modal-body">
                        <p class="fw-bold" id="quickStudentInfo"></p>
                        <input type="hidden" name="registration_ids[]" id="quickRegistrationId">
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold text-danger">
                                <i class="fas fa-calendar-alt me-1"></i>
                                تاريخ النهاية الجديد
                            </label>
                            <div class="input-group">
                                <input type="date" 
                                       name="end_date" 
                                       id="quick_end_date"
                                       class="form-control end-date-input"
                                       min="<?= date('Y-m-d', strtotime('+1 day')) ?>"
                                       value="<?= date('Y-m-d', strtotime('+7 days')) ?>"
                                       required>
                                <span class="input-group-text bg-light">
                                    <i class="fas fa-calendar"></i>
                                </span>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold text-danger">
                                <i class="fas fa-clock me-1"></i>
                                الوقت
                            </label>
                            <div class="input-group">
                                <input type="time" 
                                       name="end_time" 
                                       id="quick_end_time"
                                       class="form-control"
                                       value="23:59">
                                <span class="input-group-text bg-light">
                                    <i class="fas fa-clock"></i>
                                </span>
                            </div>
                        </div>
                        
                        <div class="alert alert-warning mt-3">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            سيتم تحديث تاريخ نهاية هذا التسجيل فقط.
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="fas fa-times me-1"></i>
                            إلغاء
                        </button>
                        <button type="submit" name="stop_registrations" class="btn btn-danger">
                            <i class="fas fa-stop-circle me-1"></i>
                            تعيين التاريخ
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            // Set minimum date for date inputs
            const today = new Date();
            const tomorrow = new Date(today);
            tomorrow.setDate(tomorrow.getDate() + 1);
            const tomorrowStr = tomorrow.toISOString().split('T')[0];
            
            const dateInputs = document.querySelectorAll('input[type="date"]');
            dateInputs.forEach(input => {
                input.min = tomorrowStr;
            });
            
            // Initialize search clear button
            const searchInput = document.getElementById('search_query');
            const clearBtn = document.querySelector('.search-clear-btn');
            if (searchInput && searchInput.value.trim() !== '') {
                clearBtn.style.display = 'block';
            }
            
            // Update selected count
            updateSelectedCount();
        });
        
        // Update selected count display
        function updateSelectedCount() {
            const selectedCount = document.querySelectorAll('.registration-checkbox:checked').length;
            const countElement = document.getElementById('selectedCount');
            if (countElement) {
                countElement.textContent = selectedCount;
            }
            
            // Update select all checkbox
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            const selectAll = document.getElementById('selectAll');
            if (selectAll) {
                selectAll.checked = selectedCount === checkboxes.length;
            }
        }
        
        // Toggle all checkboxes
        function toggleAllRegistrations(selectAll) {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
            updateSelectedCount();
        }
        
        function selectAllRegistrations() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
            });
            document.getElementById('selectAll').checked = true;
            updateSelectedCount();
        }
        
        function deselectAllRegistrations() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
            document.getElementById('selectAll').checked = false;
            updateSelectedCount();
        }
        
        function selectActiveOnly() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = checkbox.dataset.status === 'active';
            });
            updateSelectedCount();
            updateSelectAllCheckbox();
        }
        
        function selectExpiringSoon() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                // This is a simplified version - in a real implementation,
                // you would need to pass the days_remaining value
                checkbox.checked = checkbox.dataset.status === 'active';
            });
            updateSelectedCount();
            updateSelectAllCheckbox();
        }
        
        function selectNoEndDate() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = checkbox.dataset.status === 'open';
            });
            updateSelectedCount();
            updateSelectAllCheckbox();
        }
        
        function updateSelectAllCheckbox() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            const checkedCount = document.querySelectorAll('.registration-checkbox:checked').length;
            const selectAll = document.getElementById('selectAll');
            
            if (selectAll) {
                selectAll.checked = checkedCount === checkboxes.length;
            }
        }
        
        // Form submission confirmation
        document.getElementById('stopRegistrationForm')?.addEventListener('submit', function(e) {
            const selectedCount = document.querySelectorAll('.registration-checkbox:checked').length;
            const endDate = document.getElementById('end_date').value;
            
            if (selectedCount === 0) {
                e.preventDefault();
                alert('يرجى اختيار تسجيل واحد على الأقل');
                return;
            }
            
            if (!endDate) {
                e.preventDefault();
                alert('يرجى تحديد تاريخ النهاية');
                return;
            }
            
            let confirmationMessage = `⚠️ هل أنت متأكد من تحديث تاريخ النهاية لـ ${selectedCount} تسجيل/تسجيلات؟\n\n`;
            confirmationMessage += `📅 تاريخ النهاية الجديد: ${endDate}\n\n`;
            confirmationMessage += `❌ الطالب/الطلاب لن يتمكنوا من التسجيل بعد هذا التاريخ.`;
            
            if (!confirm(confirmationMessage)) {
                e.preventDefault();
            }
        });
        
        // Load sections when college changes
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            
            sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
            
            if (!collegeId || collegeId === '') {
                sectionSelect.disabled = true;
                return;
            }
            
            const form = document.createElement('form');
            form.method = 'get';
            form.style.display = 'none';
            
            const collegeInput = document.createElement('input');
            collegeInput.type = 'hidden';
            collegeInput.name = 'filter_college';
            collegeInput.value = collegeId;
            form.appendChild(collegeInput);
            
            const appliedInput = document.createElement('input');
            appliedInput.type = 'hidden';
            appliedInput.name = 'filter_applied';
            appliedInput.value = '1';
            form.appendChild(appliedInput);
            
            // Preserve other filters
            const currentSemester = "<?= isset($_GET['filter_semester']) ? $_GET['filter_semester'] : '' ?>";
            if (currentSemester) {
                const semesterInput = document.createElement('input');
                semesterInput.type = 'hidden';
                semesterInput.name = 'filter_semester';
                semesterInput.value = currentSemester;
                form.appendChild(semesterInput);
            }
            
            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);
            }
            
            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);
            }
            
            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);
            }
            
            const currentPaymentStatus = "<?= isset($_GET['filter_payment_status']) ? $_GET['filter_payment_status'] : '' ?>";
            if (currentPaymentStatus) {
                const paymentInput = document.createElement('input');
                paymentInput.type = 'hidden';
                paymentInput.name = 'filter_payment_status';
                paymentInput.value = currentPaymentStatus;
                form.appendChild(paymentInput);
            }
            
            const activeOnly = "<?= isset($_GET['filter_active_only']) ? '1' : '0' ?>";
            if (activeOnly === '1') {
                const activeInput = document.createElement('input');
                activeInput.type = 'hidden';
                activeInput.name = 'filter_active_only';
                activeInput.value = '1';
                form.appendChild(activeInput);
            }
            
            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);
            }
            
            document.body.appendChild(form);
            form.submit();
        }
        
        // Clear search field
        function clearSearch() {
            document.getElementById('search_query').value = '';
            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';
            }
        });
        
        // Quick set end date for a single registration
        function quickSetEndDate(registrationId, studentInfo) {
            document.getElementById('quickRegistrationId').value = registrationId;
            document.getElementById('quickStudentInfo').innerHTML = `
                <i class="fas fa-user-graduate me-1"></i>
                ${studentInfo}
            `;
            
            // Set default date to 7 days from now
            const date = new Date();
            date.setDate(date.getDate() + 7);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            document.getElementById('quick_end_date').value = `${year}-${month}-${day}`;
            
            // Show modal
            const modal = new bootstrap.Modal(document.getElementById('quickEndDateModal'));
            modal.show();
        }
        
        // Quick end date form submission
        document.getElementById('quickEndDateForm')?.addEventListener('submit', function(e) {
            const endDate = document.getElementById('quick_end_date').value;
            
            if (!endDate) {
                e.preventDefault();
                alert('يرجى تحديد تاريخ النهاية');
                return;
            }
            
            if (!confirm('⚠️ هل أنت متأكد من تحديث تاريخ نهاية هذا التسجيل؟')) {
                e.preventDefault();
            }
        });
        
        // Add event listeners to checkboxes
        document.querySelectorAll('.registration-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', updateSelectedCount);
        });
    </script>
</body>
</html>