<?php
// deregistration.php - PAGE TO CANCEL STUDENT REGISTRATIONS FOR A SPECIFIC SEMESTER
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 - 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;
    $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;
    $search_query = trim($_GET['search_query'] ?? '');
    // Sanitize search query to prevent XSS
    $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;
    $filter_batch_id = null;
    $filter_semester_id = null;
    $filter_payment_status = null;
    $search_query = '';
}

// Initialize registrations array
$registrations = [];

// ============== FIXED: Handle form submission for deregistration ==============
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cancel_registrations'])) {
    
    // Validate CSRF token
    if (!isset($_POST['csrf']) || !verify_csrf($_POST['csrf'])) {
        $error_message = 'رمز الأمان غير صالح. الرجاء تحديث الصفحة والمحاولة مرة أخرى.';
    } else {
        $registration_ids = $_POST['registration_ids'] ?? [];
        
        // Validate registration IDs - ensure they're integers
        $valid_ids = [];
        foreach ($registration_ids as $id) {
            if (ctype_digit($id)) {
                $valid_ids[] = (int)$id;
            }
        }
        
        if (empty($valid_ids)) {
            $error_message = 'لم يتم اختيار أي تسجيلات صالحة للإلغاء';
        } else {
            try {
                // Begin transaction
                $mysqli1->begin_transaction();
                
                // Create placeholders for IN clause
                $placeholders = implode(',', array_fill(0, count($valid_ids), '?'));
                $types = str_repeat('i', count($valid_ids));
                
                // التحقق من وجود التسجيلات أولاً
                $check_sql = "SELECT id, student_id, semester_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_ids = $check_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
                $check_stmt->close();
                
                if (empty($existing_ids)) {
                    throw new Exception('لا توجد تسجيلات صالحة للإلغاء');
                }
                
                // Extract existing IDs
                $existing_id_values = array_column($existing_ids, 'id');
                
                // FIXED: Soft delete the registrations - إزالة تحديث start و end
                $placeholders2 = implode(',', array_fill(0, count($existing_id_values), '?'));
                $types2 = str_repeat('i', count($existing_id_values));
                
                $cancel_sql = "
                    UPDATE registrations 
                    SET deleted_at = NOW(), 
                        updated_at = NOW()
                    WHERE id IN ($placeholders2) AND deleted_at IS NULL
                ";
                
                $cancel_stmt = $mysqli1->prepare($cancel_sql);
                $cancel_stmt->bind_param($types2, ...$existing_id_values);
                $cancel_stmt->execute();
                
                $cancelled_count = $cancel_stmt->affected_rows;
                $cancel_stmt->close();
                
                // Commit transaction
                $mysqli1->commit();
                
                $success_message = "تم إلغاء {$cancelled_count} تسجيل بنجاح";
                
                // Log the action
                error_log("User {$committeeId} cancelled {$cancelled_count} registrations. IDs: " . implode(',', $existing_id_values));
                
            } catch (Exception $e) {
                // Rollback transaction on error
                $mysqli1->rollback();
                $error_message = "حدث خطأ أثناء إلغاء التسجيلات: " . $e->getMessage();
                
                // Log detailed error for debugging
                error_log("Deregistration Error: " . $e->getMessage());
                error_log("SQL Error: " . $mysqli1->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 ";
    $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 && $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;
        }
        
        // Apply 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 ";
            }
        }
        
        // 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;
        }
    }
    
    // SIMPLIFIED QUERY with specialization added
    $sqlRegistrations = "
        SELECT 
            r.id, 
            r.student_id, 
            r.student_name,
            r.semester_id,
            r.is_paid,
            r.created_at,
            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
        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 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();

// 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;
        }
        .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 #f59e0b;
        }
        .filter-status {
            font-size: 0.85rem;
            padding: 0.3rem 0.6rem;
            border-radius: 6px;
        }
        .filter-status.applied {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #a7f3d0;
        }
        .filter-status.not-applied {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
        }
        .info-message {
            background-color: #f0f9ff;
            border: 1px solid #bae6fd;
            color: #0369a1;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .danger-zone {
            background-color: #fef2f2;
            border: 2px solid #fecaca;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .payment-status {
            font-size: 0.75rem;
            padding: 0.2rem 0.5rem;
            border-radius: 4px;
            font-weight: 600;
        }
        .paid-status {
            background-color: #10b981;
            color: white;
        }
        .unpaid-status {
            background-color: #ef4444;
            color: white;
        }
        .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;
        }
        .action-buttons .btn {
            padding: 0.2rem 0.5rem;
            font-size: 0.75rem;
            cursor: pointer !important;
        }
        .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;
        }
        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            border-radius: 0.25rem;
            cursor: pointer !important;
        }
        .form-control-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            border-radius: 0.25rem;
        }
        .input-group-sm > .form-control {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            border-radius: 0.25rem;
        }
        .input-group-sm > .input-group-text {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            border-radius: 0.25rem;
        }
        /* 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">
            <h3 class="mb-0 fw-bold text-danger">
                <i class="fas fa-user-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-warning alert-dismissible fade show warning-alert" role="alert">
            <div class="d-flex align-items-center">
                <i class="fas fa-exclamation-triangle fa-lg me-3"></i>
                <div>
                    <strong 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 -->
                <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>
                    
                    <!-- 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>
                
                <!-- 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="deregistration.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>

        <!-- Deregistration 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-user-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>
            
            <!-- Danger Zone Warning -->
            <div class="danger-zone mb-4">
                <div class="d-flex align-items-center mb-2">
                    <i class="fas fa-skull-crossbones fa-lg text-danger me-2"></i>
                    <h6 class="mb-0 text-danger fw-bold">منطقة الخطر</h6>
                </div>
                <p class="text-muted mb-3">
                    <i class="fas fa-info-circle me-1"></i>
                    عملية الإلغاء نهائية ولا يمكن التراجع عنها. سيتم تعيين تاريخ الحذف للتسجيلات المحددة.
                </p>
            </div>
            
            <form method="post" id="deregistrationForm">
                <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf_token, ENT_QUOTES, 'UTF-8') ?>">
                <input type="hidden" name="cancel_registrations" value="1">
                
                <!-- Action Buttons -->
                <div class="row g-3 align-items-end mb-3">
                    <div class="col-md-6">
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-outline-primary" onclick="selectAllRegistrations()">
                                <i class="fas fa-check-square me-1"></i>تحديد الكل
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="deselectAllRegistrations()">
                                <i class="fas fa-times-circle me-1"></i>إلغاء الكل
                            </button>
                            <button type="submit" class="btn btn-danger" id="cancelBtn">
                                <i class="fas fa-user-times me-1"></i>إلغاء التسجيلات المحددة
                            </button>
                        </div>
                    </div>
                    <div class="col-md-6 text-start">
                        <div class="text-muted small">
                            <i class="fas fa-info-circle me-1"></i>
                            سيتم تعيين تاريخ الحذف للتسجيلات المحددة.
                        </div>
                    </div>
                </div>
                
                <!-- 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>
                                <th>حالة الدفع</th>
                                <th>تاريخ التسجيل</th>
                                <th>الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $counter = 1; ?>
                            <?php foreach ($registrations as $reg): ?>
                                <?php
                                // Payment status
                                $payment_status = ($reg['is_paid'] == 1) ? 'مدفوعة' : 'غير مدفوعة';
                                $payment_class = ($reg['is_paid'] == 1) ? 'paid-status' : 'unpaid-status';
                                ?>
                                <tr>
                                    <td class="checkbox-cell">
                                        <input type="checkbox" name="registration_ids[]" value="<?= (int)$reg['id'] ?>" class="registration-checkbox">
                                    </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><?= htmlspecialchars($reg['program_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8') ?></td>
                                    <td>
                                        <?php if (!empty($reg['specialization_name'])): ?>
                                            <span class="specialization-badge">
                                                <i class="fas fa-microscope me-1"></i>
                                                <?= htmlspecialchars($reg['specialization_name'], ENT_QUOTES, 'UTF-8') ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="text-muted">—</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge bg-primary" style="font-size: 0.7rem;">
                                            <?= htmlspecialchars($reg['semester_name'], ENT_QUOTES, 'UTF-8') ?>
                                        </span>
                                    </td>
                                    <td><?= htmlspecialchars($reg['batch_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8') ?></td>
                                    <td>
                                        <span class="payment-status <?= $payment_class ?>">
                                            <?= $payment_status ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?= date('Y-m-d', strtotime($reg['created_at'])) ?>
                                    </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>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </form>
        </div>
        <?php elseif ($filters_applied && empty($registrations)): ?>
            <div class="card card-arabic p-5 text-center">
                <i class="fas fa-clipboard-check fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">لا يوجد تسجيلات</h5>
                <p class="text-muted mb-0">
                    <?php if (!empty($search_query)): ?>
                        لم يتم العثور على تسجيلات بناءً على عوامل التصفية المحددة والبحث: "<?= htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8') ?>"
                    <?php else: ?>
                        لم يتم العثور على تسجيلات بناءً على عوامل التصفية المحددة
                    <?php endif; ?>
                </p>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function toggleAllRegistrations(selectAll) {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
        }
        
        function selectAllRegistrations() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
            });
            document.getElementById('selectAll').checked = true;
        }
        
        function deselectAllRegistrations() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
            document.getElementById('selectAll').checked = false;
        }
        
        // Update select all checkbox when individual checkboxes change
        document.querySelectorAll('.registration-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const allChecked = document.querySelectorAll('.registration-checkbox:checked').length === document.querySelectorAll('.registration-checkbox').length;
                document.getElementById('selectAll').checked = allChecked;
            });
        });
        
        // Form submission confirmation
        document.getElementById('deregistrationForm')?.addEventListener('submit', function(e) {
            const selectedCount = document.querySelectorAll('.registration-checkbox:checked').length;
            
            if (selectedCount === 0) {
                e.preventDefault();
                alert('يرجى اختيار تسجيل واحد على الأقل للإلغاء');
                return false;
            }
            
            let confirmationMessage = `⚠️ تحذير: هل أنت متأكد من إلغاء ${selectedCount} تسجيل؟\n\n`;
            confirmationMessage += `❌ عملية الإلغاء نهائية ولا يمكن التراجع عنها.`;
            
            if (!confirm(confirmationMessage)) {
                e.preventDefault();
                return false;
            } else {
                // Disable submit button to prevent double submission
                const submitBtn = document.getElementById('cancelBtn');
                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');
            
            // Reset section select
            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;
            }
            
            // Instead of AJAX, we'll use a simple form submission to reload the page
            const form = document.createElement('form');
            form.method = 'get';
            form.style.display = 'none';
            
            // Add college parameter
            const collegeInput = document.createElement('input');
            collegeInput.type = 'hidden';
            collegeInput.name = 'filter_college';
            collegeInput.value = collegeId;
            form.appendChild(collegeInput);
            
            // Add filter_applied parameter
            const appliedInput = document.createElement('input');
            appliedInput.type = 'hidden';
            appliedInput.name = 'filter_applied';
            appliedInput.value = '1';
            form.appendChild(appliedInput);
            
            // Add current semester if exists
            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);
            }
            
            // Add current section if exists
            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);
            }
            
            // Add current program if exists
            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);
            }
            
            // Add current specialization if exists
            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);
            }
            
            // Add current batch if exists
            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);
            }
            
            // Add current payment status if exists
            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);
            }
            
            // Add search query if exists
            const searchQuery = document.getElementById('search_query').value;
            if (searchQuery) {
                const searchInput = document.createElement('input');
                searchInput.type = 'hidden';
                searchInput.name = 'search_query';
                searchInput.value = searchQuery;
                form.appendChild(searchInput);
            }
            
            document.body.appendChild(form);
            form.submit();
        }
        
        // Load specializations based on section and program
        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 = '';
            // Submit the form to reload without search
            document.getElementById('filterForm').submit();
        }
        
        // Auto-submit search on Enter key
        document.getElementById('search_query')?.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                document.getElementById('filterForm').submit();
            }
        });
        
        // Show clear button when search field has value
        document.getElementById('search_query')?.addEventListener('input', function() {
            const clearBtn = document.querySelector('.search-clear-btn');
            if (this.value.trim() !== '') {
                clearBtn.style.display = 'block';
            } else {
                clearBtn.style.display = 'none';
            }
        });
        
        // Initialize clear button visibility
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('search_query');
            const clearBtn = document.querySelector('.search-clear-btn');
            if (searchInput && searchInput.value.trim() !== '') {
                clearBtn.style.display = 'block';
            }
            
            // 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);
            }
        });
    </script>
</body>
</html>
