<?php
// fee_discounts.php - STUDENT FEE DISCOUNTS MANAGEMENT SYSTEM (ADMIN ONLY)
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';

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

$mysqli1->set_charset('utf8mb4');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Initialize variables
$success_message = '';
$error_message = '';
$selected_students = [];
$bulk_update_mode = false;

// 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);
    $search_query = trim($_GET['search_query'] ?? '');
    $filter_only_unpaid = isset($_GET['only_unpaid']) ? 1 : 0;
} else {
    // Don't apply filters by default
    $filter_college_id = null;
    $filter_section_id = null;
    $filter_program_id = null;
    $filter_specialization_id = null;
    $filter_batch_id = null;
    $filter_semester_id = null;
    $search_query = '';
    $filter_only_unpaid = 0;
}

// Handle form submission for discount update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $error_message = 'رمز الأمان غير صالح. الرجاء تحديث الصفحة والمحاولة مرة أخرى.';
    } elseif (isset($_POST['apply_discounts'])) {
        $registration_ids = $_POST['registration_ids'] ?? [];
        $update_type = $_POST['update_type'] ?? 'individual';
        
        if (empty($registration_ids)) {
            $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();
                    
                    $updated_count = 0;
                    $errors = [];
                    
                    if ($update_type === 'bulk') {
                        // Bulk update for all selected registrations
                        $bulk_discount = isset($_POST['bulk_discount']) && $_POST['bulk_discount'] !== '' ? floatval($_POST['bulk_discount']) : 0;
                        
                        if ($bulk_discount < 0) {
                            throw new Exception('قيمة التخفيض يجب أن تكون موجبة');
                        }
                        
                        // Create placeholders for IN clause
                        $placeholders = implode(',', array_fill(0, count($valid_registration_ids), '?'));
                        $types = str_repeat('i', count($valid_registration_ids));
                        
                        // Get current registration details for all selected registrations
                        $current_stmt = $mysqli1->prepare("
                            SELECT r.id, r.student_id, r.study_fees, r.registration_fees, r.insurance_fees, 
                                   r.discount, r.payment_amount, r.is_paid
                            FROM registrations r
                            WHERE r.id IN ({$placeholders}) AND r.is_paid = 0 AND r.deleted_at IS NULL
                        ");
                        $current_stmt->bind_param($types, ...$valid_registration_ids);
                        $current_stmt->execute();
                        $current_regs = $current_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
                        $current_stmt->close();
                        
                        if (empty($current_regs)) {
                            throw new Exception('لا توجد دفعات غير مدفوعة صالحة');
                        }
                        
                        foreach ($current_regs as $current_reg) {
                            // Calculate new payment amount
                            $total_fees = $current_reg['study_fees'] + $current_reg['registration_fees'] + $current_reg['insurance_fees'];
                            $new_payment_amount = $total_fees - $bulk_discount;
                            
                            // Ensure payment amount is not negative
                            if ($new_payment_amount < 0) {
                                $errors[] = "التخفيض {$bulk_discount} أكبر من الرسوم الإجمالية للدفعة {$current_reg['id']}";
                                continue;
                            }
                            
                            // Update registration with discount
                            $update_stmt = $mysqli1->prepare("
                                UPDATE registrations 
                                SET discount = ?, payment_amount = ?, updated_at = NOW()
                                WHERE id = ? AND deleted_at IS NULL
                            ");
                            $update_stmt->bind_param(
                                "ddi",
                                $bulk_discount,
                                $new_payment_amount,
                                $current_reg['id']
                            );
                            
                            if ($update_stmt->execute()) {
                                $updated_count++;
                            } else {
                                $errors[] = "خطأ في تحديث الدفعة {$current_reg['id']}: " . $update_stmt->error;
                            }
                            
                            $update_stmt->close();
                        }
                        
                        if ($updated_count > 0) {
                            $success_message = "تم تطبيق تخفيض قدره {$bulk_discount} على {$updated_count} دفعة";
                            if (!empty($errors)) {
                                $success_message .= " (حدثت أخطاء في " . count($errors) . " دفعة)";
                            }
                        }
                        
                    } else {
                        // Individual update for each registration
                        foreach ($valid_registration_ids as $registration_id) {
                            // Check if discount was provided for this registration
                            if (!isset($_POST['discount'][$registration_id])) {
                                continue;
                            }
                            
                            $discount_amount = floatval($_POST['discount'][$registration_id]);
                            
                            if ($discount_amount < 0) {
                                $errors[] = "قيمة التخفيض للدفعة {$registration_id} يجب أن تكون موجبة";
                                continue;
                            }
                            
                            // Get current registration details
                            $current_stmt = $mysqli1->prepare("
                                SELECT r.id, r.student_id, r.study_fees, r.registration_fees, r.insurance_fees, 
                                       r.discount, r.payment_amount, r.is_paid
                                FROM registrations r
                                WHERE r.id = ? AND r.is_paid = 0 AND r.deleted_at IS NULL
                            ");
                            $current_stmt->bind_param("i", $registration_id);
                            $current_stmt->execute();
                            $current_reg = $current_stmt->get_result()->fetch_assoc();
                            $current_stmt->close();
                            
                            if (!$current_reg) {
                                $errors[] = "الدفعة {$registration_id} غير موجودة أو مدفوعة بالفعل";
                                continue;
                            }
                            
                            // Calculate new payment amount
                            $total_fees = $current_reg['study_fees'] + $current_reg['registration_fees'] + $current_reg['insurance_fees'];
                            $new_payment_amount = $total_fees - $discount_amount;
                            
                            // Ensure payment amount is not negative
                            if ($new_payment_amount < 0) {
                                $errors[] = "التخفيض {$discount_amount} أكبر من الرسوم الإجمالية للدفعة {$registration_id}";
                                continue;
                            }
                            
                            // Update registration with discount
                            $update_stmt = $mysqli1->prepare("
                                UPDATE registrations 
                                SET discount = ?, payment_amount = ?, updated_at = NOW()
                                WHERE id = ? AND deleted_at IS NULL
                            ");
                            $update_stmt->bind_param(
                                "ddi",
                                $discount_amount,
                                $new_payment_amount,
                                $registration_id
                            );
                            
                            if ($update_stmt->execute()) {
                                $updated_count++;
                            } else {
                                $errors[] = "خطأ في تحديث الدفعة {$registration_id}: " . $update_stmt->error;
                            }
                            
                            $update_stmt->close();
                        }
                        
                        if ($updated_count > 0) {
                            $success_message = "تم تطبيق التخفيضات على {$updated_count} دفعة بنجاح";
                            if (!empty($errors)) {
                                $success_message .= " (حدثت أخطاء في " . count($errors) . " دفعة)";
                            }
                        }
                    }
                    
                    // Commit transaction
                    $mysqli1->commit();
                    
                } catch (Exception $e) {
                    // Rollback transaction on error
                    $mysqli1->rollback();
                    $error_message = "حدث خطأ أثناء تطبيق التخفيضات: " . $e->getMessage();
                    error_log("Discount Update Error: " . $e->getMessage());
                }
            }
        }
    }
}

// Get registrations for filtered students
$registrations = [];
if ($filters_applied) {
    // Build WHERE clause for students
    $where_students = " WHERE s.deleted_at IS NULL ";
    $student_types = ''; 
    $student_params = [];
    
    // Apply filters with validated integers
    if ($filter_college_id !== null) {
        $where_students .= " AND s.college_id = ? ";
        $student_types .= 'i'; 
        $student_params[] = $filter_college_id;
    }

    if ($filter_section_id !== null) {
        $where_students .= " AND s.section_id = ? ";
        $student_types .= 'i'; 
        $student_params[] = $filter_section_id;
    }

    if ($filter_program_id !== null) {
        $where_students .= " AND s.program_id = ? ";
        $student_types .= 'i'; 
        $student_params[] = $filter_program_id;
    }

    // Apply specialization filter
    if ($filter_specialization_id !== null) {
        $where_students .= " AND s.specialization_id = ? ";
        $student_types .= 'i'; 
        $student_params[] = $filter_specialization_id;
    }

    if ($filter_batch_id !== null) {
        $where_students .= " AND s.batch_id = ? ";
        $student_types .= 'i'; 
        $student_params[] = $filter_batch_id;
    }

    // Apply search query if provided - using LIKE with prepared statements
    if (!empty($search_query)) {
        $where_students .= " AND (s.student_id LIKE ? OR s.student_name LIKE ? OR s.student_name_eng LIKE ?) ";
        $student_types .= 'sss';
        $search_param = "%" . $search_query . "%";
        $student_params[] = $search_param;
        $student_params[] = $search_param;
        $student_params[] = $search_param;
    }
    
    // Build the main query to get registrations
    $sqlRegistrations = "
        SELECT 
            r.id AS registration_id,
            r.student_id,
            r.semester_id,
            r.study_fees,
            r.registration_fees,
            r.insurance_fees,
            r.discount,
            r.payment_amount,
            r.is_paid,
            r.created_at,
            r.updated_at,
            r.payment_reference,
            s.student_name,
            s.student_name_eng,
            s.college_id,
            s.section_id,
            s.program_id,
            s.specialization_id,
            s.batch_id,
            s.email,
            s.phone_number,
            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,
            sem.name AS semester_name,
            sem.code AS semester_code
        FROM students s
        INNER JOIN registrations r ON s.student_id = r.student_id
        LEFT JOIN colleges c ON s.college_id = c.id
        LEFT JOIN sections sec ON s.section_id = sec.id
        LEFT JOIN programs p ON s.program_id = p.id
        LEFT JOIN specializations sp ON s.specialization_id = sp.specialization_id
        LEFT JOIN batches b ON s.batch_id = b.id
        LEFT JOIN semesters sem ON r.semester_id = sem.id
        {$where_students}
        AND r.deleted_at IS NULL
    ";
    
    // Add semester filter if applied
    if ($filter_semester_id !== null) {
        $sqlRegistrations .= " AND r.semester_id = ? ";
        $student_types .= 'i'; 
        $student_params[] = $filter_semester_id;
    }
    
    // Add unpaid filter if requested
    if ($filter_only_unpaid) {
        $sqlRegistrations .= " AND r.is_paid = 0 ";
    }
    
    // Order by and limit
    $sqlRegistrations .= " ORDER BY r.created_at DESC, r.student_id DESC LIMIT 500";
    
    try {
        $reg_stmt = $mysqli1->prepare($sqlRegistrations);
        if ($student_types) {
            $reg_stmt->bind_param($student_types, ...$student_params);
        }
        $reg_stmt->execute();
        $registrations = $reg_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $reg_stmt->close();
    } catch (Exception $e) {
        $error_message = "خطأ في جلب البيانات: " . $e->getMessage();
        error_log("Registration Fetch Error: " . $e->getMessage());
    }
}

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

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

// Get all sections (for initial load)
$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 programs
$programs = [];
if ($filter_college_id !== null) {
    $programs_where = "p.deleted_at IS NULL";
    $programs_params = [];
    $programs_types = "";
    
    if ($filter_section_id !== null) {
        $programs_where .= " AND st.section_id = ?";
        $programs_types .= "i";
        $programs_params[] = $filter_section_id;
    }
    
    $programs_where .= " AND st.college_id = ?";
    $programs_types .= "i";
    $programs_params[] = $filter_college_id;
    
    $programs_sql = "
        SELECT DISTINCT p.id, p.name 
        FROM programs p 
        INNER JOIN students st ON p.id = st.program_id 
        WHERE {$programs_where} 
        ORDER BY p.name
    ";
    
    $programs_stmt = $mysqli1->prepare($programs_sql);
    if ($programs_types) {
        $programs_stmt->bind_param($programs_types, ...$programs_params);
    }
    $programs_stmt->execute();
    $programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $programs_stmt->close();
} else {
    $programs_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
    $programs_stmt->execute();
    $programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $programs_stmt->close();
}

// Get specializations based on selected section and program
$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();
    $specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
} elseif ($filter_section_id !== null) {
    // Get specializations by section only
    $specializations_sql = "
        SELECT DISTINCT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    $specializations_stmt->bind_param("i", $filter_section_id);
    $specializations_stmt->execute();
    $specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
} elseif ($filter_program_id !== null) {
    // Get specializations by program only
    $specializations_sql = "
        SELECT DISTINCT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    $specializations_stmt->bind_param("i", $filter_program_id);
    $specializations_stmt->execute();
    $specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
}

$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 semesters for filter
$semesters_stmt = $mysqli1->prepare("SELECT id, name, code FROM semesters ORDER BY id DESC");
$semesters_stmt->execute();
$semesters = $semesters_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$semesters_stmt->close();

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة تخفيضات الرسوم - لوحة مدير النظام</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body, h1,h2,h3,h4,h5,h6, p, a, button, label { 
            font-family: 'Cairo', sans-serif !important; 
        }
        .card-arabic {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        .filter-icon {
            width: 40px;
            height: 40px;
            background: #3b82f6;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.1rem;
        }
        .student-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        .checkbox-cell {
            width: 50px;
            text-align: center;
        }
        .batch-badge {
            font-size: 0.75rem;
        }
        .discount-input {
            min-width: 80px;
            max-width: 100px;
            width: 100px;
        }
        .payment-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.4rem;
        }
        .paid-badge {
            background-color: #10b981;
            color: white;
        }
        .unpaid-badge {
            background-color: #ef4444;
            color: white;
        }
        .partial-badge {
            background-color: #f59e0b;
            color: white;
        }
        .admin-badge {
            background-color: #8b5cf6;
            color: white;
        }
        .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;
        }
        .warning-message {
            background-color: #fef3c7;
            border: 1px solid #fde68a;
            color: #92400e;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .update-type-selector {
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .update-type-selector.active {
            border-color: #3b82f6;
            background-color: #eff6ff;
        }
        .form-check-input:checked {
            background-color: #3b82f6;
            border-color: #3b82f6;
        }
        .total-discount-display {
            background: linear-gradient(135deg, #f97316 0%, #ea580c 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
        }
        .discount-summary-card {
            border-left: 4px solid #f59e0b;
        }
        .date-display {
            font-size: 0.75rem;
            color: #6c757d;
        }
        .semester-badge {
            background-color: #8b5cf6;
            color: white;
            font-size: 0.7rem;
        }
        .reference-badge {
            background-color: #06b6d4;
            color: white;
            font-size: 0.7rem;
        }
        .specialization-badge {
            background-color: #f3e8ff;
            color: #7e22ce;
            font-size: 0.7rem;
            border: 1px solid #e9d5ff;
        }
        .filter-badge.specialization {
            background-color: #f3e8ff;
            color: #7e22ce;
            border: 1px solid #e9d5ff;
        }
        tr.unselected {
            background-color: #f8f9fa;
            opacity: 0.7;
        }
        tr.selected {
            background-color: #e8f5e9;
        }
        tr.paid-row {
            background-color: #f0fdf4;
        }
        .registration-checkbox:checked {
            accent-color: #3b82f6;
        }
        .selected-count-badge {
            font-size: 0.8rem;
            padding: 0.3rem 0.6rem;
        }
        .discount-preview {
            font-size: 0.8rem;
            color: #059669;
            font-weight: bold;
        }
        .original-amount {
            text-decoration: line-through;
            color: #6b7280;
            font-size: 0.75rem;
        }
        .filter-row {
            margin-bottom: 10px;
        }
        .table-actions {
            min-width: 100px;
        }
        .discount-input.is-invalid {
            border-color: #dc3545;
            box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
        }
        .filter-summary-badge.specialization {
            background: #f3e8ff;
            color: #7e22ce;
        }
        .filter-summary {
            background-color: #f8fafc;
            border: 1px solid #e2e8f0;
        }
        .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">
                <i class="fas fa-percentage me-2"></i>
                إدارة تخفيضات رسوم الطلاب
            </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; ?>

        <!-- 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">
                <!-- Hidden field to indicate filters were applied -->
                <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>
                            <div class="input-group input-group-sm">
                                <select class="form-control border-end-0" name="filter_college" id="filter_college" onchange="loadSections(this.value)">
                                    <option value="">اختر الكلية</option>
                                    <?php foreach ($colleges as $college): ?>
                                        <option value="<?= $college['id'] ?>" <?= ($filter_college_id == $college['id']) ? 'selected' : '' ?>>
                                            <?= e($college['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <span class="input-group-text bg-light border-start-0">
                                    <i class="fas fa-building"></i>
                                </span>
                            </div>
                        </div>
                    </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="input-group input-group-sm">
                                <select class="form-control border-end-0" name="filter_section" id="filter_section" onchange="loadSpecializations()" <?= !$filter_college_id ? 'disabled' : '' ?>>
                                    <option value="">جميع الأقسام</option>
                                    <?php if ($filter_college_id && !empty($sections)): ?>
                                        <?php foreach ($sections as $section): ?>
                                            <option value="<?= $section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                                <?= e($section['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                                <span class="input-group-text bg-light border-start-0">
                                    <i class="fas fa-building"></i>
                                </span>
                            </div>
                            <?php if (!$filter_college_id): ?>
                                <small class="text-muted">الرجاء اختيار كلية أولاً</small>
                            <?php endif; ?>
                        </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>
                            <div class="input-group input-group-sm">
                                <select class="form-control border-end-0" name="filter_program" id="filter_program" onchange="loadSpecializations()">
                                    <option value="">جميع البرامج</option>
                                    <?php foreach ($programs as $program): ?>
                                        <option value="<?= $program['id'] ?>" <?= ($filter_program_id == $program['id']) ? 'selected' : '' ?>>
                                            <?= e($program['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <span class="input-group-text bg-light border-start-0">
                                    <i class="fas fa-book"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 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="input-group input-group-sm">
                                <select class="form-control border-end-0" name="filter_specialization" id="filter_specialization" <?= (!$filter_section_id && !$filter_program_id) ? 'disabled' : '' ?>>
                                    <option value="">جميع التخصصات</option>
                                    <?php if (!empty($specializations)): ?>
                                        <?php foreach ($specializations as $spec): ?>
                                            <option value="<?= $spec['specialization_id'] ?>" <?= ($filter_specialization_id == $spec['specialization_id']) ? 'selected' : '' ?>>
                                                <?= e($spec['specialization_name_ar']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                                <span class="input-group-text bg-light border-start-0">
                                    <i class="fas fa-microscope"></i>
                                </span>
                            </div>
                            <small class="text-muted" id="specHint">
                                <?php if (!$filter_section_id && !$filter_program_id): ?>
                                    اختر القسم أو البرنامج أولاً
                                <?php endif; ?>
                            </small>
                        </div>
                    </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>
                            <div class="input-group input-group-sm">
                                <select class="form-control border-end-0" name="filter_batch">
                                    <option value="">جميع الدفعات</option>
                                    <?php foreach ($batches as $batch): ?>
                                        <option value="<?= $batch['id'] ?>" <?= ($filter_batch_id == $batch['id']) ? 'selected' : '' ?>>
                                            <?= e($batch['value']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <span class="input-group-text bg-light border-start-0">
                                    <i class="fas fa-calendar-alt"></i>
                                </span>
                            </div>
                        </div>
                    </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 me-1"></i>
                                الفصل الدراسي
                            </label>
                            <div class="input-group input-group-sm">
                                <select class="form-control border-end-0" name="filter_semester" id="filter_semester">
                                    <option value="">جميع الفصول الدراسية</option>
                                    <?php foreach ($semesters as $semester): ?>
                                        <option value="<?= $semester['id'] ?>" <?= ($filter_semester_id == $semester['id']) ? 'selected' : '' ?>>
                                            <?= e($semester['name']) ?> (<?= e($semester['code']) ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <span class="input-group-text bg-light border-start-0">
                                    <i class="fas fa-calendar-alt"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Second Row - Search and Unpaid Filter -->
                <div class="row">
                    <!-- Search Field -->
                    <div class="col-lg-8 col-md-8 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="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>
                        </div>
                    </div>
                    
                    <!-- Unpaid Filter -->
                    <div class="col-lg-4 col-md-4 mb-3">
                        <div class="form-group">
                            <label class="form-label fw-semibold text-muted mb-2">
                                <i class="fas fa-money-bill-wave me-1"></i>
                                خيارات إضافية
                            </label>
                            <div class="form-check form-switch mt-2">
                                <input class="form-check-input" type="checkbox" 
                                       name="only_unpaid" id="only_unpaid" 
                                       value="1" <?= $filter_only_unpaid ? 'checked' : '' ?>>
                                <label class="form-check-label" for="only_unpaid">
                                    عرض الدفعات غير المدفوعة فقط
                                </label>
                            </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="fee_discounts.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 ($filter_only_unpaid): ?>
                                        <i class="fas fa-money-bill-wave 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): ?>
                        <?php 
                        $selected_college = null;
                        foreach ($colleges as $college) {
                            if ($college['id'] == $filter_college_id) {
                                $selected_college = $college;
                                break;
                            }
                        }
                        ?>
                        <?php if ($selected_college): ?>
                            <span class="badge bg-primary filter-badge">
                                <i class="fas fa-university me-1"></i>
                                <?= e($selected_college['name']) ?>
                            </span>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php if ($filter_section_id !== null): ?>
                        <?php 
                        $selected_section = null;
                        $search_sections = $filter_college_id ? $sections : $all_sections;
                        foreach ($search_sections as $section) {
                            if ($section['id'] == $filter_section_id) {
                                $selected_section = $section;
                                break;
                            }
                        }
                        ?>
                        <?php if ($selected_section): ?>
                            <span class="badge bg-info filter-badge">
                                <i class="fas fa-layer-group me-1"></i>
                                <?= e($selected_section['name']) ?>
                            </span>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php if ($filter_program_id !== null): ?>
                        <?php 
                        $selected_program = null;
                        foreach ($programs as $program) {
                            if ($program['id'] == $filter_program_id) {
                                $selected_program = $program;
                                break;
                            }
                        }
                        ?>
                        <?php if ($selected_program): ?>
                            <span class="badge bg-success filter-badge">
                                <i class="fas fa-graduation-cap me-1"></i>
                                <?= e($selected_program['name']) ?>
                            </span>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <!-- Specialization summary -->
                    <?php if ($filter_specialization_id !== null && !empty($specializations)): ?>
                        <?php 
                        $selected_spec = null;
                        foreach ($specializations as $spec) {
                            if ($spec['specialization_id'] == $filter_specialization_id) {
                                $selected_spec = $spec;
                                break;
                            }
                        }
                        ?>
                        <?php if ($selected_spec): ?>
                            <span class="badge filter-badge" style="background-color: #f3e8ff; color: #7e22ce; border: 1px solid #e9d5ff;">
                                <i class="fas fa-microscope me-1"></i>
                                <?= e($selected_spec['specialization_name_ar']) ?>
                            </span>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php if ($filter_batch_id !== null): ?>
                        <?php 
                        $selected_batch = null;
                        foreach ($batches as $batch) {
                            if ($batch['id'] == $filter_batch_id) {
                                $selected_batch = $batch;
                                break;
                            }
                        }
                        ?>
                        <?php if ($selected_batch): ?>
                            <span class="badge bg-warning filter-badge">
                                <i class="fas fa-users me-1"></i>
                                <?= e($selected_batch['value']) ?>
                            </span>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php if ($filter_semester_id !== null): ?>
                        <?php 
                        $selected_semester = null;
                        foreach ($semesters as $semester) {
                            if ($semester['id'] == $filter_semester_id) {
                                $selected_semester = $semester;
                                break;
                            }
                        }
                        ?>
                        <?php if ($selected_semester): ?>
                            <span class="badge bg-secondary filter-badge">
                                <i class="fas fa-calendar-alt me-1"></i>
                                <?= e($selected_semester['name']) ?>
                            </span>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php if ($filter_only_unpaid): ?>
                        <span class="badge bg-danger filter-badge">
                            <i class="fas fa-money-bill-wave me-1"></i>
                            غير مدفوعة فقط
                        </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_only_unpaid): ?>
                        <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>

        <!-- Update Type Selector -->
        <?php if ($filters_applied && !empty($registrations)): ?>
        <div class="card card-arabic p-4 mb-4">
            <h6 class="fw-bold mb-3">طريقة التعديل</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="update-type-selector <?= !$bulk_update_mode ? 'active' : '' ?>" onclick="setUpdateType('individual')">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="update_type" id="updateTypeIndividual" 
                                   value="individual" <?= !$bulk_update_mode ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="updateTypeIndividual">
                                <i class="fas fa-user-edit me-2"></i>
                                تعديل فردي لكل دفعة
                            </label>
                            <p class="text-muted small mt-2 mb-0">
                                يمكنك إدخال تخفيض مختلف لكل دفعة في الجدول أدناه
                            </p>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="update-type-selector <?= $bulk_update_mode ? 'active' : '' ?>" onclick="setUpdateType('bulk')">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="update_type" id="updateTypeBulk" 
                                   value="bulk" <?= $bulk_update_mode ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="updateTypeBulk">
                                <i class="fas fa-users-cog me-2"></i>
                                تطبيق تخفيض موحد
                            </label>
                            <p class="text-muted small mt-2 mb-0">
                                تطبيق نفس قيمة التخفيض على جميع الدفعات المحددة
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Bulk Update Form -->
        <?php if ($filters_applied && !empty($registrations)): ?>
        <div class="card card-arabic p-4 mb-4" id="bulkUpdateForm" style="<?= !$bulk_update_mode ? 'display: none;' : '' ?>">
            <h6 class="fw-bold mb-3">
                <i class="fas fa-users-cog me-2"></i>
                تطبيق تخفيض موحد
            </h6>
            
            <div class="warning-message mb-3">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <strong>تنبيه:</strong> سيتم تطبيق قيمة التخفيض التالية على جميع الدفعات المحددة. سيتم تلقائياً تحديث مبلغ الدفع بناءً على التخفيض.
            </div>
            
            <form method="post" id="bulkUpdateFormContent">
                <!-- CSRF Token -->
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                
                <div class="row g-3 mb-4">
                    <div class="col-md-12">
                        <label class="form-label fw-semibold">قيمة التخفيض الموحد:</label>
                        <div class="input-group">
                            <input type="number" class="form-control" name="bulk_discount" 
                                   step="0.01" min="0" value="0" required>
                            <span class="input-group-text">SDG</span>
                        </div>
                        <small class="text-muted">سيتم خصم هذا المبلغ من الرسوم الإجمالية لكل دفعة</small>
                    </div>
                </div>
                
                <!-- Hidden registration IDs -->
                <div id="bulkRegistrationIds"></div>
                
                <!-- Action Buttons -->
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <span class="badge bg-info">
                            <i class="fas fa-info-circle me-1"></i>
                            سيتم تطبيق التخفيض على <span id="bulkSelectedCount">0</span> دفعة
                        </span>
                    </div>
                    <div>
                        <button type="button" class="btn btn-secondary me-2" onclick="showUpdateForm()">
                            <i class="fas fa-arrow-right me-1"></i>
                            العودة للتعديل الفردي
                        </button>
                        <button type="button" class="btn btn-success" onclick="submitBulkUpdate()">
                            <i class="fas fa-check-circle me-1"></i>
                            تطبيق التخفيض الموحد
                        </button>
                    </div>
                </div>
            </form>
        </div>
        <?php endif; ?>

        <!-- Discount Update Form -->
        <?php if ($filters_applied && !empty($registrations)): ?>
        <div class="card card-arabic p-4 mb-4" id="updateForm" style="<?= $bulk_update_mode ? 'display: none;' : '' ?>">
            <form method="post" id="discountUpdateForm">
                <!-- CSRF Token -->
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                
                <!-- Action Buttons with Selected Count -->
                <div class="row g-3 align-items-end mb-3">
                    <div class="col-md-6">
                        <div class="d-flex gap-2 align-items-center">
                            <button type="button" class="btn btn-outline-primary" onclick="selectAllUnpaid()">
                                <i class="fas fa-check-square me-1"></i>تحديد غير المدفوعة
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="deselectAllStudents()">
                                <i class="fas fa-times-circle me-1"></i>إلغاء الكل
                            </button>
                            <button type="button" class="btn btn-info" onclick="showBulkUpdate()">
                                <i class="fas fa-users-cog me-1"></i>تخفيض موحد
                            </button>
                            <span id="selectedCountBadge" class="badge bg-primary selected-count-badge">
                                0 مختار
                            </span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex justify-content-end">
                            <button type="submit" name="apply_discounts" class="btn btn-success">
                                <i class="fas fa-percentage me-1"></i>تطبيق التخفيضات للدفعات المحددة
                            </button>
                        </div>
                        <div class="text-muted small text-end mt-1">
                            <i class="fas fa-shield-alt me-1"></i>
                            <strong>مدير النظام:</strong> <?= e($_SESSION['user_name'] ?? '') ?>
                        </div>
                    </div>
                </div>
                
                <!-- Hidden field for update type -->
                <input type="hidden" name="update_type" value="individual">
                
                <!-- Registrations Table with Specialization Column -->
                <div class="table-responsive mt-4">
                    <table class="table table-striped student-table">
                        <thead>
                            <tr>
                                <th class="checkbox-cell">
                                    <input type="checkbox" id="selectAll" onchange="toggleAllStudents(this)">
                                </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
                                // Calculate totals
                                $study_fees = !empty($reg['study_fees']) ? floatval($reg['study_fees']) : 0.0;
                                $registration_fees = !empty($reg['registration_fees']) ? floatval($reg['registration_fees']) : 0.0;
                                $insurance_fees = !empty($reg['insurance_fees']) ? floatval($reg['insurance_fees']) : 0.0;
                                $total_fees = $study_fees + $registration_fees + $insurance_fees;
                                
                                $discount = !empty($reg['discount']) ? floatval($reg['discount']) : 0.0;
                                $payment_amount = !empty($reg['payment_amount']) ? floatval($reg['payment_amount']) : $total_fees;
                                
                                // Handle null dates safely
                                $created_at = !empty($reg['created_at']) ? date('Y-m-d H:i', strtotime($reg['created_at'])) : '';
                                $updated_at = !empty($reg['updated_at']) ? date('Y-m-d H:i', strtotime($reg['updated_at'])) : '';
                                
                                // Determine row class
                                $row_class = $reg['is_paid'] == 1 ? 'paid-row' : 'unselected';
                                $is_paid = $reg['is_paid'] == 1;
                                $is_disabled = $is_paid ? 'disabled' : '';
                                
                                // Prepare data for JavaScript
                                $total_fees_for_js = $total_fees;
                                $total_fees_display = number_format($total_fees, 2);
                                ?>
                                <tr class="<?= $row_class ?>" id="row-<?= $reg['registration_id'] ?>">
                                    <td class="checkbox-cell">
                                        <input type="checkbox" name="registration_ids[]" 
                                               value="<?= e($reg['registration_id']) ?>" 
                                               class="registration-checkbox" 
                                               data-paid="<?= $is_paid ? '1' : '0' ?>"
                                               <?= $is_paid ? 'disabled' : '' ?>>
                                    </td>
                                    <td class="text-muted"><?= $counter++ ?></td>
                                    <td>
                                        <code><?= e($reg['student_id']) ?></code>
                                    </td>
                                    <td>
                                        <?= e($reg['student_name']) ?>
                                        <?php if ($reg['student_name_eng']): ?>
                                            <br><small class="text-muted"><?= e($reg['student_name_eng']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= e($reg['college_name']) ?></td>
                                   
                                    <td>
                                        <?php if (!empty($reg['specialization_name'])): ?>
                                            <span class="badge specialization-badge">
                                                <i class="fas fa-microscope me-1"></i>
                                                <?= e($reg['specialization_name']) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="text-muted">—</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge semester-badge">
                                            <?= e($reg['semester_name']) ?>
                                            <?php if ($reg['semester_code']): ?>
                                                <br><small class="text-white"><?= e($reg['semester_code']) ?></small>
                                            <?php endif; ?>
                                        </span>
                                    </td>
                                 
                                    <td>
                                        <span class="badge bg-secondary payment-badge" data-original-fees="<?= $total_fees_for_js ?>">
                                            <?= $total_fees_display ?> SDG
                                        </span>
                                        <div class="small text-muted">
                                            دراسة: <?= number_format($study_fees, 2) ?><br>
                                            تسجيل: <?= number_format($registration_fees, 2) ?><br>
                                            تأمين: <?= number_format($insurance_fees, 2) ?>
                                        </div>
                                    </td>
                                    <td>
                                        <?php if ($is_paid): ?>
                                            <span class="badge bg-secondary">
                                                <?= number_format($discount, 2) ?> SDG
                                            </span>
                                            <div class="small text-muted">مدفوعة</div>
                                        <?php else: ?>
                                            <input type="number" 
                                                   class="form-control form-control-sm discount-input" 
                                                   name="discount[<?= e($reg['registration_id']) ?>]" 
                                                   value="<?= number_format($discount, 2, '.', '') ?>" 
                                                   step="0.01" 
                                                   min="0" 
                                                   max="<?= $total_fees ?>"
                                                   oninput="updatePaymentPreview(<?= $reg['registration_id'] ?>, this.value, <?= $total_fees_for_js ?>)"
                                                   required>
                                            <small class="text-muted">الحد الأقصى: <?= $total_fees_display ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td id="payment-preview-<?= $reg['registration_id'] ?>">
                                        <?php if ($is_paid): ?>
                                            <span class="badge paid-badge">
                                                <?= number_format($payment_amount, 2) ?> SDG
                                            </span>
                                        <?php else: ?>
                                            <span class="badge unpaid-badge">
                                                <?= number_format($payment_amount, 2) ?> SDG
                                            </span>
                                            <div class="discount-preview">
                                                تخفيض: <?= number_format($discount, 2) ?> SDG
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($is_paid): ?>
                                            <span class="badge paid-badge">
                                                <i class="fas fa-check-circle me-1"></i>مدفوعة
                                            </span>
                                        <?php else: ?>
                                            <span class="badge unpaid-badge">
                                                <i class="fas fa-clock me-1"></i>غير مدفوعة
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                                                      
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </form>
        </div>
        
        <!-- Discount Summary -->
        <div class="card card-arabic p-4 discount-summary-card">
            <div class="row">
                <div class="col-md-3">
                    <div class="total-discount-display text-center">
                        <div class="small">إجمالي التخفيضات</div>
                        <h4 class="fw-bold mb-0" id="totalDiscountDisplay">0.0 SDG</h4>
                        <small>لجميع الدفعات المحددة</small>
                    </div>
                </div>
                <div class="col-md-9">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="text-center p-3">
                                <div class="text-muted small mb-1">الرسوم الإجمالية</div>
                                <div class="h5 fw-bold text-info" id="totalOriginalFees">0.0</div>
                                <small class="text-muted">SDG</small>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="text-center p-3">
                                <div class="text-muted small mb-1">إجمالي الدفع بعد التخفيض</div>
                                <div class="h5 fw-bold text-success" id="totalPaymentAfterDiscount">0.0</div>
                                <small class="text-muted">SDG</small>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="text-center p-3">
                                <div class="text-muted small mb-1">متوسط نسبة التخفيض</div>
                                <div class="h5 fw-bold text-warning" id="averageDiscountPercentage">0.0%</div>
                                <small class="text-muted">من الرسوم الإجمالية</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php elseif ($filters_applied && empty($registrations)): ?>
            <div class="card card-arabic p-5 text-center">
                <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">لا يوجد دفعات</h5>
                <p class="text-muted mb-0">
                    <?php if (!empty($search_query)): ?>
                        لم يتم العثور على دفعات بناءً على عوامل التصفية المحددة والبحث: "<?= e($search_query) ?>"
                    <?php elseif ($filter_only_unpaid): ?>
                        لا توجد دفعات غير مدفوعة بناءً على عوامل التصفية المحددة
                    <?php else: ?>
                        لم يتم العثور على دفعات بناءً على عوامل التصفية المحددة
                    <?php endif; ?>
                </p>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // تخزين جميع التخصصات للاستخدام في AJAX
        const allSpecializations = <?= json_encode($specializations) ?>;
        
        // 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');
            
            if (!collegeId || collegeId === '') {
                sectionSelect.disabled = true;
                sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
                specSelect.disabled = true;
                specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                if (specHint) specHint.innerHTML = 'اختر القسم أو البرنامج أولاً';
                return;
            }
            
            // Submit the form to reload with new college
            const form = document.getElementById('filterForm');
            form.submit();
        }
        
        // 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');
            
            if (!sectionId && !programId) {
                specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                specSelect.disabled = true;
                if (specHint) specHint.innerHTML = 'اختر القسم أو البرنامج أولاً';
                return;
            }
            
            // Build query string
            let url = 'ajax/get_specializations.php?';
            if (sectionId) url += `section_id=${encodeURIComponent(sectionId)}&`;
            if (programId) url += `program_id=${encodeURIComponent(programId)}`;
            
            // Show loading
            specSelect.innerHTML = '<option value="">جاري التحميل...</option>';
            specSelect.disabled = false;
            if (specHint) specHint.innerHTML = 'جاري تحميل التخصصات...';
            
            // Fetch specializations via AJAX
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    
                    if (data && data.length > 0) {
                        data.forEach(spec => {
                            const option = document.createElement('option');
                            option.value = spec.specialization_id;
                            option.textContent = spec.specialization_name_ar;
                            
                            // Check if this specialization was previously selected
                            const urlParams = new URLSearchParams(window.location.search);
                            const selectedSpec = urlParams.get('filter_specialization');
                            if (selectedSpec && selectedSpec == spec.specialization_id) {
                                option.selected = true;
                            }
                            
                            specSelect.appendChild(option);
                        });
                        if (specHint) specHint.innerHTML = `${data.length} تخصص متاح`;
                    } else {
                        if (specHint) specHint.innerHTML = 'لا توجد تخصصات متاحة';
                    }
                    
                    specSelect.disabled = false;
                })
                .catch(error => {
                    console.error('Error loading specializations:', error);
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    specSelect.disabled = false;
                    if (specHint) specHint.innerHTML = 'حدث خطأ في تحميل التخصصات';
                });
        }
        
        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            // Initially all rows are unselected
            document.querySelectorAll('.registration-checkbox').forEach(checkbox => {
                checkbox.checked = false;
            });
            document.getElementById('selectAll').checked = false;
            calculateTotals();
            
            // Initialize payment previews for unpaid registrations
            document.querySelectorAll('.discount-input').forEach(input => {
                const nameAttr = input.getAttribute('name');
                const registrationId = nameAttr.match(/\[(\d+)\]/)[1];
                const row = input.closest('tr');
                const feesBadge = row.querySelector('.badge.bg-secondary.payment-badge');
                
                if (feesBadge) {
                    const originalFees = feesBadge.getAttribute('data-original-fees') ? 
                        parseFloat(feesBadge.getAttribute('data-original-fees')) : 
                        parseFloat(feesBadge.textContent.replace('SDG', '').trim().replace(/,/g, '')) || 0;
                    
                    const discount = parseFloat(input.value) || 0;
                    
                    updatePaymentPreview(registrationId, discount, originalFees);
                }
            });
            
            // Load specializations if section or program is selected
            const sectionId = document.getElementById('filter_section')?.value;
            const programId = document.getElementById('filter_program')?.value;
            
            if ((sectionId || programId) && sectionId !== '' && programId !== '') {
                setTimeout(() => {
                    loadSpecializations();
                }, 100);
            }
        });
        
        function toggleAllStudents(selectAll) {
            const checkboxes = document.querySelectorAll('.registration-checkbox:not(:disabled)');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
                updateRowSelection(checkbox);
            });
            calculateTotals();
        }
        
        function selectAllUnpaid() {
            const checkboxes = document.querySelectorAll('.registration-checkbox:not(:disabled)');
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
                updateRowSelection(checkbox);
            });
            document.getElementById('selectAll').checked = true;
            calculateTotals();
        }
        
        function deselectAllStudents() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
                updateRowSelection(checkbox);
            });
            document.getElementById('selectAll').checked = false;
            calculateTotals();
        }
        
        function updateRowSelection(checkbox) {
            const row = checkbox.closest('tr');
            if (row) {
                if (checkbox.checked) {
                    row.classList.remove('unselected');
                    row.classList.add('selected');
                } else {
                    row.classList.remove('selected');
                    const isPaid = checkbox.getAttribute('data-paid') === '1';
                    row.classList.add(isPaid ? 'paid-row' : 'unselected');
                }
            }
        }
        
        document.querySelectorAll('.registration-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                updateRowSelection(this);
                
                const allCheckboxes = document.querySelectorAll('.registration-checkbox:not(:disabled)');
                const allChecked = document.querySelectorAll('.registration-checkbox:not(:disabled):checked').length === allCheckboxes.length;
                document.getElementById('selectAll').checked = allChecked;
                calculateTotals();
            });
        });
        
        function updatePaymentPreview(registrationId, discount, totalFees) {
            discount = parseFloat(discount) || 0;
            totalFees = typeof totalFees === 'string' ? 
                        parseFloat(totalFees.replace(/,/g, '')) || 0 : 
                        totalFees || 0;
            
            if (discount > totalFees) {
                discount = totalFees;
                const input = document.querySelector(`input[name="discount[${registrationId}]"]`);
                if (input) input.value = discount.toFixed(2);
            }
            
            const paymentAmount = totalFees - discount;
            
            const previewElement = document.getElementById(`payment-preview-${registrationId}`);
            if (previewElement) {
                const formatNumber = (num) => {
                    return num.toLocaleString('en-US', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                };
                
                previewElement.innerHTML = `
                    <span class="badge ${paymentAmount > 0 ? 'unpaid-badge' : 'paid-badge'}">
                        ${formatNumber(paymentAmount)} SDG
                    </span>
                    <div class="discount-preview">
                        تخفيض: ${formatNumber(discount)} SDG
                    </div>
                    ${discount > 0 ? `<div class="original-amount">${formatNumber(totalFees)} SDG</div>` : ''}
                `;
            }
            
            calculateTotals();
        }
        
        function calculateTotals() {
            let totalOriginalFees = 0;
            let totalDiscount = 0;
            let totalPaymentAfterDiscount = 0;
            let selectedCount = 0;
            
            document.querySelectorAll('.registration-checkbox:checked:not(:disabled)').forEach(checkbox => {
                selectedCount++;
                const row = checkbox.closest('tr');
                const registrationId = row.id.replace('row-', '');
                
                const discountInput = row.querySelector(`input[name="discount[${registrationId}]"]`);
                let discount = 0;
                
                if (discountInput) {
                    discount = parseFloat(discountInput.value) || 0;
                } else {
                    const discountSpan = row.querySelector('td:nth-child(11) .badge.bg-secondary');
                    if (discountSpan) {
                        const discountText = discountSpan.textContent.replace('SDG', '').trim().replace(/,/g, '');
                        discount = parseFloat(discountText) || 0;
                    }
                }
                
                const feesBadge = row.querySelector('.badge.bg-secondary.payment-badge');
                if (feesBadge) {
                    const originalFees = feesBadge.getAttribute('data-original-fees') ? 
                        parseFloat(feesBadge.getAttribute('data-original-fees')) : 
                        parseFloat(feesBadge.textContent.replace('SDG', '').trim().replace(/,/g, '')) || 0;
                    
                    totalOriginalFees += originalFees;
                    totalDiscount += discount;
                    totalPaymentAfterDiscount += (originalFees - discount);
                }
            });
            
            let averageDiscountPercentage = 0;
            if (totalOriginalFees > 0 && totalDiscount > 0) {
                averageDiscountPercentage = (totalDiscount / totalOriginalFees) * 100;
            }
            
            const formatNumber = (num) => {
                return num.toLocaleString('en-US', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
            };
            
            document.getElementById('totalOriginalFees').textContent = formatNumber(totalOriginalFees);
            document.getElementById('totalDiscountDisplay').textContent = formatNumber(totalDiscount) + ' SDG';
            document.getElementById('totalPaymentAfterDiscount').textContent = formatNumber(totalPaymentAfterDiscount);
            document.getElementById('averageDiscountPercentage').textContent = averageDiscountPercentage.toFixed(2) + '%';
            
            const selectedBadge = document.getElementById('selectedCountBadge');
            if (selectedBadge) {
                selectedBadge.textContent = selectedCount + ' مختار';
            }
            
            const bulkSelectedCount = document.getElementById('bulkSelectedCount');
            if (bulkSelectedCount) {
                bulkSelectedCount.textContent = selectedCount;
            }
        }
        
        document.querySelectorAll('.discount-input').forEach(input => {
            input.addEventListener('input', calculateTotals);
        });
        
        document.getElementById('discountUpdateForm')?.addEventListener('submit', function(e) {
            const selectedCount = document.querySelectorAll('.registration-checkbox:checked:not(:disabled)').length;
            
            if (selectedCount === 0) {
                e.preventDefault();
                alert('يرجى اختيار دفعة واحدة على الأقل لتطبيق التخفيض');
                return;
            }
            
            let invalidDiscounts = false;
            let errorMessages = [];
            
            document.querySelectorAll('.registration-checkbox:checked:not(:disabled)').forEach(checkbox => {
                const row = checkbox.closest('tr');
                const registrationId = row.id.replace('row-', '');
                const discountInput = row.querySelector(`input[name="discount[${registrationId}]"]`);
                
                if (discountInput) {
                    const discount = parseFloat(discountInput.value) || 0;
                    const feesBadge = row.querySelector('.badge.bg-secondary.payment-badge');
                    
                    if (feesBadge) {
                        const originalFees = feesBadge.getAttribute('data-original-fees') ? 
                            parseFloat(feesBadge.getAttribute('data-original-fees')) : 
                            parseFloat(feesBadge.textContent.replace('SDG', '').trim().replace(/,/g, '')) || 0;
                        
                        if (discount > originalFees) {
                            invalidDiscounts = true;
                            discountInput.classList.add('is-invalid');
                            errorMessages.push(`التخفيض ${discount.toFixed(2)} أكبر من الرسوم الإجمالية ${originalFees.toFixed(2)} للدفعة ${registrationId}`);
                        } else {
                            discountInput.classList.remove('is-invalid');
                        }
                    }
                }
            });
            
            if (invalidDiscounts) {
                e.preventDefault();
                alert('بعض قيم التخفيض أكبر من الرسوم الإجمالية. الرجاء تصحيحها قبل المتابعة.');
                return;
            }
            
            if (!confirm(`هل أنت متأكد من تطبيق التخفيضات على ${selectedCount} دفعة؟`)) {
                e.preventDefault();
            }
        });
        
        function setUpdateType(type) {
            document.querySelectorAll('input[name="update_type"]').forEach(radio => {
                if (radio.value === type) {
                    radio.checked = true;
                    radio.closest('.update-type-selector').classList.add('active');
                } else {
                    radio.closest('.update-type-selector').classList.remove('active');
                }
            });
            
            if (type === 'bulk') {
                showBulkUpdate();
            } else {
                showUpdateForm();
            }
        }
        
        function showBulkUpdate() {
            document.getElementById('updateForm').style.display = 'none';
            document.getElementById('bulkUpdateForm').style.display = 'block';
            
            const registrationIds = [];
            document.querySelectorAll('.registration-checkbox:checked:not(:disabled)').forEach(checkbox => {
                registrationIds.push(checkbox.value);
            });
            
            if (registrationIds.length === 0) {
                alert('الرجاء اختيار دفعات غير مدفوعة أولاً قبل استخدام التخفيض الموحد');
                showUpdateForm();
                return;
            }
            
            const container = document.getElementById('bulkRegistrationIds');
            container.innerHTML = '';
            registrationIds.forEach(id => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'registration_ids[]';
                input.value = id;
                container.appendChild(input);
            });
        }
        
        function showUpdateForm() {
            document.getElementById('updateForm').style.display = 'block';
            document.getElementById('bulkUpdateForm').style.display = 'none';
        }
        
        function submitBulkUpdate() {
            const form = document.getElementById('bulkUpdateFormContent');
            const registrationIds = document.querySelectorAll('#bulkRegistrationIds input');
            const bulkDiscountInput = document.querySelector('input[name="bulk_discount"]');
            
            if (registrationIds.length === 0) {
                alert('الرجاء اختيار دفعات أولاً');
                return;
            }
            
            if (!bulkDiscountInput || bulkDiscountInput.value === '') {
                alert('الرجاء إدخال قيمة التخفيض');
                return;
            }
            
            const bulkDiscount = parseFloat(bulkDiscountInput.value);
            if (isNaN(bulkDiscount) || bulkDiscount < 0) {
                alert('قيمة التخفيض غير صالحة');
                return;
            }
            
            if (!confirm(`هل أنت متأكد من تطبيق تخفيض قدره ${bulkDiscount.toFixed(2)} على ${registrationIds.length} دفعة؟`)) {
                return;
            }
            
            const submitForm = document.createElement('form');
            submitForm.method = 'post';
            submitForm.style.display = 'none';
            document.body.appendChild(submitForm);
            
            registrationIds.forEach(input => {
                const newInput = document.createElement('input');
                newInput.type = 'hidden';
                newInput.name = input.name;
                newInput.value = input.value;
                submitForm.appendChild(newInput);
            });
            
            const discountInput = document.createElement('input');
            discountInput.type = 'hidden';
            discountInput.name = 'bulk_discount';
            discountInput.value = bulkDiscount;
            submitForm.appendChild(discountInput);
            
            const updateTypeInput = document.createElement('input');
            updateTypeInput.type = 'hidden';
            updateTypeInput.name = 'update_type';
            updateTypeInput.value = 'bulk';
            submitForm.appendChild(updateTypeInput);
            
            const submitInput = document.createElement('input');
            submitInput.type = 'hidden';
            submitInput.name = 'apply_discounts';
            submitInput.value = '1';
            submitForm.appendChild(submitInput);
            
            // Add CSRF token
            const csrfInput = document.createElement('input');
            csrfInput.type = 'hidden';
            csrfInput.name = 'csrf_token';
            csrfInput.value = '<?= $_SESSION['csrf_token'] ?>';
            submitForm.appendChild(csrfInput);
            
            submitForm.submit();
        }
    </script>
</body>
</html>
