<?php
// extend_registration.php - تمديد فترات التسجيل (نسخة معدلة مع إضافة التخصص)
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

// CSRF Protection
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$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 = [];

// Validate and sanitize filter parameters
function validateInt($value) {
    return $value !== null && $value !== '' && ctype_digit($value) ? (int)$value : null;
}

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

// Get filter parameters - with proper sanitization
if ($filters_applied) {
    $filter_college_id = validateInt($_GET['filter_college'] ?? null);
    $filter_section_id = validateInt($_GET['filter_section'] ?? null);
    $filter_program_id = validateInt($_GET['filter_program'] ?? null);
    $filter_specialization_id = validateInt($_GET['filter_specialization'] ?? null);
    $filter_batch_id = validateInt($_GET['filter_batch'] ?? null);
    $filter_semester_id = validateInt($_GET['filter_semester'] ?? null);
    $filter_expiration_status = isset($_GET['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_specialization_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'])) {
    // Verify authentication for AJAX
    if (!isset($_SESSION['committee_id'])) {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }
    
    $college_id = validateInt($_GET['college_id']) ?? 0;
    $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();
    }
    
    header('Content-Type: application/json');
    echo json_encode($sections);
    exit;
}

// Handle AJAX request for specializations
if (isset($_GET['ajax']) && $_GET['ajax'] === 'get_specializations' && isset($_GET['section_id']) && isset($_GET['program_id'])) {
    // Verify authentication for AJAX
    if (!isset($_SESSION['committee_id'])) {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }
    
    $section_id = validateInt($_GET['section_id']) ?? 0;
    $program_id = validateInt($_GET['program_id']) ?? 0;
    $specializations = [];
    
    if ($section_id > 0 && $program_id > 0) {
        $specializations_sql = "
            SELECT specialization_id, specialization_name_ar 
            FROM specializations 
            WHERE section_id = ? AND program_id = ? AND deleted_at IS NULL 
            ORDER BY specialization_name_ar
        ";
        $specializations_stmt = $mysqli1->prepare($specializations_sql);
        $specializations_stmt->bind_param("ii", $section_id, $program_id);
        $specializations_stmt->execute();
        $specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $specializations_stmt->close();
    }
    
    header('Content-Type: application/json');
    echo json_encode($specializations);
    exit;
}

// Handle form submission for extension
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['extend_registrations'])) {
    // Verify CSRF token
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $error_message = 'رمز الأمان غير صالح. الرجاء تحديث الصفحة والمحاولة مرة أخرى.';
    } else {
        $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 {
            // Validate date format
            $new_end_timestamp = date('Y-m-d H:i:s', strtotime($new_end_date));
            if (!$new_end_timestamp) {
                $error_message = 'صيغة التاريخ غير صالحة';
            } else {
                // Validate registration IDs are integers
                $valid_registration_ids = [];
                foreach ($registration_ids as $id) {
                    if (ctype_digit($id)) {
                        $valid_registration_ids[] = (int)$id;
                    }
                }
                
                if (empty($valid_registration_ids)) {
                    $error_message = 'معرفات التسجيل غير صالحة';
                } else {
                    try {
                        $mysqli1->begin_transaction();
                        
                        $extended_count = 0;
                        $skipped_count = 0;
                        
                        foreach ($valid_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_specialization_id) $redirect_url .= "&filter_specialization=" . $filter_specialization_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=" . urlencode($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 !== null) {
        $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 !== null) {
        $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 !== null) {
        $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;
    }

    // NEW: Apply specialization filter
    if ($filter_specialization_id !== null) {
        $where .= " AND EXISTS (
            SELECT 1 FROM students s 
            WHERE s.student_id = r.student_id 
            AND s.specialization_id = ?
        ) ";
        $types .= 'i'; 
        $params[] = $filter_specialization_id;
    }

    if ($filter_batch_id !== null) {
        $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 !== null) {
        $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 - using LIKE with prepared statements
    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,
            sem.name as semester_name,
            c.name as college_name,
            sec.name as section_name,
            p.name as program_name,
            sp.specialization_name_ar as specialization_name,
            b.value as batch_name
        FROM registrations r
        LEFT JOIN semesters sem ON r.semester_id = sem.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 specializations sp ON st.specialization_id = sp.specialization_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 !== null) {
    $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();
}

// Get all sections (for filter summary)
$all_sections_stmt = $mysqli1->prepare("SELECT id, name FROM sections WHERE deleted_at IS NULL ORDER BY name");
$all_sections_stmt->execute();
$all_sections = $all_sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$all_sections_stmt->close();

// Get all specializations (for filter summary)
$all_specializations = [];
if ($filter_section_id !== null && $filter_program_id !== null) {
    $specializations_sql = "
        SELECT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    $specializations_stmt->bind_param("ii", $filter_section_id, $filter_program_id);
    $specializations_stmt->execute();
    $all_specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
} elseif ($filter_section_id !== null) {
    $specializations_sql = "
        SELECT DISTINCT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    $specializations_stmt->bind_param("i", $filter_section_id);
    $specializations_stmt->execute();
    $all_specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
} elseif ($filter_program_id !== null) {
    $specializations_sql = "
        SELECT DISTINCT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    $specializations_stmt->bind_param("i", $filter_program_id);
    $specializations_stmt->execute();
    $all_specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
}

// Get filter names for summary
$college_name = "";
if ($filter_college_id !== null) {
    foreach ($colleges as $college) {
        if ($college['id'] == $filter_college_id) {
            $college_name = $college['name'];
            break;
        }
    }
}

$section_name = "";
if ($filter_section_id !== null) {
    $search_sections = $filter_college_id ? $sections : $all_sections;
    foreach ($search_sections as $section) {
        if ($section['id'] == $filter_section_id) {
            $section_name = $section['name'];
            break;
        }
    }
}

$program_name = "";
if ($filter_program_id !== null) {
    foreach ($programs as $program) {
        if ($program['id'] == $filter_program_id) {
            $program_name = $program['name'];
            break;
        }
    }
}

$specialization_name = "";
if ($filter_specialization_id !== null && !empty($all_specializations)) {
    foreach ($all_specializations as $spec) {
        if ($spec['specialization_id'] == $filter_specialization_id) {
            $specialization_name = $spec['specialization_name_ar'];
            break;
        }
    }
}

$batch_name = "";
if ($filter_batch_id !== null) {
    foreach ($batches as $batch) {
        if ($batch['id'] == $filter_batch_id) {
            $batch_name = $batch['value'];
            break;
        }
    }
}

$semester_name = "";
if ($filter_semester_id !== null) {
    foreach ($semesters as $semester) {
        if ($semester['id'] == $filter_semester_id) {
            $semester_name = $semester['name'] . ' (' . $semester['code'] . ')';
            break;
        }
    }
}

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', 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;
        }
        .total-fees-row {
            background-color: #e5e7eb;
            padding: 4px 8px;
            border-radius: 4px;
            margin-top: 4px;
        }
        .filter-badge.specialization {
            background-color: #f3e8ff;
            color: #7e22ce;
            border: 1px solid #e9d5ff;
        }
        .filter-summary {
            background-color: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
        }
        .filter-badge {
            font-size: 0.85rem;
            padding: 0.4rem 0.8rem;
        }
    </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="badge admin-badge me-2">
                    <i class="fas fa-user-shield me-1"></i>مدير النظام
                </span>
                <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; ?>

        <!-- 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 with Specialization -->
        <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" class="row g-3 align-items-end" id="filterForm">
                <input type="hidden" name="filter_applied" value="1">
                
                <!-- First Row of Filters -->
                <div class="row">
                    <!-- College Filter -->
                    <div class="col-lg-2 col-md-6 mb-3">
                        <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 -->
                    <div class="col-lg-2 col-md-6 mb-3">
                        <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" 
                                        onchange="loadSpecializations()" <?= !$filter_college_id ? 'disabled' : '' ?>>
                                    <option value="">جميع الأقسام</option>
                                    <?php if ($filter_college_id && !empty($sections)): ?>
                                        <?php foreach ($sections as $section): ?>
                                            <option value="<?= $section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                                <?= e($section['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </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 mb-3">
                        <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" id="filter_program" 
                                    onchange="loadSpecializations()">
                                <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>
                    
                    <!-- NEW: Specialization Filter -->
                    <div class="col-lg-2 col-md-6 mb-3">
                        <div class="form-group">
                            <label class="form-label fw-semibold text-muted mb-2">
                                <i class="fas fa-microscope me-1"></i>
                                التخصص
                            </label>
                            <div class="position-relative">
                                <select class="form-control form-control-sm" name="filter_specialization" id="filter_specialization" <?= (!$filter_section_id && !$filter_program_id) ? 'disabled' : '' ?>>
                                    <option value="">جميع التخصصات</option>
                                    <?php if (!empty($all_specializations)): ?>
                                        <?php foreach ($all_specializations as $spec): ?>
                                            <option value="<?= $spec['specialization_id'] ?>" <?= ($filter_specialization_id == $spec['specialization_id']) ? 'selected' : '' ?>>
                                                <?= e($spec['specialization_name_ar']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                                <div class="ajax-loading" id="specializationLoading" style="display: none;">
                                    <i class="fas fa-spinner fa-spin"></i>
                                </div>
                            </div>
                            <small class="text-muted" id="specHint">
                                <?php if (!$filter_section_id && !$filter_program_id): ?>
                                    اختر القسم أو البرنامج أولاً
                                <?php endif; ?>
                            </small>
                        </div>
                    </div>
                    
                    <!-- Batch Filter -->
                    <div class="col-lg-2 col-md-6 mb-3">
                        <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 mb-3">
                        <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']) ?> (<?= e($semester['code']) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
                
                <!-- Second Row - Expiration Status and Search -->
                <div class="row">
                    <!-- Expiration Status Filter -->
                    <div class="col-lg-4 col-md-6 mb-3">
                        <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-lg-8 col-md-6 mb-3">
                        <div class="form-group">
                            <label class="form-label fw-semibold text-muted mb-2">
                                <i class="fas fa-search me-1"></i>
                                البحث
                            </label>
                            <div class="search-input-group">
                                <input type="text" 
                                       class="form-control form-control-sm" 
                                       name="search_query" 
                                       id="search_query"
                                       placeholder="بحث برقم الطالب أو اسم الطالب..."
                                       value="<?= e($search_query) ?>"
                                       autocomplete="off">
                                <button type="button" class="search-clear-btn" onclick="clearSearch()" title="مسح البحث">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Action Buttons -->
                <div class="row">
                    <div class="col-12">
                        <div class="d-flex gap-2 pt-2 justify-content-between">
                            <div>
                                <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>
                            </div>
                            <?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>
                </div>
            </form>
            
            <!-- Filter Summary - MOVED BELOW THE FORM -->
            <?php if ($filters_applied): ?>
            <div class="filter-summary mt-4 p-3 bg-light rounded">
                <div class="d-flex align-items-center mb-2">
                    <i class="fas fa-info-circle text-primary me-2"></i>
                    <span class="fw-semibold">ملخص التصفية المطبقة:</span>
                </div>
                <div class="d-flex flex-wrap gap-2">
                    <?php if ($filter_college_id !== null && $college_name): ?>
                        <span class="badge bg-primary filter-badge">
                            <i class="fas fa-university me-1"></i>
                            <?= e($college_name) ?>
                        </span>
                    <?php endif; ?>
                    
                    <?php if ($filter_section_id !== null && $section_name): ?>
                        <span class="badge bg-info filter-badge">
                            <i class="fas fa-layer-group me-1"></i>
                            <?= e($section_name) ?>
                        </span>
                    <?php endif; ?>
                    
                    <?php if ($filter_program_id !== null && $program_name): ?>
                        <span class="badge bg-success filter-badge">
                            <i class="fas fa-graduation-cap me-1"></i>
                            <?= e($program_name) ?>
                        </span>
                    <?php endif; ?>
                    
                    <!-- Specialization summary -->
                    <?php if ($filter_specialization_id !== null && $specialization_name): ?>
                        <span class="badge filter-badge" style="background-color: #f3e8ff; color: #7e22ce; border: 1px solid #e9d5ff;">
                            <i class="fas fa-microscope me-1"></i>
                            <?= e($specialization_name) ?>
                        </span>
                    <?php endif; ?>
                    
                    <?php if ($filter_batch_id !== null && $batch_name): ?>
                        <span class="badge bg-warning filter-badge">
                            <i class="fas fa-users me-1"></i>
                            <?= e($batch_name) ?>
                        </span>
                    <?php endif; ?>
                    
                    <?php if ($filter_semester_id !== null && $semester_name): ?>
                        <span class="badge bg-secondary filter-badge">
                            <i class="fas fa-calendar-alt me-1"></i>
                            <?= e($semester_name) ?>
                        </span>
                    <?php endif; ?>
                    
                    <?php if ($filter_expiration_status): ?>
                        <span class="badge bg-info filter-badge">
                            <i class="fas fa-clock me-1"></i>
                            <?php 
                            if ($filter_expiration_status == 'active') echo 'نشط';
                            elseif ($filter_expiration_status == 'expiring_soon') echo 'قريب الانتهاء';
                            elseif ($filter_expiration_status == 'expired') echo 'منتهي';
                            ?>
                        </span>
                    <?php endif; ?>
                    
                    <?php if (!empty($search_query)): ?>
                        <span class="badge bg-warning filter-badge">
                            <i class="fas fa-search me-1"></i>
                            بحث: "<?= e($search_query) ?>"
                        </span>
                    <?php endif; ?>
                    
                    <?php if ($filter_college_id === null && $filter_section_id === null && $filter_program_id === null && $filter_specialization_id === null && $filter_batch_id === null && $filter_semester_id === null && empty($search_query) && !$filter_expiration_status): ?>
                        <span class="badge bg-light text-dark filter-badge">
                            <i class="fas fa-list-alt me-1"></i>
                            جميع التسجيلات غير المدفوعة
                        </span>
                    <?php endif; ?>
                    
                    <span class="badge bg-primary filter-badge">
                        <i class="fas fa-users me-1"></i>
                        عدد التسجيلات: <?= count($registrations) ?>
                    </span>
                </div>
            </div>
            <?php endif; ?>
        </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
                $expired_count = 0;
                $today = date('Y-m-d');
                foreach ($registrations as $reg) {
                    $end_date = date('Y-m-d', strtotime($reg['end']));
                    if ($end_date < $today) $expired_count++;
                }
                ?>
                <?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; ?>
            </div>
            
            <form method="post" id="extensionForm">
                <!-- CSRF Token -->
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                
                <!-- 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 with Specialization Column -->
                <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>
                                <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);
                                ?>
                                <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>
                                        <?php if (!empty($reg['specialization_name'])): ?>
                                            <span class="badge" style="background-color: #f3e8ff; color: #7e22ce;">
                                                <?= e($reg['specialization_name']) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="text-muted">—</span>
                                        <?php endif; ?>
                                    </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 ($payment_amount > 0): ?>
                                                <div class="fees-row">
                                                    <span class="fee-label">المبلغ المدفوع:</span>
                                                    <span class="fee-value fee-value-positive">-<?= number_format($payment_amount, 2) ?> SDG</span>
                                                </div>
                                                <?php else: ?>
                                                <div class="fees-row">
                                                    <span class="fee-label">المبلغ المدفوع:</span>
                                                    <span class="fee-value">0.00 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>
        // Function to load sections based on selected college
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            const specSelect = document.getElementById('filter_specialization');
            const specHint = document.getElementById('specHint');
            const loadingElement = document.getElementById('sectionLoading');
            
            if (!collegeId || collegeId === '') {
                sectionSelect.disabled = true;
                sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
                specSelect.disabled = true;
                specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                if (specHint) specHint.innerHTML = 'اختر القسم أو البرنامج أولاً';
                return;
            }
            
            // Reset section select
            sectionSelect.innerHTML = '<option value="">جاري تحميل الأقسام...</option>';
            sectionSelect.disabled = true;
            
            // 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 => {
                    sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
                    sections.forEach(section => {
                        const option = document.createElement('option');
                        option.value = section.id;
                        option.textContent = section.name;
                        <?php if ($filter_section_id): ?>
                        if (section.id == <?= $filter_section_id ?>) {
                            option.selected = true;
                        }
                        <?php endif; ?>
                        sectionSelect.appendChild(option);
                    });
                    
                    sectionSelect.disabled = false;
                    loadingElement.style.display = 'none';
                })
                .catch(error => {
                    console.error('Error loading sections:', error);
                    sectionSelect.innerHTML = '<option value="">خطأ في تحميل الأقسام</option>';
                    sectionSelect.disabled = false;
                    loadingElement.style.display = 'none';
                });
        }
        
        // Function to load specializations based on section and program
        function loadSpecializations() {
            const sectionId = document.getElementById('filter_section').value;
            const programId = document.getElementById('filter_program').value;
            const specSelect = document.getElementById('filter_specialization');
            const specHint = document.getElementById('specHint');
            const loadingElement = document.getElementById('specializationLoading');
            
            if (!sectionId || !programId) {
                specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                specSelect.disabled = true;
                if (specHint) specHint.innerHTML = 'اختر القسم أو البرنامج أولاً';
                return;
            }
            
            // Show loading
            specSelect.innerHTML = '<option value="">جاري تحميل التخصصات...</option>';
            specSelect.disabled = true;
            if (specHint) specHint.innerHTML = 'جاري تحميل التخصصات...';
            loadingElement.style.display = 'block';
            
            // Make AJAX request
            fetch(`extend_registration.php?ajax=get_specializations&section_id=${sectionId}&program_id=${programId}`)
                .then(response => response.json())
                .then(specializations => {
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    
                    if (specializations && specializations.length > 0) {
                        specializations.forEach(spec => {
                            const option = document.createElement('option');
                            option.value = spec.specialization_id;
                            option.textContent = spec.specialization_name_ar;
                            
                            <?php if ($filter_specialization_id): ?>
                            if (spec.specialization_id == <?= $filter_specialization_id ?>) {
                                option.selected = true;
                            }
                            <?php endif; ?>
                            
                            specSelect.appendChild(option);
                        });
                        if (specHint) specHint.innerHTML = `${specializations.length} تخصص متاح`;
                    } else {
                        if (specHint) specHint.innerHTML = 'لا توجد تخصصات متاحة';
                    }
                    
                    specSelect.disabled = false;
                    loadingElement.style.display = 'none';
                })
                .catch(error => {
                    console.error('Error loading specializations:', error);
                    specSelect.innerHTML = '<option value="">خطأ في تحميل التخصصات</option>';
                    specSelect.disabled = false;
                    loadingElement.style.display = 'none';
                    if (specHint) specHint.innerHTML = 'حدث خطأ في تحميل التخصصات';
                });
        }
        
        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 on page load
        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;
            }
            
            // Load sections if college is selected
            const collegeId = "<?= $filter_college_id ?>";
            if (collegeId && collegeId !== '') {
                loadSections(collegeId);
            }
            
            // Load specializations if section and program are selected
            const sectionId = "<?= $filter_section_id ?>";
            const programId = "<?= $filter_program_id ?>";
            if (sectionId && sectionId !== '' && programId && programId !== '') {
                setTimeout(() => {
                    loadSpecializations();
                }, 200);
            }
        });
    </script>
</body>
</html>
