<?php
// extend_registration.php - تمديد فترات التسجيل (نسخة معدلة)
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 = '';
$registrations = [];
$extension_logs = [];

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

// Get filter parameters
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_expiration_status = $_GET['filter_expiration_status'] ?? null;
    $search_query = trim($_GET['search_query'] ?? '');
} else {
    $filter_college_id = null;
    $filter_section_id = null;
    $filter_program_id = null;
    $filter_batch_id = null;
    $filter_semester_id = null;
    $filter_expiration_status = null;
    $search_query = '';
}

// Handle AJAX request for sections
if (isset($_GET['ajax']) && $_GET['ajax'] === 'get_sections' && isset($_GET['college_id'])) {
    $college_id = (int)$_GET['college_id'];
    $sections = [];
    
    if ($college_id > 0) {
        $sections_sql = "
            SELECT DISTINCT s.id, s.name
            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", $college_id);
        $sections_stmt->execute();
        $sections = $sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $sections_stmt->close();
    }
    
    echo json_encode($sections);
    exit;
}

// Handle form submission for extension
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['extend_registrations'])) {
    $new_end_date = $_POST['new_end_date'] ?? '';
    $registration_ids = $_POST['registration_ids'] ?? [];
    
    if (empty($new_end_date)) {
        $error_message = 'يرجى تحديد تاريخ نهاية جديد';
    } elseif (empty($registration_ids)) {
        $error_message = 'لم يتم اختيار أي تسجيلات للتمديد';
    } else {
        $new_end_timestamp = date('Y-m-d H:i:s', strtotime($new_end_date));
        
        try {
            $mysqli1->begin_transaction();
            
            $extended_count = 0;
            $skipped_count = 0;
            
            foreach ($registration_ids as $registration_id) {
                // Get current registration details
                $check_stmt = $mysqli1->prepare("
                    SELECT id, student_id, student_name, end, semester_id, start, is_paid
                    FROM registrations 
                    WHERE id = ? AND deleted_at IS NULL
                ");
                $check_stmt->bind_param("i", $registration_id);
                $check_stmt->execute();
                $registration = $check_stmt->get_result()->fetch_assoc();
                $check_stmt->close();
                
                if (!$registration) {
                    $skipped_count++;
                    continue;
                }
                
                // Check if registration is already paid
                if ($registration['is_paid'] == 1) {
                    $skipped_count++;
                    $extension_logs[] = [
                        'student_id' => $registration['student_id'],
                        'student_name' => $registration['student_name'],
                        'status' => 'skipped',
                        'reason' => 'التسجيل مدفوع بالفعل'
                    ];
                    continue;
                }
                
                // Check if new end date is after current end date
                $current_end = strtotime($registration['end']);
                $new_end = strtotime($new_end_timestamp);
                
                if ($new_end <= $current_end) {
                    $skipped_count++;
                    $extension_logs[] = [
                        'student_id' => $registration['student_id'],
                        'student_name' => $registration['student_name'],
                        'status' => 'skipped',
                        'reason' => 'التاريخ الجديد ليس بعد التاريخ الحالي',
                        'old_end' => date('Y-m-d', $current_end),
                        'new_end' => date('Y-m-d', $new_end)
                    ];
                    continue;
                }
                
                // Update registration end date
                $update_stmt = $mysqli1->prepare("
                    UPDATE registrations 
                    SET end = ?, updated_at = NOW() 
                    WHERE id = ?
                ");
                $update_stmt->bind_param("si", $new_end_timestamp, $registration_id);
                
                if ($update_stmt->execute()) {
                    $extended_count++;
                    
                    $extension_logs[] = [
                        'student_id' => $registration['student_id'],
                        'student_name' => $registration['student_name'],
                        'status' => 'extended',
                        'old_end' => date('Y-m-d', strtotime($registration['end'])),
                        'new_end' => date('Y-m-d', strtotime($new_end_timestamp))
                    ];
                } else {
                    $extension_logs[] = [
                        'student_id' => $registration['student_id'],
                        'student_name' => $registration['student_name'],
                        'status' => 'failed',
                        'reason' => 'فشل في تحديث قاعدة البيانات'
                    ];
                }
                
                $update_stmt->close();
            }
            
            $mysqli1->commit();
            
            if ($extended_count > 0) {
                $success_message = "تم تمديد {$extended_count} تسجيل بنجاح";
                if ($skipped_count > 0) {
                    $success_message .= " (تم تخطي {$skipped_count} تسجيل)";
                }
            } else {
                $error_message = "لم يتم تمديد أي تسجيل.";
            }
            
            $_SESSION['extension_logs'] = $extension_logs;
            
            // Redirect to show results with current filters
            $redirect_url = "extend_registration.php?filter_applied=1";
            if ($filter_college_id) $redirect_url .= "&filter_college=" . $filter_college_id;
            if ($filter_section_id) $redirect_url .= "&filter_section=" . $filter_section_id;
            if ($filter_program_id) $redirect_url .= "&filter_program=" . $filter_program_id;
            if ($filter_batch_id) $redirect_url .= "&filter_batch=" . $filter_batch_id;
            if ($filter_semester_id) $redirect_url .= "&filter_semester=" . $filter_semester_id;
            if ($filter_expiration_status) $redirect_url .= "&filter_expiration_status=" . $filter_expiration_status;
            if ($search_query) $redirect_url .= "&search_query=" . urlencode($search_query);
            
            header("Location: " . $redirect_url);
            exit;
            
        } catch (Exception $e) {
            $mysqli1->rollback();
            $error_message = "حدث خطأ أثناء تمديد التسجيلات: " . $e->getMessage();
            error_log("Extension Error: " . $e->getMessage());
        }
    }
}

// Build WHERE clause for filtering registrations
$where = " WHERE r.deleted_at IS NULL AND r.is_paid = 0 "; // فقط التسجيلات غير المدفوعة
$types = ''; 
$params = [];

// Apply scope restrictions
if (!$canAll && $scopeCollege !== null) {
    $where .= " AND EXISTS (
        SELECT 1 FROM students s 
        WHERE s.student_id = r.student_id 
        AND s.college_id = ?
    ) ";
    $types .= 'i'; 
    $params[] = $scopeCollege;
    if (!$filter_college_id) {
        $filter_college_id = $scopeCollege;
    }
} elseif (!$canAll && $scopeCollege === null) {
    $where .= " AND 1=0 ";
}

// Apply filters if they were applied
if ($filters_applied) {
    if ($filter_college_id && !empty($filter_college_id)) {
        $where .= " AND EXISTS (
            SELECT 1 FROM students s 
            WHERE s.student_id = r.student_id 
            AND s.college_id = ?
        ) ";
        $types .= 'i'; 
        $params[] = $filter_college_id;
    }

    if ($filter_section_id && !empty($filter_section_id)) {
        $where .= " AND EXISTS (
            SELECT 1 FROM students s 
            WHERE s.student_id = r.student_id 
            AND s.section_id = ?
        ) ";
        $types .= 'i'; 
        $params[] = $filter_section_id;
    }

    if ($filter_program_id && !empty($filter_program_id)) {
        $where .= " AND EXISTS (
            SELECT 1 FROM students s 
            WHERE s.student_id = r.student_id 
            AND s.program_id = ?
        ) ";
        $types .= 'i'; 
        $params[] = $filter_program_id;
    }

    if ($filter_batch_id && !empty($filter_batch_id)) {
        $where .= " AND EXISTS (
            SELECT 1 FROM students s 
            WHERE s.student_id = r.student_id 
            AND s.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;
    }
    
    // Filter by expiration status
    if ($filter_expiration_status && !empty($filter_expiration_status)) {
        $today = date('Y-m-d H:i:s');
        if ($filter_expiration_status === 'expired') {
            $where .= " AND r.end < ? ";
            $types .= 's';
            $params[] = $today;
        } elseif ($filter_expiration_status === 'active') {
            $where .= " AND r.end >= ? ";
            $types .= 's';
            $params[] = $today;
        } elseif ($filter_expiration_status === 'expiring_soon') {
            $next_week = date('Y-m-d H:i:s', strtotime('+7 days'));
            $where .= " AND r.end >= ? AND r.end <= ? ";
            $types .= 'ss';
            $params[] = $today;
            $params[] = $next_week;
        }
    }

    // Apply search query
    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;
    }
}

// Get filtered registrations
if ($filters_applied) {
    $sqlRegistrations = "
        SELECT 
            r.id, r.student_id, r.student_name,
            r.semester_id, r.study_fees, r.registration_fees, r.insurance_fees,
            r.discount, r.payment_amount, r.due_amount, r.is_paid, r.start, r.end,
            r.created_at, r.updated_at,
            s.name as semester_name,
            c.name as college_name,
            sec.name as section_name,
            p.name as program_name,
            b.value as batch_name
        FROM registrations r
        LEFT JOIN semesters s ON r.semester_id = s.id
        LEFT JOIN students st ON r.student_id = st.student_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.end ASC, r.created_at DESC
        LIMIT 500
    ";

    $registrations_stmt = $mysqli1->prepare($sqlRegistrations);
    if ($types) {
        $registrations_stmt->bind_param($types, ...$params);
    }
    $registrations_stmt->execute();
    $registrations = $registrations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $registrations_stmt->close();
}

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

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

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

// Get initial sections if college is selected
$sections = [];
if ($filter_college_id && !empty($filter_college_id)) {
    $sections_sql = "
        SELECT DISTINCT s.id, s.name
        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();
}

include 'header.php';

// Check extension logs from session
$session_logs = $_SESSION['extension_logs'] ?? [];
if (!empty($session_logs)) {
    $extension_logs = $session_logs;
    unset($_SESSION['extension_logs']);
}
?>

<!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: #3b82f6;
            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;
        }
        .checkbox-cell {
            width: 50px;
            text-align: center;
        }
        .date-inputs {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
        }
        .status-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.4rem;
        }
        .expired-badge {
            background-color: #f59e0b;
        }
        .active-badge {
            background-color: #3b82f6;
        }
        .expiring-soon-badge {
            background-color: #fbbf24;
        }
        .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;
        }
        .form-group {
            position: relative;
        }
        .search-input-group {
            position: relative;
        }
        .search-clear-btn {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #6c757d;
            cursor: pointer;
            display: none;
        }
        .search-input-group input:not(:placeholder-shown) + .search-clear-btn {
            display: block;
        }
        .date-cell {
            font-family: monospace;
            font-size: 0.85rem;
        }
        .log-table {
            font-size: 0.85rem;
        }
        .log-table th {
            background-color: #f3f4f6;
        }
        .date-status {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .remaining-days {
            font-size: 0.75rem;
            padding: 2px 6px;
            border-radius: 4px;
            background-color: #f3f4f6;
        }
        .expiring-soon {
            background-color: #fef3c7;
            color: #92400e;
        }
        .expired {
            background-color: #fee2e2;
            color: #991b1b;
        }
        .fees-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.4rem;
        }
        .total-students-badge {
            font-size: 0.9rem;
        }
        .ajax-loading {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            display: none;
        }
        .filter-row {
            position: relative;
        }
        .fees-details {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }
        .fees-row {
            display: flex;
            justify-content: space-between;
            font-size: 0.75rem;
        }
        .fee-label {
            color: #6b7280;
        }
        .fee-value {
            font-weight: 600;
        }
        .fee-value-positive {
            color: #059669;
        }
        .fee-value-negative {
            color: #dc2626;
        }
        .due-amount {
            font-weight: bold;
            color: #dc2626;
        }
        .fees-summary {
            background: #f8f9fa;
            padding: 8px;
            border-radius: 6px;
            margin-top: 4px;
        }
        .calculation-formula {
            font-size: 0.7rem;
            color: #6b7280;
            margin-top: 4px;
            padding-top: 4px;
            border-top: 1px dashed #d1d5db;
            text-align: center;
        }
        .math-equation {
            font-family: monospace;
            color: #374151;
            font-weight: bold;
        }
        .total-fees-row {
            background-color: #e5e7eb;
            padding: 4px 8px;
            border-radius: 4px;
            margin-top: 4px;
        }
        .payment-row {
            display: flex;
            justify-content: space-between;
            font-size: 0.75rem;
        }
        .payment-value {
            font-weight: 600;
        }
        .payment-negative {
            color: #dc2626;
        }
    </style>
</head>
<body>
    <div class="container py-4" dir="rtl">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4">
            <h3 class="mb-0 fw-bold">تمديد فترات التسجيل (التسجيلات غير المدفوعة فقط)</h3>
            <div class="ms-auto">
                <span class="filter-status <?= $filters_applied ? 'applied' : 'not-applied' ?> me-2">
                    <i class="fas fa-<?= $filters_applied ? 'check-circle' : 'exclamation-triangle' ?> me-1"></i>
                    <?= $filters_applied ? 'تم تطبيق التصفية' : 'لم يتم تطبيق أي تصفية' ?>
                </span>
                <a class="btn btn-outline-secondary" href="committee_dashboard.php">
                    <i class="fas fa-arrow-right me-2"></i>العودة للوحة التحكم
                </a>
            </div>
        </div>

        <?php if (!$filters_applied): ?>
            <div class="info-message">
                <i class="fas fa-info-circle me-2"></i>
                <strong>تنبيه:</strong> لم يتم تطبيق أي تصفية. الرجاء اختيار عوامل التصفية ثم النقر على "تطبيق التصفية" لعرض التسجيلات غير المدفوعة.
            </div>
        <?php endif; ?>

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

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

        <!-- Extension Results Log -->
        <?php if (!empty($extension_logs)): ?>
        <div class="card card-arabic mb-4">
            <div class="card-header bg-primary text-white">
                <h6 class="mb-0"><i class="fas fa-clipboard-list me-2"></i>نتائج عملية التمديد</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table log-table">
                        <thead>
                            <tr>
                                <th>رقم الطالب</th>
                                <th>اسم الطالب</th>
                                <th>الحالة</th>
                                <th>التاريخ القديم</th>
                                <th>التاريخ الجديد</th>
                                <th>السبب</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($extension_logs as $log): ?>
                            <tr>
                                <td><code><?= e($log['student_id']) ?></code></td>
                                <td><?= e($log['student_name']) ?></td>
                                <td>
                                    <?php if ($log['status'] === 'extended'): ?>
                                        <span class="badge bg-success">تم التمديد</span>
                                    <?php elseif ($log['status'] === 'skipped'): ?>
                                        <span class="badge bg-warning">تم التخطي</span>
                                    <?php elseif ($log['status'] === 'failed'): ?>
                                        <span class="badge bg-danger">فشل</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= $log['old_end'] ?? '-' ?></td>
                                <td><?= $log['new_end'] ?? '-' ?></td>
                                <td><?= $log['reason'] ?? 'تم التمديد بنجاح' ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Filter Card -->
        <div class="card card-arabic p-4 mb-4">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="d-flex align-items-center mb-3">
                        <div class="filter-icon me-2">
                            <i class="fas fa-filter"></i>
                        </div>
                        <h6 class="fw-bold mb-0 text-dark">تصفية التسجيلات غير المدفوعة</h6>
                        <div class="ms-3">
                            <span class="badge bg-light text-dark border">
                                <i class="fas fa-sliders-h me-1"></i>
                                <?= $filters_applied ? 'تصفية مطبقة' : 'في انتظار التطبيق' ?>
                            </span>
                        </div>
                    </div>
                    
                    <form method="get" class="row g-3 align-items-end" id="filterForm">
                        <input type="hidden" name="filter_applied" value="1">
                        
                        <!-- College Filter -->
                        <div class="col-lg-3 col-md-6 filter-row">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-university me-1"></i>
                                    الكلية
                                </label>
                                <select class="form-control form-control-sm" name="filter_college" id="filter_college" 
                                        onchange="loadSections(this.value)">
                                    <option value="">جميع الكليات</option>
                                    <?php foreach ($colleges as $college): ?>
                                        <?php if (!$canAll && $scopeCollege !== null && $college['id'] != $scopeCollege) continue; ?>
                                        <option value="<?= $college['id'] ?>" <?= ($filter_college_id == $college['id']) ? 'selected' : '' ?>>
                                            <?= e($college['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <!-- Section Filter (AJAX loaded) -->
                        <div class="col-lg-3 col-md-6 filter-row">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-layer-group me-1"></i>
                                    القسم
                                </label>
                                <div class="position-relative">
                                    <select class="form-control form-control-sm" name="filter_section" id="filter_section">
                                        <option value="">جميع الأقسام</option>
                                        <?php foreach ($sections as $section): ?>
                                            <option value="<?= $section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                                <?= e($section['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="ajax-loading" id="sectionLoading" style="display: none;">
                                        <i class="fas fa-spinner fa-spin"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Program Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-graduation-cap me-1"></i>
                                    البرنامج
                                </label>
                                <select class="form-control form-control-sm" name="filter_program">
                                    <option value="">جميع البرامج</option>
                                    <?php foreach ($programs as $program): ?>
                                        <option value="<?= $program['id'] ?>" <?= ($filter_program_id == $program['id']) ? 'selected' : '' ?>>
                                            <?= e($program['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <!-- Batch Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-users me-1"></i>
                                    الدفعة
                                </label>
                                <select class="form-control form-control-sm" name="filter_batch">
                                    <option value="">جميع الدفعات</option>
                                    <?php foreach ($batches as $batch): ?>
                                        <option value="<?= $batch['id'] ?>" <?= ($filter_batch_id == $batch['id']) ? 'selected' : '' ?>>
                                            <?= e($batch['value']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <!-- Semester Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-calendar-alt me-1"></i>
                                    الفصل
                                </label>
                                <select class="form-control form-control-sm" name="filter_semester">
                                    <option value="">جميع الفصول</option>
                                    <?php foreach ($semesters as $semester): ?>
                                        <option value="<?= $semester['id'] ?>" <?= ($filter_semester_id == $semester['id']) ? 'selected' : '' ?>>
                                            <?= e($semester['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <!-- Expiration Status Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-clock me-1"></i>
                                    حالة الانتهاء
                                </label>
                                <select class="form-control form-control-sm" name="filter_expiration_status">
                                    <option value="">جميع الحالات</option>
                                    <option value="active" <?= ($filter_expiration_status == 'active') ? 'selected' : '' ?>>نشط</option>
                                    <option value="expiring_soon" <?= ($filter_expiration_status == 'expiring_soon') ? 'selected' : '' ?>>قريب الانتهاء</option>
                                    <option value="expired" <?= ($filter_expiration_status == 'expired') ? 'selected' : '' ?>>منتهي</option>
                                </select>
                            </div>
                        </div>
                        
                        <!-- Search Field -->
                        <div class="col-12 mt-2">
                            <div class="search-input-group">
                                <div class="input-group input-group-sm">
                                    <input type="text" 
                                           class="form-control" 
                                           name="search_query" 
                                           id="search_query"
                                           placeholder="بحث برقم الطالب أو اسم الطالب..."
                                           value="<?= e($search_query) ?>"
                                           autocomplete="off">
                                    <span class="input-group-text bg-light">
                                        <i class="fas fa-search"></i>
                                    </span>
                                </div>
                                <button type="button" class="search-clear-btn" onclick="clearSearch()" title="مسح البحث">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div class="col-12">
                            <div class="d-flex gap-2 pt-2">
                                <button type="submit" class="btn btn-primary btn-sm px-3">
                                    <i class="fas fa-filter me-1"></i>
                                    تطبيق التصفية والبحث
                                </button>
                                <a href="extend_registration.php" class="btn btn-outline-secondary btn-sm px-3">
                                    <i class="fas fa-sync-alt me-1"></i>
                                    إعادة تعيين
                                </a>
                                <?php if ($filters_applied): ?>
                                    <span class="badge bg-success align-self-center px-3 py-2">
                                        <i class="fas fa-check me-1"></i>
                                        تم تطبيق التصفية
                                        <?php if (!empty($search_query)): ?>
                                            <i class="fas fa-search ms-1"></i>
                                        <?php endif; ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                </div>
                
                <!-- Filter Summary -->
                <div class="col-md-4">
                    <div class="bg-light rounded p-3 h-100">
                        <div class="d-flex align-items-center mb-2">
                            <i class="fas fa-info-circle me-2 <?= $filters_applied ? 'text-primary' : 'text-secondary' ?>"></i>
                            <span class="fw-semibold">ملخص التصفية</span>
                        </div>
                        <div class="small">
                            <?php if ($filters_applied): ?>
                                <div class="mb-1">عدد التسجيلات غير المدفوعة: <strong><?= count($registrations) ?></strong></div>
                                
                                <?php if (!empty($search_query)): ?>
                                    <div class="mb-2 p-2 bg-warning bg-opacity-10 rounded">
                                        <div class="fw-semibold text-warning mb-1">
                                            <i class="fas fa-search me-1"></i>
                                            نتيجة البحث
                                        </div>
                                        <div class="text-truncate">
                                            "<?= e($search_query) ?>"
                                        </div>
                                    </div>
                                <?php endif; ?>
                                
                                <?php
                                $expired_count = 0;
                                $active_count = 0;
                                $expiring_soon_count = 0;
                                $total_due_amount = 0;
                                $today = date('Y-m-d');
                                
                                foreach ($registrations as $reg) {
                                    $end_date = date('Y-m-d', strtotime($reg['end']));
                                    $days_remaining = floor((strtotime($end_date) - strtotime($today)) / (60 * 60 * 24));
                                    
                                    if ($end_date < $today) {
                                        $expired_count++;
                                    } elseif ($days_remaining <= 7) {
                                        $expiring_soon_count++;
                                    } else {
                                        $active_count++;
                                    }
                                    
                                    // حساب الرسوم المستحقة بشكل صحيح
                                    $study_fees = floatval($reg['study_fees'] ?? 0);
                                    $registration_fees = floatval($reg['registration_fees'] ?? 0);
                                    $insurance_fees = floatval($reg['insurance_fees'] ?? 0);
                                    $discount = floatval($reg['discount'] ?? 0);
                                    $payment_amount = floatval($reg['payment_amount'] ?? 0);
                                    
                                    // الحساب الصحيح
                                    $total_fees = $study_fees + $registration_fees + $insurance_fees;
                                    $due_amount = $total_fees - $discount - $payment_amount;
                                    $total_due_amount += max(0, $due_amount); // تجنب القيم السالبة
                                }
                                ?>
                                
                                <div class="mb-2 p-2 <?= $expired_count > 0 ? 'bg-warning bg-opacity-10' : 'bg-success bg-opacity-10' ?> rounded">
                                    <div class="fw-semibold <?= $expired_count > 0 ? 'text-warning' : 'text-success' ?> mb-1">
                                        <i class="fas fa-clock me-1"></i>
                                        حالة التسجيلات
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <span>نشطة:</span>
                                        <strong><?= $active_count ?></strong>
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <span>قريبة الانتهاء:</span>
                                        <strong class="text-warning"><?= $expiring_soon_count ?></strong>
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <span>منتهية:</span>
                                        <strong class="<?= $expired_count > 0 ? 'text-danger' : '' ?>"><?= $expired_count ?></strong>
                                    </div>
                                </div>
                                
                                <div class="mb-2 p-2 bg-info bg-opacity-10 rounded">
                                    <div class="fw-semibold text-info mb-1">
                                        <i class="fas fa-money-bill-wave me-1"></i>
                                        إجمالي الرسوم المستحقة
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <span>المبلغ الإجمالي:</span>
                                        <strong class="text-danger"><?= number_format($total_due_amount, 2) ?> SDG</strong>
                                    </div>
                                </div>
                                
                                <div class="alert alert-warning alert-sm mb-0">
                                    <i class="fas fa-exclamation-triangle me-1"></i>
                                    يتم عرض التسجيلات غير المدفوعة فقط
                                </div>
                                
                            <?php else: ?>
                                <div class="text-center py-3">
                                    <i class="fas fa-filter fa-2x text-muted mb-3"></i>
                                    <p class="text-muted mb-0">لم يتم تطبيق أي تصفية بعد</p>
                                    <p class="text-muted small">الرجاء اختيار عوامل التصفية ثم النقر على "تطبيق التصفية"</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Extension 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">تمديد فترات التسجيل غير المدفوعة</h6>
                <span class="badge bg-primary ms-2 total-students-badge"><?= 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; ?>
                <?php if ($expired_count > 0): ?>
                    <span class="badge bg-warning ms-2">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        <?= $expired_count ?> منتهي
                    </span>
                <?php endif; ?>
                <?php if ($expiring_soon_count > 0): ?>
                    <span class="badge bg-warning ms-2">
                        <i class="fas fa-clock me-1"></i>
                        <?= $expiring_soon_count ?> قريب الانتهاء
                    </span>
                <?php endif; ?>
            </div>
            
            <form method="post" id="extensionForm">
                <!-- Extension Details Section -->
                <div class="date-inputs mb-4">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">تاريخ نهاية جديد:</label>
                            <input type="date" class="form-control" name="new_end_date" required 
                                   min="<?= date('Y-m-d') ?>" value="<?= date('Y-m-d', strtotime('+30 days')) ?>">
                            <small class="text-muted">التاريخ الجديد يجب أن يكون بعد التواريخ الحالية</small>
                        </div>
                        <div class="col-md-6">
                            <div class="alert alert-info mb-0 h-100 d-flex align-items-center">
                                <div>
                                    <i class="fas fa-info-circle me-2"></i>
                                    <strong>ملاحظة:</strong> سيتم تمديد التسجيلات المحددة فقط (غير المدفوعة)
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Action Buttons -->
                <div class="row g-3 align-items-end mb-3">
                    <div class="col-md-6">
                        <div class="d-flex gap-2 flex-wrap">
                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="selectAllRegistrations()">
                                <i class="fas fa-check-square me-1"></i>تحديد الكل
                            </button>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="deselectAllRegistrations()">
                                <i class="fas fa-times-circle me-1"></i>إلغاء الكل
                            </button>
                            <button type="button" class="btn btn-outline-warning btn-sm" onclick="selectExpiredOnly()">
                                <i class="fas fa-clock me-1"></i>اختيار المنتهية فقط
                            </button>
                            <button type="submit" name="extend_registrations" class="btn btn-success btn-sm">
                                <i class="fas fa-calendar-plus me-1"></i>تمديد التسجيلات المحددة
                            </button>
                        </div>
                    </div>
                    <div class="col-md-6 text-start">
                        <div class="text-muted small">
                            <i class="fas fa-info-circle me-1"></i>
                            سيتم تحديث تاريخ الانتهاء للتسجيلات غير المدفوعة المحددة
                            <?php if ($expired_count > 0): ?>
                                <br>
                                <i class="fas fa-exclamation-triangle me-1 text-warning"></i>
                                <span class="text-warning">يوجد <?= $expired_count ?> تسجيل منتهي بحاجة للتمديد</span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Registrations Table -->
                <div class="table-responsive mt-4">
                    <table class="table table-striped registration-table">
                        <thead>
                            <tr>
                                <th class="checkbox-cell">
                                    <input type="checkbox" id="selectAll" onchange="toggleAllRegistrations(this)">
                                </th>
                                <th>#</th>
                                <th>رقم الطالب</th>
                                <th>اسم الطالب</th>
                                <th>الكلية</th>
                                <th>القسم</th>
                                <th>البرنامج</th>
                                <th>الدفعة</th>
                                <th>الفصل</th>
                                <th>فترة التسجيل</th>
                                <th>الرسوم المستحقة</th>
                                <th>الحالة</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $counter = 1; ?>
                            <?php foreach ($registrations as $reg): ?>
                                <?php
                                $today = date('Y-m-d');
                                $end_date = date('Y-m-d', strtotime($reg['end']));
                                $days_remaining = floor((strtotime($end_date) - strtotime($today)) / (60 * 60 * 24));
                                
                                $status_class = '';
                                $status_text = '';
                                $remaining_class = '';
                                
                                if ($end_date < $today) {
                                    $status_class = 'expired-badge';
                                    $status_text = 'منتهي';
                                    $remaining_class = 'expired';
                                } elseif ($days_remaining <= 7) {
                                    $status_class = 'expiring-soon-badge';
                                    $status_text = 'قريب الانتهاء';
                                    $remaining_class = 'expiring-soon';
                                } else {
                                    $status_class = 'active-badge';
                                    $status_text = 'نشط';
                                }
                                
                                // حساب الرسوم المستحقة بشكل صحيح
                                $study_fees = floatval($reg['study_fees'] ?? 0);
                                $registration_fees = floatval($reg['registration_fees'] ?? 0);
                                $insurance_fees = floatval($reg['insurance_fees'] ?? 0);
                                $discount = floatval($reg['discount'] ?? 0);
                                $payment_amount = floatval($reg['payment_amount'] ?? 0);
                                $due_amount_field = floatval($reg['due_amount'] ?? 0);
                                
                                // الحساب الصحيح
                                $total_fees = $study_fees + $registration_fees + $insurance_fees;
                                $calculated_due_amount = $total_fees - $discount - $payment_amount;
                                
                                // استخدام القيمة المحسوبة أو قيمة الحقل (أيهما أكبر من 0)
                                $due_amount = $calculated_due_amount > 0 ? $calculated_due_amount : ($due_amount_field > 0 ? $due_amount_field : 0);
                                
                                // حساب المبلغ المدفوع للعرض (إذا كان بالسالب نجعله صفر)
                                $display_payment_amount = $payment_amount < 0 ? 0 : $payment_amount;
                                ?>
                                <tr>
                                    <td class="checkbox-cell">
                                        <input type="checkbox" name="registration_ids[]" 
                                               value="<?= e($reg['id']) ?>" 
                                               class="registration-checkbox"
                                               data-end-date="<?= $end_date ?>"
                                               data-is-expired="<?= $end_date < $today ? 'true' : 'false' ?>">
                                    </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['section_name'] ?? 'غير معروف') ?></td>
                                    <td><?= e($reg['program_name'] ?? 'غير معروف') ?></td>
                                    <td>
                                        <span class="badge bg-secondary"><?= e($reg['batch_name'] ?? 'غير معروف') ?></span>
                                    </td>
                                    <td><?= e($reg['semester_name'] ?? 'غير معروف') ?></td>
                                    <td class="date-cell">
                                        <div class="date-status">
                                            <div>
                                                <div><small>من: <?= date('Y-m-d', strtotime($reg['start'])) ?></small></div>
                                                <div><small>إلى: <?= $end_date ?></small></div>
                                            </div>
                                            <span class="remaining-days <?= $remaining_class ?>">
                                                <?= $end_date < $today ? 'منتهي' : "{$days_remaining} يوم" ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="fees-summary">
                                            <div class="fees-details">
                                                <?php if ($study_fees > 0): ?>
                                                <div class="fees-row">
                                                    <span class="fee-label">رسوم الدراسة:</span>
                                                    <span class="fee-value"><?= number_format($study_fees, 2) ?> SDG</span>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <?php if ($registration_fees > 0): ?>
                                                <div class="fees-row">
                                                    <span class="fee-label">رسوم التسجيل:</span>
                                                    <span class="fee-value"><?= number_format($registration_fees, 2) ?> SDG</span>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <?php if ($insurance_fees > 0): ?>
                                                <div class="fees-row">
                                                    <span class="fee-label">رسوم التأمين:</span>
                                                    <span class="fee-value"><?= number_format($insurance_fees, 2) ?> SDG</span>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <div class="total-fees-row">
                                                    <div class="fees-row">
                                                        <span class="fee-label">مجموع الرسوم:</span>
                                                        <span class="fee-value"><?= number_format($total_fees, 2) ?> SDG</span>
                                                    </div>
                                                </div>
                                                
                                                <?php if ($discount > 0): ?>
                                                <div class="fees-row">
                                                    <span class="fee-label">الخصم:</span>
                                                    <span class="fee-value fee-value-positive">-<?= number_format($discount, 2) ?> SDG</span>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <?php if ($display_payment_amount > 0): ?>
                                                <div class="fees-row">
                                                    <span class="fee-label">المبلغ المدفوع:</span>
                                                    <span class="fee-value fee-value-positive">-<?= number_format($display_payment_amount, 2) ?> SDG</span>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <div class="fees-row mt-1 pt-1 border-top">
                                                    <span class="fee-label due-amount">المبلغ المستحق:</span>
                                                    <span class="fee-value due-amount"><?= number_format($due_amount, 2) ?> SDG</span>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge <?= $status_class ?> status-badge"><?= $status_text ?></span>
                                    </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-calendar-times 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">
                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="clearSearch()">
                            <i class="fas fa-times me-1"></i>إلغاء البحث
                        </button>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // AJAX function to load sections
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            const loadingElement = document.getElementById('sectionLoading');
            
            // Reset section select
            sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
            
            if (!collegeId || collegeId === '') {
                return;
            }
            
            // Show loading indicator
            loadingElement.style.display = 'block';
            
            // Make AJAX request
            fetch(`extend_registration.php?ajax=get_sections&college_id=${collegeId}`)
                .then(response => response.json())
                .then(sections => {
                    // Add sections to select
                    sections.forEach(section => {
                        const option = document.createElement('option');
                        option.value = section.id;
                        option.textContent = section.name;
                        sectionSelect.appendChild(option);
                    });
                    
                    // Hide loading indicator
                    loadingElement.style.display = 'none';
                })
                .catch(error => {
                    console.error('Error loading sections:', error);
                    loadingElement.style.display = 'none';
                });
        }
        
        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;
        }
        
        function selectExpiredOnly() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                const isExpired = checkbox.getAttribute('data-is-expired') === 'true';
                checkbox.checked = isExpired;
            });
            
            const allChecked = document.querySelectorAll('.registration-checkbox:checked').length === document.querySelectorAll('.registration-checkbox').length;
            document.getElementById('selectAll').checked = allChecked;
            
            const expiredCount = document.querySelectorAll('.registration-checkbox[data-is-expired="true"]:checked').length;
            if (expiredCount > 0) {
                alert(`تم اختيار ${expiredCount} تسجيل منتهي`);
            } else {
                alert('لا توجد تسجيلات منتهية في القائمة الحالية');
            }
        }
        
        // Update select all checkbox
        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 validation
        document.getElementById('extensionForm')?.addEventListener('submit', function(e) {
            const selectedCount = document.querySelectorAll('.registration-checkbox:checked').length;
            const newEndDate = document.querySelector('input[name="new_end_date"]').value;
            
            if (selectedCount === 0) {
                e.preventDefault();
                alert('يرجى اختيار تسجيل واحد على الأقل للتمديد');
                return;
            }
            
            if (!newEndDate) {
                e.preventDefault();
                alert('يرجى تحديد تاريخ نهاية جديد');
                return;
            }
            
            const today = new Date();
            const selectedDate = new Date(newEndDate);
            if (selectedDate <= today) {
                if (!confirm('التاريخ الجديد ليس في المستقبل. هل تريد المتابعة؟')) {
                    e.preventDefault();
                    return;
                }
            }
            
            let confirmationMessage = `هل أنت متأكد من تمديد ${selectedCount} تسجيل غير مدفوع إلى تاريخ ${newEndDate}؟`;
            
            if (!confirm(confirmationMessage)) {
                e.preventDefault();
            }
        });
        
        // Clear search field
        function clearSearch() {
            document.getElementById('search_query').value = '';
            document.getElementById('filterForm').submit();
        }
        
        // Auto-submit search on Enter
        document.getElementById('search_query')?.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                document.getElementById('filterForm').submit();
            }
        });
        
        // Show clear button
        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
        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';
            }
            
            // Set default end date to 30 days from today
            const today = new Date();
            const futureDate = new Date();
            futureDate.setDate(today.getDate() + 30);
            const defaultEndDate = futureDate.toISOString().split('T')[0];
            
            const newEndDateInput = document.querySelector('input[name="new_end_date"]');
            if (newEndDateInput && !newEndDateInput.value) {
                newEndDateInput.value = defaultEndDate;
            }
        });
    </script>
</body>
</html>