<?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 - only use them if filters were applied
if ($filters_applied) {
    $filter_college_id = $_GET['filter_college'] ?? null;
    $filter_section_id = $_GET['filter_section'] ?? null;
    $filter_program_id = $_GET['filter_program'] ?? null;
    $filter_batch_id = $_GET['filter_batch'] ?? null;
    $filter_semester_id = $_GET['filter_semester'] ?? null;
    $filter_payment_status = $_GET['filter_payment_status'] ?? null;
    $search_query = trim($_GET['search_query'] ?? '');
} else {
    // Don't apply filters by default
    $filter_college_id = null;
    $filter_section_id = null;
    $filter_program_id = null;
    $filter_batch_id = null;
    $filter_semester_id = null;
    $filter_payment_status = null;
    $search_query = '';
}

// Initialize registrations array
$registrations = [];

// Handle form submission for deregistration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cancel_registrations'])) {
    $registration_ids = $_POST['registration_ids'] ?? [];
    
    if (empty($registration_ids)) {
        $error_message = 'لم يتم اختيار أي تسجيلات للإلغاء';
    } else {
        try {
            // Begin transaction
            $mysqli1->begin_transaction();
            
            $cancelled_count = 0;
            
            foreach ($registration_ids as $reg_id) {
                // Check if registration exists and not already cancelled
                $check_stmt = $mysqli1->prepare("
                    SELECT id FROM registrations 
                    WHERE id = ? AND deleted_at IS NULL
                ");
                $check_stmt->bind_param("i", $reg_id);
                $check_stmt->execute();
                $exists = $check_stmt->get_result()->fetch_assoc();
                $check_stmt->close();
                
                if (!$exists) {
                    continue; // Skip if registration not found or already cancelled
                }
                
                // Soft delete the registration (set deleted_at timestamp)
                $cancel_stmt = $mysqli1->prepare("
                    UPDATE registrations 
                    SET deleted_at = NOW(), updated_at = NOW() , start='2000-01-01 00:00:00', end ='2000-01-02 00:00:00'
                    WHERE id = ? AND deleted_at IS NULL
                ");
                $cancel_stmt->bind_param("i", $reg_id);
                
                if ($cancel_stmt->execute()) {
                    $cancelled_count++;
                }
                $cancel_stmt->close();
            }
            
            // Commit transaction
            $mysqli1->commit();
            
            $success_message = "تم إلغاء {$cancelled_count} تسجيل بنجاح";
            
        } 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);
        }
    }
}

// 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 && !empty($filter_college_id)) {
            $where .= " AND st.college_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_college_id;
        }
        
        if ($filter_section_id && !empty($filter_section_id)) {
            $where .= " AND st.section_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_section_id;
        }
        
        if ($filter_program_id && !empty($filter_program_id)) {
            $where .= " AND st.program_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_program_id;
        }
        
        if ($filter_batch_id && !empty($filter_batch_id)) {
            $where .= " AND st.batch_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_batch_id;
        }
        
        if ($filter_semester_id && !empty($filter_semester_id)) {
            $where .= " AND r.semester_id = ? ";
            $types .= 'i'; 
            $params[] = $filter_semester_id;
        }
        
        if ($filter_payment_status && !empty($filter_payment_status)) {
            if ($filter_payment_status === 'paid') {
                $where .= " AND r.is_paid = 1 ";
            } elseif ($filter_payment_status === 'unpaid') {
                $where .= " AND r.is_paid = 0 ";
            }
        }
        
        // 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
    $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,
            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
        LEFT JOIN sections sec ON st.section_id = sec.id
        LEFT JOIN programs p ON st.program_id = p.id
        LEFT JOIN batches b ON st.batch_id = b.id
        {$where}
        ORDER BY r.created_at DESC
        LIMIT 500
    ";
    
    $reg_stmt = $mysqli1->prepare($sqlRegistrations);
    if ($types) {
        $reg_stmt->bind_param($types, ...$params);
    }
    $reg_stmt->execute();
    $registrations = $reg_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $reg_stmt->close();
} else {
    // No registrations to show initially
    $registrations = [];
}

// Get semesters for filter dropdown
$semesters_stmt = $mysqli1->prepare("SELECT id, name, code FROM semesters WHERE deleted_at IS NULL ORDER BY id DESC");
$semesters_stmt->execute();
$semesters = $semesters_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$semesters_stmt->close();

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

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

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

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

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إلغاء تسجيلات الطلاب - لوحة اللجنة</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body, h1,h2,h3,h4,h5,h6, p, a, button, label { 
            font-family: 'Cairo', system-ui, -apple-system, sans-serif !important; 
        }
        .card-arabic {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        .filter-icon {
            width: 40px;
            height: 40px;
            background: #ef4444;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.1rem;
        }
        .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;
            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;
        }
        .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;
        }
        .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;
        }
    </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>
                <?= $success_message ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

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

        <!-- Warning Alert -->
        <div class="alert alert-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 1: All filters in one row -->
                <div class="filter-row">
                    <!-- College Filter -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <i class="fas fa-university me-1"></i>
                            الكلية
                        </label>
                        <div class="input-group input-group-sm">
                            <select class="form-control border-end-0" name="filter_college" id="filter_college" onchange="loadSections(this.value)">
                                <option value="">جميع الكليات</option>
                                <?php foreach ($colleges as $college): ?>
                                    <?php 
                                    // Don't show college filter if user has scope restriction
                                    if (!$canAll && $scopeCollege !== null && $college['id'] != $scopeCollege) {
                                        continue;
                                    }
                                    ?>
                                    <option value="<?= $college['id'] ?>" <?= (isset($_GET['filter_college']) && $_GET['filter_college'] == $college['id']) ? 'selected' : '' ?>>
                                        <?= e($college['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-building"></i>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Section Filter -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <i class="fas fa-layer-group me-1"></i>
                            القسم
                        </label>
                        <div class="input-group input-group-sm">
                            <select class="form-control border-end-0" name="filter_section" id="filter_section" <?= !$filter_college_id ? 'disabled' : '' ?>>
                                <option value="">جميع الأقسام</option>
                                <?php if ($filter_college_id && !empty($sections)): ?>
                                    <?php foreach ($sections as $section): ?>
                                        <option value="<?= $section['id'] ?>" <?= (isset($_GET['filter_section']) && $_GET['filter_section'] == $section['id']) ? 'selected' : '' ?>>
                                            <?= e($section['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-building"></i>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Program Filter -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <i class="fas fa-graduation-cap me-1"></i>
                            البرنامج
                        </label>
                        <div class="input-group input-group-sm">
                            <select class="form-control border-end-0" name="filter_program" id="filter_program">
                                <option value="">جميع البرامج</option>
                                <?php foreach ($programs as $program): ?>
                                    <option value="<?= $program['id'] ?>" <?= (isset($_GET['filter_program']) && $_GET['filter_program'] == $program['id']) ? 'selected' : '' ?>>
                                        <?= e($program['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-book"></i>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Batch Filter -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <i class="fas fa-users me-1"></i>
                            الدفعة
                        </label>
                        <div class="input-group input-group-sm">
                            <select class="form-control border-end-0" name="filter_batch">
                                <option value="">جميع الدفعات</option>
                                <?php foreach ($batches as $batch): ?>
                                    <option value="<?= $batch['id'] ?>" <?= (isset($_GET['filter_batch']) && $_GET['filter_batch'] == $batch['id']) ? 'selected' : '' ?>>
                                        <?= e($batch['value']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-calendar-alt"></i>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Semester Filter -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <i class="fas fa-calendar-alt me-1"></i>
                            الفصل الدراسي
                        </label>
                        <div class="input-group input-group-sm">
                            <select class="form-control border-end-0" name="filter_semester" id="filter_semester">
                                <option value="">جميع الفصول</option>
                                <?php foreach ($semesters as $semester): ?>
                                    <option value="<?= $semester['id'] ?>" <?= (isset($_GET['filter_semester']) && $_GET['filter_semester'] == $semester['id']) ? 'selected' : '' ?>>
                                        <?= e($semester['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-calendar"></i>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Payment Status Filter -->
                    <div class="filter-group">
                        <label class="form-label fw-semibold text-muted mb-2 small">
                            <i class="fas fa-money-bill-wave me-1"></i>
                            حالة الدفع
                        </label>
                        <div class="input-group input-group-sm">
                            <select class="form-control border-end-0" name="filter_payment_status">
                                <option value="">جميع الحالات</option>
                                <option value="paid" <?= (isset($_GET['filter_payment_status']) && $_GET['filter_payment_status'] == 'paid') ? 'selected' : '' ?>>
                                    مدفوعة
                                </option>
                                <option value="unpaid" <?= (isset($_GET['filter_payment_status']) && $_GET['filter_payment_status'] == 'unpaid') ? 'selected' : '' ?>>
                                    غير مدفوعة
                                </option>
                            </select>
                            <span class="input-group-text bg-light border-start-0">
                                <i class="fas fa-credit-card"></i>
                            </span>
                        </div>
                    </div>
                </div>
                
                <!-- Search Row -->
                <div class="search-row">
                    <div class="search-input-group">
                        <div class="input-group input-group-sm">
                            <input type="text" 
                                   class="form-control" 
                                   name="search_query" 
                                   id="search_query"
                                   placeholder="بحث برقم الطالب أو اسم الطالب..."
                                   value="<?= e($search_query) ?>"
                                   autocomplete="off">
                            <span class="input-group-text bg-light">
                                <i class="fas fa-search"></i>
                            </span>
                        </div>
                        <button type="button" class="search-clear-btn" onclick="clearSearch()" title="مسح البحث">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
                
                <!-- Action Buttons -->
                <div class="d-flex gap-2 pt-2">
                    <button type="submit" class="btn btn-primary btn-sm px-3">
                        <i class="fas fa-filter me-1"></i>
                        تطبيق التصفية والبحث
                    </button>
                    <a href="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>
                        بحث: "<?= e($search_query) ?>"
                    </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">
                <!-- 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" name="cancel_registrations" class="btn btn-danger">
                                <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>
                
                <!-- SIMPLIFIED Registrations Table -->
                <div class="table-responsive mt-4">
                    <table class="table table-striped registration-table compact-table">
                        <thead>
                            <tr>
                                <th class="checkbox-cell">
                                    <input type="checkbox" id="selectAll" onchange="toggleAllRegistrations(this)">
                                </th>
                                <th>#</th>
                                <th>رقم الطالب</th>
                                <th>اسم الطالب</th>
                                <th>الكلية</th>
                                <th>البرنامج</th>
                                <th>الفصل الدراسي</th>
                                <th>حالة الدفع</th>
                                <th>تاريخ التسجيل</th>
                                <th>الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $counter = 1; ?>
                            <?php foreach ($registrations as $reg): ?>
                                <?php
                                // Payment status - SIMPLE VERSION
                                $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="<?= e($reg['id']) ?>" class="registration-checkbox">
                                    </td>
                                    <td class="text-muted"><?= $counter++ ?></td>
                                    <td><code><?= e($reg['student_id']) ?></code></td>
                                    <td><?= e($reg['student_name']) ?></td>
                                    <td><?= e($reg['college_name'] ?? 'غير محدد') ?></td>
                                    <td><?= e($reg['program_name'] ?? 'غير محدد') ?></td>
                                    <td>
                                        <span class="badge bg-primary" style="font-size: 0.7rem;">
                                            <?= e($reg['semester_name']) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <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)): ?>
                        لم يتم العثور على تسجيلات بناءً على عوامل التصفية المحددة والبحث: "<?= e($search_query) ?>"
                    <?php else: ?>
                        لم يتم العثور على تسجيلات بناءً على عوامل التصفية المحددة
                    <?php endif; ?>
                </p>
                <?php if (!empty($search_query)): ?>
                    <div class="mt-3">
                        <a href="deregistration.php?filter_applied=1&filter_semester=<?= e($filter_semester_id) ?>&filter_college=<?= e($filter_college_id) ?>&filter_section=<?= e($filter_section_id) ?>&filter_program=<?= e($filter_program_id) ?>&filter_batch=<?= e($filter_batch_id) ?>&filter_payment_status=<?= e($filter_payment_status) ?>" 
                           class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-times me-1"></i>إلغاء البحث وعرض جميع التسجيلات
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function 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;
            }
            
            let confirmationMessage = `⚠️ تحذير: هل أنت متأكد من إلغاء ${selectedCount} تسجيل؟\n\n`;
            confirmationMessage += `\n❌ عملية الإلغاء نهائية ولا يمكن التراجع عنها.`;
            
            if (!confirm(confirmationMessage)) {
                e.preventDefault();
            }
        });
        
        // Load sections when college changes
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            
            // Reset section select
            sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
            
            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 = "<?= isset($_GET['filter_semester']) ? $_GET['filter_semester'] : '' ?>";
            if (currentSemester) {
                const semesterInput = document.createElement('input');
                semesterInput.type = 'hidden';
                semesterInput.name = 'filter_semester';
                semesterInput.value = currentSemester;
                form.appendChild(semesterInput);
            }
            
            // Add current section if exists
            const currentSection = "<?= isset($_GET['filter_section']) ? $_GET['filter_section'] : '' ?>";
            if (currentSection) {
                const sectionInput = document.createElement('input');
                sectionInput.type = 'hidden';
                sectionInput.name = 'filter_section';
                sectionInput.value = currentSection;
                form.appendChild(sectionInput);
            }
            
            // Add current program if exists
            const currentProgram = "<?= isset($_GET['filter_program']) ? $_GET['filter_program'] : '' ?>";
            if (currentProgram) {
                const programInput = document.createElement('input');
                programInput.type = 'hidden';
                programInput.name = 'filter_program';
                programInput.value = currentProgram;
                form.appendChild(programInput);
            }
            
            // Add current batch if exists
            const currentBatch = "<?= isset($_GET['filter_batch']) ? $_GET['filter_batch'] : '' ?>";
            if (currentBatch) {
                const batchInput = document.createElement('input');
                batchInput.type = 'hidden';
                batchInput.name = 'filter_batch';
                batchInput.value = currentBatch;
                form.appendChild(batchInput);
            }
            
            // Add current payment status if exists
            const currentPaymentStatus = "<?= isset($_GET['filter_payment_status']) ? $_GET['filter_payment_status'] : '' ?>";
            if (currentPaymentStatus) {
                const paymentInput = document.createElement('input');
                paymentInput.type = 'hidden';
                paymentInput.name = 'filter_payment_status';
                paymentInput.value = currentPaymentStatus;
                form.appendChild(paymentInput);
            }
            
            // 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();
        }
        
        // Clear search field
        function clearSearch() {
            document.getElementById('search_query').value = '';
            // Submit the form to reload without search
            document.getElementById('filterForm').submit();
        }
        
        // Auto-submit search on Enter key
        document.getElementById('search_query')?.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                document.getElementById('filterForm').submit();
            }
        });
        
        // Show clear button when search field has value
        document.getElementById('search_query')?.addEventListener('input', function() {
            const clearBtn = document.querySelector('.search-clear-btn');
            if (this.value.trim() !== '') {
                clearBtn.style.display = 'block';
            } else {
                clearBtn.style.display = 'none';
            }
        });
        
        // Initialize clear button visibility
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('search_query');
            const clearBtn = document.querySelector('.search-clear-btn');
            if (searchInput && searchInput.value.trim() !== '') {
                clearBtn.style.display = 'block';
            }
        });
    </script>
</body>
</html>