<?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';

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

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

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

// Get filter parameters - only use them if filters were applied
if ($filters_applied) {
    $filter_college_id = $_GET['filter_college'] ?? null;
    $filter_section_id = $_GET['filter_section'] ?? null;
    $filter_program_id = $_GET['filter_program'] ?? null;
    $filter_batch_id = $_GET['filter_batch'] ?? null;
    $filter_semester_id = $_GET['filter_semester'] ?? null;
    $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_batch_id = null;
    $filter_semester_id = null;
    $search_query = '';
    $filter_only_unpaid = 0;
}

// Handle form submission for discount update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['apply_discounts'])) {
        $registration_ids = $_POST['registration_ids'] ?? [];
        $update_type = $_POST['update_type'] ?? 'individual';
        
        if (empty($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;
                    
                    foreach ($registration_ids as $registration_id) {
                        // 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 - $bulk_discount;
                        
                        // Ensure payment amount is not negative
                        if ($new_payment_amount < 0) {
                            $errors[] = "التخفيض $bulk_discount أكبر من الرسوم الإجمالية للدفعة $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",
                            $bulk_discount,
                            $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 = "تم تطبيق تخفيض قدره {$bulk_discount} على {$updated_count} دفعة";
                        if (!empty($errors)) {
                            $success_message .= " (حدثت أخطاء في " . count($errors) . " دفعة)";
                        }
                    }
                    
                } else {
                    // Individual update for each registration
                    foreach ($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]);
                        
                        // 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
    if ($filter_college_id && !empty($filter_college_id)) {
        $where_students .= " AND s.college_id = ? ";
        $student_types .= 'i'; 
        $student_params[] = $filter_college_id;
    }

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

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

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

    // Apply search query if provided
    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 like committee_student_profile.php
    $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.batch_id,
            s.email,
            s.phone_number,
            c.name AS college_name,
            sec.name AS section_name,
            p.name AS program_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 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 && !empty($filter_semester_id)) {
        $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 && !empty($filter_college_id)) {
    $sections_sql = "
        SELECT DISTINCT s.id, s.name, s.parent
        FROM sections s 
        WHERE s.parent = ? AND s.deleted_at IS NULL 
        ORDER BY s.name
    ";
    $sections_stmt = $mysqli1->prepare($sections_sql);
    $sections_stmt->bind_param("i", $filter_college_id);
    $sections_stmt->execute();
    $sections = $sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $sections_stmt->close();
}

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

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

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

// إضافة header بعد معالجة جميع العمليات وقبل أي إخراج HTML
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: 120px;
            max-width: 150px;
            width: 150px;
        }
        .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;
        }
        /* Style for unselected rows */
        tr.unselected {
            background-color: #f8f9fa;
            opacity: 0.7;
        }
        /* Style for selected rows */
        tr.selected {
            background-color: #e8f5e9;
        }
        /* Style for paid rows */
        tr.paid-row {
            background-color: #f0fdf4;
        }
        /* Highlight when checkbox is checked */
        .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;
        }
    </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 -->
        <div class="card card-arabic p-4 mb-4">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="d-flex align-items-center mb-3">
                        <div class="filter-icon me-2">
                            <i class="fas fa-filter"></i>
                        </div>
                        <h6 class="fw-bold mb-0 text-dark">تصفية دفعات الطلاب</h6>
                        <div class="ms-3">
                            <span class="badge bg-light text-dark border">
                                <i class="fas fa-sliders-h me-1"></i>
                                <?= $filters_applied ? 'تصفية مطبقة' : 'في انتظار التطبيق' ?>
                            </span>
                        </div>
                    </div>
                    
                    <form method="get" class="row g-3 align-items-end" id="filterForm">
                        <!-- Hidden field to indicate filters were applied -->
                        <input type="hidden" name="filter_applied" value="1">
                        
                        <!-- First Row of Filters -->
                        <div class="row filter-row">
                            <!-- College Filter -->
                            <div class="col-lg-3 col-md-6">
                                <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'] ?>" <?= (isset($_GET['filter_college']) && $_GET['filter_college'] == $college['id']) ? 'selected' : '' ?>>
                                                    <?= e($college['name']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <span class="input-group-text bg-light border-start-0">
                                            <i class="fas fa-building"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Section Filter -->
                            <div class="col-lg-3 col-md-6">
                                <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" <?= !$filter_college_id ? 'disabled' : '' ?>>
                                            <option value="">جميع الأقسام</option>
                                            <?php if ($filter_college_id && !empty($sections)): ?>
                                                <?php foreach ($sections as $section): ?>
                                                    <option value="<?= $section['id'] ?>" <?= (isset($_GET['filter_section']) && $_GET['filter_section'] == $section['id']) ? 'selected' : '' ?>>
                                                        <?= e($section['name']) ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </select>
                                        <span class="input-group-text bg-light border-start-0">
                                            <i class="fas fa-building"></i>
                                        </span>
                                    </div>
                                    <?php if (!$filter_college_id): ?>
                                        <small class="text-muted">الرجاء اختيار كلية أولاً</small>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Program Filter -->
                            <div class="col-lg-3 col-md-6">
                                <div class="form-group">
                                    <label class="form-label fw-semibold text-muted mb-2">
                                        <i class="fas fa-graduation-cap me-1"></i>
                                        البرنامج
                                    </label>
                                    <div class="input-group input-group-sm">
                                        <select class="form-control border-end-0" name="filter_program" id="filter_program">
                                            <option value="">جميع البرامج</option>
                                            <?php foreach ($programs as $program): ?>
                                                <option value="<?= $program['id'] ?>" <?= (isset($_GET['filter_program']) && $_GET['filter_program'] == $program['id']) ? 'selected' : '' ?>>
                                                    <?= e($program['name']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <span class="input-group-text bg-light border-start-0">
                                            <i class="fas fa-book"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Batch Filter -->
                            <div class="col-lg-3 col-md-6">
                                <div class="form-group">
                                    <label class="form-label fw-semibold text-muted mb-2">
                                        <i class="fas fa-users me-1"></i>
                                        الدفعة
                                    </label>
                                    <div class="input-group input-group-sm">
                                        <select class="form-control border-end-0" name="filter_batch">
                                            <option value="">جميع الدفعات</option>
                                            <?php foreach ($batches as $batch): ?>
                                                <option value="<?= $batch['id'] ?>" <?= (isset($_GET['filter_batch']) && $_GET['filter_batch'] == $batch['id']) ? 'selected' : '' ?>>
                                                    <?= e($batch['value']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <span class="input-group-text bg-light border-start-0">
                                            <i class="fas fa-calendar-alt"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Second Row of Filters -->
                        <div class="row filter-row">
                            <!-- Semester Filter -->
                            <div class="col-lg-6 col-md-6">
                                <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'] ?>" <?= (isset($_GET['filter_semester']) && $_GET['filter_semester'] == $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>
                            
                            <!-- Search Field -->
                            <div class="col-lg-6 col-md-6">
                                <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>
                        </div>
                        
                        <!-- Third Row - Options and Buttons -->
                        <div class="row filter-row">
                            <div class="col-lg-6 col-md-6">
                                <div class="form-check form-switch">
                                    <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">
                                        <i class="fas fa-money-bill-wave me-1"></i>
                                        عرض الدفعات غير المدفوعة فقط
                                    </label>
                                </div>
                            </div>
                            <div class="col-lg-6 col-md-6">
                                <div class="d-flex gap-2 pt-2 justify-content-end">
                                    <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>
                                    <?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>
                </div>
                
                <!-- Filter Summary -->
                <div class="col-md-4">
                    <div class="bg-light rounded p-3 h-100">
                        <div class="d-flex align-items-center mb-2">
                            <i class="fas fa-info-circle me-2 <?= $filters_applied ? 'text-primary' : 'text-secondary' ?>"></i>
                            <span class="fw-semibold">ملخص التصفية</span>
                        </div>
                        <div class="small">
                            <?php if ($filters_applied): ?>
                                <div class="mb-1">عدد الدفعات: <strong><?= count($registrations) ?></strong></div>
                                <?php if ($filter_only_unpaid): ?>
                                    <div class="mb-1 text-success">
                                        <i class="fas fa-money-bill-wave me-1"></i>
                                        غير مدفوعة فقط
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($filter_semester_id && !empty($filter_semester_id)): ?>
                                    <div class="mb-1">
                                        <i class="fas fa-calendar me-1"></i>
                                        الفصل الدراسي المحدد
                                    </div>
                                <?php else: ?>
                                    <div class="mb-1">
                                        <i class="fas fa-list-alt me-1"></i>
                                        جميع الفصول الدراسية
                                    </div>
                                <?php endif; ?>
                                
                                <?php if (!empty($search_query)): ?>
                                    <div class="mb-2 p-2 bg-warning bg-opacity-10 rounded">
                                        <div class="fw-semibold text-warning mb-1">
                                            <i class="fas fa-search me-1"></i>
                                            نتيجة البحث
                                        </div>
                                        <div class="text-truncate">
                                            "<?= e($search_query) ?>"
                                        </div>
                                    </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <div class="text-center py-3">
                                    <i class="fas fa-filter fa-2x text-muted mb-3"></i>
                                    <p class="text-muted mb-0">لم يتم تطبيق أي تصفية بعد</p>
                                    <p class="text-muted small">الرجاء اختيار عوامل التصفية ثم النقر على "تطبيق التصفية"</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 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 (Hidden by default) -->
        <?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">
                <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">
                
                <!-- 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>
                
                <!-- Registrations Table -->
                <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>
                                <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.00;
                                $registration_fees = !empty($reg['registration_fees']) ? floatval($reg['registration_fees']) : 0.00;
                                $insurance_fees = !empty($reg['insurance_fees']) ? floatval($reg['insurance_fees']) : 0.00;
                                $total_fees = $study_fees + $registration_fees + $insurance_fees;
                                
                                $discount = !empty($reg['discount']) ? floatval($reg['discount']) : 0.00;
                                $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' : '';
                                ?>
                                <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><?= e($reg['program_name']) ?></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>
                                        <?php if (!empty($reg['payment_reference'])): ?>
                                            <span class="badge reference-badge"><?= e($reg['payment_reference']) ?></span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge bg-secondary payment-badge">
                                            <?= number_format($total_fees, 2) ?> 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 ?>)"
                                                   required>
                                            <small class="text-muted">الحد الأقصى: <?= number_format($total_fees, 2) ?></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>
                                    <td>
                                        <?php if ($created_at): ?>
                                            <small class="date-display"><?= $created_at ?></small>
                                        <?php else: ?>
                                            <small class="text-muted">-</small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($updated_at): ?>
                                            <small class="date-display"><?= $updated_at ?></small>
                                        <?php else: ?>
                                            <small class="text-muted">-</small>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Hidden field for update type -->
                <input type="hidden" name="update_type" value="individual">
            </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.00 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.00</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.00</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.00%</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>
        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');
                }
            }
        }
        
        // Update select all checkbox when individual checkboxes change
        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();
            });
        });
        
        // Update payment preview when discount changes
        function updatePaymentPreview(registrationId, discount, totalFees) {
            discount = parseFloat(discount) || 0;
            totalFees = parseFloat(totalFees) || 0;
            
            // Ensure discount doesn't exceed total fees
            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) {
                previewElement.innerHTML = `
                    <span class="badge ${paymentAmount > 0 ? 'unpaid-badge' : 'paid-badge'}">
                        ${paymentAmount.toFixed(2)} SDG
                    </span>
                    <div class="discount-preview">
                        تخفيض: ${discount.toFixed(2)} SDG
                    </div>
                    ${discount > 0 ? `<div class="original-amount">${totalFees.toFixed(2)} SDG</div>` : ''}
                `;
            }
            
            calculateTotals();
        }
        
        // Calculate and update totals
        function calculateTotals() {
            let totalOriginalFees = 0;
            let totalDiscount = 0;
            let totalPaymentAfterDiscount = 0;
            let selectedCount = 0;
            
            document.querySelectorAll('.registration-checkbox').forEach(checkbox => {
                const row = checkbox.closest('tr');
                if (row && checkbox.checked && !checkbox.disabled) {
                    selectedCount++;
                    
                    // Get registration ID from row ID
                    const registrationId = row.id.replace('row-', '');
                    
                    // Get discount input
                    const discountInput = row.querySelector(`input[name="discount[${registrationId}]"]`);
                    if (discountInput) {
                        const discount = parseFloat(discountInput.value) || 0;
                        
                        // Calculate original fees from the displayed total
                        const feesBadge = row.querySelector('.badge.bg-secondary');
                        if (feesBadge) {
                            const feesText = feesBadge.textContent.replace('SDG', '').trim();
                            const originalFees = parseFloat(feesText) || 0;
                            
                            totalOriginalFees += originalFees;
                            totalDiscount += discount;
                            totalPaymentAfterDiscount += (originalFees - discount);
                        }
                    }
                }
            });
            
            // Calculate average discount percentage
            const averageDiscountPercentage = totalOriginalFees > 0 ? 
                ((totalDiscount / totalOriginalFees) * 100).toFixed(2) : 0;
            
            // Update display
            document.getElementById('totalOriginalFees').textContent = totalOriginalFees.toFixed(2);
            document.getElementById('totalDiscountDisplay').textContent = totalDiscount.toFixed(2) + ' SDG';
            document.getElementById('totalPaymentAfterDiscount').textContent = totalPaymentAfterDiscount.toFixed(2);
            document.getElementById('averageDiscountPercentage').textContent = averageDiscountPercentage + '%';
            
            // Update selected count badge
            const selectedBadge = document.getElementById('selectedCountBadge');
            if (selectedBadge) {
                selectedBadge.textContent = selectedCount + ' مختار';
            }
            
            // Update bulk selected count
            const bulkSelectedCount = document.getElementById('bulkSelectedCount');
            if (bulkSelectedCount) {
                bulkSelectedCount.textContent = selectedCount;
            }
        }
        
        // Listen to input changes in discount fields
        document.querySelectorAll('.discount-input').forEach(input => {
            input.addEventListener('input', calculateTotals);
        });
        
        // Form submission confirmation
        document.getElementById('discountUpdateForm')?.addEventListener('submit', function(e) {
            const selectedCount = document.querySelectorAll('.registration-checkbox:checked').length;
            
            if (selectedCount === 0) {
                e.preventDefault();
                alert('يرجى اختيار دفعة واحدة على الأقل لتطبيق التخفيض');
                return;
            }
            
            // Validate discount amounts
            let invalidDiscounts = false;
            document.querySelectorAll('.registration-checkbox:checked').forEach(checkbox => {
                if (!checkbox.disabled) {
                    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');
                        
                        if (feesBadge) {
                            const feesText = feesBadge.textContent.replace('SDG', '').trim();
                            const originalFees = parseFloat(feesText) || 0;
                            
                            if (discount > originalFees) {
                                invalidDiscounts = true;
                                discountInput.classList.add('is-invalid');
                            } 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';
            
            // Collect all checked registration IDs
            const registrationIds = [];
            document.querySelectorAll('.registration-checkbox:checked:not(:disabled)').forEach(checkbox => {
                registrationIds.push(checkbox.value);
            });
            
            // Show warning if no registrations selected
            if (registrationIds.length === 0) {
                alert('الرجاء اختيار دفعات غير مدفوعة أولاً قبل استخدام التخفيض الموحد');
                showUpdateForm();
                return;
            }
            
            // Create hidden inputs for registration IDs
            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;
            }
            
            // Create a new form for submission
            const submitForm = document.createElement('form');
            submitForm.method = 'post';
            submitForm.style.display = 'none';
            document.body.appendChild(submitForm);
            
            // Add all registration IDs
            registrationIds.forEach(input => {
                const newInput = document.createElement('input');
                newInput.type = 'hidden';
                newInput.name = input.name;
                newInput.value = input.value;
                submitForm.appendChild(newInput);
            });
            
            // Add bulk discount
            const discountInput = document.createElement('input');
            discountInput.type = 'hidden';
            discountInput.name = 'bulk_discount';
            discountInput.value = bulkDiscount;
            submitForm.appendChild(discountInput);
            
            // Add update type
            const updateTypeInput = document.createElement('input');
            updateTypeInput.type = 'hidden';
            updateTypeInput.name = 'update_type';
            updateTypeInput.value = 'bulk';
            submitForm.appendChild(updateTypeInput);
            
            // Add submit button
            const submitInput = document.createElement('input');
            submitInput.type = 'hidden';
            submitInput.name = 'apply_discounts';
            submitInput.value = '1';
            submitForm.appendChild(submitInput);
            
            submitForm.submit();
        }
        
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            
            if (!collegeId || collegeId === '') {
                sectionSelect.disabled = true;
                sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
                return;
            }
            
            // Submit the form to reload with new college
            const form = document.getElementById('filterForm');
            form.submit();
        }
        
        // 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
            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');
                
                if (feesBadge) {
                    const feesText = feesBadge.textContent.replace('SDG', '').trim();
                    const totalFees = parseFloat(feesText) || 0;
                    const discount = parseFloat(input.value) || 0;
                    
                    updatePaymentPreview(registrationId, discount, totalFees);
                }
            });
        });
    </script>
</body>
</html>
