<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }

// 1. إيقاف عرض الأخطاء العادية لمنع تشوه واجهة المستخدم
error_reporting(E_ALL); 
ini_set('display_errors', 1);

require_once 'db_connect.php'; 

// 2. تعريف المتغير الأساسي
$current_school = isset($_SESSION['school_name']) ? $conn->real_escape_string($_SESSION['school_name']) : '';

// 3. جلب اسم ولوجو المدرسة
$school_display_name = $current_school ?: 'أكاديمية روزماري التعليمية';
$school_logo = 'images/icon.png'; 
$school_res = $conn->query("SELECT school_name, school_logo FROM schools WHERE school_name = '$current_school' LIMIT 1");
if ($school_res && $school_res->num_rows > 0) {
    $s_data = $school_res->fetch_assoc();
    if (!empty($s_data['school_name'])) $school_display_name = $s_data['school_name'];
    if (!empty($s_data['school_logo'])) $school_logo = $s_data['school_logo'];
}

// 4. إنشاء وجلب مصفوفة الأسعار الذكية
$conn->query("CREATE TABLE IF NOT EXISTS acc_pricing_matrix (
    id INT AUTO_INCREMENT PRIMARY KEY,
    school_name VARCHAR(150),
    stage_name VARCHAR(100) NOT NULL,
    base_price DECIMAL(15,2) NOT NULL DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY unique_stage_school (school_name, stage_name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");

$pricing_matrix = [];
$price_res = $conn->query("SELECT stage_name, base_price FROM acc_pricing_matrix WHERE school_name = '$current_school'");
if ($price_res && $price_res->num_rows > 0) {
    while($row = $price_res->fetch_assoc()) {
        $pricing_matrix[$row['stage_name']] = $row['base_price'];
    }
}

// جلب الوسوم (المراحل) الخاصة بالمدرسة الحالية لتغذية مصفوفة الأسعار
$school_stages = [];
$tags_query = $conn->query("SELECT DISTINCT stage_name FROM school_tags WHERE school_name = '$current_school' AND stage_name != ''");
if ($tags_query && $tags_query->num_rows > 0) {
    while($t_row = $tags_query->fetch_assoc()) {
        $school_stages[] = $t_row['stage_name'];
    }
}
$json_school_stages = json_encode($school_stages, JSON_UNESCAPED_UNICODE) ?: '[]';

$json_pricing = json_encode($pricing_matrix, JSON_UNESCAPED_UNICODE) ?: '{}';

// 5. جلب بيانات الطلاب والأقساط
$students_data = [];
$students_query = "
    SELECT 
        s.student_id as id, 
        s.student_name as name, 
        COALESCE(s.stage, 'عام') as stage, 
        COALESCE(s.department, 'عام') as dept, 
        COALESCE(s.branch, 'عام') as section,
        COALESCE(s.enrollment_status, 'active') as enrollment_status,
        COALESCE(f.financial_id, 0) as financial_id,
        COALESCE(f.net_total, 0) as total,
        COALESCE(f.discount_percentage, 0) as discount,
        COALESCE(f.total_paid, 0) as paid,
        COALESCE(f.total_refunded, 0) as refunded
    FROM students s
    LEFT JOIN acc_student_financials f ON s.student_id = f.student_id
    WHERE s.school_name = '$current_school' OR '$current_school' = ''
    ORDER BY s.student_name ASC
";
$students_res = $conn->query($students_query);
if ($students_res && $students_res->num_rows > 0) {
    while($row = $students_res->fetch_assoc()) {
        $row['installments'] = [];
        if ($row['financial_id'] > 0) {
            $fin_id = $row['financial_id'];
            $inst_q = $conn->query("SELECT due_date, amount_due, is_paid FROM acc_installments WHERE financial_id = $fin_id ORDER BY due_date ASC");
            if ($inst_q && $inst_q->num_rows > 0) {
                while($i = $inst_q->fetch_assoc()) {
                    $row['installments'][] = [
                        'date' => $i['due_date'],
                        'amount' => $i['amount_due'],
                        'stat' => $i['is_paid'] == 1 ? 'مدفوع' : 'غير مدفوع'
                    ];
                }
            }
        }
        $students_data[] = $row;
    }
}
$json_students = json_encode($students_data, JSON_UNESCAPED_UNICODE) ?: '[]';

// 6. استخراج الفلاتر الفريدة للطلاب
$unique_stages = []; $unique_depts = []; $unique_sections = [];
if (!empty($students_data)) {
    foreach ($students_data as $s) {
        if (!empty($s['stage']) && !in_array($s['stage'], $unique_stages) && $s['stage'] !== 'عام') { $unique_stages[] = $s['stage']; }
        if (!empty($s['dept']) && !in_array($s['dept'], $unique_depts) && $s['dept'] !== 'عام') { $unique_depts[] = $s['dept']; }
        if (!empty($s['section']) && !in_array($s['section'], $unique_sections) && $s['section'] !== 'عام' && $s['section'] !== 'الكل') { $unique_sections[] = $s['section']; }
    }
}

// 7. جلب سجل الرواتب
$salaries_data = [];
$salaries_query = "SELECT sp.sp_id as id, sp.payment_month as month, sp.base_amount as base, sp.bonuses as bonus, sp.deductions as deductions, sp.net_paid as net, sp.payment_method as method, t.display_name as name, t.role FROM acc_salary_payments sp JOIN acc_employee_contracts c ON sp.contract_id = c.contract_id JOIN teachers t ON c.reference_id = t.id ORDER BY sp.payment_date DESC LIMIT 50";
$sal_res = $conn->query($salaries_query);
if ($sal_res && $sal_res->num_rows > 0) {
    while($row = $sal_res->fetch_assoc()) {
        $row['role_ar'] = $row['role'] == 'admin' ? 'إدارة' : ($row['role'] == 'accountant' || $row['role'] == 'إداري' ? 'محاسب / إداري' : 'مدرس');
        $salaries_data[] = $row;
    }
}
$json_salaries = json_encode($salaries_data, JSON_UNESCAPED_UNICODE) ?: '[]';

// 8. جلب سجل الصرفيات
$expenses_data = [];
$expenses_query = "SELECT expense_id as id, expense_date as date, category_name as cat, description as desc_text, amount, recorded_by as receiver, invoice_attachment as attachment FROM acc_expenses ORDER BY expense_date DESC LIMIT 50";
$exp_res = $conn->query($expenses_query);
if ($exp_res && $exp_res->num_rows > 0) {
    while($row = $exp_res->fetch_assoc()) {
        $expenses_data[] = ['id' => $row['id'], 'date' => $row['date'], 'cat' => $row['cat'], 'desc' => $row['desc_text'], 'amount' => $row['amount'], 'receiver' => $row['receiver']];
    }
}
$json_expenses = json_encode($expenses_data, JSON_UNESCAPED_UNICODE) ?: '[]';
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>المركز المالي | Fintech Dashboard</title>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;700;900&display=swap');
        
        body { 
            font-family: 'Tajawal', sans-serif; 
            background-color: #0b0f19; 
            color: #f8fafc;
            margin: 0; padding: 0;
            overflow-x: hidden;
        }

        .glass-panel {
            background: rgba(255, 255, 255, 0.02);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            border: 1px solid rgba(255, 255, 255, 0.05);
            border-radius: 20px;
            box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
        }

        /* STREAMING_CHUNK:Styles */
        .text-neon-green { color: #10b981; text-shadow: 0 0 15px rgba(16, 185, 129, 0.4); }
        .text-neon-red { color: #ef4444; text-shadow: 0 0 15px rgba(239, 68, 68, 0.4); }
        .text-neon-gold { color: #f59e0b; text-shadow: 0 0 15px rgba(245, 158, 11, 0.4); }
        .border-neon-green { border-color: rgba(16, 185, 129, 0.3); box-shadow: inset 0 0 20px rgba(16, 185, 129, 0.05); }
        .border-neon-red { border-color: rgba(239, 68, 68, 0.3); box-shadow: inset 0 0 20px rgba(239, 68, 68, 0.05); }
        .fin-font { font-family: 'Courier New', Courier, monospace; letter-spacing: -0.5px; }

        .omni-container { position: fixed; bottom: 30px; left: 30px; z-index: 999; }
        .omni-btn {
            width: 70px; height: 70px; border-radius: 50%;
            background: linear-gradient(135deg, #10b981, #059669);
            box-shadow: 0 0 30px rgba(16, 185, 129, 0.5);
            display: flex; justify-content: center; align-items: center;
            font-size: 30px; color: white; cursor: pointer;
            transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
        }
        .omni-menu {
            position: absolute; bottom: 85px; left: 10px;
            background: rgba(15, 23, 42, 0.95); backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.1); border-radius: 20px;
            padding: 15px; display: flex; flex-direction: column; gap: 10px;
            opacity: 0; transform: translateY(20px) scale(0.9); pointer-events: none;
            transition: all 0.3s ease; box-shadow: 0 10px 40px rgba(0,0,0,0.5);
            width: 220px;
        }
        .omni-container:hover .omni-menu { opacity: 1; transform: translateY(0) scale(1); pointer-events: auto; }
        .omni-container:hover .omni-btn { transform: rotate(45deg); background: linear-gradient(135deg, #ef4444, #dc2626); box-shadow: 0 0 30px rgba(239, 68, 68, 0.5);}
        .omni-item { display: flex; align-items: center; gap: 10px; padding: 10px 15px; border-radius: 12px; cursor: pointer; transition: 0.2s; font-weight: bold; font-size: 14px;}
        .omni-item:hover { background: rgba(255,255,255,0.05); }

        #toast-container { position: fixed; top: 20px; left: 20px; z-index: 9999; display: flex; flex-direction: column; gap: 10px; }
        .toast {
            min-width: 250px; padding: 15px 20px; border-radius: 12px;
            background: rgba(15, 23, 42, 0.95); backdrop-filter: blur(10px);
            color: white; font-weight: bold; display: flex; align-items: center; gap: 12px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3); border: 1px solid rgba(255,255,255,0.1);
            transform: translateX(-120%); transition: transform 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
        }
        .toast.show { transform: translateX(0); }
        .toast.success { border-right: 4px solid #10b981; }
        .toast.error { border-right: 4px solid #ef4444; }
        .toast.info { border-right: 4px solid #3b82f6; }

        .timeline-scroll::-webkit-scrollbar { width: 4px; }
        .timeline-scroll::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 10px; }
        
        .nav-item.active { background: rgba(255,255,255,0.05); color: #fff; border-color: rgba(255,255,255,0.1); }
        .nav-item.active i { color: #3b82f6; text-shadow: 0 0 15px rgba(59, 130, 246, 0.4); }
        
        .modal-input { width: 100%; padding: 12px; background: #0f172a; border: 1px solid #334155; color: white; border-radius: 8px; outline: none; transition: 0.3s; }
        .modal-input:focus { border-color: #3b82f6; }
        .modal-label { display: block; color: #94a3b8; font-size: 13px; font-weight: bold; margin-bottom: 5px; }
    </style>
</head>
<body onload="initFintechApp()">
    <div id="toast-container"></div>

    <div class="flex h-screen overflow-hidden">
        
        <!-- 🔴 الشريط الجانبي الأنيق 🔴 -->
        <aside class="w-64 glass-panel border-l-0 rounded-r-none border-y-0 hidden md:flex flex-col relative z-50">
            <div class="p-6 flex items-center gap-3 border-b border-[rgba(255,255,255,0.05)]">
                <div class="w-10 h-10 rounded-full bg-gradient-to-br from-[#10b981] to-[#047857] flex items-center justify-center text-xl shadow-[0_0_15px_rgba(16,185,129,0.3)]">
                    <i class="fas fa-chart-line"></i>
                </div>
                <div>
                    <h2 class="font-black text-sm tracking-wide">المركز المالي</h2>
                    <p class="text-[10px] text-gray-400">روزماري أكاديمي</p>
                </div>
            </div>
            
            <!-- STREAMING_CHUNK:Rendering navigation sidebar... -->
            <nav class="flex-1 p-4 space-y-2 overflow-y-auto timeline-scroll">
                <a href="#" onclick="switchTab('radarSection', this); return false;" class="nav-item active flex items-center gap-3 p-3 rounded-xl transition font-bold text-gray-400 hover:text-white"><i class="fas fa-radar text-neon-green"></i> الرادار التنفيذي</a>
                
                <!-- 🚀 القائمة المنسدلة لبوابة الطلاب 🚀 -->
                <div class="relative">
                    <button onclick="toggleSubmenu('students-submenu')" class="nav-item w-full flex items-center justify-between p-3 rounded-xl text-gray-400 hover:text-white hover:bg-[rgba(255,255,255,0.02)] transition font-bold">
                        <div class="flex items-center gap-3"><i class="fas fa-users-class"></i> شؤون الطلبة والأقساط</div>
                        <i class="fas fa-chevron-down text-xs transition-transform" id="icon-students-submenu"></i>
                    </button>
                    <div id="students-submenu" class="hidden flex-col pl-8 pr-4 py-2 space-y-2 border-r-2 border-[#10b981]/30 mr-4 mt-1">
                        <a href="#" onclick="switchTab('studentsSection', this.parentElement.previousElementSibling); return false;" class="text-sm font-bold text-gray-400 hover:text-neon-green transition block py-1"><i class="fas fa-money-check-edit me-2"></i> سجل الأقساط والدفعات</a>
                        
                        <a href="#" onclick="openNewStudentWindow(); return false;" class="text-sm font-bold text-gray-400 hover:text-neon-green transition block py-1"><i class="fas fa-user-plus me-2"></i> تسجيل طالب وقيد مالي</a>
                        
                        <a href="#" onclick="switchTab('installmentsSection', this.parentElement.previousElementSibling); return false;" class="text-sm font-bold text-purple-400 hover:text-purple-300 transition block py-1 bg-purple-900/10 px-2 rounded border border-purple-900/30 mt-2"><i class="fas fa-calendar-alt me-2"></i> إدارة الأقساط المجدولة</a>
                        
                        <a href="#" onclick="switchTab('notificationsSection', this.parentElement.previousElementSibling); return false;" class="text-sm font-bold text-blue-400 hover:text-blue-300 transition block py-1 bg-blue-900/10 px-2 rounded border border-blue-900/30 mt-2"><i class="fas fa-bell me-2"></i> مركز الإشعارات المالية</a>
                        
                        <a href="#" onclick="switchTab('promotionSection', this.parentElement.previousElementSibling); return false;" class="text-sm font-bold text-red-400 hover:text-red-300 transition block py-1 bg-red-900/10 px-2 rounded border border-red-900/30 mt-2"><i class="fas fa-rocket me-2"></i> ترحيل الطلاب الأكاديمي</a>
                        
                        <a href="#" onclick="switchTab('temp_studentsSection', this.parentElement.previousElementSibling); return false;" class="text-sm font-bold text-yellow-500 hover:text-yellow-400 transition block py-1 bg-yellow-900/10 px-2 rounded border border-yellow-900/30 mt-2"><i class="fas fa-user-clock me-2"></i> المؤقتين والمنسحبين</a>
                    </div>
                </div>

                <a href="#" onclick="showToast('سيتم برمجة قسم المصروفات في الخطوة القادمة', 'info'); return false;" class="nav-item flex items-center gap-3 p-3 rounded-xl text-gray-400 hover:text-white hover:bg-[rgba(255,255,255,0.02)] transition font-bold"><i class="fas fa-file-invoice-dollar"></i> المصروفات والرواتب</a>
                <a href="#" onclick="showToast('سيتم برمجة قسم التقارير في الخطوة القادمة', 'info'); return false;" class="nav-item flex items-center gap-3 p-3 rounded-xl text-gray-400 hover:text-white hover:bg-[rgba(255,255,255,0.02)] transition font-bold"><i class="fas fa-print"></i> مركز التقارير والتدقيق</a>
                
                <a href="#" onclick="openPricingMatrixModal(); return false;" class="nav-item flex items-center gap-3 p-3 rounded-xl text-gray-400 hover:text-white hover:bg-[rgba(255,255,255,0.02)] transition font-bold"><i class="fas fa-cog"></i> مصفوفة الأسعار الأساسية</a>
            </nav>

            <div class="p-4 border-t border-[rgba(255,255,255,0.05)]">
                <a href="admin_dashboard.php" class="flex items-center gap-3 p-3 rounded-xl text-gray-400 hover:text-red-400 transition font-bold text-sm"><i class="fas fa-sign-out-alt"></i> عودة للإدارة الأكاديمية</a>
            </div>
        </aside>

        <!-- 🔴 محتوى الشاشة الرئيسية 🔴 -->
        <main class="flex-1 p-4 md:p-8 overflow-y-auto relative">
            <header class="flex justify-between items-center mb-8">
                <div>
                    <h1 class="text-3xl font-black text-white tracking-wide" id="pageTitle">الرادار المالي <span class="text-sm font-normal text-gray-500 ml-2">Executive Dashboard</span></h1>
                </div>
                <div class="flex gap-3">
                    <button onclick="fetchLiveStats()" class="glass-panel px-4 py-2 text-sm font-bold hover:bg-[rgba(255,255,255,0.05)] transition flex items-center gap-2">
                        <i class="fas fa-sync-alt text-blue-400" id="sync-icon"></i> تحديث حي
                    </button>
                    <div class="w-10 h-10 rounded-full bg-gray-800 border border-gray-600 flex items-center justify-center overflow-hidden">
                        <img src="<?= htmlspecialchars($school_logo) ?>" onerror="this.style.display='none'">
                    </div>
                </div>
            </header>

            <!-- ========================================== -->
            <!-- 📊 1. الرادار المالي 📊 -->
            <!-- ========================================== -->
            <!-- STREAMING_CHUNK:Rendering Radar Section... -->
            <section id="radarSection" class="animate-[fadeIn_0.3s_ease-in-out]">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                    <div class="glass-panel p-6 border-neon-green relative overflow-hidden group">
                        <div class="absolute -right-4 -top-4 text-green-500/10 text-7xl transition-transform group-hover:scale-110"><i class="fas fa-vault"></i></div>
                        <div class="flex justify-between items-start relative z-10">
                            <div>
                                <p class="text-gray-400 text-sm font-bold mb-1">الرصيد الفعلي (الخزينة)</p>
                                <h2 class="text-3xl font-black text-neon-green fin-font" id="dash-treasury">0 <span class="text-sm font-normal text-gray-500">د.ع</span></h2>
                            </div>
                            <div class="bg-green-500/10 text-green-400 p-2 rounded-lg border border-green-500/20"><i class="fas fa-arrow-trend-up"></i></div>
                        </div>
                    </div>
                    <div class="glass-panel p-6 border-yellow-500/30 relative overflow-hidden group">
                        <div class="absolute -right-4 -top-4 text-yellow-500/10 text-7xl transition-transform group-hover:scale-110"><i class="fas fa-balance-scale-left"></i></div>
                        <div class="flex justify-between items-start relative z-10">
                            <div>
                                <p class="text-gray-400 text-sm font-bold mb-1">الديون المعلقة بالسوق</p>
                                <h2 class="text-3xl font-black text-neon-gold fin-font" id="dash-receivables">0 <span class="text-sm font-normal text-gray-500">د.ع</span></h2>
                            </div>
                            <div class="bg-yellow-500/10 text-yellow-400 p-2 rounded-lg border border-yellow-500/20"><i class="fas fa-clock"></i></div>
                        </div>
                    </div>
                    <div class="glass-panel p-6 border-neon-red relative overflow-hidden group">
                        <div class="absolute -right-4 -top-4 text-red-500/10 text-7xl transition-transform group-hover:scale-110"><i class="fas fa-chart-line-down"></i></div>
                        <div class="flex justify-between items-start relative z-10">
                            <div>
                                <p class="text-gray-400 text-sm font-bold mb-1">إجمالي المصروفات التشغيلية</p>
                                <h2 class="text-3xl font-black text-neon-red fin-font" id="dash-expenses">0 <span class="text-sm font-normal text-gray-500">د.ع</span></h2>
                            </div>
                            <div class="bg-red-500/10 text-red-400 p-2 rounded-lg border border-red-500/20"><i class="fas fa-arrow-trend-down"></i></div>
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    <div class="lg:col-span-2 glass-panel p-6">
                        <div class="flex justify-between items-center mb-6">
                            <h3 class="font-bold text-gray-200">التدفق النقدي (Cashflow Graph)</h3>
                            <div class="flex gap-4 text-xs font-bold">
                                <span class="flex items-center gap-1 text-green-400"><span class="w-3 h-3 rounded-full bg-green-500"></span> إيرادات</span>
                                <span class="flex items-center gap-1 text-red-400"><span class="w-3 h-3 rounded-full bg-red-500"></span> مصروفات</span>
                            </div>
                        </div>
                        <div style="position: relative; height: 320px; width: 100%;">
                            <canvas id="mainCashflowChart"></canvas>
                        </div>
                    </div>
                    <div class="glass-panel p-0 overflow-hidden flex flex-col h-[400px]">
                        <div class="p-5 border-b border-[rgba(255,255,255,0.05)] flex justify-between items-center bg-[rgba(0,0,0,0.2)]">
                            <h3 class="font-bold text-gray-200">المعاملات الأخيرة</h3>
                            <i class="fas fa-ellipsis-h text-gray-500"></i>
                        </div>
                        <div class="p-5 flex-1 overflow-y-auto timeline-scroll space-y-4" id="live-timeline">
                            <div class="text-center text-gray-500 text-sm mt-10"><i class="fas fa-spinner fa-spin"></i> جاري التحميل...</div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- ========================================== -->
            <!-- 🎓 2. بوابة الطلاب والأقساط 🎓 -->
            <!-- ========================================== -->
            <!-- STREAMING_CHUNK:Rendering Students Section... -->
            <section id="studentsSection" class="hidden animate-[fadeIn_0.3s_ease-in-out]">
                
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                    <div class="glass-panel p-4 border-t-2 border-blue-500">
                        <p class="text-xs text-gray-400 font-bold mb-1">الطلاب المسجلين مالياً</p>
                        <h3 class="text-2xl font-black text-white" id="stat-student-count">0 <span class="text-xs text-gray-500 font-normal">طالب</span></h3>
                    </div>
                    <div class="glass-panel p-4 border-t-2 border-neon-green">
                        <p class="text-xs text-gray-400 font-bold mb-1">إجمالي المستلم (الوارد)</p>
                        <h3 class="text-2xl font-black text-neon-green fin-font" id="stat-student-paid">0</h3>
                    </div>
                    <div class="glass-panel p-4 border-t-2 border-neon-red">
                        <p class="text-xs text-gray-400 font-bold mb-1">إجمالي الديون (المتبقي)</p>
                        <h3 class="text-2xl font-black text-neon-red fin-font" id="stat-student-debt">0</h3>
                    </div>
                    <div class="glass-panel p-4 border-t-2 border-neon-gold">
                        <p class="text-xs text-gray-400 font-bold mb-1">متأخرات عاجلة</p>
                        <h3 class="text-2xl font-black text-neon-gold fin-font" id="stat-student-late">0</h3>
                    </div>
                </div>

                <div class="glass-panel p-4 mb-6 flex flex-col md:flex-row gap-4 items-center bg-[#0f172a] border border-gray-800">
                    <div class="relative flex-1 w-full">
                        <i class="fas fa-search absolute right-4 top-3.5 text-gray-400"></i>
                        <input type="text" id="filter-name" onkeyup="renderStudentsCards()" placeholder="ابحث عن طالب بالاسم أو الكود..." class="w-full bg-[#1e293b] border border-gray-700 text-white font-bold rounded-xl py-3 pr-11 pl-4 outline-none focus:border-[#3b82f6] transition shadow-sm">
                    </div>
                    <div class="flex flex-wrap gap-2 w-full md:w-auto">
                        <select id="filter-stage" onchange="renderStudentsCards()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-[#3b82f6] cursor-pointer">
                            <option value="">المرحلة (الكل)</option>
                            <?php foreach($unique_stages as $stg): ?><option value="<?= htmlspecialchars($stg) ?>"><?= htmlspecialchars($stg) ?></option><?php endforeach; ?>
                        </select>
                        <select id="filter-dept" onchange="renderStudentsCards()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-[#3b82f6] cursor-pointer">
                            <option value="">القسم (الكل)</option>
                            <?php foreach($unique_depts as $dpt): ?><option value="<?= htmlspecialchars($dpt) ?>"><?= htmlspecialchars($dpt) ?></option><?php endforeach; ?>
                        </select>
                        <select id="filter-section" onchange="renderStudentsCards()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-[#3b82f6] cursor-pointer">
                            <option value="">الشعبة (الكل)</option>
                            <?php foreach($unique_sections as $sec): ?><option value="<?= htmlspecialchars($sec) ?>"><?= htmlspecialchars($sec) ?></option><?php endforeach; ?>
                        </select>
                        <select id="filter-status" onchange="renderStudentsCards()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-[#3b82f6] cursor-pointer">
                            <option value="">حالة الدفع (الكل)</option>
                            <option value="completed" class="text-green-500 font-bold">خالص (مكتمل)</option>
                            <option value="pending" class="text-orange-400 font-bold">مطلوب (متبقي)</option>
                            <option value="late" class="text-red-500 font-bold">متأخر عن السداد ⚠️</option>
                        </select>
                    </div>
                </div>

                <div id="student-cards-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 pb-20">
                    <div class="col-span-full text-center text-gray-500 py-10"><i class="fas fa-spinner fa-spin text-2xl mb-2"></i><br>جاري الفلترة وبناء البطاقات...</div>
                </div>
            </section>

            <!-- ========================================== -->
            <!-- 📅 3. إدارة الأقساط المجدولة (القسم المستقل) -->
            <!-- ========================================== -->
            <!-- STREAMING_CHUNK:Rendering Installments Section... -->
            <section id="installmentsSection" class="hidden animate-[fadeIn_0.3s_ease-in-out]">
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                    <div class="glass-panel p-4 border-t-2 border-purple-500 relative overflow-hidden">
                        <i class="fas fa-users absolute -left-2 -bottom-2 text-5xl text-purple-500/10"></i>
                        <p class="text-xs text-gray-400 font-bold mb-1">الطلاب المعروضين</p>
                        <h3 class="text-2xl font-black text-white" id="inst-stat-count">0</h3>
                    </div>
                    <div class="glass-panel p-4 border-t-2 border-green-500 relative overflow-hidden">
                        <i class="fas fa-check-double absolute -left-2 -bottom-2 text-5xl text-green-500/10"></i>
                        <p class="text-xs text-gray-400 font-bold mb-1">إجمالي المستلم (الوارد)</p>
                        <h3 class="text-2xl font-black text-green-400 fin-font" id="inst-stat-paid">0</h3>
                    </div>
                    <div class="glass-panel p-4 border-t-2 border-red-500 relative overflow-hidden">
                        <i class="fas fa-balance-scale absolute -left-2 -bottom-2 text-5xl text-red-500/10"></i>
                        <p class="text-xs text-gray-400 font-bold mb-1">الديون المتبقية</p>
                        <h3 class="text-2xl font-black text-red-400 fin-font" id="inst-stat-debt">0</h3>
                    </div>
                    <div class="glass-panel p-4 border-t-2 border-orange-500 relative overflow-hidden">
                        <i class="fas fa-exclamation-triangle absolute -left-2 -bottom-2 text-5xl text-orange-500/10"></i>
                        <p class="text-xs text-gray-400 font-bold mb-1">أقساط متأخرة</p>
                        <h3 class="text-2xl font-black text-orange-400 fin-font" id="inst-stat-delayed">0</h3>
                    </div>
                </div>

                <div class="glass-panel p-4 mb-6 flex flex-col md:flex-row gap-4 items-center bg-[#0f172a] border border-purple-900/30">
                    <div class="relative flex-1 w-full">
                        <i class="fas fa-search absolute right-4 top-3.5 text-gray-400"></i>
                        <input type="text" id="inst-filter-name" onkeyup="renderInstallmentsTable()" placeholder="ابحث عن طالب لجدولة قسطه..." class="w-full bg-[#1e293b] border border-gray-700 text-white font-bold rounded-xl py-3 pr-11 pl-4 outline-none focus:border-purple-500 transition shadow-sm">
                    </div>
                    <div class="flex flex-wrap gap-2 w-full md:w-auto">
                        <select id="inst-filter-stage" onchange="renderInstallmentsTable()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-purple-500 cursor-pointer">
                            <option value="">كل المراحل</option>
                            <?php foreach($unique_stages as $stg): ?><option value="<?= htmlspecialchars($stg) ?>"><?= htmlspecialchars($stg) ?></option><?php endforeach; ?>
                        </select>
                        <select id="inst-filter-dept" onchange="renderInstallmentsTable()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-purple-500 cursor-pointer">
                            <option value="">كل الأقسام</option>
                            <?php foreach($unique_depts as $dpt): ?><option value="<?= htmlspecialchars($dpt) ?>"><?= htmlspecialchars($dpt) ?></option><?php endforeach; ?>
                        </select>
                        <select id="inst-filter-section" onchange="renderInstallmentsTable()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-purple-500 cursor-pointer">
                            <option value="">كل الشعب</option>
                            <?php foreach($unique_sections as $sec): ?><option value="<?= htmlspecialchars($sec) ?>"><?= htmlspecialchars($sec) ?></option><?php endforeach; ?>
                        </select>
                        <select id="inst-filter-status" onchange="renderInstallmentsTable()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-purple-500 cursor-pointer">
                            <option value="">حالة الدفع (الكل)</option>
                            <option value="completed" class="text-green-500">خالص (مكتمل)</option>
                            <option value="pending" class="text-orange-400">مطلوب (متبقي)</option>
                            <option value="late" class="text-red-500">متأخر ⚠️</option>
                        </select>
                    </div>
                </div>

                <div class="overflow-x-auto rounded-xl border border-gray-800 shadow-xl bg-[#0f172a]">
                    <table class="w-full text-right text-sm whitespace-nowrap">
                        <thead class="bg-[#1e293b] text-gray-400 border-b border-gray-700">
                            <tr>
                                <th class="p-4 font-bold text-white">اسم الطالب</th>
                                <th class="p-4 font-bold">الصف / القسم</th>
                                <th class="p-4 font-bold text-center">الصافي الكلي</th>
                                <th class="p-4 font-bold text-center text-green-400">الواصل</th>
                                <th class="p-4 font-bold text-center text-red-400">الديون المتبقية</th>
                                <th class="p-4 font-bold text-center w-48">نسبة السداد</th>
                                <th class="p-4 font-bold text-center">الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody id="installments-table-body" class="divide-y divide-gray-800">
                            <!-- يعبأ بواسطة JS -->
                        </tbody>
                    </table>
                </div>
            </section>

            <!-- ========================================== -->
            <!-- 🔔 4. مركز الإشعارات المالية (القسم الجديد) 🔔 -->
            <!-- ========================================== -->
            <!-- STREAMING_CHUNK:Rendering Notifications Section... -->
            <section id="notificationsSection" class="hidden animate-[fadeIn_0.3s_ease-in-out]">
                <div class="glass-panel p-6 border-t-2 border-blue-500 mb-6">
                    <h2 class="text-xl font-bold text-white mb-6 border-b border-gray-800 pb-4"><i class="fas fa-paper-plane text-blue-500 me-2"></i> محصل الديون الآلي (Smart Alerts)</h2>
                    
                    <form id="bulkNotificationForm" onsubmit="sendBulkFinancialAlert(event)">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                            
                            <!-- طريقة الإرسال -->
                            <div class="bg-[#0f172a] p-4 rounded-xl border border-gray-800">
                                <label class="text-gray-400 text-sm font-bold mb-3 block">طريقة تبليغ ولي الأمر:</label>
                                <div class="flex flex-col gap-3">
                                    <label class="flex items-center gap-3 text-white cursor-pointer hover:bg-gray-800 p-2 rounded-lg transition">
                                        <input type="checkbox" name="send_platform" checked class="w-5 h-5 accent-blue-500"> 
                                        <span><i class="fas fa-bell text-blue-500 me-2"></i> إشعار رسمي داخل لوحة ولي الأمر</span>
                                    </label>
                                    <label class="flex items-center gap-3 text-green-400 cursor-pointer hover:bg-gray-800 p-2 rounded-lg transition">
                                        <input type="checkbox" name="send_whatsapp" checked class="w-5 h-5 accent-green-500"> 
                                        <span><i class="fab fa-whatsapp text-lg me-2"></i> رسالة واتساب مباشرة</span>
                                    </label>
                                </div>
                            </div>

                            <!-- الفئة المستهدفة -->
                            <div class="bg-[#0f172a] p-4 rounded-xl border border-gray-800">
                                <label class="text-gray-400 text-sm font-bold mb-3 block">الفئة المستهدفة للتبليغ المالي:</label>
                                <select name="target_audience" class="w-full bg-[#1e293b] border border-gray-700 text-white font-bold rounded-xl py-3 px-4 outline-none focus:border-blue-500 cursor-pointer">
                                    <option value="all_defaulters">🔴 جميع الطلاب المتأخرين عن السداد (الفرز الآلي)</option>
                                    <option value="upcoming_installments">🟡 تذكير بالأقساط التي تستحق خلال 3 أيام</option>
                                </select>
                                <p class="text-xs text-blue-400 mt-3"><i class="fas fa-info-circle"></i> سيقوم النظام تلقائياً باستبعاد من سددوا أقساطهم.</p>
                            </div>
                        </div>

                        <!-- قالب الرسالة الذكية -->
                        <div class="bg-[#0f172a] p-4 rounded-xl border border-gray-800 mb-6">
                            <div class="flex justify-between items-end mb-3">
                                <label class="text-gray-400 text-sm font-bold block">صيغة الرسالة (قالب ذكي):</label>
                                <span class="text-xs text-blue-400 font-bold bg-blue-900/20 px-2 py-1 rounded">المتغيرات المدعومة: [اسم_الطالب] , [المبلغ] , [تاريخ_الاستحقاق]</span>
                            </div>
                            <textarea name="msg_body" rows="5" class="w-full bg-[#1e293b] border border-blue-900/50 text-white font-bold rounded-xl p-4 outline-none focus:border-blue-500 leading-relaxed" required>السيد ولي أمر الطالب [اسم_الطالب] المحترم،
تحية طيبة من إدارة الأكاديمية..
نود تذكيركم بوجود قسط دراسي مستحق الدفع بقيمة ([المبلغ]) وتجاوز تاريخ الاستحقاق.
يرجى تسديد المبلغ المتبقي في أقرب وقت. شكراً لتعاونكم.</textarea>
                        </div>

                        <button type="submit" id="btn-bulk-alert" class="w-full bg-blue-600 hover:bg-blue-500 text-white font-bold py-4 rounded-xl transition shadow-[0_0_20px_rgba(59,130,246,0.3)] text-lg">
                            <i class="fas fa-paper-plane me-2"></i> بدء الفرز وتوليد المطالبات المالية
                        </button>
                    </form>
                </div>
            </section>

            <!-- ========================================== -->
            <!-- 🛑 5. قسم الطلاب المؤقتين والمنسحبين 🛑 -->
            <!-- ========================================== -->
            <!-- STREAMING_CHUNK:Rendering Temporary Students Section... -->
            <section id="temp_studentsSection" class="hidden animate-[fadeIn_0.3s_ease-in-out]">
                <div class="flex justify-between items-center mb-5 no-print">
                    <h2 class="text-xl font-bold text-yellow-500"><i class="fas fa-user-clock"></i> السجل المالي للطلاب المؤقتين والمنسحبين</h2>
                    <button onclick="prepareAndPrintTempStudents('الكشف المالي للطلاب المؤقتين والمنسحبين')" class="bg-gray-800 text-white px-5 py-2.5 rounded-xl font-bold hover:bg-gray-700 transition border border-gray-700 shadow-lg"><i class="fas fa-print me-1"></i> طباعة الكشف</button>
                </div>
                
                <div class="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6 no-print">
                    <div class="glass-panel p-4 border-t-2 border-yellow-500">
                        <p class="text-[10px] text-gray-400 font-bold mb-1">العدد (مؤقت/منسحب)</p>
                        <h3 class="text-2xl font-black text-white" id="stat-temp-count">0</h3>
                    </div>
                    <div class="glass-panel p-4 border-t-2 border-blue-500">
                        <p class="text-[10px] text-gray-400 font-bold mb-1">الصافي الكلي المطلوب</p>
                        <h3 class="text-xl font-black text-blue-400 fin-font" id="stat-temp-total">0</h3>
                    </div>
                    <div class="glass-panel p-4 border-t-2 border-neon-green">
                        <p class="text-[10px] text-gray-400 font-bold mb-1">المستحصل منهم (أرباح)</p>
                        <h3 class="text-xl font-black text-neon-green fin-font" id="stat-temp-paid">0</h3>
                    </div>
                    <div class="glass-panel p-4 border-t-2 border-neon-red">
                        <p class="text-[10px] text-gray-400 font-bold mb-1">المتبقي بذمتهم (ديون)</p>
                        <h3 class="text-xl font-black text-neon-red fin-font" id="stat-temp-debt">0</h3>
                    </div>
                    <div class="glass-panel p-4 border-t-2 border-orange-500">
                        <p class="text-[10px] text-gray-400 font-bold mb-1">المسترجع لهم (فائض)</p>
                        <h3 class="text-xl font-black text-orange-400 fin-font" id="stat-temp-refund">0</h3>
                    </div>
                </div>

                <div class="glass-panel p-4 mb-6 flex flex-col md:flex-row gap-4 items-center bg-[#0f172a] border border-yellow-900/30">
                    <div class="relative flex-1 w-full">
                        <i class="fas fa-search absolute right-4 top-3.5 text-gray-400"></i>
                        <input type="text" id="temp-filter-name" onkeyup="renderTempStudentsTable()" placeholder="ابحث بالاسم عن المنسحبين..." class="w-full bg-[#1e293b] border border-gray-700 text-white font-bold rounded-xl py-3 pr-11 pl-4 outline-none focus:border-yellow-500 transition shadow-sm">
                    </div>
                    <div class="flex flex-wrap gap-2 w-full md:w-auto">
                        <select id="temp-filter-stage" onchange="renderTempStudentsTable()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-yellow-500 cursor-pointer">
                            <option value="">المرحلة (الكل)</option>
                            <?php foreach($unique_stages as $stg): ?><option value="<?= htmlspecialchars($stg) ?>"><?= htmlspecialchars($stg) ?></option><?php endforeach; ?>
                        </select>
                        <select id="temp-filter-dept" onchange="renderTempStudentsTable()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-yellow-500 cursor-pointer">
                            <option value="">القسم (الكل)</option>
                            <?php foreach($unique_depts as $dpt): ?><option value="<?= htmlspecialchars($dpt) ?>"><?= htmlspecialchars($dpt) ?></option><?php endforeach; ?>
                        </select>
                        
                        <!-- 🚀 تم إرجاع فلتر الشعبة هنا 🚀 -->
                        <select id="temp-filter-section" onchange="renderTempStudentsTable()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-yellow-500 cursor-pointer">
                            <option value="">الشعبة (الكل)</option>
                            <?php foreach($unique_sections as $sec): ?><option value="<?= htmlspecialchars($sec) ?>"><?= htmlspecialchars($sec) ?></option><?php endforeach; ?>
                        </select>

                        <select id="temp-filter-status" onchange="renderTempStudentsTable()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-yellow-500 cursor-pointer">
                            <option value="">كل الحالات</option>
                            <option value="temporary" class="text-orange-400">مؤقت</option>
                            <option value="withdrawn" class="text-red-500">منسحب</option>
                        </select>
                    </div>
                </div>

                <div class="overflow-x-auto rounded-xl border border-gray-800 shadow-xl bg-[#0f172a]">
                    <table class="w-full text-right text-sm whitespace-nowrap">
                        <thead class="bg-[#1e293b] text-gray-400 border-b border-gray-700">
                            <tr>
                                <th class="p-4 font-bold text-white">اسم الطالب / المعرف</th>
                                <th class="p-4 font-bold">الصف / القسم</th>
                                <th class="p-4 font-bold text-center">الحالة</th>
                                <th class="p-4 font-bold text-center text-blue-400">الصافي المطلوب</th>
                                <th class="p-4 font-bold text-center text-green-400">المستحصل</th>
                                <th class="p-4 font-bold text-center text-orange-400">المسترجع (فائض)</th>
                                <th class="p-4 font-bold text-center text-red-400">ديون (متبقي)</th>
                                <th class="p-4 font-bold text-center no-print">الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody id="tempStudentTable" class="divide-y divide-gray-800">
                            <!-- يعبأ بواسطة JS -->
                        </tbody>
                    </table>
                </div>
            </section>

            <!-- ========================================== -->
            <!-- 🚀 6. قسم الترحيل الأكاديمي الشامل 🚀 -->
            <!-- ========================================== -->
            <!-- STREAMING_CHUNK:Rendering Promotion Section... -->
            <section id="promotionSection" class="hidden animate-[fadeIn_0.3s_ease-in-out]">
                <div class="glass-panel p-6 border-t-2 border-red-500 mb-6">
                    <div class="flex justify-between items-center mb-6 border-b border-gray-800 pb-4">
                        <h2 class="text-xl font-bold text-white"><i class="fas fa-rocket text-red-500 me-2"></i> مركز الترحيل الأكاديمي للعام الجديد</h2>
                        <button onclick="openPromotionModal()" class="bg-red-600 hover:bg-red-500 text-white px-6 py-2.5 rounded-xl font-bold transition shadow-[0_0_15px_rgba(239,68,68,0.4)] flex items-center gap-2">
                            <i class="fas fa-paper-plane"></i> ترحيل الطلاب المحددين
                        </button>
                    </div>

                    <div class="bg-red-900/10 border border-red-900/30 p-4 rounded-xl mb-6 text-sm text-red-200 font-bold">
                        <i class="fas fa-info-circle text-red-400 me-2"></i> قم بفلترة الطلاب حسب مرحلتهم الحالية، ثم حدد الناجحين لترحيلهم دفعة واحدة للمرحلة القادمة.
                    </div>

                    <div class="flex flex-col md:flex-row gap-4 items-center bg-[#0f172a] p-4 rounded-xl border border-gray-800 mb-6">
                        <div class="relative flex-1 w-full">
                            <i class="fas fa-search absolute right-4 top-3.5 text-gray-400"></i>
                            <input type="text" id="promo-filter-name" onkeyup="renderPromotionTable()" placeholder="ابحث بالاسم..." class="w-full bg-[#1e293b] border border-gray-700 text-white font-bold rounded-xl py-3 pr-11 pl-4 outline-none focus:border-red-500 transition shadow-sm">
                        </div>
                        <div class="flex flex-wrap gap-2 w-full md:w-auto">
                            <select id="promo-filter-stage" onchange="renderPromotionTable()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-red-500 cursor-pointer">
                                <option value="">المرحلة الحالية (الكل)</option>
                                <?php foreach($unique_stages as $stg): ?><option value="<?= htmlspecialchars($stg) ?>"><?= htmlspecialchars($stg) ?></option><?php endforeach; ?>
                            </select>
                            <select id="promo-filter-dept" onchange="renderPromotionTable()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-red-500 cursor-pointer">
                                <option value="">القسم الحالي (الكل)</option>
                                <?php foreach($unique_depts as $dpt): ?><option value="<?= htmlspecialchars($dpt) ?>"><?= htmlspecialchars($dpt) ?></option><?php endforeach; ?>
                            </select>
                            <select id="promo-filter-section" onchange="renderPromotionTable()" class="bg-[#1e293b] border border-gray-700 text-gray-300 font-bold rounded-xl py-3 px-4 outline-none focus:border-red-500 cursor-pointer">
                                <option value="">الشعبة الحالية (الكل)</option>
                                <?php foreach($unique_sections as $sec): ?><option value="<?= htmlspecialchars($sec) ?>"><?= htmlspecialchars($sec) ?></option><?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="overflow-x-auto rounded-xl border border-gray-800 shadow-xl bg-[#0f172a]">
                        <table class="w-full text-right text-sm whitespace-nowrap">
                            <thead class="bg-[#1e293b] text-gray-400 border-b border-gray-700">
                                <tr>
                                    <th class="p-4 text-center w-12"><input type="checkbox" onclick="toggleAllPromotion(this)" class="w-5 h-5 accent-red-500 cursor-pointer"></th>
                                    <th class="p-4 font-bold text-white">اسم الطالب / المعرف</th>
                                    <th class="p-4 font-bold">المرحلة الحالية</th>
                                    <th class="p-4 font-bold text-center">القسم / الشعبة</th>
                                    <th class="p-4 font-bold text-center">الموقف المالي</th>
                                </tr>
                            </thead>
                            <tbody id="promotionTableBody" class="divide-y divide-gray-800">
                                <!-- يعبأ بواسطة JS -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>
        </main>
    </div>
    
    <div class="omni-container no-print">
        <div class="omni-menu">
            <div class="omni-item text-green-400" onclick="showToast('افتح بطاقة الطالب للقيام بهذه العملية', 'info')">
                <i class="fas fa-hand-holding-usd w-5 text-center"></i> <span>استلام مبلغ (وارد)</span>
            </div>
            <div class="omni-item text-red-400" onclick="showToast('سيتم برمجة قسم المصروفات لاحقاً', 'info')">
                <i class="fas fa-file-invoice-dollar w-5 text-center"></i> <span>صرف مبلغ (صادر)</span>
            </div>
        </div>
        <div class="omni-btn"><i class="fas fa-plus"></i></div>
    </div>

    <!-- ========================================== -->
    <!-- 🚀 جميع النوافذ المنبثقة (Modals) 🚀 -->
    <!-- ========================================== -->
    <!-- STREAMING_CHUNK:Rendering Modals... -->

    <!-- 1. نافذة مصفوفة الأسعار -->
    <div id="pricingMatrixModal" class="fixed inset-0 bg-black bg-opacity-90 hidden items-center justify-center z-[100] no-print backdrop-blur-sm">
        <div class="bg-[#0f172a] border border-blue-500 rounded-2xl p-6 w-11/12 max-w-lg shadow-[0_0_50px_rgba(59,130,246,0.2)]">
            <div class="flex justify-between items-center mb-5 border-b border-gray-800 pb-3">
                <h3 class="text-xl font-bold text-white"><i class="fas fa-cog text-blue-500 me-2"></i> مصفوفة الأسعار الأساسية</h3>
                <button onclick="closeModal('pricingMatrixModal')" class="text-gray-500 hover:text-white transition"><i class="fas fa-times text-2xl"></i></button>
            </div>
            <div class="text-sm text-gray-400 mb-4 bg-blue-900/20 p-3 rounded-lg border border-blue-900/50">
                حدد القسط الثابت لكل مرحلة هنا مرة واحدة. عند تسجيل قيد مالي لأي طالب، سيقوم النظام بسحب القسط تلقائياً.
            </div>
            <form id="pricingMatrixForm" onsubmit="submitPricingMatrix(event)">
                <div id="pricing_rows" class="space-y-3 mb-4 max-h-60 overflow-y-auto pr-2"></div>
                <div class="flex justify-end gap-3 pt-4 border-t border-gray-800">
                    <button type="button" onclick="closeModal('pricingMatrixModal')" class="bg-gray-800 text-gray-300 px-5 py-2.5 rounded-lg font-bold hover:bg-gray-700 transition">إلغاء</button>
                    <button type="submit" class="bg-blue-600 text-white px-6 py-2.5 rounded-lg font-bold hover:bg-blue-500 transition shadow-lg"><i class="fas fa-save me-1"></i> حفظ الإعدادات</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 2. النافذة البيضاء الشاملة -->
    <div id="newStudentModalBox" class="fixed inset-0 bg-black bg-opacity-90 hidden items-center justify-center z-[100] no-print backdrop-blur-sm">
        <div class="bg-white border-2 border-[#10b981] rounded-2xl p-6 w-11/12 max-w-3xl shadow-[0_0_50px_rgba(16,185,129,0.2)] transform transition-all" style="max-height: 90vh; overflow-y: auto;">
            <div style="display: flex; justify-between; align-items: center; margin-bottom: 25px; border-bottom: 2px solid #f1f5f9; padding-bottom: 15px;">
                <h3 style="margin: 0; color: #1e293b; font-size: 1.4rem; font-weight: 900;"><i class="fas fa-user-graduate" style="color: #10b981; margin-left: 8px;"></i> تسجيل طالب وقيد مالي جديد</h3>
                <button type="button" onclick="closeAndResetStudentModal()" class="text-gray-400 hover:text-red-500 text-3xl font-bold bg-transparent border-none cursor-pointer">&times;</button>
            </div>
            
            <form id="adminNewStudentForm" enctype="multipart/form-data" onsubmit="event.preventDefault(); saveAdminNewStudent();">
                <div style="margin-bottom: 15px; text-align: right;">
                    <label style="font-weight: bold; color: #333; display: block; margin-bottom: 8px;">المنطقة الزمنية (توقيت المدرسة):</label>
                    <select name="timezone" class="w-full p-3 bg-white border border-gray-300 text-gray-800 rounded-lg outline-none focus:border-[#10b981] transition font-bold">
                        <option value="Asia/Baghdad">العراق (بغداد)</option>
                        <option value="Asia/Riyadh">السعودية (الرياض)</option>
                        <option value="Asia/Dubai">الإمارات (دبي)</option>
                        <option value="Asia/Amman">الأردن (عمان)</option>
                        <option value="Africa/Cairo">مصر (القاهرة)</option>
                    </select>
                </div>

                <div style="margin-bottom: 15px; text-align: right;">
                    <label style="display: block; font-weight: bold; margin-bottom: 8px; color: #334155;">الاسم الكامل:</label>
                    <input type="text" name="student_name" class="w-full p-3 bg-gray-50 border border-gray-300 text-gray-800 rounded-lg outline-none focus:border-[#10b981] transition font-bold" placeholder="اكتب اسم الطالب الثلاثي..." required>
                </div>

                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; margin-bottom: 15px; direction: rtl;">
                    <div style="text-align: right;">
                        <label style="display: block; font-weight: bold; margin-bottom: 8px; color: #334155;">رقم الموبايل:</label>
                        <input type="text" name="phone" class="w-full p-3 bg-gray-50 border border-gray-300 text-gray-800 rounded-lg outline-none focus:border-[#10b981] transition font-bold" placeholder="07xxxxxxxxx" required dir="ltr">
                    </div>
                    <div style="text-align: right;">
                        <label style="display: block; font-weight: bold; margin-bottom: 8px; color: #334155;">البريد الإلكتروني (للوحة الطالب):</label>
                        <input type="email" name="email" class="w-full p-3 bg-gray-50 border border-gray-300 text-gray-800 rounded-lg outline-none focus:border-[#10b981] transition font-bold" placeholder="student@example.com" required dir="ltr">
                    </div>
                </div>

                <div style="background: rgba(16, 185, 129, 0.1); border: 1px dashed #10b981; padding: 10px; border-radius: 8px; margin-bottom: 15px; text-align: center; color: #059669; font-weight: bold; font-size: 0.9rem;">
                    <i class="fas fa-info-circle"></i> كلمة المرور الافتراضية للوحة تحكم الطالب هي: <strong>1234567</strong>
                </div>

                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin-bottom: 20px; direction: rtl;">
                    <div style="text-align: right;">
                        <label style="display: block; font-size: 13px; font-weight: bold; margin-bottom: 6px; color: #334155;">المرحلة (تحدد السعر):</label>
                        <select name="stage" id="combined_stage_select" class="dynamic-stage-filter w-full p-3 bg-gray-50 border border-gray-300 text-gray-800 rounded-lg outline-none focus:border-[#10b981] transition font-bold" required onchange="updateCombinedPrice()">
                            <option value="">-- اختر المرحلة --</option>
                        </select>
                    </div>
                    <div style="text-align: right;">
                        <label style="display: block; font-size: 13px; font-weight: bold; margin-bottom: 6px; color: #334155;">القسم:</label>
                        <select name="department" class="dynamic-dept-filter w-full p-3 bg-gray-50 border border-gray-300 text-gray-800 rounded-lg outline-none focus:border-[#10b981] transition font-bold">
                            <option value="عام">عام</option>
                        </select>
                    </div>
                    <div style="text-align: right;">
                        <label style="display: block; font-size: 13px; font-weight: bold; margin-bottom: 6px; color: #334155;">الشعبة:</label>
                        <select name="branch" class="dynamic-branch-filter w-full p-3 bg-gray-50 border border-gray-300 text-gray-800 rounded-lg outline-none focus:border-[#10b981] transition font-bold">
                            <option value="الكل">الكل</option>
                        </select>
                    </div>
                </div>

                <div style="background: #f8fafc; border: 1px solid #cbd5e1; padding: 20px; border-radius: 12px; margin-bottom: 20px; direction: rtl;">
                    <h4 style="margin-top:0; color:#0f172a; font-weight:900; border-bottom:2px solid #e2e8f0; padding-bottom:8px; margin-bottom:15px;"><i class="fas fa-file-invoice-dollar" style="color:#10b981; margin-left:5px;"></i> الإعداد المالي المباشر للقسط</h4>
                    
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px;">
                        <div>
                            <label style="font-size:12px; font-weight:bold; color:#64748b; display:block; margin-bottom:5px;">القسط الأساسي (يُسحب تلقائياً):</label>
                            <input type="text" id="auto_base_price" style="width: 100%; padding: 12px; border-radius: 8px; border: 1px solid #cbd5e1; background:#e2e8f0; color:#334155; font-weight:bold; font-size: 16px;" readonly value="0">
                        </div>
                        <div>
                            <label style="font-size:12px; font-weight:bold; color:#f59e0b; display:block; margin-bottom:5px;">مبلغ الخصم (إن وجد) د.ع:</label>
                            <input type="number" id="auto_discount" name="discount" style="width: 100%; padding: 12px; border-radius: 8px; border: 2px solid #fcd34d; color:#d97706; font-weight:bold; font-size: 16px; outline:none;" value="0" min="0" oninput="calcCombinedNet()">
                        </div>
                        <div>
                            <label style="font-size:12px; font-weight:bold; color:#10b981; display:block; margin-bottom:5px;">الصافي المطلوب دفعه:</label>
                            <input type="text" id="auto_net_price" name="net_total" style="width: 100%; padding: 12px; border-radius: 8px; border: 2px solid #10b981; background:#dcfce7; color:#047857; font-weight:900; font-size:18px;" readonly value="0">
                        </div>
                    </div>
                </div>

                <div style="background: rgba(16, 185, 129, 0.05); border: 1px dashed #10b981; padding: 15px; border-radius: 12px; margin-bottom: 25px; text-align: center;">
                    <label style="font-weight: bold; font-size: 14px; display: block; margin-bottom: 10px; color: #047857;">معرف المزامنة للبطاقة الذكية (Sync ID):</label>
                    <div style="display: flex; gap: 10px;">
                        <input type="text" name="student_id" id="admin-std-syncid" style="flex: 1; font-weight: bold; color: #047857; text-align: center; font-size: 18px; letter-spacing: 2px; background: white; border: 1px solid #10b981; border-radius: 10px; padding: 12px; box-sizing: border-box; outline: none;" readonly placeholder="اضغط على توليد لبناء المعرف">
                        <button type="button" style="background: #1e293b; color: white; width: auto; padding: 0 20px; border: none; border-radius: 10px; cursor: pointer; font-weight: bold; transition: 0.2s;" onclick="generateAdminSyncID()">توليد الكود</button>
                    </div>
                </div>

                <button type="submit" id="btn-final-save" style="width: 100%; font-size: 1.2rem; padding: 15px; background: linear-gradient(135deg, #10b981, #059669); color: white; border: none; border-radius: 12px; font-weight: 900; cursor: pointer; box-shadow: 0 5px 15px rgba(16, 185, 129, 0.4); transition: 0.2s;">
                    <i class="fas fa-check-double ml-2"></i> حفظ الطالب وتثبيت القيد المالي
                </button>
            </form>
        </div>
    </div>

    <!-- 3. نافذة السند المالي الذكية (قبض / صرف) -->
    <div id="addPaymentModal" class="fixed inset-0 bg-black bg-opacity-90 hidden items-center justify-center z-[200] no-print backdrop-blur-sm">
        <div id="voucher-modal-bg" class="bg-[#0f172a] border-2 border-green-500 rounded-2xl p-6 w-11/12 max-w-md shadow-[0_0_50px_rgba(16,185,129,0.2)] transition-colors duration-300">
            <div class="flex justify-between items-center mb-5 border-b border-gray-800 pb-3">
                <h3 id="voucher-modal-title" class="text-xl font-bold text-green-500"><i id="voucher-modal-icon" class="fas fa-hand-holding-usd me-2"></i> تسجيل دفعة (سند قبض)</h3>
                <button onclick="closeModal('addPaymentModal')" class="text-gray-500 hover:text-white transition"><i class="fas fa-times text-2xl"></i></button>
            </div>
            <form onsubmit="submitPayment(event)">
                <input type="hidden" id="pay-student-id">
                
                <div class="mb-4 bg-gray-900/50 p-3 rounded-lg border border-gray-800">
                    <label class="modal-label text-white">نوع السند المالي:</label>
                    <select id="pay-voucher-type" class="w-full p-2 bg-[#1e293b] border border-gray-600 text-white rounded font-bold outline-none cursor-pointer" onchange="toggleStudentVoucherType()">
                        <option value="income">🟢 سند قبض (استلام مبلغ من الطالب)</option>
                        <option value="expense">🔴 سند صرف (استرجاع مبلغ للطالب)</option>
                    </select>
                </div>

                <div class="mb-4">
                    <label class="modal-label">اسم الطالب:</label>
                    <input type="text" id="pay-student-name" class="modal-input bg-gray-800 text-gray-400 font-bold cursor-not-allowed" disabled>
                </div>
                <div class="mb-4">
                    <label class="modal-label" id="lbl-amount">المبلغ المستلم (د.ع):</label>
                    <input type="number" id="pay-amount" class="w-full p-3 bg-[#0f172a] border-2 border-gray-600 font-black text-2xl text-center tracking-wider rounded-lg outline-none text-white focus:border-blue-500 transition" required min="1">
                </div>
                <div class="grid grid-cols-2 gap-4 mb-6">
                    <div>
                        <label class="modal-label">طريقة الدفع:</label>
                        <select id="pay-method" class="modal-input font-bold">
                            <option value="كاش">كاش (نقدي)</option>
                            <option value="حوالة بنكية">حوالة بنكية</option>
                            <option value="زين كاش">زين كاش</option>
                        </select>
                    </div>
                    <div>
                        <label class="modal-label">تاريخ الحركة:</label>
                        <input type="date" id="pay-date" class="modal-input font-mono font-bold" required>
                    </div>
                </div>
                <div class="flex justify-end gap-3 pt-2 border-t border-gray-800">
                    <button type="button" onclick="closeModal('addPaymentModal')" class="bg-gray-800 text-gray-300 px-5 py-2.5 rounded-lg font-bold hover:bg-gray-700 transition">إلغاء</button>
                    <button type="submit" id="btn-submit-voucher" class="bg-green-600 text-white px-6 py-2.5 rounded-lg font-bold hover:bg-green-500 transition shadow-lg"><i class="fas fa-check-circle me-1"></i> تأكيد الاستلام</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 4. نافذة التسوية المالية (تثبيت القسط للقدامى) -->
    <div id="smartEnrollmentModal" class="fixed inset-0 bg-black bg-opacity-90 hidden items-center justify-center z-[100] no-print backdrop-blur-sm">
        <div class="bg-[#0f172a] border border-[#3b82f6] rounded-2xl p-6 w-11/12 max-w-md shadow-[0_0_50px_rgba(59,130,246,0.2)] transform transition-all">
            <div class="flex justify-between items-center mb-5 border-b border-gray-800 pb-3">
                <h3 class="text-xl font-bold text-white"><i class="fas fa-file-signature text-[#3b82f6] me-2"></i> التسوية المالية (تثبيت القسط)</h3>
                <button type="button" onclick="closeModal('smartEnrollmentModal')" class="text-gray-400 hover:text-red-500 text-2xl font-bold bg-transparent border-none cursor-pointer">&times;</button>
            </div>
            
            <form onsubmit="event.preventDefault(); submitSmartEnrollment();">
                <input type="hidden" id="se_student_id">
                
                <div class="mb-4 text-center bg-blue-900/20 p-3 rounded-lg border border-blue-800/50">
                    <span class="text-gray-400 text-sm font-bold block mb-1">اسم الطالب:</span>
                    <span id="se_student_name_display" class="text-white font-black text-lg"></span>
                </div>
                
                <div class="mb-4">
                    <label style="font-size:12px; font-weight:bold; color:#64748b; display:block; margin-bottom:5px;">القسط السنوي المقرر (الأساسي):</label>
                    <input type="number" id="se_base_price" class="w-full p-3 bg-gray-900 border border-gray-700 text-white rounded-lg outline-none focus:border-[#3b82f6] transition font-bold" required oninput="calcOldStudentNet()">
                </div>
                
                <div class="mb-4">
                    <label style="font-size:12px; font-weight:bold; color:#f59e0b; display:block; margin-bottom:5px;">مبلغ الخصم (إن وجد) د.ع:</label>
                    <input type="number" id="se_discount_amt" class="w-full p-3 bg-gray-900 border border-yellow-700 text-yellow-500 rounded-lg outline-none focus:border-yellow-500 transition font-bold" value="0" min="0" oninput="calcOldStudentNet()">
                </div>
                
                <div class="mb-6">
                    <label style="font-size:12px; font-weight:bold; color:#10b981; display:block; margin-bottom:5px;">الصافي النهائي للمطالبة:</label>
                    <input type="number" id="se_net_price" class="w-full p-3 bg-green-900/20 border-2 border-[#10b981] text-green-400 text-xl font-black rounded-lg outline-none" readonly required>
                </div>
                
                <button type="submit" id="btn-submit-se" class="w-full bg-[#3b82f6] text-white px-6 py-3 rounded-xl font-bold hover:bg-[#2563eb] transition shadow-[0_5px_15px_rgba(59,130,246,0.3)]">
                    <i class="fas fa-save me-1"></i> اعتماد القيد المالي
                </button>
            </form>
        </div>
    </div>

    <!-- 5. نافذة إعادة الجدولة والمطالبات الأقساط -->
    <div id="rescheduleModal" class="fixed inset-0 bg-black bg-opacity-90 hidden items-center justify-center z-[100] no-print backdrop-blur-sm">
        <div class="bg-[#0f172a] border border-purple-600 rounded-2xl p-6 w-11/12 max-w-xl max-h-[90vh] overflow-y-auto shadow-[0_0_50px_rgba(147,51,234,0.3)]">
            <div class="flex justify-between items-center mb-4 border-b border-gray-800 pb-3">
                <h3 class="text-xl font-bold text-white"><i class="fas fa-cogs text-purple-500 me-2"></i> خطة الجدولة وتقسيم الأقساط</h3>
                <button onclick="closeModal('rescheduleModal')" class="text-gray-400 hover:text-red-500 text-2xl font-bold bg-transparent border-none cursor-pointer">&times;</button>
            </div>
            <form onsubmit="submitReschedule(event)">
                <input type="hidden" id="resch-student-id">
                <div class="grid grid-cols-2 gap-4 mb-4">
                    <div>
                        <label class="text-gray-400 text-xs mb-1 block font-bold">اسم الطالب:</label>
                        <input type="text" id="resch-student-name" class="w-full p-3 bg-gray-900 border border-gray-800 text-purple-400 rounded-xl font-bold" disabled>
                    </div>
                    <div>
                        <label class="text-gray-400 text-xs mb-1 block font-bold">الدين المتبقي للجدولة:</label>
                        <input type="text" id="resch-remaining-debt" class="w-full p-3 bg-gray-900 border border-gray-800 text-red-500 rounded-xl font-bold fin-font text-lg" disabled>
                        <input type="hidden" id="resch-raw-debt">
                    </div>
                </div>
                
                <div class="bg-purple-900/10 p-4 rounded-xl mb-4 border border-purple-900/30">
                    <div class="flex gap-2 items-end mb-4">
                        <div class="flex-1">
                            <label class="text-purple-300 text-xs font-bold mb-1 block">عدد الأقساط المطلوبة:</label>
                            <input type="number" id="resch-inst-count" value="1" min="1" class="w-full p-3 bg-gray-900 border border-purple-900/50 text-white rounded-xl font-bold outline-none focus:border-purple-500">
                        </div>
                        <button type="button" onclick="generateRescheduleRows()" class="bg-purple-600 hover:bg-purple-500 text-white px-6 py-3 rounded-xl font-bold transition shadow-md">
                            توليد الأقساط
                        </button>
                    </div>
                    
                    <div id="resch_inst_rows" class="space-y-3 max-h-60 overflow-y-auto pr-1"></div>
                    
                    <div id="resch-validation-msg" class="hidden mt-3 text-red-400 text-xs font-bold text-center bg-red-900/20 p-2 rounded-lg border border-red-900/50">
                        <i class="fas fa-exclamation-triangle me-1"></i> مجموع الأقساط لا يساوي الدين المتبقي!
                    </div>
                </div>

                <button type="submit" id="btn-submit-resch" class="w-full bg-purple-600 hover:bg-purple-500 text-white py-3.5 rounded-xl font-bold text-lg transition shadow-[0_5px_15px_rgba(147,51,234,0.3)]">
                    <i class="fas fa-check-circle me-1"></i> اعتماد وحفظ خطة الجدولة
                </button>
            </form>
        </div>
    </div>
    
    <!-- 6. كشف الحساب -->
    <div id="statementModal" class="fixed inset-0 bg-black bg-opacity-90 hidden items-center justify-center z-[150] no-print backdrop-blur-sm">
        <div class="bg-[#0f172a] border border-blue-500 rounded-2xl p-6 w-11/12 max-w-4xl max-h-[90vh] overflow-y-auto shadow-[0_0_50px_rgba(59,130,246,0.2)] print-bg-white">
            
            <div class="flex justify-between items-center mb-6 border-b border-gray-800 pb-4 print-border">
                <div class="flex items-center gap-4">
                    <div class="w-12 h-12 bg-blue-500/20 text-blue-500 rounded-xl flex items-center justify-center text-2xl border border-blue-500/50">
                        <i class="fas fa-file-invoice-dollar"></i>
                    </div>
                    <div>
                        <h2 class="text-2xl font-black text-white">كشف حساب تفصيلي</h2>
                        <p class="text-sm text-gray-400 font-mono" id="stmt-date"></p>
                        <input type="hidden" id="stmt-current-student-id">
                    </div>
                </div>
                <div class="flex gap-3 no-print">
                    <button id="btn-email-statement" onclick="sendStatementEmail()" class="bg-purple-600 hover:bg-purple-500 text-white px-5 py-2.5 rounded-xl font-bold transition shadow-lg flex items-center gap-2">
                        <i class="fas fa-envelope"></i> إرسال لولي الأمر
                    </button>
                    <button onclick="window.print()" class="bg-blue-600 hover:bg-blue-500 text-white px-5 py-2.5 rounded-xl font-bold transition shadow-lg">
                        <i class="fas fa-print me-2"></i> طباعة الكشف
                    </button>
                    <button onclick="closeModal('statementModal')" class="bg-gray-800 text-gray-400 hover:text-red-500 w-10 h-10 rounded-xl font-bold transition text-xl">
                        &times;
                    </button>
                </div>
            </div>

            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6 bg-gray-900/50 p-4 rounded-xl border border-gray-800 print-bg-white print-border">
                <div>
                    <span class="block text-xs text-gray-500 font-bold mb-1">اسم الطالب:</span>
                    <span class="font-bold text-white text-base" id="stmt-name">-</span>
                </div>
                <div>
                    <span class="block text-xs text-gray-500 font-bold mb-1">رقم القيد (المعرف):</span>
                    <span class="font-bold text-white text-base font-mono" id="stmt-id">-</span>
                </div>
                <div>
                    <span class="block text-xs text-gray-500 font-bold mb-1">المرحلة والقسم:</span>
                    <span class="font-bold text-white text-base" id="stmt-stage">-</span>
                </div>
                <div class="text-left md:text-right">
                    <span class="block text-xs text-gray-500 font-bold mb-1">صافي القسط السنوي:</span>
                    <span class="font-black text-blue-400 text-xl fin-font" id="stmt-total">0</span>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div>
                    <h3 class="text-white font-bold mb-3 border-r-4 border-green-500 pr-2">سجل المدفوعات (الواصل)</h3>
                    <div class="overflow-x-auto rounded-xl border border-gray-800 print-border bg-[#0f172a] print-bg-white">
                        <table class="w-full text-right text-sm">
                            <thead class="bg-gray-800 text-gray-400 border-b border-gray-700 print-border print-bg-white">
                                <tr>
                                    <th class="p-3 font-bold"># الوصل</th>
                                    <th class="p-3 font-bold">تاريخ الدفع</th>
                                    <th class="p-3 font-bold text-green-400">المبلغ المستلم</th>
                                    <th class="p-3 font-bold">الطريقة</th>
                                </tr>
                            </thead>
                            <tbody id="stmt-payments-body" class="divide-y divide-gray-800 print-border">
                                <!-- يعبأ بواسطة JS -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <div>
                    <div class="flex justify-between items-end mb-3 border-r-4 border-red-500 pr-2">
                        <h3 class="text-white font-bold">خطة الأقساط (الديون)</h3>
                        <div class="text-sm font-bold text-gray-400">
                            إجمالي المتبقي: <span class="text-red-400 fin-font font-black text-xl ml-1" id="stmt-debt">0</span>
                        </div>
                    </div>
                    <div class="overflow-x-auto rounded-xl border border-gray-800 print-border bg-[#0f172a] print-bg-white">
                        <table class="w-full text-right text-sm">
                            <thead class="bg-gray-800 text-gray-400 border-b border-gray-700 print-border print-bg-white">
                                <tr>
                                    <th class="p-3 font-bold">تاريخ الاستحقاق</th>
                                    <th class="p-3 font-bold text-red-400">المبلغ المطلوب</th>
                                    <th class="p-3 font-bold text-center">الحالة</th>
                                </tr>
                            </thead>
                            <tbody id="stmt-installments-body" class="divide-y divide-gray-800 print-border">
                                <!-- يعبأ بواسطة JS -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 🚀 الإضافة الجديدة: صندوق المسترجعات للكشف 🚀 -->
            <div id="stmt-refunds-section" class="mt-6 hidden">
                <h3 class="text-white font-bold mb-3 border-r-4 border-orange-500 pr-2">سجل المبالغ المسترجعة (المصروفة للطالب)</h3>
                <div class="bg-orange-900/10 border border-orange-800/50 p-4 rounded-xl flex justify-between items-center print-border print-bg-white">
                    <span class="text-gray-300 font-bold">إجمالي المبالغ التي تم استرجاعها للطالب:</span>
                    <span class="text-orange-400 font-black text-xl fin-font" id="stmt-refund-total">0 د.ع</span>
                </div>
            </div>

            <div class="mt-8 pt-4 border-t border-gray-300 hidden text-center" style="display: none;">
                <p class="font-bold text-sm">تم إصدار هذا الكشف آلياً من النظام المالي الأكاديمي.</p>
                <p class="text-xs text-gray-500 mt-1" id="print-timestamp"></p>
            </div>
        </div>
    </div>

            <div class="mt-8 pt-4 border-t border-gray-300 hidden text-center" style="display: none;">
                <p class="font-bold text-sm">تم إصدار هذا الكشف آلياً من النظام المالي الأكاديمي.</p>
                <p class="text-xs text-gray-500 mt-1" id="print-timestamp"></p>
            </div>
        </div>
    </div>

    <!-- 7. نافذة روابط الواتساب المالية -->
    <div id="financialWhatsappModal" class="fixed inset-0 bg-black bg-opacity-90 hidden items-center justify-center z-[200] no-print backdrop-blur-sm">
        <div class="bg-[#0f172a] border border-[#25D366] rounded-2xl p-6 w-11/12 max-w-lg shadow-[0_0_50px_rgba(37,211,102,0.2)]">
            <div class="flex justify-between items-center mb-5 border-b border-gray-800 pb-3">
                <h3 class="text-xl font-bold text-white"><i class="fab fa-whatsapp text-[#25D366] me-2 text-2xl"></i> روابط إرسال المطالبات</h3>
                <button type="button" onclick="closeModal('financialWhatsappModal')" class="text-gray-400 hover:text-red-500 text-2xl font-bold bg-transparent border-none cursor-pointer">&times;</button>
            </div>
            <p class="text-sm text-gray-400 mb-4 font-bold">تم تجهيز الرسائل بالأرقام والمبالغ الدقيقة. اضغط على اسم كل طالب لإرسال رسالته عبر الواتساب:</p>
            <div id="financial-whatsapp-links" class="max-h-60 overflow-y-auto space-y-2 pr-2 timeline-scroll"></div>
            <button onclick="closeModal('financialWhatsappModal')" class="w-full mt-5 bg-gray-800 hover:bg-gray-700 text-white py-3 rounded-xl font-bold transition">إنهاء وإغلاق</button>
        </div>
    </div>

    <!-- 8. نافذة تغيير حالة قيد الطالب (منسحب / مؤقت) -->
    <div id="statusModal" class="fixed inset-0 bg-black bg-opacity-90 hidden items-center justify-center z-[200] no-print backdrop-blur-sm">
        <div class="bg-[#0f172a] border border-yellow-600 rounded-2xl p-6 w-11/12 max-w-md shadow-[0_0_50px_rgba(234,179,8,0.2)] transform transition-all">
            <div class="flex justify-between items-center mb-5 border-b border-gray-800 pb-3">
                <h3 class="text-xl font-bold text-white"><i class="fas fa-exchange-alt text-yellow-500 me-2"></i> تغيير حالة قيد الطالب</h3>
                <button onclick="closeModal('statusModal')" class="text-gray-500 hover:text-white transition"><i class="fas fa-times text-2xl"></i></button>
            </div>
            <form onsubmit="submitChangeStatus(event)">
                <input type="hidden" id="status-student-id">
                <div class="mb-4">
                    <label class="block text-gray-400 text-sm font-bold mb-2">اسم الطالب:</label>
                    <input type="text" id="status-student-name" class="w-full p-3 bg-gray-900 border border-gray-800 text-gray-500 font-bold rounded-lg outline-none cursor-not-allowed" disabled>
                </div>
                <div class="mb-6">
                    <label class="block text-gray-400 text-sm font-bold mb-3">حالة القيد الأكاديمي والمالي:</label>
                    <select id="status-select" class="w-full p-3 bg-[#1e293b] border border-yellow-800 text-white rounded-lg outline-none focus:border-yellow-500 transition font-bold">
                        <option value="active">🟢 مستمر (طالب نظامي نشط)</option>
                        <option value="temporary">🟠 مؤقت (يداوم لفترة محددة)</option>
                        <option value="withdrawn">🔴 منسحب / منقول (ترك المدرسة)</option>
                    </select>
                </div>
                <div class="flex justify-end gap-3 pt-2 border-t border-gray-800 mt-2">
                    <button type="button" onclick="closeModal('statusModal')" class="bg-gray-800 text-gray-300 px-5 py-2.5 rounded-lg font-bold hover:bg-gray-700 transition">إلغاء</button>
                    <button type="submit" class="bg-yellow-600 text-white px-6 py-2.5 rounded-lg font-bold hover:bg-yellow-500 transition shadow-lg"><i class="fas fa-save me-1"></i> حفظ الحالة</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 9. نافذة الترحيل المنبثقة (Promotion Modal) -->
    <div id="promotionModal" class="fixed inset-0 bg-black bg-opacity-90 hidden items-center justify-center z-[200] no-print backdrop-blur-sm">
        <div class="bg-[#0f172a] border border-red-500 rounded-2xl p-6 w-11/12 max-w-md shadow-[0_0_50px_rgba(239,68,68,0.2)] transform transition-all">
            <div class="flex justify-between items-center mb-5 border-b border-gray-800 pb-3">
                <h3 class="text-xl font-bold text-white"><i class="fas fa-rocket text-red-500 me-2"></i> ترحيل الطلاب المحددين</h3>
                <button onclick="closeModal('promotionModal')" class="text-gray-500 hover:text-white transition"><i class="fas fa-times text-2xl"></i></button>
            </div>
            <div style="padding: 10px;">
                <p class="text-gray-400 mb-5 text-sm font-bold">اختر المرحلة والصف الجديد الذي سيتم ترحيل الطلاب المحددين إليه:</p>
                <form onsubmit="event.preventDefault(); executePromotion();">
                    <div class="mb-4">
                        <label class="text-gray-400 text-xs font-bold mb-2 block">المرحلة الجديدة:</label>
                        <select id="promo_stage" class="w-full p-3 bg-[#1e293b] border border-gray-700 text-white rounded-lg outline-none focus:border-red-500 transition font-bold" required>
                            <option value="">-- اختر المرحلة --</option>
                        </select>
                    </div>
                    <div class="mb-4">
                        <label class="text-gray-400 text-xs font-bold mb-2 block">القسم/المسار الجديد:</label>
                        <select id="promo_dept" class="w-full p-3 bg-[#1e293b] border border-gray-700 text-white rounded-lg outline-none focus:border-red-500 transition font-bold">
                            <option value="عام">عام</option>
                        </select>
                    </div>
                    <div class="mb-6">
                        <label class="text-gray-400 text-xs font-bold mb-2 block">الشعبة الجديدة:</label>
                        <select id="promo_section" class="w-full p-3 bg-[#1e293b] border border-gray-700 text-white rounded-lg outline-none focus:border-red-500 transition font-bold">
                            <option value="الكل">الكل</option>
                        </select>
                    </div>
                    <div class="flex justify-end gap-3 pt-2 border-t border-gray-800 mt-2">
                        <button type="button" onclick="closeModal('promotionModal')" class="bg-gray-800 text-gray-300 px-5 py-2.5 rounded-lg font-bold hover:bg-gray-700 transition">إلغاء</button>
                        <button type="submit" id="btn-submit-promo" class="bg-red-600 text-white px-6 py-2.5 rounded-lg font-bold hover:bg-red-500 transition shadow-lg"><i class="fas fa-check-circle me-1"></i> تأكيد الترحيل</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 10. نافذة شهادة براءة الذمة (Clearance Certificate) -->
    <div id="clearanceModal" class="fixed inset-0 bg-black bg-opacity-90 hidden items-center justify-center z-[200] no-print backdrop-blur-sm">
        <span class="absolute top-6 right-8 text-4xl text-white cursor-pointer z-50 hover:text-red-500 transition" onclick="closeModal('clearanceModal')">&times;</span>
        <div class="w-11/12 max-w-3xl max-h-[90vh] overflow-y-auto bg-transparent rounded-xl flex flex-col items-center">
            <div id="printable-clearance" class="w-full bg-white p-8 rounded-xl text-black relative shadow-[0_10px_30px_rgba(0,0,0,0.5)]">
                <div class="absolute inset-3 border-2 border-double border-gray-800 rounded-lg pointer-events-none"></div>

                <div class="flex justify-between items-start border-b-2 border-gray-800 pb-4 mb-6 relative z-10">
                    <div class="text-right w-1/3">
                        <h3 class="m-0 text-sm text-black font-bold">جمهورية العراق</h3>
                        <h4 class="mt-1 text-lg font-black text-gray-900"><?= htmlspecialchars($school_display_name ?? 'المدرسة') ?></h4>
                        <p class="mt-1 text-xs font-bold text-gray-600">قسم الشؤون المالية</p>
                    </div>
                    <div class="text-center w-1/3">
                        <img src="<?= htmlspecialchars($school_logo ?? 'images/icon.png') ?>" class="h-16 object-contain mx-auto" onerror="this.style.display='none'">
                    </div>
                    <div class="text-left w-1/3 text-xs font-bold">
                        <p class="m-0">العدد: <span class="font-mono">CLR-<?= rand(1000, 9999) ?></span></p>
                        <p class="mt-1">التاريخ: <span dir="ltr"><?= date('Y/m/d') ?></span></p>
                    </div>
                </div>

                <h1 class="text-center text-black text-2xl font-black mb-6 underline underline-offset-8 decoration-2">شـهــادة بــراءة ذمـــة</h1>

                <div class="text-base leading-relaxed text-justify mb-8 px-4 font-bold">
                    تشهد إدارة <strong><?= htmlspecialchars($school_display_name ?? 'المدرسة') ?></strong> بأن الطالب(ة): <br>
                    <div class="text-center text-xl font-black text-gray-900 my-4 bg-gray-100 p-3 rounded-lg" id="clr-name">اسم الطالب</div>
                    المقيد في ( <strong id="clr-stage">المرحلة</strong> - <strong id="clr-dept">القسم</strong> - <strong id="clr-sec">الشعبة</strong> )، قد قام بتسوية كافة متعلقاته والتزاماته المالية مع المدرسة للعام الدراسي الحالي.<br>
                    <div id="clr-debt-status" class="mt-4 font-bold text-sm">وبناءً عليه، لا توجد بذمته أي ديون مالية للمدرسة، وأُعطيت له هذه الشهادة بناءً على طلبه لتقديمها لمن يهمه الأمر.</div>
                </div>

                <div class="flex justify-between text-center mt-10 font-bold text-sm">
                    <div class="w-1/3">
                        <p class="mb-10">المحاسب المالي</p>
                        <div class="border-t border-black w-4/5 mx-auto pt-1">التوقيع</div>
                    </div>
                    <div class="w-1/3">
                        <p class="mb-10">ختم المدرسة</p>
                        <div class="w-16 h-16 border-2 border-dashed border-gray-300 rounded-full mx-auto flex items-center justify-center text-gray-300 text-[10px] -rotate-12">مكان الختم</div>
                    </div>
                    <div class="w-1/3">
                        <p class="mb-10">مدير المؤسسة</p>
                        <div class="border-t border-black w-4/5 mx-auto pt-1">التوقيع</div>
                    </div>
                </div>
            </div>

            <button type="button" class="mt-6 w-full max-w-xl bg-blue-600 hover:bg-blue-500 text-white text-lg py-3 rounded-xl font-bold shadow-lg transition" onclick="executePrintClearance()">
                <i class="fas fa-print me-2"></i> طباعة براءة الذمة
            </button>
        </div>
    </div>

<script>
    // ==========================================
    // 1. البيانات الحقيقية من السيرفر (PHP)
    // ==========================================
    const data = {
        students: <?php echo $json_students ?? '[]'; ?>,
        salaries: <?php echo $json_salaries ?? '[]'; ?>,
        expenses: <?php echo $json_expenses ?? '[]'; ?>,
        pricing: <?php echo $json_pricing ?? '{}'; ?>,
        school_stages: <?php echo $json_school_stages ?? '[]'; ?>
    };

    let cashflowChart;

    // ==========================================
    // 2. نظام الإشعارات العائمة والنوافذ الأساسية
    // ==========================================
    function showToast(message, type = 'info') {
        const container = document.getElementById('toast-container');
        if(!container) return;
        const toast = document.createElement('div');
        let icon = 'fa-info-circle text-blue-400';
        if (type === 'success') icon = 'fa-check-circle text-green-400';
        if (type === 'error') icon = 'fa-exclamation-circle text-red-400';
        toast.className = `toast ${type}`;
        toast.innerHTML = `<i class="fas ${icon} text-xl"></i> <span>${message}</span>`;
        container.appendChild(toast);
        setTimeout(() => toast.classList.add('show'), 10);
        setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 400); }, 3000);
    }

   function closeModal(modalId) { 
        const modal = document.getElementById(modalId);
        if(modal) { modal.classList.remove('flex'); modal.classList.add('hidden'); }
    }

    function toggleSubmenu(id) {
        const submenu = document.getElementById(id);
        const icon = document.getElementById('icon-' + id);
        if (submenu && icon) {
            if (submenu.classList.contains('hidden')) {
                submenu.classList.remove('hidden'); submenu.classList.add('flex');
                icon.style.transform = 'rotate(180deg)';
            } else {
                submenu.classList.add('hidden'); submenu.classList.remove('flex');
                icon.style.transform = 'rotate(0deg)';
            }
        }
    }

    function switchTab(sectionId, navElement) {
        const allSections = [
            'radarSection', 'studentsSection', 'installmentsSection', 
            'notificationsSection', 'temp_studentsSection', 'promotionSection',
            'salariesSection', 'expensesSection', 'categoriesSection', 'reportSection'
        ];
        
        allSections.forEach(id => {
            const el = document.getElementById(id);
            if (el) { el.classList.add('hidden'); el.classList.remove('block'); }
        });
        
        const target = document.getElementById(sectionId);
        if (target) { target.classList.remove('hidden'); target.classList.add('block'); }

        const titles = {
            'radarSection': 'الرادار المالي <span class="text-sm font-normal text-gray-500 ml-2">Executive Dashboard</span>',
            'studentsSection': 'بوابة الطلاب والأقساط <span class="text-sm font-normal text-gray-500 ml-2">Student Billing Portal</span>',
            'installmentsSection': 'إدارة الأقساط المجدولة <span class="text-sm font-normal text-gray-500 ml-2">Installments Management</span>',
            'notificationsSection': 'مركز الإشعارات المالية <span class="text-sm font-normal text-gray-500 ml-2">Financial Notifications</span>',
            'temp_studentsSection': 'الطلاب المؤقتين والمنسحبين <span class="text-sm font-normal text-gray-500 ml-2">Temporary Students</span>',
            'promotionSection': 'الترحيل الأكاديمي <span class="text-sm font-normal text-gray-500 ml-2">Students Promotion</span>',
            'salariesSection': 'المصروفات والرواتب <span class="text-sm font-normal text-gray-500 ml-2">Payroll</span>'
        };
        if(document.getElementById('pageTitle')) document.getElementById('pageTitle').innerHTML = titles[sectionId] || '';

        document.querySelectorAll('.nav-item').forEach(el => {
            el.classList.remove('active', 'border-[rgba(255,255,255,0.05)]', 'bg-[rgba(255,255,255,0.05)]', 'text-white');
            el.classList.add('text-gray-400');
            let icon = el.querySelector('i');
            if(icon && !el.classList.contains('text-purple-400')) icon.classList.remove('text-neon-green');
        });

        if(navElement) {
            if(!navElement.classList.contains('text-purple-400')) {
                navElement.classList.add('active', 'border-[rgba(255,255,255,0.05)]', 'bg-[rgba(255,255,255,0.05)]', 'text-white');
                navElement.classList.remove('text-gray-400');
                let activeIcon = navElement.querySelector('i');
                if(activeIcon) activeIcon.classList.add('text-neon-green');
            }
        }

        try {
            if(sectionId === 'radarSection') fetchLiveStats();
            if(sectionId === 'studentsSection') renderStudentsCards();
            if(sectionId === 'installmentsSection') renderInstallmentsTable(); 
            if(sectionId === 'temp_studentsSection') renderTempStudentsTable(); 
            if(sectionId === 'promotionSection') renderPromotionTable(); 
        } catch(e) { console.log(e); }
    }

    function initFintechApp() {
        showToast('مرحباً بك في المركز المالي', 'success');
        try { fetchLiveStats(); } catch(e) {}
        try { renderTimeline(); } catch(e) {}
        try { renderStudentsCards(); } catch(e) {}
        try { renderTempStudentsTable(); } catch(e) {}
    }
    
   // ==========================================
    // 4. محرك بناء البطاقات الذكية للطلاب النشطين
    // ==========================================
    function renderStudentsCards() {
        const grid = document.getElementById('student-cards-grid');
        if (!grid) return;

        const search = document.getElementById('filter-name') ? document.getElementById('filter-name').value.toLowerCase() : '';
        const fStage = document.getElementById('filter-stage') ? document.getElementById('filter-stage').value : '';
        const fDept = document.getElementById('filter-dept') ? document.getElementById('filter-dept').value : '';
        const fSection = document.getElementById('filter-section') ? document.getElementById('filter-section').value : '';
        const statFilter = document.getElementById('filter-status') ? document.getElementById('filter-status').value : '';

        grid.innerHTML = '';
        let totalNet = 0; let totalPaid = 0; let totalDebt = 0; let lateCount = 0; let activeCount = 0;
        let todayDate = new Date().toISOString().split('T')[0]; 

        if(data && data.students) {
            data.students.forEach(s => {
                if(s.enrollment_status !== 'active') return; 

                const mSearch = s.name.toLowerCase().includes(search) || String(s.id).toLowerCase().includes(search);
                const mStage = fStage === "" || s.stage === fStage;
                const mDept = fDept === "" || s.dept === fDept;
                const mSection = fSection === "" || s.section === fSection;

                if (!mSearch || !mStage || !mDept || !mSection) return;

                const net = parseFloat(s.total) || 0;
                if (search.trim() === "" && net === 0) return;

                // 🚀 المعادلات المحاسبية الدقيقة 🚀
                const gross_paid = parseFloat(s.paid) || 0; 
                const refunded = parseFloat(s.refunded) || 0; 
                const actual_school_holds = gross_paid - refunded; // ما تملكه المدرسة فعلياً
                
                let debt = net - actual_school_holds;
                if (debt < 0) debt = 0;
                const isCompleted = debt <= 0 && net > 0;

                let hasFinancialAlert = false;
                if (net > 0 && actual_school_holds === 0) { hasFinancialAlert = true; } 
                else if (s.installments && s.installments.length > 0) {
                    s.installments.forEach(inst => { if (inst.stat !== 'مدفوع' && inst.date < todayDate) hasFinancialAlert = true; });
                }

                const mStat = statFilter === "" || 
                              (statFilter === "completed" && isCompleted) || 
                              (statFilter === "pending" && (!isCompleted || net === 0)) ||
                              (statFilter === "late" && hasFinancialAlert);

                if (!mStat) return;

                activeCount++;
                totalNet += net; 
                totalPaid += actual_school_holds; 
                totalDebt += debt;
                if(hasFinancialAlert) lateCount++;

                let statusColor = 'bg-gray-500'; let statusBorder = 'border-gray-700';
                let progressPercent = net > 0 ? (actual_school_holds / net) * 100 : 0;
                if(progressPercent > 100) progressPercent = 100;

                if (isCompleted) { statusColor = 'bg-[#10b981] shadow-[0_0_10px_rgba(16,185,129,0.5)]'; statusBorder = 'border-neon-green'; } 
                else if (debt > 0 && !hasFinancialAlert) { statusColor = 'bg-[#f59e0b] shadow-[0_0_10px_rgba(245,158,11,0.5)]'; statusBorder = 'border-yellow-500/30'; }
                else if (hasFinancialAlert) { statusColor = 'bg-[#ef4444] shadow-[0_0_10px_rgba(239,68,68,0.8)] animate-pulse'; statusBorder = 'border-neon-red'; }

                let safeName = String(s.name).replace(/'/g, "\\'");
                let alertBadge = hasFinancialAlert ? `<span class="absolute top-4 left-4 w-3 h-3 rounded-full bg-red-500 animate-pulse shadow-[0_0_10px_rgba(239,68,68,1)]" title="متأخر عن السداد"></span>` : '';
                let checkboxHtml = `<input type="checkbox" class="student-chk absolute top-4 right-4 w-5 h-5 accent-blue-500 z-20 cursor-pointer" value="${s.id}">`;

                let cardActions = '';
                if (net === 0) {
                    cardActions = `<button onclick="openSmartEnrollmentModal('${s.id}', '${safeName}', '${s.stage}')" class="w-full bg-[#3b82f6] text-white font-bold py-2.5 rounded-lg text-sm hover:bg-[#2563eb] transition shadow-[0_0_15px_rgba(59,130,246,0.3)] mt-2"><i class="fas fa-cog me-1"></i> إعداد القيد المالي للقدامى</button>`;
                } else {
                    cardActions = `
                        <div class="grid grid-cols-2 gap-2 relative z-10 border-t border-[rgba(255,255,255,0.05)] pt-4 mt-2">
                            <button onclick="openDynamicVoucherModal('${s.id}', '${safeName}', ${net - actual_school_holds})" class="bg-[#10b981]/20 text-[#10b981] border border-[#10b981]/50 p-2 rounded-lg hover:bg-[#10b981] hover:text-white transition text-xs shadow-sm font-bold" title="إصدار سند مالي">
                                <i class="fas fa-file-invoice-dollar"></i> سند
                            </button>
                            <button onclick="openStatementModal('${s.id}')" class="bg-gray-800 text-gray-300 border border-gray-700 font-bold py-2 rounded-lg text-xs hover:bg-gray-700 hover:text-white transition shadow-[0_5px_10px_rgba(0,0,0,0.2)]" title="كشف الحساب">
                                <i class="fas fa-list-alt"></i> كشف
                            </button>
                            <button onclick="printClearance('${safeName}', '${s.stage}', '${s.dept}', '${s.section}', ${debt})" class="bg-yellow-900/30 text-yellow-400 border border-yellow-800/50 font-bold py-2 rounded-lg text-xs hover:bg-yellow-600 hover:text-white transition shadow-sm" title="براءة ذمة">
                                <i class="fas fa-certificate"></i> ذمة
                            </button>
                            <button onclick="openStatusModal('${s.id}', '${safeName}', '${s.enrollment_status}')" class="bg-blue-900/30 text-blue-400 border border-blue-800/50 font-bold py-2 rounded-lg text-xs hover:bg-blue-600 hover:text-white transition shadow-sm" title="تغيير الحالة (مؤقت/منسحب)">
                                <i class="fas fa-exchange-alt"></i> تغيير حالة
                            </button>
                        </div>
                    `;
                }

                grid.innerHTML += `
                    <div class="glass-panel p-5 ${statusBorder} hover:border-[#3b82f6] transition-all duration-300 relative group overflow-hidden flex flex-col justify-between">
                        ${alertBadge}
                        ${checkboxHtml}
                        <div class="absolute -right-6 -bottom-6 text-[8rem] opacity-5 transition-transform group-hover:scale-110 text-white pointer-events-none"><i class="fas fa-user-graduate"></i></div>

                        <div>
                            <div class="flex items-center justify-between mb-4 relative z-10 pr-6">
                                <div>
                                    <h3 class="font-bold text-white text-lg leading-tight truncate w-32" title="${s.name}">${s.name}</h3>
                                    <p class="text-[10px] text-gray-400 mt-1">${s.stage} - ${s.dept}</p>
                                </div>
                                <div class="w-10 h-10 rounded-full bg-gray-800 border border-gray-600 flex items-center justify-center text-gray-400">
                                    <i class="fas fa-user"></i>
                                </div>
                            </div>

                            <div class="mb-4 relative z-10">
                                <div class="flex justify-between text-[10px] mb-1">
                                    <span class="text-gray-400">نسبة السداد</span>
                                    <span class="font-bold text-white">%${progressPercent.toFixed(0)}</span>
                                </div>
                                <div class="w-full h-1.5 bg-gray-800 rounded-full overflow-hidden">
                                    <div class="h-full ${statusColor} rounded-full" style="width: ${progressPercent}%"></div>
                                </div>
                            </div>

                            <div class="flex justify-between items-end mb-2 relative z-10 bg-[rgba(0,0,0,0.3)] p-3 rounded-xl border border-[rgba(255,255,255,0.02)]">
                                <div>
                                    <p class="text-[10px] text-gray-500 mb-1">المتبقي (الديون)</p>
                                    <p class="font-black ${debt > 0 ? 'text-neon-red' : 'text-neon-green'} fin-font text-lg">${debt.toLocaleString()} <span class="text-[10px] text-gray-500 font-normal">د.ع</span></p>
                                </div>
                                <div class="text-left">
                                    <p class="text-[10px] text-gray-500 mb-1">إجمالي الدفعات</p>
                                    <p class="font-bold text-gray-300 fin-font text-sm">${gross_paid.toLocaleString()}</p>
                                </div>
                            </div>
                        </div>

                        ${cardActions}
                    </div>
                `;
            });
        }

        if (activeCount === 0) grid.innerHTML = '<div class="col-span-full text-center text-gray-500 py-10 bg-[#0f172a] rounded-xl border border-gray-800">لا يوجد طلاب يطابقون بحثك.</div>';

        if(document.getElementById('stat-student-count')) document.getElementById('stat-student-count').innerHTML = activeCount + ' <span class="text-xs text-gray-500 font-normal">طالب</span>';
        if(document.getElementById('stat-student-paid')) document.getElementById('stat-student-paid').innerHTML = totalPaid.toLocaleString() + ' <span class="text-xs text-gray-500 font-normal">د.ع</span>';
        if(document.getElementById('stat-student-debt')) document.getElementById('stat-student-debt').innerHTML = totalDebt.toLocaleString() + ' <span class="text-xs text-gray-500 font-normal">د.ع</span>';
        if(document.getElementById('stat-student-late')) document.getElementById('stat-student-late').innerHTML = lateCount + ' <span class="text-xs text-gray-500 font-normal">طالب</span>';
    }


  // ==========================================
    // 🛑 8. محرك فرز وطباعة الطلاب المؤقتين والمنسحبين (إحصائيات ومعادلات دقيقة 100%) 🛑
    // ==========================================
    function renderTempStudentsTable() {
        const tbodyTemp = document.getElementById('tempStudentTable');
        if (!tbodyTemp) return;

        const search = document.getElementById('temp-filter-name') ? document.getElementById('temp-filter-name').value.toLowerCase() : '';
        const fStage = document.getElementById('temp-filter-stage') ? document.getElementById('temp-filter-stage').value : '';
        const fDept = document.getElementById('temp-filter-dept') ? document.getElementById('temp-filter-dept').value : '';
        const fStat = document.getElementById('temp-filter-status') ? document.getElementById('temp-filter-status').value : '';
        const fSec = document.getElementById('temp-filter-section') ? document.getElementById('temp-filter-section').value : '';

        tbodyTemp.innerHTML = '';
        let tempTotal = 0; let tempPaid = 0; let tempDebt = 0; let tempRefund = 0; let tempCount = 0;

        if(data && data.students) {
            data.students.forEach(s => {
                if(s.enrollment_status === 'active') return; 

                const mSearch = s.name.toLowerCase().includes(search) || String(s.id).toLowerCase().includes(search);
                const mStage = fStage === "" || s.stage === fStage;
                const mDept = fDept === "" || s.dept === fDept;
                const mStat = fStat === "" || s.enrollment_status === fStat;
                const mSecMatch = !fSec || fSec === "" || s.section === fSec;

                if (!mSearch || !mStage || !mDept || !mStat || !mSecMatch) return;

                // 🚀 المعادلات الرياضية المحاسبية المعتمدة 🚀
                const net = parseFloat(s.total) || 0; // الصافي المطلوب
                const gross_paid = parseFloat(s.paid) || 0; // إجمالي ما سدده الطالب طوال السنة
                const refunded = parseFloat(s.refunded) || 0; // ما استرجعه (أخذها بيده كمرتجع)
                
                // 1. المستحصل الفعلي للمدرسة (ما بقي في الخزينة)
                const actual_school_holds = gross_paid - refunded; 

                // 2. حساب الديون (الصافي المطلوب - المستحصل الفعلي)
                const balance = net - actual_school_holds; 

                let debt = 0; let pending_refund = 0; let debtHtml = '';
                
                if (balance > 0) {
                    debt = balance; // عليه ديون
                    debtHtml = `<span class="text-red-400 font-black">${debt.toLocaleString()} (دين)</span>`;
                } else if (balance < 0) {
                    pending_refund = Math.abs(balance); // يطلب المدرسة فائض
                    debtHtml = `<span class="text-orange-400 font-black">${pending_refund.toLocaleString()} (يطلبنا)</span>`;
                } else {
                    debtHtml = `<span class="text-green-500 font-bold"><i class="fas fa-check-double"></i> خالص</span>`;
                }

                tempCount++; 
                tempTotal += net; 
                tempPaid += actual_school_holds; // الإحصائيات العلوية تجمع الصافي فقط
                tempDebt += debt; 
                tempRefund += refunded; 
                
                let badge = s.enrollment_status === 'temporary' 
                    ? '<span class="bg-orange-900/40 text-orange-400 border border-orange-800 px-3 py-1 rounded-lg text-xs font-bold">مؤقت</span>' 
                    : '<span class="bg-red-900/40 text-red-400 border border-red-800 px-3 py-1 rounded-lg text-xs font-bold">منسحب</span>';

                let safeName = String(s.name).replace(/'/g, "\\'");
                
                let voucherBalance = pending_refund > 0 ? -pending_refund : debt;
                let voucherBtnClass = voucherBalance < 0 ? 'bg-red-900/30 text-red-400 hover:bg-red-600 border-red-800/50' : 'bg-[#10b981]/20 text-[#10b981] hover:bg-[#10b981] border-[#10b981]/50';
                
                let actionsHtml = `
                    <div class="flex items-center justify-center gap-1.5 flex-nowrap">
                        <button onclick="openDynamicVoucherModal('${s.id}', '${safeName}', ${voucherBalance})" class="${voucherBtnClass} px-2 py-1.5 rounded flex items-center gap-1 hover:text-white transition text-[11px] shadow-sm font-bold" title="إصدار سند">
                            <i class="fas fa-file-invoice-dollar"></i> سند
                        </button>
                        <button onclick="openStatementModal('${s.id}')" class="bg-gray-800 text-gray-300 border border-gray-700 px-2 py-1.5 rounded flex items-center gap-1 hover:bg-gray-700 hover:text-white transition text-[11px] shadow-sm font-bold" title="كشف الحساب">
                            <i class="fas fa-list-alt"></i> كشف
                        </button>
                        <button onclick="printClearance('${safeName}', '${s.stage}', '${s.dept}', '${s.section}', ${debt})" class="bg-yellow-900/30 text-yellow-400 border border-yellow-800/50 px-2 py-1.5 rounded flex items-center gap-1 hover:bg-yellow-600 hover:text-white transition text-[11px] shadow-sm font-bold" title="براءة ذمة">
                            <i class="fas fa-certificate"></i> ذمة
                        </button>
                        <button onclick="openStatusModal('${s.id}', '${safeName}', '${s.enrollment_status}')" class="bg-blue-900/30 text-blue-400 border border-blue-800/50 px-2 py-1.5 rounded flex items-center gap-1 hover:bg-blue-600 hover:text-white transition text-[11px] shadow-sm font-bold" title="تغيير الحالة">
                            <i class="fas fa-exchange-alt"></i> إرجاع
                        </button>
                    </div>
                `;

                // 🚀 عرض إجمالي ما دفعه، وبخط صغير تحته عرض (الصافي الفعلي بالخزينة) 🚀
                let paidDisplay = `
                    ${gross_paid.toLocaleString()}
                    ${refunded > 0 ? `<br><span class="text-[10px] text-gray-500 font-normal">الصافي بالخزينة: ${actual_school_holds.toLocaleString()}</span>` : ''}
                `;

                // تحديث عنوان العمود بصرياً ليصبح "إجمالي الدفعات" بدلاً من "المستحصل"
                const headerCells = document.querySelectorAll('#tempStudentTable').length > 0 ? document.getElementById('tempStudentTable').previousElementSibling.querySelectorAll('th') : [];
                if (headerCells.length > 4 && headerCells[4].innerText.includes("المستحصل")) {
                    headerCells[4].innerHTML = "إجمالي الدفعات";
                }

                tbodyTemp.innerHTML += `
                    <tr class="hover:bg-[rgba(255,255,255,0.02)] transition duration-200">
                        <td class="p-3">
                            <div class="font-bold text-white text-sm">${s.name}</div>
                            <div class="text-[10px] text-gray-500 font-mono mt-1">${s.id}</div>
                        </td>
                        <td class="p-3 text-[11px] text-gray-400">${s.stage}<br>${s.dept} - ${s.section}</td>
                        <td class="p-3 text-center align-middle">${badge}</td>
                        <td class="p-3 text-center font-bold text-blue-400 fin-font">${net.toLocaleString()}</td>
                        <td class="p-3 text-center font-bold text-green-400 fin-font" title="إجمالي ما دفعه الطالب بيده">${paidDisplay}</td>
                        <td class="p-3 text-center font-bold text-orange-400 fin-font">${refunded > 0 ? refunded.toLocaleString() : '-'}</td>
                        <td class="p-3 text-center font-black align-middle fin-font text-base">${debtHtml}</td>
                        <td class="p-3 text-center align-middle no-print">${actionsHtml}</td>
                    </tr>
                `;
            });
        }

        if (tempCount === 0) {
            tbodyTemp.innerHTML = '<tr><td colspan="8" class="text-center text-gray-500 py-8 font-bold bg-[#0f172a]">لا يوجد طلاب مؤقتين أو منسحبين يطابقون الفلاتر.</td></tr>';
        }

        if (document.getElementById('stat-temp-count')) document.getElementById('stat-temp-count').innerText = tempCount;
        if (document.getElementById('stat-temp-total')) document.getElementById('stat-temp-total').innerText = tempTotal.toLocaleString();
        if (document.getElementById('stat-temp-paid')) document.getElementById('stat-temp-paid').innerText = tempPaid.toLocaleString();
        if (document.getElementById('stat-temp-debt')) document.getElementById('stat-temp-debt').innerText = tempDebt.toLocaleString();
        if (document.getElementById('stat-temp-refund')) document.getElementById('stat-temp-refund').innerText = tempRefund.toLocaleString();
    }


   // ==========================================
    // 🚀 9. محرك الترحيل الأكاديمي 🚀
    // ==========================================
   function renderPromotionTable() {
        const tbodyPromo = document.getElementById('promotionTableBody');
        if (!tbodyPromo) return;

        const search = document.getElementById('promo-filter-name') ? document.getElementById('promo-filter-name').value.toLowerCase() : '';
        const fStage = document.getElementById('promo-filter-stage') ? document.getElementById('promo-filter-stage').value : '';
        const fDept = document.getElementById('promo-filter-dept') ? document.getElementById('promo-filter-dept').value : '';
        const fSec = document.getElementById('promo-filter-section') ? document.getElementById('promo-filter-section').value : '';

        tbodyPromo.innerHTML = '';
        let pCount = 0;

        if(data && data.students) {
            data.students.forEach(s => {
                if(s.enrollment_status !== 'active') return; 

                const mSearch = s.name.toLowerCase().includes(search) || String(s.id).toLowerCase().includes(search);
                const mStage = fStage === "" || s.stage === fStage;
                const mDept = fDept === "" || s.dept === fDept;
                const mSecMatch = fSec === "" || s.section === fSec;

                if (!mSearch || !mStage || !mDept || !mSecMatch) return;

                const net = parseFloat(s.total) || 0;
                const gross_paid = parseFloat(s.paid) || 0;
                const refunded = parseFloat(s.refunded) || 0;
                const actual_paid = gross_paid - refunded;

                let debt = Math.max(0, net - actual_paid); 
                
                let finStatus = debt > 0 
                    ? `<span class="text-red-400 font-bold"><i class="fas fa-times-circle"></i> مديون بـ ${debt.toLocaleString()}</span>` 
                    : `<span class="text-green-500 font-bold"><i class="fas fa-check-circle"></i> نقي (خالص)</span>`;

                pCount++;
                tbodyPromo.innerHTML += `
                    <tr class="hover:bg-[rgba(255,255,255,0.02)] transition duration-200">
                        <td class="p-4 text-center align-middle">
                            <input type="checkbox" class="promo-chk w-5 h-5 accent-red-500 cursor-pointer" value="${s.id}">
                        </td>
                        <td class="p-4">
                            <div class="font-bold text-white text-md">${s.name}</div>
                            <div class="text-xs text-gray-500 font-mono mt-1">${s.id}</div>
                        </td>
                        <td class="p-4 text-sm font-bold text-blue-300">${s.stage}</td>
                        <td class="p-4 text-center text-gray-400 text-xs">${s.dept} - ${s.section}</td>
                        <td class="p-4 text-center align-middle">${finStatus}</td>
                    </tr>
                `;
            });
        }

        if (pCount === 0) {
            tbodyPromo.innerHTML = '<tr><td colspan="5" class="text-center text-gray-500 py-8 font-bold bg-[#0f172a]">لا يوجد طلاب نشطين يطابقون الفلتر.</td></tr>';
        }
    }

    function toggleAllPromotion(source) {
        document.querySelectorAll('.promo-chk').forEach(cb => cb.checked = source.checked);
    }

   

   // ==========================================
    // 🚀 الإدارة الذكية للنافذة المالية (سندات القبض والصرف) 🚀
    // ==========================================
    function openDynamicVoucherModal(id, name, balance) {
        document.getElementById('pay-student-id').value = id;
        document.getElementById('pay-student-name').value = name;
        document.getElementById('pay-date').valueAsDate = new Date(); 
        
        const typeSelect = document.getElementById('pay-voucher-type');
        const amountInput = document.getElementById('pay-amount');

        if (balance < 0) {
            // المدرسة مدينة للطالب (استرجاع)
            typeSelect.value = 'expense';
            amountInput.value = Math.abs(balance);
        } else {
            // الطالب مدين (تسديد)
            typeSelect.value = 'income';
            amountInput.value = balance > 0 ? balance : '';
        }
        
        toggleStudentVoucherType();
        
        const modal = document.getElementById('addPaymentModal');
        if (modal) {
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            modal.style.zIndex = '999999';
        }
    }

    function openPaymentModal(id, name) {
        openDynamicVoucherModal(id, name, 1); // 1 = force income
    }

    function toggleStudentVoucherType() {
        const type = document.getElementById('pay-voucher-type').value;
        const bg = document.getElementById('voucher-modal-bg');
        const title = document.getElementById('voucher-modal-title');
        const btn = document.getElementById('btn-submit-voucher');
        const lblAmount = document.getElementById('lbl-amount');
        const inputAmount = document.getElementById('pay-amount');

        if (type === 'income') {
            bg.className = "bg-[#0f172a] border-2 border-green-500 rounded-2xl p-6 w-11/12 max-w-md shadow-[0_0_50px_rgba(16,185,129,0.2)] transition-colors duration-300";
            title.className = "text-xl font-bold text-green-500";
            title.innerHTML = '<i class="fas fa-hand-holding-usd me-2"></i> تسجيل دفعة (سند قبض)';
            btn.className = "bg-green-600 text-white px-6 py-2.5 rounded-lg font-bold hover:bg-green-500 transition shadow-lg";
            btn.innerHTML = '<i class="fas fa-check-circle me-1"></i> تأكيد الاستلام';
            lblAmount.innerText = "المبلغ المستلم (د.ع):";
            inputAmount.className = "w-full p-3 bg-[#0f172a] border-2 border-green-500/50 font-black text-2xl text-center tracking-wider text-green-400 rounded-lg outline-none focus:border-green-500 transition";
        } else {
            bg.className = "bg-[#0f172a] border-2 border-red-500 rounded-2xl p-6 w-11/12 max-w-md shadow-[0_0_50px_rgba(239,68,68,0.2)] transition-colors duration-300";
            title.className = "text-xl font-bold text-red-500";
            title.innerHTML = '<i class="fas fa-money-bill-wave me-2"></i> استرجاع مبلغ (سند صرف)';
            btn.className = "bg-red-600 text-white px-6 py-2.5 rounded-lg font-bold hover:bg-red-500 transition shadow-lg";
            btn.innerHTML = '<i class="fas fa-arrow-up me-1"></i> تأكيد الصرف والمخالصة';
            lblAmount.innerText = "المبلغ المسترجع للطالب (د.ع):";
            inputAmount.className = "w-full p-3 bg-[#0f172a] border-2 border-red-500/50 font-black text-2xl text-center tracking-wider text-red-400 rounded-lg outline-none focus:border-red-500 transition";
        }
    }

    function submitPayment(e) {
        e.preventDefault();
        const btn = document.getElementById('btn-submit-voucher');
        const origText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري التسجيل...'; 
        btn.disabled = true;

        const type = document.getElementById('pay-voucher-type').value;
        const formData = new FormData();
        
        formData.append('student_id', document.getElementById('pay-student-id').value);
        formData.append('amount', document.getElementById('pay-amount').value);
        formData.append('date', document.getElementById('pay-date').value);
        formData.append('method', document.getElementById('pay-method').value);
        
        if (type === 'income') {
            formData.append('action', 'pay');
            fetch('save_accounting_data.php', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(resData => {
                if (resData.status === 'success') {
                    showToast('تم تسجيل سند القبض بنجاح', 'success');
                    setTimeout(() => location.reload(), 1000);
                } else { showToast(resData.message, 'error'); btn.innerHTML = origText; btn.disabled = false;}
            }).catch(err => { showToast('فشل الاتصال', 'error'); btn.innerHTML = origText; btn.disabled = false;});
        } 
        else {
            // 🚀 توجيه السندات الراجعة إلى Refund Student 🚀
            formData.append('action', 'refund_student');
            formData.append('student_name', document.getElementById('pay-student-name').value);
            
            fetch('save_accounting_data.php', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(resData => {
                if (resData.status === 'success') {
                    showToast('تم تسجيل سند الصرف واسترجاع المبلغ بنجاح', 'success');
                    setTimeout(() => location.reload(), 1000);
                } else { showToast(resData.message, 'error'); btn.innerHTML = origText; btn.disabled = false;}
            }).catch(err => { showToast('فشل الاتصال بالخادم', 'error'); btn.innerHTML = origText; btn.disabled = false;});
        }
    }


    // ==========================================
    // 🚀 كشف الحساب والمطبوعات
    // ==========================================
    function openStatementModal(studentId) {
        showToast('جاري جلب السجل المالي...', 'info');
        
        let fd = new FormData();
        fd.append('action', 'get_statement');
        fd.append('student_id', studentId);

        fetch('save_accounting_data.php', { method: 'POST', body: fd })
        .then(async res => {
            const text = await res.text();
            try { return JSON.parse(text); } 
            catch (err) { console.error("PHP Error:", text); throw new Error("السيرفر أرجع استجابة غير صالحة"); }
        })
        .then(resData => {
            if (resData && resData.status === 'success') {
                const data = resData.data;
                
                if(document.getElementById('stmt-name')) document.getElementById('stmt-name').innerText = data.info.name;
                if(document.getElementById('stmt-id')) document.getElementById('stmt-id').innerText = data.info.id;
                if(document.getElementById('stmt-stage')) document.getElementById('stmt-stage').innerText = `${data.info.stage} - ${data.info.dept}`;
                
                const net = parseFloat(data.info.net_total) || 0;
                const paid = parseFloat(data.info.total_paid) || 0;
                const refunded = parseFloat(data.info.total_refunded) || 0; 
                
                const actual_paid = paid - refunded;
                let debt = net - actual_paid; 
                if (debt < 0) debt = 0;
                
                if(document.getElementById('stmt-total')) document.getElementById('stmt-total').innerText = net.toLocaleString();
                if(document.getElementById('stmt-debt')) document.getElementById('stmt-debt').innerText = debt.toLocaleString();

                const payBody = document.getElementById('stmt-payments-body');
                if(payBody) {
                    payBody.innerHTML = '';
                    if (data.payments.length > 0) {
                        data.payments.forEach(p => {
                            payBody.innerHTML += `
                                <tr>
                                    <td class="p-3 font-mono text-gray-500 print:text-gray-600">#${p.id}</td>
                                    <td class="p-3 font-mono">${p.date}</td>
                                    <td class="p-3 font-bold text-green-400 print:text-green-700 fin-font">${parseFloat(p.amount).toLocaleString()}</td>
                                    <td class="p-3">${p.method}</td>
                                </tr>
                            `;
                        });
                    } else {
                        payBody.innerHTML = '<tr><td colspan="4" class="p-4 text-center text-gray-500">لا توجد أي مدفوعات مسجلة.</td></tr>';
                    }
                }

                const instBody = document.getElementById('stmt-installments-body');
                if(instBody) {
                    instBody.innerHTML = '';
                    if (data.installments.length > 0) {
                        data.installments.forEach(i => {
                            const statHtml = i.is_paid == 1 
                                ? `<span class="bg-green-500/20 text-green-400 border border-green-500/50 px-2 py-1 rounded text-xs">مكتمل</span>`
                                : `<span class="bg-red-500/20 text-red-400 border border-red-500/50 px-2 py-1 rounded text-xs">مطلوب</span>`;
                            instBody.innerHTML += `
                                <tr>
                                    <td class="p-3 font-mono">${i.date}</td>
                                    <td class="p-3 font-bold fin-font">${parseFloat(i.amount).toLocaleString()}</td>
                                    <td class="p-3 text-center">${statHtml}</td>
                                </tr>
                            `;
                        });
                    } else {
                        instBody.innerHTML = '<tr><td colspan="3" class="p-4 text-center text-gray-500">لا توجد أقساط مجدولة.</td></tr>';
                    }
                }

                const refundSection = document.getElementById('stmt-refunds-section');
                const refundTotalLabel = document.getElementById('stmt-refund-total');
                if (refundSection && refundTotalLabel) {
                    if (refunded > 0) {
                        refundSection.classList.remove('hidden');
                        refundTotalLabel.innerText = refunded.toLocaleString() + ' د.ع';
                    } else {
                        refundSection.classList.add('hidden');
                    }
                }

                if(document.getElementById('stmt-current-student-id')) {
                    document.getElementById('stmt-current-student-id').value = studentId;
                }
                
                const modal = document.getElementById('statementModal');
                if(modal) {
                    modal.classList.remove('hidden');
                    modal.classList.add('flex');
                }
            } else {
                showToast(resData.message, 'error');
            }
        })
        .catch(err => {
            console.error(err);
            showToast('حدث خطأ أثناء جلب البيانات', 'error');
        });
    }

   function printClearance(name, stage, dept, sec, debt) {
        document.getElementById('clr-name').innerText = name;
        document.getElementById('clr-stage').innerText = stage;
        document.getElementById('clr-dept').innerText = dept;
        document.getElementById('clr-sec').innerText = sec;

        const statusDiv = document.getElementById('clr-debt-status');
        if (debt > 0) {
            statusDiv.innerHTML = '<span class="text-red-600">تنبيه: يوجد بذمة الطالب مبلغ متبقي وقدره (' + debt.toLocaleString() + ' د.ع)، وهذه الوثيقة تعتبر كشف حالة مالية وليست براءة ذمة تامة حتى يتم السداد.</span>';
        } else {
            statusDiv.innerHTML = '<span class="text-green-600">وبناءً عليه، لا توجد بذمته أي ديون مالية للمدرسة، وأُعطيت له هذه الشهادة بناءً على طلبه لتقديمها لمن يهمه الأمر.</span>';
        }

        const modal = document.getElementById('clearanceModal');
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }

    function executePrintClearance() {
        const printContents = document.getElementById('printable-clearance').outerHTML;
        const printWin = window.open('', '', 'width=900,height=700');
        printWin.document.write(`
            <html dir="rtl">
            <head>
                <title>طباعة براءة الذمة</title>
                <script src="https://cdn.tailwindcss.com"><\/script>
                <style>
                    @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;700;900&display=swap');
                    body { font-family: 'Tajawal', sans-serif; margin: 0; padding: 20px; display: flex; justify-content: center; background: #fff; }
                    @media print {
                        @page { size: A4 portrait; margin: 10mm; }
                        body { background: #fff; padding: 0; margin: 0; }
                        #printable-clearance { width: 100% !important; max-width: 100% !important; box-shadow: none !important; border-radius: 0 !important; padding: 20px !important; page-break-after: avoid; height: auto; }
                    }
                </style>
            </head>
            <body>
                ${printContents}
            </body>
            </html>
        `);
        printWin.document.close();
        setTimeout(() => { printWin.print(); printWin.close(); }, 800);
    }

    function openStatusModal(id, name, currentStatus) {
        if(document.getElementById('status-student-id')) document.getElementById('status-student-id').value = id;
        if(document.getElementById('status-student-name')) document.getElementById('status-student-name').value = name;
        
        if(document.getElementById('status-select')) {
            document.getElementById('status-select').value = currentStatus && currentStatus !== 'undefined' && currentStatus !== 'null' ? currentStatus : 'active';
        }
        
        const modal = document.getElementById('statusModal');
        if (modal) {
            modal.classList.remove('hidden');
            modal.classList.add('flex');
        }
    }

   function submitChangeStatus(e) {
        e.preventDefault();
        const btn = e.target.querySelector('button[type="submit"]');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> جاري الحفظ...';
        btn.disabled = true;

        let formData = new FormData();
        formData.append('action', 'change_status'); 
        formData.append('student_id', document.getElementById('status-student-id').value);
        formData.append('new_status', document.getElementById('status-select').value);

        fetch('save_enrollment.php', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(resData => {
            if(resData.status === 'success') {
                showToast('تم تغيير الحالة بنجاح', 'success');
                closeModal('statusModal');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast('خطأ: ' + resData.message, 'error');
            }
        })
        .catch(err => { showToast('خطأ في الاتصال بالخادم.', 'error'); })
        .finally(() => { btn.innerHTML = originalText; btn.disabled = false; });
    }

// ==========================================
    // 5. محرك الأقساط المجدولة
    // ==========================================
    function renderInstallmentsTable() {
        const tbody = document.getElementById('installments-table-body');
        if (!tbody) return;

        const search = document.getElementById('inst-filter-name') ? document.getElementById('inst-filter-name').value.toLowerCase() : '';
        const fStage = document.getElementById('inst-filter-stage') ? document.getElementById('inst-filter-stage').value : '';
        const fDept = document.getElementById('inst-filter-dept') ? document.getElementById('inst-filter-dept').value : '';
        const fSection = document.getElementById('inst-filter-section') ? document.getElementById('inst-filter-section').value : '';
        const fStat = document.getElementById('inst-filter-status') ? document.getElementById('inst-filter-status').value : '';

        tbody.innerHTML = '';
        let tCount = 0; let tPaid = 0; let tDebt = 0; let tDelayed = 0;
        let todayDate = new Date().toISOString().split('T')[0]; 

        if(typeof data !== 'undefined' && data.students) {
            data.students.forEach(s => {
                if(s.enrollment_status !== 'active') return; 

                const net = parseFloat(s.total) || 0;
                if (net === 0) return; 

                const gross_paid = parseFloat(s.paid) || 0;
                const refunded = parseFloat(s.refunded) || 0;
                const actual_school_holds = gross_paid - refunded;

                let debt = net - actual_school_holds;
                if (debt < 0) debt = 0; 
                const isCompleted = debt <= 0 && net > 0;

                let hasDelay = false;
                let delayedAmount = 0;
                if (s.installments && s.installments.length > 0) {
                    s.installments.forEach(inst => { 
                        if (inst.stat !== 'مدفوع' && inst.date < todayDate) {
                            hasDelay = true; delayedAmount += parseFloat(inst.amount) || 0;
                        }
                    });
                } else if (debt > 0) {
                    hasDelay = true; delayedAmount = debt;
                }

                const mSearch = s.name.toLowerCase().includes(search) || String(s.id).toLowerCase().includes(search);
                const mStage = fStage === "" || s.stage === fStage;
                const mDept = fDept === "" || s.dept === fDept;
                const mSec = fSection === "" || s.section === fSection;

                if (!mSearch || !mStage || !mDept || !mSec) return;

                const mStat = fStat === "" || 
                              (fStat === "completed" && isCompleted) || 
                              (fStat === "pending" && (!isCompleted || net == 0)) ||
                              (fStat === "late" && hasDelay);

                if (!mStat) return;

                tCount++; 
                tPaid += actual_school_holds; 
                tDebt += debt;
                if(hasDelay) tDelayed += delayedAmount;

                let progressPercent = net > 0 ? (actual_school_holds / net) * 100 : 0;
                if(progressPercent > 100) progressPercent = 100;
                let progressColor = progressPercent === 100 ? 'bg-green-500' : (hasDelay ? 'bg-red-500 animate-pulse' : 'bg-purple-500');
                let safeName = String(s.name).replace(/'/g, "\\'");
                
                let notifyBtn = hasDelay 
                    ? `<button onclick="notifyParentFinancial('${s.id}', '${safeName}', 'تأخر في سداد القسط')" class="bg-red-900/30 text-red-400 border border-red-800/50 w-10 h-10 rounded-lg hover:bg-red-600 hover:text-white transition shadow-[0_0_10px_rgba(220,38,38,0.5)] me-1 animate-pulse flex items-center justify-center" title="إرسال إنذار"><i class="fas fa-bell"></i></button>` 
                    : `<button class="bg-gray-800 text-gray-600 border border-gray-700 w-10 h-10 rounded-lg cursor-not-allowed shadow-sm me-1 flex items-center justify-center" title="لا توجد متأخرات"><i class="fas fa-bell-slash"></i></button>`;

                tbody.innerHTML += `
                    <tr class="hover:bg-[rgba(255,255,255,0.02)] transition duration-200">
                        <td class="p-4">
                            <div class="font-bold text-white text-md">${s.name} ${hasDelay ? '<i class="fas fa-exclamation-circle text-red-500 text-xs ml-1" title="متأخر"></i>' : ''}</div>
                            <div class="text-xs text-gray-500 font-mono mt-1">${s.id}</div>
                        </td>
                        <td class="p-4 text-xs text-gray-400">${s.stage}<br>${s.dept} - ${s.section}</td>
                        <td class="p-4 text-center font-bold text-gray-300 fin-font">${net.toLocaleString()}</td>
                        <td class="p-4 text-center font-bold text-green-400 fin-font">${actual_school_holds.toLocaleString()}</td>
                        <td class="p-4 text-center font-black ${debt > 0 ? 'text-red-400' : 'text-gray-500'} fin-font">${debt.toLocaleString()}</td>
                        <td class="p-4 align-middle">
                            <div class="w-full bg-gray-800 rounded-full h-2 mb-1">
                                <div class="${progressColor} h-2 rounded-full" style="width: ${progressPercent}%"></div>
                            </div>
                        </td>
                        <td class="p-4 text-center flex justify-center gap-1">
                            ${notifyBtn}
                            <button onclick="openRescheduleModal('${s.id}', '${safeName}', ${debt})" class="bg-purple-600/20 text-purple-400 border border-purple-600/30 px-3 py-2 rounded-lg font-bold hover:bg-purple-600 hover:text-white transition shadow-sm text-xs flex-1">
                                <i class="fas fa-cogs me-1"></i> الجدولة
                            </button>
                        </td>
                    </tr>
                `;
            });
        }

        if (tCount === 0) tbody.innerHTML = '<tr><td colspan="7" class="text-center text-gray-500 py-8 font-bold">لا يوجد طلاب يطابقون الفلاتر المحددة.</td></tr>';
        if(document.getElementById('inst-stat-count')) document.getElementById('inst-stat-count').innerText = tCount;
        if(document.getElementById('inst-stat-paid')) document.getElementById('inst-stat-paid').innerText = tPaid.toLocaleString() + ' د.ع';
        if(document.getElementById('inst-stat-debt')) document.getElementById('inst-stat-debt').innerText = tDebt.toLocaleString() + ' د.ع';
        if(document.getElementById('inst-stat-delayed')) document.getElementById('inst-stat-delayed').innerText = tDelayed.toLocaleString() + ' د.ع';
    }

    function openPricingMatrixModal() {
        const container = document.getElementById('pricing_rows');
        container.innerHTML = '';
        let stages = data.school_stages || [];
        if(stages.length === 0) {
            container.innerHTML = '<div class="text-center text-gray-500 text-sm">لا توجد مراحل دراسية مسجلة (وسوم) في إعدادات هذه المدرسة.</div>';
        } else {
            stages.forEach(stg => {
                let currentPrice = data.pricing[stg] || 0;
                container.innerHTML += `
                    <div class="flex justify-between items-center bg-gray-800 p-3 rounded-lg border border-gray-700">
                        <span class="font-bold text-gray-200 w-1/3">${stg}</span>
                        <div class="flex items-center gap-2 flex-1">
                            <input type="number" name="price_${stg}" value="${currentPrice}" class="modal-input font-mono text-blue-400" placeholder="0">
                            <span class="text-xs text-gray-500 font-bold">د.ع</span>
                        </div>
                    </div>
                `;
            });
        }
        const modal = document.getElementById('pricingMatrixModal');
        if(modal) { modal.classList.remove('hidden'); modal.classList.add('flex'); }
    }

  function submitPricingMatrix(e) {
        e.preventDefault();
        const btn = e.target.querySelector('button[type="submit"]');
        const origText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري الحفظ...'; 
        btn.disabled = true;
        let pricingData = {};
        e.target.querySelectorAll('input[type="number"]').forEach(input => {
            pricingData[input.name.replace('price_', '')] = input.value;
        });
        let fd = new FormData();
        fd.append('action', 'save_pricing_matrix');
        fd.append('pricing_data', JSON.stringify(pricingData));
        fetch('save_accounting_data.php', { method: 'POST', body: fd })
        .then(res => res.json())
        .then(data => {
            if(data.status === 'success') { showToast('✅ ' + data.message, 'success'); closeModal('pricingMatrixModal'); setTimeout(() => location.reload(), 1000);
            } else { showToast('❌ ' + data.message, 'error'); }
        }).catch(err => showToast('خطأ بالخادم', 'error')).finally(() => { btn.innerHTML = origText; btn.disabled = false; });
    }

    function openNewStudentWindow() {
        const modal = document.getElementById('newStudentModalBox');
        if (modal) { modal.classList.remove('hidden'); modal.classList.add('flex'); }
        fetch('load_school_tags.php').then(res => res.json()).then(data => {
            if(data && !data.error) {
                const fillSelect = (sel, def, arr) => {
                    document.querySelectorAll(sel).forEach(s => {
                        s.innerHTML = `<option value="">${def}</option>` + arr.map(opt => `<option value="${opt}">${opt}</option>`).join('');
                    });
                };
                fillSelect('.dynamic-stage-filter', '-- اختر المرحلة --', [...new Set(data.map(i => i.stage_name).filter(Boolean))]);
                fillSelect('.dynamic-dept-filter', 'بدون قسم (عام)', [...new Set(data.map(i => i.department_name).filter(Boolean))]);
                fillSelect('.dynamic-branch-filter', 'بدون شعبة (الكل)', [...new Set(data.map(i => i.section_name).filter(Boolean))]);
            }
        }).catch(err => {});
    }

    function updateCombinedPrice() {
        const stage = document.getElementById('combined_stage_select').value;
        document.getElementById('auto_base_price').value = (data.pricing && data.pricing[stage]) ? parseFloat(data.pricing[stage]) : 0;
        calcCombinedNet();
    }

    function calcCombinedNet() {
        const base = parseFloat(document.getElementById('auto_base_price').value) || 0;
        const discount = parseFloat(document.getElementById('auto_discount').value) || 0;
        document.getElementById('auto_net_price').value = Math.max(0, base - discount);
    }

  function generateAdminSyncID() {
        const randomPart = Array.from({length:4}, () => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.charAt(Math.floor(Math.random() * 36))).join('');
        document.getElementById('admin-std-syncid').value = 'RM-' + new Date().getFullYear().toString().slice(-2) + '-' + randomPart;
    }

    function closeAndResetStudentModal() {
        closeModal('newStudentModalBox');
        const form = document.getElementById('adminNewStudentForm');
        if (form) form.reset();
        ['admin-std-syncid', 'auto_base_price', 'auto_net_price'].forEach(id => {
            let el = document.getElementById(id);
            if(el) el.value = id.includes('price') ? '0' : '';
        });
    }

    function saveAdminNewStudent() {
        const syncId = document.getElementById('admin-std-syncid').value;
        if (!syncId) { showToast('⚠️ يرجى توليد المعرف!', 'error'); return; }
        const form = document.getElementById('adminNewStudentForm'); 
        const btn = document.getElementById('btn-final-save');
        const origText = btn.innerHTML; 
        btn.innerHTML = '<i class="fas fa-spinner fa-spin ml-2"></i> جاري التأسيس...'; btn.disabled = true;

        fetch('add_student.php', { method: 'POST', body: new FormData(form) })
        .then(async res => {
            const text = await res.text();
            try { return JSON.parse(text); } catch (err) { throw new Error("فشل التسجيل الأكاديمي"); }
        })
        .then(dataResponse => {
            if (dataResponse.status === 'success') { 
                const finData = new FormData();
                finData.append('student_id', syncId);
                finData.append('total_amount', document.getElementById('auto_net_price').value || 0);
                finData.append('discount', document.getElementById('auto_discount').value || 0);
                finData.append('action', 'setup_financials');
                return fetch('save_accounting_data.php', { method: 'POST', body: finData });
            } else throw new Error(dataResponse.message || 'فشل التسجيل.');
        })
        .then(res => res ? res.json() : null)
        .then(finRes => {
            if(finRes && finRes.status === 'success') {
                showToast('✅ تم التسجيل بنجاح!', 'success');
                setTimeout(() => location.reload(), 1500); 
            } else if (finRes) {
                showToast('⚠️ سجل الطالب، لكن فشل المالي.', 'warning');
                setTimeout(() => location.reload(), 2000); 
            }
        }).catch(err => { showToast('❌ ' + err.message, 'error'); btn.innerHTML = origText; btn.disabled = false; });
    }

    function openSmartEnrollmentModal(stdId, stdName, stage) {
        document.getElementById('se_student_id').value = stdId;
        document.getElementById('se_student_name_display').innerText = stdName;
        document.getElementById('se_base_price').value = (data.pricing && data.pricing[stage]) ? parseFloat(data.pricing[stage]) : 0;
        document.getElementById('se_discount_amt').value = 0;
        calcOldStudentNet();
        const modal = document.getElementById('smartEnrollmentModal');
        if(modal) { modal.classList.remove('hidden'); modal.classList.add('flex'); }
    }

    function submitSmartEnrollment() {
        const stdId = document.getElementById('se_student_id').value;
        const netPrice = document.getElementById('se_net_price').value;
        if(!stdId || netPrice <= 0) return;

        const btn = document.getElementById('btn-submit-se'); const origText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري التثبيت...'; btn.disabled = true;

        const fd = new FormData();
        fd.append('student_id', stdId); 
        fd.append('total_amount', netPrice);
        fd.append('discount', document.getElementById('se_discount_amt').value);
        fd.append('action', 'setup_financials'); 

        fetch('save_accounting_data.php', { method: 'POST', body: fd })
        .then(res => res.json())
        .then(resData => { 
            if(resData.status === 'success') { 
                showToast('✅ ' + resData.message, 'success'); 
                closeModal('smartEnrollmentModal'); setTimeout(() => location.reload(), 1000); 
            } else showToast(resData.message, 'error'); 
        })
        .catch(err => showToast('خطأ خادم', 'error')).finally(() => { btn.innerHTML = origText; btn.disabled = false; });
    }

    function fetchLiveStats() {
        const icon = document.getElementById('sync-icon');
        if(icon) icon.classList.add('fa-spin');

        fetch('fetch_statistics.php', { method: 'POST' })
        .then(res => res.json())
        .then(resData => {
            if(resData.status === 'success') {
                const stats = resData.data;
                document.getElementById('dash-treasury').innerHTML = stats.treasury_net.toLocaleString() + ' <span class="text-sm font-normal text-gray-500">د.ع</span>'; 
                document.getElementById('dash-receivables').innerHTML = stats.total_debt.toLocaleString() + ' <span class="text-sm font-normal text-gray-500">د.ع</span>';
                document.getElementById('dash-expenses').innerHTML = stats.total_expenses.toLocaleString() + ' <span class="text-sm font-normal text-gray-500">د.ع</span>';
                renderMainChart(stats);
            }
        })
        .catch(err => { renderMainChart(null); })
        .finally(() => { if(icon) icon.classList.remove('fa-spin'); });
    }

   function renderTimeline() {
        const timeline = document.getElementById('live-timeline');
        if(!timeline) return;
        let allTransactions = [];
        if (data.expenses) { data.expenses.forEach(e => { allTransactions.push({ type: 'out', title: e.desc || e.cat, amount: e.amount, date: new Date(e.date), icon: 'fa-arrow-up', color: 'text-red-400', bg: 'bg-red-500/20' }); }); }
        if (data.salaries) { data.salaries.forEach(s => { allTransactions.push({ type: 'out', title: 'راتب: ' + s.name, amount: s.net, date: new Date(s.date || new Date()), icon: 'fa-wallet', color: 'text-yellow-400', bg: 'bg-yellow-500/20' }); }); }
        allTransactions.sort((a, b) => b.date - a.date); const recent = allTransactions.slice(0, 10);
        
        if (recent.length === 0) { timeline.innerHTML = '<div class="text-center text-gray-500 text-sm mt-10">لا توجد حركات مالية مسجلة بعد.</div>'; return; }
        
        timeline.innerHTML = '';
        recent.forEach(t => {
            let timeStr = t.date.toLocaleTimeString('ar-IQ', { hour: '2-digit', minute: '2-digit' });
            timeline.innerHTML += `
                <div class="flex items-start gap-4 relative">
                    <div class="absolute left-4 top-8 bottom-[-16px] w-[1px] bg-[rgba(255,255,255,0.05)]"></div>
                    <div class="w-8 h-8 rounded-full flex-shrink-0 flex items-center justify-center ${t.bg} ${t.color} z-10 border border-[rgba(255,255,255,0.05)]"><i class="fas ${t.icon} text-xs"></i></div>
                    <div class="flex-1 pb-1">
                        <div class="flex justify-between items-start"><h4 class="text-sm font-bold text-gray-200">${t.title}</h4><span class="text-xs text-gray-500 font-mono" dir="ltr">${timeStr}</span></div>
                        <p class="text-xs ${t.color} font-bold fin-font mt-1" dir="ltr">${t.type === 'in' ? '+' : '-'}${parseFloat(t.amount).toLocaleString()}</p>
                    </div>
                </div>
            `;
        });
    }

    function renderMainChart(stats) {
        const canvas = document.getElementById('mainCashflowChart');
        if(!canvas) return;
        const ctx = canvas.getContext('2d');
        if (cashflowChart) cashflowChart.destroy();

        let gradGreen = ctx.createLinearGradient(0, 0, 0, 300);
        gradGreen.addColorStop(0, 'rgba(16, 185, 129, 0.4)'); gradGreen.addColorStop(1, 'rgba(16, 185, 129, 0.0)');
        let gradRed = ctx.createLinearGradient(0, 0, 0, 300);
        gradRed.addColorStop(0, 'rgba(239, 68, 68, 0.4)'); gradRed.addColorStop(1, 'rgba(239, 68, 68, 0.0)');

        let incomesData = [1500000, 2200000, 1800000, 2500000, 3100000, 2900000, 3500000, 4200000, 3800000, 4500000, 5000000, 4800000];
        let expensesData = [800000, 900000, 700000, 1100000, 1300000, 900000, 1500000, 1200000, 1800000, 1400000, 2000000, 1600000];

        cashflowChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'],
                datasets: [
                    { label: 'الإيرادات', data: incomesData, borderColor: '#10b981', backgroundColor: gradGreen, borderWidth: 3, fill: true, tension: 0.4, pointRadius: 0, pointHoverRadius: 6, pointBackgroundColor: '#10b981' },
                    { label: 'المصروفات', data: expensesData, borderColor: '#ef4444', backgroundColor: gradRed, borderWidth: 3, fill: true, tension: 0.4, pointRadius: 0, pointHoverRadius: 6, pointBackgroundColor: '#ef4444' }
                ]
            },
            options: {
                responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false },
                plugins: { legend: { display: false }, tooltip: { backgroundColor: 'rgba(15, 23, 42, 0.9)', titleFont: { family: 'Tajawal' }, bodyFont: { family: 'Tajawal' }, borderColor: 'rgba(255,255,255,0.1)', borderWidth: 1, padding: 10 } },
                scales: { 
                    y: { grid: { color: 'rgba(255,255,255,0.03)', drawBorder: false }, ticks: { color: '#64748b' } }, 
                    x: { grid: { display: false }, ticks: { color: '#64748b', font: { family: 'Tajawal', size: 12 } } } 
                }
            }
        });
    }

  function sendStatementEmail() {
        const studentId = document.getElementById('stmt-current-student-id').value;
        if (!studentId) { showToast('معرف الطالب مفقود', 'error'); return; }

        const btn = document.getElementById('btn-email-statement');
        const origText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> جاري الإرسال...';
        btn.disabled = true;

        let fd = new FormData();
        fd.append('action', 'send_statement_email');
        fd.append('student_id', studentId);

        fetch('save_accounting_data.php', { method: 'POST', body: fd })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') { showToast('✅ ' + data.message, 'success'); } 
            else { showToast('❌ ' + data.message, 'error'); }
        }).catch(err => { showToast('خطأ في الاتصال بالسيرفر', 'error'); }).finally(() => { btn.innerHTML = origText; btn.disabled = false; });
    }

    function notifyParentFinancial(studentId, studentName, alertType) {
        const btn = event.currentTarget; 
        if(!confirm(`⚠️ تأكيد الإرسال:\nهل تريد إرسال إشعار عاجل لولي أمر الطالب (${studentName}) بخصوص: ${alertType}؟\nسيظهر الإشعار فوراً في لوحة تحكم ولي الأمر.`)) return;

        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>'; btn.disabled = true;

        let fd = new FormData();
        fd.append('action', 'single_alert');
        fd.append('student_id', studentId);
        fd.append('title', 'تنبيه مالي عاجل ⚠️');
        fd.append('message', `نود إعلامكم بأن الطالب (${studentName}) لديه متعلقات مالية متأخرة الدفع. يرجى مراجعة قسم الحسابات لتسوية المبلغ المتبقي.`);

        fetch('api_send_financial_alert.php', { method: 'POST', body: fd })
        .then(res => res.json())
        .then(resData => {
            if (resData.status === 'success') {
                showToast("✅ تم إرسال الإشعار لولي الأمر بنجاح!", 'success');
                btn.classList.remove('bg-red-900/30', 'text-red-400', 'animate-pulse', 'border-red-800/50');
                btn.classList.add('bg-green-900/30', 'text-green-500', 'border-green-800/50');
                btn.innerHTML = '<i class="fas fa-check-double"></i>';
            } else { showToast("❌ " + resData.message, 'error'); btn.innerHTML = originalHtml; btn.disabled = false; }
        }).catch(e => { showToast("⚠️ حدث خطأ في الاتصال بالخادم!", 'error'); btn.innerHTML = originalHtml; btn.disabled = false; });
    }

    function sendBulkFinancialAlert(e) {
        e.preventDefault();
        const form = document.getElementById('bulkNotificationForm');
        const fd = new FormData(form);
        fd.append('action', 'bulk_alert');

        const btn = document.getElementById('btn-bulk-alert');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> جاري توليد المطالبات المالية...';
        btn.disabled = true;

        fetch('api_send_financial_alert.php', { method: 'POST', body: fd })
        .then(res => res.json())
        .then(resData => {
            if(resData.status === 'success') {
                showToast(`✅ تم معالجة الإشعارات. (تم إرسال ${resData.platform_sent} إشعار منصة)`, 'success');
                if(resData.whatsapp_links && resData.whatsapp_links.length > 0) {
                    const container = document.getElementById('financial-whatsapp-links');
                    container.innerHTML = '';
                    resData.whatsapp_links.forEach(link => { container.innerHTML += link; });
                    const modal = document.getElementById('financialWhatsappModal');
                    if(modal) { modal.classList.remove('hidden'); modal.classList.add('flex'); }
                }
            } else { showToast('❌ ' + resData.message, 'error'); }
        }).catch(err => { showToast('حدث خطأ في الاتصال بالسيرفر.', 'error'); })
        .finally(() => { btn.innerHTML = originalText; btn.disabled = false; });
    }

    function openRescheduleModal(id, name, remainingDebt) {
        if (remainingDebt <= 0) { showToast('الطالب لا يحتوي على ديون متبقية للجدولة!', 'info'); return; }
        document.getElementById('resch-student-id').value = id;
        document.getElementById('resch-student-name').value = name;
        document.getElementById('resch-remaining-debt').value = remainingDebt.toLocaleString() + ' د.ع';
        document.getElementById('resch-raw-debt').value = remainingDebt;
        document.getElementById('resch-inst-count').value = 1;
        generateRescheduleRows(); 
        const modal = document.getElementById('rescheduleModal');
        if(modal) { modal.classList.remove('hidden'); modal.classList.add('flex'); }
    }

    function generateRescheduleRows() {
        const count = parseInt(document.getElementById('resch-inst-count').value) || 1;
        const totalDebt = parseFloat(document.getElementById('resch-raw-debt').value) || 0;
        const amountPerInst = Math.round(totalDebt / count);
        const container = document.getElementById('resch_inst_rows'); 
        container.innerHTML = '';
        for (let i = 1; i <= count; i++) {
            let d = new Date(); d.setMonth(d.getMonth() + i); let dateStr = d.toISOString().split('T')[0];
            let finalAmount = (i === count) ? (totalDebt - (amountPerInst * (count - 1))) : amountPerInst;
            container.innerHTML += `
                <div class="flex gap-3 items-center bg-[#090204] p-3 rounded-lg border border-purple-900/50">
                    <span class="text-purple-400 font-bold w-16 text-sm">قسط ${i}:</span>
                    <input type="number" name="resch_amount[]" value="${finalAmount}" class="flex-1 p-2 bg-[#1a0b12] text-white rounded-md text-center outline-none focus:border-purple-500 font-bold" oninput="validateRescheduleSum()" required>
                    <input type="date" name="resch_date[]" value="${dateStr}" class="w-40 p-2 bg-[#1a0b12] text-gray-300 rounded-md outline-none" required>
                </div>
            `;
        }
        validateRescheduleSum();
    }

    function validateRescheduleSum() {
        const totalDebt = parseFloat(document.getElementById('resch-raw-debt').value) || 0;
        let currentSum = 0; 
        document.querySelectorAll('input[name="resch_amount[]"]').forEach(input => currentSum += parseFloat(input.value) || 0);
        const msgEl = document.getElementById('resch-validation-msg'); 
        const submitBtn = document.getElementById('btn-submit-resch');
        if (Math.abs(currentSum - totalDebt) > 1) {
            if(msgEl) msgEl.classList.remove('hidden'); 
            if(submitBtn) { submitBtn.disabled = true; submitBtn.classList.add('opacity-50', 'cursor-not-allowed'); }
        } else {
            if(msgEl) msgEl.classList.add('hidden'); 
            if(submitBtn) { submitBtn.disabled = false; submitBtn.classList.remove('opacity-50', 'cursor-not-allowed'); }
        }
    }

    function submitReschedule(e) {
        e.preventDefault();
        const btn = document.getElementById('btn-submit-resch'); const origText = btn.innerHTML; 
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> جاري الحفظ...'; btn.disabled = true;
        let fd = new FormData(); 
        fd.append('action', 'reschedule'); 
        fd.append('student_id', document.getElementById('resch-student-id').value);
        const amounts = document.querySelectorAll('input[name="resch_amount[]"]'); 
        const dates = document.querySelectorAll('input[name="resch_date[]"]');
        for(let i = 0; i < amounts.length; i++) { fd.append('resch_amount[]', amounts[i].value); fd.append('resch_date[]', dates[i].value); }
        fetch('save_accounting_data.php', { method: 'POST', body: fd })
        .then(res => res.json())
        .then(resData => {
            if(resData.status === 'success') { showToast('✅ تم إعادة جدولة الأقساط بنجاح!', 'success'); closeModal('rescheduleModal'); renderInstallmentsTable(); 
            } else { showToast('❌ ' + resData.message, 'error'); }
        }).catch(err => showToast('خطأ بالاتصال بالخادم', 'error')).finally(() => { btn.innerHTML = origText; btn.disabled = false; });
    }
</script>
</body>
</html>
