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

// ============== FIXED: Get filter parameters with proper sanitization ==============
if ($filters_applied) {
    $filter_college_id = isset($_GET['filter_college']) && ctype_digit($_GET['filter_college']) ? (int)$_GET['filter_college'] : null;
    $filter_section_id = isset($_GET['filter_section']) && ctype_digit($_GET['filter_section']) ? (int)$_GET['filter_section'] : null;
    $filter_program_id = isset($_GET['filter_program']) && ctype_digit($_GET['filter_program']) ? (int)$_GET['filter_program'] : null;
    $filter_specialization_id = isset($_GET['filter_specialization']) && ctype_digit($_GET['filter_specialization']) ? (int)$_GET['filter_specialization'] : null; // NEW
    $filter_batch_id = isset($_GET['filter_batch']) && ctype_digit($_GET['filter_batch']) ? (int)$_GET['filter_batch'] : null;
    $filter_semester_id = isset($_GET['filter_semester']) && ctype_digit($_GET['filter_semester']) ? (int)$_GET['filter_semester'] : null;
    $filter_payment_status = isset($_GET['filter_payment_status']) && in_array($_GET['filter_payment_status'], ['paid', 'unpaid']) ? $_GET['filter_payment_status'] : null;
    $filter_active_only = isset($_GET['filter_active_only']) ? 1 : 0;
    $search_query = trim($_GET['search_query'] ?? '');
    // Sanitize search query
    $search_query = htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8');
} else {
    // Don't apply filters by default
    $filter_college_id = null;
    $filter_section_id = null;
    $filter_program_id = null;
    $filter_specialization_id = null; // NEW
    $filter_batch_id = null;
    $filter_semester_id = null;
    $filter_payment_status = null;
    $filter_active_only = 0;
    $search_query = '';
}

// Initialize registrations array
$registrations = [];

// ============== FIXED: Handle form submission with CSRF protection ==============
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['stop_registrations'])) {
    
    // Validate CSRF token
    if (!isset($_POST['csrf']) || !verify_csrf($_POST['csrf'])) {
        $error_message = 'رمز الأمان غير صالح. الرجاء تحديث الصفحة والمحاولة مرة أخرى.';
    } else {
        $registration_ids = $_POST['registration_ids'] ?? [];
        $end_date = $_POST['end_date'] ?? '';
        $end_time = $_POST['end_time'] ?? '23:59:59';
        
        // Validate registration IDs
        $valid_ids = [];
        if (is_array($registration_ids)) {
            foreach ($registration_ids as $id) {
                if (ctype_digit($id)) {
                    $valid_ids[] = (int)$id;
                }
            }
        }
        
        if (empty($valid_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 === false) {
                    throw new Exception('صيغة التاريخ غير صالحة');
                }
                
                if ($end_timestamp <= $now_timestamp) {
                    $error_message = 'تاريخ النهاية يجب أن يكون في المستقبل';
                    throw new Exception('End date must be in the future');
                }
                
                // Begin transaction
                $mysqli1->begin_transaction();
                
                // First, check which registrations exist and are not deleted
                $placeholders = implode(',', array_fill(0, count($valid_ids), '?'));
                $types = str_repeat('i', count($valid_ids));
                
                $check_sql = "SELECT id FROM registrations WHERE id IN ($placeholders) AND deleted_at IS NULL";
                $check_stmt = $mysqli1->prepare($check_sql);
                $check_stmt->bind_param($types, ...$valid_ids);
                $check_stmt->execute();
                $existing_result = $check_stmt->get_result();
                $existing_ids = [];
                while ($row = $existing_result->fetch_assoc()) {
                    $existing_ids[] = (int)$row['id'];
                }
                $check_stmt->close();
                
                if (empty($existing_ids)) {
                    throw new Exception('لا توجد تسجيلات صالحة للتحديث');
                }
                
                // Update the end date of the registrations
                $placeholders2 = implode(',', array_fill(0, count($existing_ids), '?'));
                $types2 = str_repeat('i', count($existing_ids));
                
                $update_sql = "
                    UPDATE registrations 
                    SET end = ?, updated_at = NOW()
                    WHERE id IN ($placeholders2) AND deleted_at IS NULL
                ";
                $update_stmt = $mysqli1->prepare($update_sql);
                
                // Create parameters array with end_datetime first, then IDs
                $update_params = array_merge([$end_datetime], $existing_ids);
                $update_types = 's' . $types2;
                
                $update_stmt->bind_param($update_types, ...$update_params);
                $update_stmt->execute();
                $updated_count = $update_stmt->affected_rows;
                $update_stmt->close();
                
                // Commit transaction
                $mysqli1->commit();
                
                $success_message = "تم تحديث تاريخ نهاية التسجيل لـ {$updated_count} تسجيل/تسجيلات بنجاح";
                
                // Log the action
                error_log("User {$committeeId} updated end date for {$updated_count} registrations. New end: {$end_datetime}");
                
            } 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'));
            }
        }
    }
}

// Generate CSRF token
$csrf_token = csrf_token();

// 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
    if ($filters_applied) {
        if ($filter_college_id && $filter_college_id > 0) {
            $where .= " AND st.college_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_college_id;
        }
        
        if ($filter_section_id && $filter_section_id > 0) {
            $where .= " AND st.section_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_section_id;
        }
        
        if ($filter_program_id && $filter_program_id > 0) {
            $where .= " AND st.program_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_program_id;
        }
        
        // ============== NEW: Add specialization filter ==============
        if ($filter_specialization_id && $filter_specialization_id > 0) {
            $where .= " AND st.specialization_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_specialization_id;
        }
        
        if ($filter_batch_id && $filter_batch_id > 0) {
            $where .= " AND st.batch_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_batch_id;
        }
        
        if ($filter_semester_id && $filter_semester_id > 0) {
            $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() OR r.end IS NULL) ";
        }
        
        // 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;
        }
    }
    
    // ============== FIXED: Query with specialization added ==============
    $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,
            sp.specialization_name_ar as specialization_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 AND c.deleted_at IS NULL
        LEFT JOIN sections sec ON st.section_id = sec.id AND sec.deleted_at IS NULL
        LEFT JOIN programs p ON st.program_id = p.id AND p.deleted_at IS NULL
        LEFT JOIN specializations sp ON st.specialization_id = sp.specialization_id AND sp.deleted_at IS NULL
        LEFT JOIN batches b ON st.batch_id = b.id AND b.deleted_at IS NULL
        {$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 (!empty($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 && $filter_college_id > 0) {
    $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
$programs = [];
$programs_sql = "SELECT DISTINCT p.id, p.name FROM programs p WHERE p.deleted_at IS NULL ORDER BY p.name";
$programs_stmt = $mysqli1->prepare($programs_sql);
$programs_stmt->execute();
$programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$programs_stmt->close();

// ============== NEW: Get specializations based on selected section and program ==============
$specializations = [];
if ($filter_section_id && $filter_section_id > 0 && $filter_program_id && $filter_program_id > 0) {
    $specializations_sql = "
        SELECT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    $specializations_stmt->bind_param("ii", $filter_section_id, $filter_program_id);
    $specializations_stmt->execute();
    $specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
} elseif ($filter_section_id && $filter_section_id > 0) {
    $specializations_sql = "
        SELECT DISTINCT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    $specializations_stmt->bind_param("i", $filter_section_id);
    $specializations_stmt->execute();
    $specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
} elseif ($filter_program_id && $filter_program_id > 0) {
    $specializations_sql = "
        SELECT DISTINCT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    $specializations_stmt->bind_param("i", $filter_program_id);
    $specializations_stmt->execute();
    $specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
}

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

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: #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 !important;
            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);
        }
        /* NEW: Specialization badge */
        .specialization-badge {
            background-color: #f3e8ff;
            color: #7e22ce;
            padding: 0.2rem 0.5rem;
            border-radius: 4px;
            font-size: 0.7rem;
            font-weight: 500;
            border: 1px solid #e9d5ff;
        }
        /* Cursor pointer for all buttons */
        button, .btn, [type="button"], [type="submit"], [type="reset"] {
            cursor: pointer !important;
        }
        .btn:disabled {
            cursor: not-allowed !important;
            opacity: 0.6;
        }
    </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>
                <?= htmlspecialchars($success_message, ENT_QUOTES, 'UTF-8') ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

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

        <!-- 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="<?= (int)$college['id'] ?>" <?= ($filter_college_id == $college['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-building"></i>
                            </span>
                        </div>
                    </div>
                    
                    <!-- 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" onchange="loadSpecializations()" <?= !$filter_college_id ? 'disabled' : '' ?>>
                                <option value="">جميع الأقسام</option>
                                <?php if ($filter_college_id && !empty($sections)): ?>
                                    <?php foreach ($sections as $section): ?>
                                        <option value="<?= (int)$section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($section['name'], ENT_QUOTES, 'UTF-8') ?>
                                        </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-building"></i>
                            </span>
                        </div>
                    </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" onchange="loadSpecializations()">
                                <option value="">جميع البرامج</option>
                                <?php foreach ($programs as $program): ?>
                                    <option value="<?= (int)$program['id'] ?>" <?= ($filter_program_id == $program['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($program['name'], ENT_QUOTES, 'UTF-8') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-book"></i>
                            </span>
                        </div>
                    </div>
                    
                    <!-- ============== NEW: Specialization Filter ============== -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <i class="fas fa-microscope me-1"></i>
                            التخصص
                        </label>
                        <div class="input-group input-group-sm">
                            <select class="form-control border-end-0" name="filter_specialization" id="filter_specialization" <?= (!$filter_section_id && !$filter_program_id) ? 'disabled' : '' ?>>
                                <option value="">جميع التخصصات</option>
                                <?php if (!empty($specializations)): ?>
                                    <?php foreach ($specializations as $spec): ?>
                                        <option value="<?= (int)$spec['specialization_id'] ?>" <?= ($filter_specialization_id == $spec['specialization_id']) ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($spec['specialization_name_ar'], ENT_QUOTES, 'UTF-8') ?>
                                        </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-microscope"></i>
                            </span>
                        </div>
                        <small class="text-muted" id="specHint">
                            <?php if (!$filter_section_id && !$filter_program_id): ?>
                                الرجاء اختيار القسم أو البرنامج أولاً
                            <?php endif; ?>
                        </small>
                    </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="<?= (int)$batch['id'] ?>" <?= ($filter_batch_id == $batch['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($batch['value'], ENT_QUOTES, 'UTF-8') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-calendar-alt"></i>
                            </span>
                        </div>
                    </div>
                    
                    <!-- 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="<?= (int)$semester['id'] ?>" <?= ($filter_semester_id == $semester['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($semester['name'] . ' (' . $semester['code'] . ')', ENT_QUOTES, 'UTF-8') ?>
                                    </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" <?= ($filter_payment_status == 'paid') ? 'selected' : '' ?>>
                                    مدفوعة
                                </option>
                                <option value="unpaid" <?= ($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="<?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?>"
                                   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>
                        بحث: "<?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?>"
                    </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">
                    <form method="post" id="stopRegistrationForm">
                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf_token, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="stop_registrations" value="1">
                        
                        <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"
                                           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"
                                           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" 
                                        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>
                    
                        <!-- Action Buttons -->
                        <div class="row g-3 align-items-end mb-3 mt-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 with Specialization -->
                        <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>
                                    </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'])) : 'مفتوح';
                                        
                                        // Time remaining warning
                                        $is_expiring_soon = ($reg['days_remaining'] !== null && $reg['days_remaining'] <= 3 && $reg['days_remaining'] > 0 && $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="<?= (int)$reg['id'] ?>" 
                                                       class="registration-checkbox"
                                                       data-status="<?= htmlspecialchars($reg['status_class'], ENT_QUOTES, 'UTF-8') ?>"
                                                       data-end="<?= htmlspecialchars($reg['end'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                                       data-days="<?= (int)$reg['days_remaining'] ?>"
                                                       onchange="updateSelectedCount()">
                                            </td>
                                            <td class="text-muted"><?= $counter++ ?></td>
                                            <td><code><?= htmlspecialchars($reg['student_id'], ENT_QUOTES, 'UTF-8') ?></code></td>
                                            <td><?= htmlspecialchars($reg['student_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                            <td><?= htmlspecialchars($reg['college_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8') ?></td>
                                            <td><?= htmlspecialchars($reg['section_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8') ?></td>
                                             
                                            <td>
                                                <i class="fas fa-play-circle text-success me-1"></i>
                                                <?= htmlspecialchars($start_date, ENT_QUOTES, 'UTF-8') ?>
                                            </td>
                                            <td>
                                                <?php if ($reg['end']): ?>
                                                    <span class="badge-end-date">
                                                        <i class="fas fa-stop-circle me-1"></i>
                                                        <?= htmlspecialchars(date('Y-m-d H:i', strtotime($reg['end'])), ENT_QUOTES, 'UTF-8') ?>
                                                    </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 ?>">
                                                    <?= htmlspecialchars($status_text, ENT_QUOTES, 'UTF-8') ?>
                                                </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): ?>
                                                            <?= (int)$reg['days_remaining'] ?> يوم
                                                        <?php else: ?>
                                                            <?= (int)$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(<?= (int)$reg['id'] ?>, '<?= htmlspecialchars($reg['student_name'] . ' (' . $reg['student_id'] . ')', ENT_QUOTES, 'UTF-8') ?>')"
                                                            title="تعيين تاريخ نهاية سريع">
                                                        <i class="fas fa-stop-circle"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- 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 && $r['days_remaining'] > 0; 
                            })) ?>
                        </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)): ?>
                        لم يتم العثور على تسجيلات بناءً على عوامل التصفية المحددة والبحث: "<?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?>"
                    <?php else: ?>
                        لم يتم العثور على تسجيلات بناءً على عوامل التصفية المحددة
                    <?php endif; ?>
                </p>
            </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">
                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf_token, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="stop_registrations" value="1">
                    
                    <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" 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();
            
            // Load specializations if section and program are selected
            const sectionId = "<?= (int)$filter_section_id ?>";
            const programId = "<?= (int)$filter_program_id ?>";
            if (sectionId && programId) {
                setTimeout(() => {
                    loadSpecializations();
                }, 100);
            }
        });
        
        // 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();
        }
        
        function selectExpiringSoon() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                const days = parseInt(checkbox.dataset.days) || 0;
                checkbox.checked = checkbox.dataset.status === 'active' && days <= 3 && days > 0;
            });
            updateSelectedCount();
        }
        
        function selectNoEndDate() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = checkbox.dataset.status === 'open';
            });
            updateSelectedCount();
        }
        
        // 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 false;
            }
            
            if (!endDate) {
                e.preventDefault();
                alert('يرجى تحديد تاريخ النهاية');
                return false;
            }
            
            let confirmationMessage = `⚠️ هل أنت متأكد من تحديث تاريخ النهاية لـ ${selectedCount} تسجيل/تسجيلات؟\n\n`;
            confirmationMessage += `📅 تاريخ النهاية الجديد: ${endDate}\n\n`;
            confirmationMessage += `❌ الطالب/الطلاب لن يتمكنوا من التسجيل بعد هذا التاريخ.`;
            
            if (!confirm(confirmationMessage)) {
                e.preventDefault();
                return false;
            }
            
            // Disable submit button to prevent double submission
            const submitBtn = e.target.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> جاري التحديث...';
            }
        });
        
        // Load sections when college changes
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            const specSelect = document.getElementById('filter_specialization');
            const specHint = document.getElementById('specHint');
            
            sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
            
            // Reset specialization select
            if (specSelect) {
                specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                specSelect.disabled = true;
            }
            if (specHint) specHint.innerHTML = 'الرجاء اختيار القسم أو البرنامج أولاً';
            
            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 = "<?= (int)$filter_semester_id ?>";
            if (currentSemester) {
                const semesterInput = document.createElement('input');
                semesterInput.type = 'hidden';
                semesterInput.name = 'filter_semester';
                semesterInput.value = currentSemester;
                form.appendChild(semesterInput);
            }
            
            const currentSection = "<?= (int)$filter_section_id ?>";
            if (currentSection) {
                const sectionInput = document.createElement('input');
                sectionInput.type = 'hidden';
                sectionInput.name = 'filter_section';
                sectionInput.value = currentSection;
                form.appendChild(sectionInput);
            }
            
            const currentProgram = "<?= (int)$filter_program_id ?>";
            if (currentProgram) {
                const programInput = document.createElement('input');
                programInput.type = 'hidden';
                programInput.name = 'filter_program';
                programInput.value = currentProgram;
                form.appendChild(programInput);
            }
            
            const currentSpecialization = "<?= (int)$filter_specialization_id ?>";
            if (currentSpecialization) {
                const specInput = document.createElement('input');
                specInput.type = 'hidden';
                specInput.name = 'filter_specialization';
                specInput.value = currentSpecialization;
                form.appendChild(specInput);
            }
            
            const currentBatch = "<?= (int)$filter_batch_id ?>";
            if (currentBatch) {
                const batchInput = document.createElement('input');
                batchInput.type = 'hidden';
                batchInput.name = 'filter_batch';
                batchInput.value = currentBatch;
                form.appendChild(batchInput);
            }
            
            const currentPaymentStatus = "<?= htmlspecialchars($filter_payment_status ?? '', ENT_QUOTES, 'UTF-8') ?>";
            if (currentPaymentStatus) {
                const paymentInput = document.createElement('input');
                paymentInput.type = 'hidden';
                paymentInput.name = 'filter_payment_status';
                paymentInput.value = currentPaymentStatus;
                form.appendChild(paymentInput);
            }
            
            const activeOnly = <?= $filter_active_only ? '1' : '0' ?>;
            if (activeOnly) {
                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();
        }
        
        // ============== NEW: Load specializations ==============
        function loadSpecializations() {
            const sectionId = document.getElementById('filter_section').value;
            const programId = document.getElementById('filter_program').value;
            const specSelect = document.getElementById('filter_specialization');
            const specHint = document.getElementById('specHint');
            
            if (!sectionId && !programId) {
                specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                specSelect.disabled = true;
                if (specHint) specHint.innerHTML = 'الرجاء اختيار القسم أو البرنامج أولاً';
                return;
            }
            
            // Show loading
            specSelect.innerHTML = '<option value="">جاري التحميل...</option>';
            specSelect.disabled = false;
            if (specHint) specHint.innerHTML = 'جاري تحميل التخصصات...';
            
            // Build URL with available parameters
            let url = '../ajax/get_specializations.php?';
            if (sectionId) url += `section_id=${encodeURIComponent(sectionId)}&`;
            if (programId) url += `program_id=${encodeURIComponent(programId)}&`;
            
            // Fetch specializations
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    
                    if (data && data.length > 0) {
                        data.forEach(spec => {
                            const option = document.createElement('option');
                            option.value = spec.specialization_id;
                            option.textContent = spec.specialization_name_ar;
                            
                            // Check if this specialization was previously selected
                            const currentSpec = "<?= (int)$filter_specialization_id ?>";
                            if (currentSpec && currentSpec == spec.specialization_id) {
                                option.selected = true;
                            }
                            
                            specSelect.appendChild(option);
                        });
                        if (specHint) specHint.innerHTML = `${data.length} تخصص متاح`;
                    } else {
                        if (specHint) specHint.innerHTML = 'لا توجد تخصصات متاحة';
                    }
                })
                .catch(error => {
                    console.error('Error loading specializations:', error);
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    if (specHint) specHint.innerHTML = 'حدث خطأ في تحميل التخصصات';
                });
        }
        
        // 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 false;
            }
            
            if (!confirm('⚠️ هل أنت متأكد من تحديث تاريخ نهاية هذا التسجيل؟')) {
                e.preventDefault();
                return false;
            }
            
            // Disable submit button to prevent double submission
            const submitBtn = e.target.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> جاري التحديث...';
            }
        });
        
        // Add event listeners to checkboxes
        document.querySelectorAll('.registration-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', updateSelectedCount);
        });
    </script>
    
    <!-- Bootstrap JS for modal -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
