<?php
// school/student_view_finance.php
// تبويب المالية — يُحمّل عبر AJAX من student_view.php
// يعرض: ملخص السنة، الأقساط، المدفوعات، متأخرات السنين السابقة

/* ============================================================
   ✅ هذا الملف يُستدعى بطريقتين:
   1. عبر AJAX من student_view.php → يُرجع HTML فقط
   2. مباشرة في المتصفح → يعرض صفحة كاملة
   ============================================================ */

$is_ajax = (
    isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'
);

if (!$is_ajax) {
    $page_title = 'المالية — ملف الطالب';
    require_once('../includes/header.php');
    require_once('../includes/permissions.php');
} else {
    /* عند AJAX: نجلب الاتصال فقط */
    if (!defined('IN_AJAX')) define('IN_AJAX', true);
    require_once('../includes/permissions.php');
}

/* ============================================================
   Polyfills
   ============================================================ */
if (!function_exists('h'))     { function h($s)     { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); } }
if (!function_exists('money')) { function money($n) { return number_format((float)$n, 2); } }

/* ============================================================
   الوصول
   ============================================================ */
if (empty($_SESSION['user_id'])) { http_response_code(403); exit('Forbidden'); }

$current_role = isset($_SESSION['role']) ? $_SESSION['role'] : '';
$is_super     = ($current_role === 'super_admin');
$is_general   = ($current_role === 'general_supervisor');
$can_see_all  = ($is_super || $is_general);
$can_manage   = ($is_super || $is_general || $current_role === 'school_admin' || $current_role === 'accountant');
$my_school    = isset($_SESSION['school_id']) ? (int)$_SESSION['school_id'] : 0;

$allowed_roles = array('super_admin','general_supervisor','school_admin','accountant','teacher');
if (!in_array($current_role, $allowed_roles, true)) {
    echo '<div class="alert alert-error">🔒 غير مصرح.</div>';
    exit;
}

/* ============================================================
   GET — معرّف الطالب + فلترة السنة
   ============================================================ */
$student_id  = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$filter_year = isset($_GET['year_id']) ? (int)$_GET['year_id'] : 0;

if ($student_id <= 0) {
    echo '<div class="alert alert-error">❌ معرّف الطالب غير صالح.</div>';
    exit;
}

/* ============================================================
   جلب الطالب
   ============================================================ */
$stmt = mysqli_prepare($conn,
    "SELECT s.*, 
            (SELECT school_name FROM schools WHERE school_id = s.school_id LIMIT 1) AS school_name
     FROM students s WHERE s.student_id = ? LIMIT 1");
if (!$stmt) {
    echo '<div class="alert alert-error">خطأ: ' . h(mysqli_error($conn)) . '</div>';
    exit;
}
mysqli_stmt_bind_param($stmt, 'i', $student_id);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);
$stu = $res ? mysqli_fetch_assoc($res) : null;
mysqli_stmt_close($stmt);

if (!$stu) {
    echo '<div class="alert alert-error">❌ الطالب غير موجود.</div>';
    exit;
}

/* فحص الصلاحية */
if (!$can_see_all && $my_school > 0 && (int)$stu['school_id'] !== $my_school) {
    echo '<div class="alert alert-error">🔒 غير مصرح بعرض بيانات هذا الطالب.</div>';
    exit;
}

/* ============================================================
   ✅ السنة الحالية
   ============================================================ */
$current_year = null;
$r = @mysqli_query($conn, "SELECT * FROM years WHERE is_active = 1 ORDER BY year_id DESC LIMIT 1");
if ($r && $row = mysqli_fetch_assoc($r)) $current_year = $row;

/* جميع السنوات (للفلترة) */
$years_all = array();
$r = @mysqli_query($conn, "SELECT * FROM years ORDER BY year_id DESC");
if ($r) while ($row = mysqli_fetch_assoc($r)) $years_all[] = $row;

/* السنة المعروضة */
$display_year = null;
if ($filter_year > 0) {
    foreach ($years_all as $y) {
        if ((int)$y['year_id'] === $filter_year) { $display_year = $y; break; }
    }
}
if (!$display_year) $display_year = $current_year;

$display_year_id = $display_year ? (int)$display_year['year_id'] : 0;

/* ============================================================
   ✅ جلب جميع الرسوم (student_fees) للطالب
   ============================================================ */
$all_fees = array();
$r = @mysqli_query($conn,
    "SELECT sf.*, 
            f.fee_name, 
            f.school_id AS fee_school_id,
            y.year_name,
            y.is_active AS year_is_active,
            y.start_date AS year_start,
            y.end_date AS year_end
     FROM student_fees sf
     LEFT JOIN fees f ON f.fee_id = sf.fee_id
     LEFT JOIN years y ON y.year_id = sf.year_id
     WHERE sf.student_id = " . (int)$student_id . "
     ORDER BY sf.year_id DESC, sf.student_fee_id DESC");
if ($r) while ($row = mysqli_fetch_assoc($r)) $all_fees[] = $row;

/* ============================================================
   ✅ جلب جميع الأقساط
   ============================================================ */
$all_installments = array();
$r = @mysqli_query($conn,
    "SELECT i.*, 
            sf.year_id,
            y.year_name
     FROM installments i
     LEFT JOIN student_fees sf ON sf.student_fee_id = i.student_fee_id
     LEFT JOIN years y ON y.year_id = sf.year_id
     WHERE sf.student_id = " . (int)$student_id . "
     ORDER BY i.due_date ASC, i.seq_no ASC");
if ($r) while ($row = mysqli_fetch_assoc($r)) $all_installments[] = $row;

/* ============================================================
   ✅ جلب جميع المدفوعات
   ============================================================ */
$all_payments = array();
$r = @mysqli_query($conn,
    "SELECT p.*, 
            sf.year_id,
            sf.student_fee_id,
            f.fee_name,
            y.year_name
     FROM payments p
     LEFT JOIN student_fees sf ON sf.student_fee_id = p.student_fee_id
     LEFT JOIN fees f ON f.fee_id = sf.fee_id
     LEFT JOIN years y ON y.year_id = sf.year_id
     WHERE sf.student_id = " . (int)$student_id . "
     ORDER BY p.paid_at DESC, p.payment_id DESC");
if ($r) while ($row = mysqli_fetch_assoc($r)) $all_payments[] = $row;

/* ============================================================
   ✅ حساب الملخصات
   ============================================================ */

/* ---- ملخص السنة المعروضة ---- */
$summary_current = array(
    'total'    => 0,  // إجمالي الرسوم (قبل الخصم)
    'discount' => 0,  // الخصومات
    'net'      => 0,  // الصافي المطلوب
    'paid'     => 0,  // المدفوع
    'remaining'=> 0,  // المتبقي
    'count'    => 0,  // عدد الرسوم
);

/* ---- متأخرات السنين السابقة ---- */
$previous_years = array();  // [year_id => ملخص]

foreach ($all_fees as $sf) {
    $sf_year_id = (int)$sf['year_id'];
    $amount     = (float)$sf['amount'];
    $discount   = (float)$sf['discount'];
    $paid       = (float)$sf['paid_amount'];
    $net        = $amount - $discount;
    $remaining  = max(0, $net - $paid);

    if ($sf_year_id === $display_year_id) {
        $summary_current['total']     += $amount;
        $summary_current['discount']  += $discount;
        $summary_current['net']       += $net;
        $summary_current['paid']      += $paid;
        $summary_current['remaining'] += $remaining;
        $summary_current['count']++;
    } else {
        /* سنة سابقة */
        if (!isset($previous_years[$sf_year_id])) {
            $previous_years[$sf_year_id] = array(
                'year_id'   => $sf_year_id,
                'year_name' => $sf['year_name'] ?: 'غير محدد',
                'total'     => 0,
                'discount'  => 0,
                'net'       => 0,
                'paid'      => 0,
                'remaining' => 0,
                'count'     => 0,
            );
        }
        $previous_years[$sf_year_id]['total']     += $amount;
        $previous_years[$sf_year_id]['discount']  += $discount;
        $previous_years[$sf_year_id]['net']       += $net;
        $previous_years[$sf_year_id]['paid']      += $paid;
        $previous_years[$sf_year_id]['remaining'] += $remaining;
        $previous_years[$sf_year_id]['count']++;
    }
}

/* ---- إجمالي كل السنوات ---- */
$grand_total = array(
    'total'    => 0,
    'discount' => 0,
    'net'      => 0,
    'paid'     => 0,
    'remaining'=> 0,
);

foreach ($all_fees as $sf) {
    $grand_total['total']     += (float)$sf['amount'];
    $grand_total['discount']  += (float)$sf['discount'];
    $grand_total['net']       += (float)$sf['amount'] - (float)$sf['discount'];
    $grand_total['paid']      += (float)$sf['paid_amount'];
}
$grand_total['remaining'] = max(0, $grand_total['net'] - $grand_total['paid']);

/* إجمالي المتأخرات (كل السنوات ما عدا السنة الحالية) */
$total_arrears = 0;
foreach ($previous_years as $py) {
    $total_arrears += $py['remaining'];
}

/* ============================================================
   ✅ فلترة الأقساط والمدفوعات حسب السنة المعروضة
   ============================================================ */
$display_installments = array();
foreach ($all_installments as $inst) {
    if ((int)$inst['year_id'] === $display_year_id) {
        $display_installments[] = $inst;
    }
}

$display_payments = array();
foreach ($all_payments as $p) {
    if ((int)$p['year_id'] === $display_year_id) {
        $display_payments[] = $p;
    }
}

/* ============================================================
   ✅ حساب حالة القسط
   ============================================================ */
function installment_status($inst) {
    $status = isset($inst['status']) ? strtolower($inst['status']) : 'unpaid';
    $amount = (float)$inst['amount'];
    $paid   = (float)$inst['paid_amount'];
    $due    = !empty($inst['due_date']) ? strtotime($inst['due_date']) : null;
    $today  = strtotime(date('Y-m-d'));

    if ($status === 'cancelled') {
        return array('ملغى', 'cancelled', '🚫');
    }

    if ($paid >= $amount && $amount > 0) {
        return array('مدفوع', 'paid', '✅');
    }

    if ($paid > 0 && $paid < $amount) {
        if ($due && $due < $today) {
            return array('متأخر جزئي', 'partial-overdue', '⚠️');
        }
        return array('جزئي', 'partial', '🟡');
    }

    if ($due && $due < $today) {
        return array('متأخر', 'overdue', '⏰');
    }

    return array('قادم', 'upcoming', '🔵');
}

/* ============================================================
   ✅ حالة الرسم student_fees
   ============================================================ */
function fee_status_display($sf) {
    $status = isset($sf['status']) ? strtolower($sf['status']) : 'unpaid';
    $amount = (float)$sf['amount'] - (float)$sf['discount'];
    $paid   = (float)$sf['paid_amount'];

    if ($status === 'paid' || $paid >= $amount) {
        return array('مدفوع بالكامل', 'paid', '✅');
    }
    if ($status === 'partial' || ($paid > 0 && $paid < $amount)) {
        return array('مدفوع جزئياً', 'partial', '🟡');
    }
    return array('غير مدفوع', 'unpaid', '⏰');
}

$base_url = 'student_view_finance.php?id=' . $student_id;
?>
<?php if (!$is_ajax): ?>
<?php require_once('includes/sidebar.php'); ?>
<div class="span10 main-content">
<?php endif; ?>

<style>
/* ═══════════════════════════════════════════════════════════
   المالية — CSS
   ═══════════════════════════════════════════════════════════ */
.fin-toolbar {
    display: flex;
    gap: 10px;
    align-items: center;
    flex-wrap: wrap;
    padding: 14px 18px;
    background: white;
    border-radius: 14px;
    border: 1.5px solid #e2e8f0;
    margin-bottom: 16px;
}
.fin-toolbar label {
    font-weight: 500;
    font-size: 0.9rem;
    color: #475569;
    margin: 0;
}
.fin-toolbar select {
    padding: 8px 12px;
    border: 1.5px solid #e2e8f0;
    border-radius: 10px;
    font-size: 0.9rem;
    background: #f9fbfd;
    font-family: inherit;
    min-width: 180px;
}
.fin-toolbar .btn {
    padding: 8px 16px;
    border-radius: 10px;
    border: none;
    cursor: pointer;
    font-weight: 600;
    font-size: 0.85rem;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.15s;
}
.fin-toolbar .btn.primary {
    background: #3b82f6;
    color: white;
}
.fin-toolbar .btn.primary:hover { background: #2563eb; }
.fin-toolbar .btn.success {
    background: #10b981;
    color: white;
}
.fin-toolbar .btn.success:hover { background: #059669; }
.fin-toolbar .btn.gray {
    background: #f1f5f9;
    color: #334155;
    border: 1px solid #e2e8f0;
}
.fin-toolbar .btn.gray:hover { background: #e2e8f0; }

/* بطاقات الملخص */
.summary-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 12px;
    margin-bottom: 20px;
}
.summary-card {
    padding: 18px 20px;
    border-radius: 14px;
    background: white;
    border: 1.5px solid #e2e8f0;
    position: relative;
    overflow: hidden;
}
.summary-card::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 5px;
    height: 100%;
}
.summary-card.blue::before    { background: #3b82f6; }
.summary-card.green::before   { background: #10b981; }
.summary-card.orange::before  { background: #f59e0b; }
.summary-card.red::before     { background: #ef4444; }
.summary-card.purple::before  { background: #8b5cf6; }
.summary-card.teal::before    { background: #14b8a6; }

.summary-card .icon {
    font-size: 1.5rem;
    margin-bottom: 6px;
    opacity: 0.85;
}
.summary-card .value {
    font-size: 1.6rem;
    font-weight: 700;
    color: #1e293b;
    line-height: 1.1;
    direction: ltr;
}
.summary-card .label {
    font-size: 0.82rem;
    color: #64748b;
    margin-top: 4px;
    font-weight: 500;
}
.summary-card .sub {
    font-size: 0.72rem;
    color: #94a3b8;
    margin-top: 6px;
}

/* شريط التقدم للسداد */
.progress-bar-wrap {
    background: #f1f5f9;
    border-radius: 20px;
    height: 30px;
    overflow: hidden;
    margin: 8px 0;
    position: relative;
}
.progress-bar-fill {
    height: 100%;
    background: linear-gradient(90deg, #10b981, #059669);
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: 600;
    font-size: 0.85rem;
    transition: width 0.5s;
}
.progress-bar-fill.partial {
    background: linear-gradient(90deg, #f59e0b, #d97706);
}
.progress-bar-fill.low {
    background: linear-gradient(90deg, #ef4444, #dc2626);
}

/* بطاقات الأقسام */
.fin-card {
    background: white;
    border-radius: 14px;
    border: 1.5px solid #e2e8f0;
    padding: 20px 24px;
    margin-bottom: 16px;
}
.fin-card h4 {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    font-size: 1.05rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0 0 16px 0;
    padding-bottom: 12px;
    border-bottom: 2px solid #f1f5f9;
    flex-wrap: wrap;
}
.fin-card h4 .title {
    display: inline-flex;
    align-items: center;
    gap: 8px;
}
.fin-card h4 .count {
    font-size: 0.75rem;
    background: #eff6ff;
    color: #1e40af;
    padding: 3px 10px;
    border-radius: 20px;
    font-weight: 600;
}

/* جدول */
.fin-table {
    width: 100%;
    border-collapse: collapse;
}
.fin-table thead th {
    padding: 12px 10px;
    background: #f8fafc;
    color: #475569;
    font-weight: 600;
    font-size: 0.82rem;
    border-bottom: 2px solid #e2e8f0;
    text-align: right;
    white-space: nowrap;
}
.fin-table tbody td {
    padding: 10px;
    border-bottom: 1px solid #f1f5f9;
    font-size: 0.88rem;
    color: #334155;
    vertical-align: middle;
}
.fin-table tbody tr:hover { background: #f8fafc; }
.fin-table tbody tr:last-child td { border-bottom: none; }

.fin-table tfoot td {
    padding: 12px 10px;
    background: #f8fafc;
    font-weight: 600;
    font-size: 0.88rem;
    color: #1e293b;
    border-top: 2px solid #e2e8f0;
}

/* شارات الحالة */
.st-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 10px;
    border-radius: 8px;
    font-size: 0.76rem;
    font-weight: 600;
    white-space: nowrap;
}
.st-paid            { background: #d1fae5; color: #065f46; }
.st-partial         { background: #fef3c7; color: #92400e; }
.st-partial-overdue { background: #fed7aa; color: #9a3412; }
.st-overdue         { background: #fee2e2; color: #991b1b; }
.st-upcoming        { background: #dbeafe; color: #1e40af; }
.st-cancelled       { background: #f1f5f9; color: #64748b; }
.st-unpaid          { background: #fee2e2; color: #991b1b; }

/* شارات طريقة الدفع */
.method-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 3px 10px;
    border-radius: 8px;
    font-size: 0.78rem;
    font-weight: 600;
}
.method-cash   { background: #d1fae5; color: #065f46; }
.method-bank   { background: #dbeafe; color: #1e40af; }
.method-card   { background: #e9d5ff; color: #6b21a8; }
.method-online { background: #fef3c7; color: #92400e; }
.method-other  { background: #f1f5f9; color: #334155; }

/* المتأخرات */
.arrears-banner {
    background: linear-gradient(135deg, #fee2e2, #fecaca);
    border: 2px solid #ef4444;
    border-radius: 14px;
    padding: 18px 22px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
}
.arrears-banner .icon {
    font-size: 2.5rem;
}
.arrears-banner .text {
    flex: 1;
    min-width: 200px;
}
.arrears-banner .text h4 {
    margin: 0 0 4px 0;
    color: #991b1b;
    font-size: 1.1rem;
    border: none;
    padding: 0;
}
.arrears-banner .text p {
    margin: 0;
    color: #7f1d1d;
    font-size: 0.9rem;
}
.arrears-banner .amount {
    font-size: 1.6rem;
    font-weight: 700;
    color: #991b1b;
    direction: ltr;
}

/* الحالة الفارغة */
.empty-fin {
    text-align: center;
    padding: 40px 20px;
    color: #94a3b8;
}
.empty-fin .icon {
    font-size: 3rem;
    margin-bottom: 10px;
    opacity: 0.6;
}
.empty-fin h4 {
    border: none;
    justify-content: center;
    color: #64748b;
    margin: 0 0 8px 0;
    padding: 0;
}

/* الطباعة */
@media print {
    .fin-toolbar, .no-print, .action-btn { display: none !important; }
    .fin-card { break-inside: avoid; page-break-inside: avoid; }
    .summary-grid { grid-template-columns: repeat(3, 1fr); }
}

@media (max-width: 768px) {
    .fin-toolbar { flex-direction: column; align-items: stretch; }
    .fin-toolbar select { width: 100%; }
    .summary-grid { grid-template-columns: repeat(2, 1fr); }
    .fin-table { font-size: 0.78rem; }
    .fin-table thead th, .fin-table tbody td { padding: 6px 4px; }
    .arrears-banner { flex-direction: column; text-align: center; }
}
</style>

<!-- ═══════════════════════════════════════════════════════════
     شريط الأدوات
     ═══════════════════════════════════════════════════════════ -->
<div class="fin-toolbar no-print">
    <label>📅 السنة الدراسية:</label>
    <select id="finYearSelect" onchange="finChangeYear(this.value)">
        <?php foreach ($years_all as $y): 
            $yid = (int)$y['year_id'];
            $is_active = (int)$y['is_active'];
        ?>
            <option value="<?php echo $yid; ?>"
                <?php echo $yid === $display_year_id ? 'selected' : ''; ?>>
                📅 <?php echo h($y['year_name']); ?>
                <?php if ($is_active): ?> — (الحالية)<?php endif; ?>
            </option>
        <?php endforeach; ?>
    </select>

    <?php if ($can_manage): ?>
        <button class="btn success" onclick="finAddPayment()">
            ➕ إضافة دفعة
        </button>
    <?php endif; ?>

    <button class="btn primary" onclick="window.print()">
        🖨️ طباعة كشف الحساب
    </button>

    <button class="btn gray" onclick="finRefresh()">
        🔄 تحديث
    </button>
</div>

<!-- ═══════════════════════════════════════════════════════════
     تنبيه المتأخرات
     ═══════════════════════════════════════════════════════════ -->
<?php if ($total_arrears > 0): ?>
<div class="arrears-banner no-print">
    <div class="icon">⚠️</div>
    <div class="text">
        <h4>يوجد متأخرات مالية من سنوات سابقة</h4>
        <p>عدد السنوات المتأخرة: <strong><?php echo count($previous_years); ?></strong>
           — يجب تسوية هذه المتأخرات في أقرب وقت.</p>
    </div>
    <div class="amount"><?php echo money($total_arrears); ?> ر.س</div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════
     [1] ملخص السنة الدراسية
     ═══════════════════════════════════════════════════════════ -->
<div class="fin-card">
    <h4>
        <span class="title">
            💰 ملخص السنة الدراسية:
            <strong><?php echo $display_year ? h($display_year['year_name']) : '—'; ?></strong>
            <?php if ($display_year && (int)$display_year['is_active']): ?>
                <span class="count">السنة الحالية ✅</span>
            <?php endif; ?>
        </span>
    </h4>

    <div class="summary-grid">
        <div class="summary-card blue">
            <div class="icon">💵</div>
            <div class="value"><?php echo money($summary_current['net']); ?></div>
            <div class="label">المطلوب (الصافي)</div>
            <div class="sub">قبل الخصومات: <?php echo money($summary_current['total']); ?></div>
        </div>

        <div class="summary-card green">
            <div class="icon">✅</div>
            <div class="value" style="color:#10b981"><?php echo money($summary_current['paid']); ?></div>
            <div class="label">المدفوع</div>
            <div class="sub">
                <?php 
                $percent = $summary_current['net'] > 0 
                    ? round(($summary_current['paid'] / $summary_current['net']) * 100, 1) 
                    : 0;
                echo $percent . '%'; 
                ?>
            </div>
        </div>

        <div class="summary-card red">
            <div class="icon">⏰</div>
            <div class="value" style="color:<?php echo $summary_current['remaining'] > 0 ? '#ef4444' : '#10b981'; ?>">
                <?php echo money($summary_current['remaining']); ?>
            </div>
            <div class="label">المتبقي</div>
            <div class="sub">
                <?php if ($summary_current['remaining'] == 0): ?>
                    مسددة بالكامل ✅
                <?php else: ?>
                    يجب السداد
                <?php endif; ?>
            </div>
        </div>

        <div class="summary-card orange">
            <div class="icon">🎁</div>
            <div class="value"><?php echo money($summary_current['discount']); ?></div>
            <div class="label">الخصومات</div>
            <div class="sub">عدد الرسوم: <?php echo $summary_current['count']; ?></div>
        </div>
    </div>

    <!-- شريط التقدم -->
    <?php if ($summary_current['net'] > 0): 
        $pct = round(($summary_current['paid'] / $summary_current['net']) * 100, 1);
        $cls = $pct >= 100 ? '' : ($pct >= 50 ? 'partial' : 'low');
    ?>
    <div style="margin-top:15px">
        <div style="display:flex;justify-content:space-between;font-size:0.85rem;color:#64748b;margin-bottom:6px">
            <span>نسبة السداد</span>
            <span><strong><?php echo $pct; ?>%</strong></span>
        </div>
        <div class="progress-bar-wrap">
            <div class="progress-bar-fill <?php echo $cls; ?>" style="width:<?php echo min(100, $pct); ?>%">
                <?php echo $pct >= 15 ? $pct . '%' : ''; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════
     [2] تفاصيل الرسوم
     ═══════════════════════════════════════════════════════════ -->
<?php
$display_fees = array();
foreach ($all_fees as $sf) {
    if ((int)$sf['year_id'] === $display_year_id) $display_fees[] = $sf;
}
?>
<div class="fin-card">
    <h4>
        <span class="title">📋 تفاصيل الرسوم</span>
        <span class="count"><?php echo count($display_fees); ?> رسم</span>
    </h4>

    <?php if (!empty($display_fees)): ?>
    <div style="overflow-x:auto">
        <table class="fin-table">
            <thead>
                <tr>
                    <th width="50">#</th>
                    <th>اسم الرسم</th>
                    <th width="110">المبلغ</th>
                    <th width="100">الخصم</th>
                    <th width="110">الصافي</th>
                    <th width="110">المدفوع</th>
                    <th width="110">المتبقي</th>
                    <th width="140">الحالة</th>
                </tr>
            </thead>
            <tbody>
                <?php $i = 1; foreach ($display_fees as $sf):
                    $amount   = (float)$sf['amount'];
                    $discount = (float)$sf['discount'];
                    $paid     = (float)$sf['paid_amount'];
                    $net      = $amount - $discount;
                    $remaining = max(0, $net - $paid);
                    $st = fee_status_display($sf);
                ?>
                <tr>
                    <td><?php echo $i++; ?></td>
                    <td>
                        <strong><?php echo h($sf['fee_name'] ?: 'رسم #' . $sf['fee_id']); ?></strong>
                        <?php if (!empty($sf['discount_reason'])): ?>
                            <br><small style="color:#64748b">🎁 <?php echo h($sf['discount_reason']); ?></small>
                        <?php endif; ?>
                    </td>
                    <td><?php echo money($amount); ?></td>
                    <td style="color:#f59e0b"><?php echo $discount > 0 ? money($discount) : '—'; ?></td>
                    <td><strong><?php echo money($net); ?></strong></td>
                    <td style="color:#10b981"><strong><?php echo money($paid); ?></strong></td>
                    <td style="color:<?php echo $remaining > 0 ? '#ef4444' : '#10b981'; ?>">
                        <strong><?php echo money($remaining); ?></strong>
                    </td>
                    <td>
                        <span class="st-badge st-<?php echo $st[1]; ?>">
                            <?php echo $st[2]; ?> <?php echo $st[0]; ?>
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="2">الإجمالي</td>
                    <td><?php echo money($summary_current['total']); ?></td>
                    <td><?php echo money($summary_current['discount']); ?></td>
                    <td><?php echo money($summary_current['net']); ?></td>
                    <td><?php echo money($summary_current['paid']); ?></td>
                    <td style="color:<?php echo $summary_current['remaining'] > 0 ? '#ef4444' : '#10b981'; ?>">
                        <?php echo money($summary_current['remaining']); ?>
                    </td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    </div>
    <?php else: ?>
        <div class="empty-fin">
            <div class="icon">📭</div>
            <h4>لا توجد رسوم لهذه السنة</h4>
        </div>
    <?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════
     [3] جدول الأقساط
     ═══════════════════════════════════════════════════════════ -->
<div class="fin-card">
    <h4>
        <span class="title">📅 جدول الأقساط</span>
        <span class="count"><?php echo count($display_installments); ?> قسط</span>
    </h4>

    <?php if (!empty($display_installments)): ?>
    <div style="overflow-x:auto">
        <table class="fin-table">
            <thead>
                <tr>
                    <th width="50">#</th>
                    <th width="80">القسط</th>
                    <th width="110">المبلغ</th>
                    <th width="110">المدفوع</th>
                    <th width="110">المتبقي</th>
                    <th width="120">تاريخ الاستحقاق</th>
                    <th width="140">الحالة</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($display_installments as $inst):
                    $amount   = (float)$inst['amount'];
                    $paid     = (float)$inst['paid_amount'];
                    $remaining = max(0, $amount - $paid);
                    $st = installment_status($inst);
                    $due_ts = !empty($inst['due_date']) ? strtotime($inst['due_date']) : null;
                    $today  = strtotime(date('Y-m-d'));
                    $late_days = ($due_ts && $due_ts < $today && $remaining > 0) 
                        ? floor(($today - $due_ts) / 86400) 
                        : 0;
                ?>
                <tr>
                    <td><?php echo (int)$inst['seq_no']; ?></td>
                    <td>
                        <span style="background:#f1f5f9;padding:2px 8px;border-radius:6px;font-size:0.8rem">
                            #<?php echo (int)$inst['seq_no']; ?>
                        </span>
                    </td>
                    <td><?php echo money($amount); ?></td>
                    <td style="color:#10b981"><strong><?php echo money($paid); ?></strong></td>
                    <td style="color:<?php echo $remaining > 0 ? '#ef4444' : '#10b981'; ?>">
                        <strong><?php echo money($remaining); ?></strong>
                    </td>
                    <td>
                        <?php echo !empty($inst['due_date']) ? h($inst['due_date']) : '—'; ?>
                        <?php if ($late_days > 0): ?>
                            <br><small style="color:#ef4444">متأخر <?php echo $late_days; ?> يوم</small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="st-badge st-<?php echo $st[1]; ?>">
                            <?php echo $st[2]; ?> <?php echo $st[0]; ?>
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
        <div class="empty-fin">
            <div class="icon">📅</div>
            <h4>لا توجد أقساط مسجلة لهذه السنة</h4>
        </div>
    <?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════
     [4] سجل المدفوعات
     ═══════════════════════════════════════════════════════════ -->
<div class="fin-card">
    <h4>
        <span class="title">💵 سجل المدفوعات</span>
        <span class="count"><?php echo count($display_payments); ?> دفعة</span>
    </h4>

    <?php if (!empty($display_payments)): ?>
    <div style="overflow-x:auto">
        <table class="fin-table">
            <thead>
                <tr>
                    <th width="50">#</th>
                    <th width="110">التاريخ</th>
                    <th>الرسم</th>
                    <th width="110">المبلغ</th>
                    <th width="100">الطريقة</th>
                    <th width="150">رقم الإيصال</th>
                    <th width="80">إجراء</th>
                </tr>
            </thead>
            <tbody>
                <?php $i = 1; foreach ($display_payments as $p):
                    $method = strtolower($p['method'] ?: 'other');
                    $method_map = array(
                        'cash'   => array('نقداً',    '💵', 'cash'),
                        'bank'   => array('بنك',      '🏦', 'bank'),
                        'card'   => array('بطاقة',    '💳', 'card'),
                        'online' => array('إلكتروني', '🌐', 'online'),
                    );
                    $mm = isset($method_map[$method]) ? $method_map[$method] : array($method, '💰', 'other');
                ?>
                <tr>
                    <td><?php echo $i++; ?></td>
                    <td>
                        <?php echo !empty($p['paid_at']) ? h($p['paid_at']) : '—'; ?>
                    </td>
                    <td>
                        <strong><?php echo h($p['fee_name'] ?: '—'); ?></strong>
                    </td>
                    <td style="color:#10b981"><strong><?php echo money($p['amount']); ?></strong></td>
                    <td>
                        <span class="method-badge method-<?php echo $mm[2]; ?>">
                            <?php echo $mm[1]; ?> <?php echo $mm[0]; ?>
                        </span>
                    </td>
                    <td>
                        <?php if (!empty($p['reference_no'])): ?>
                            <code style="font-size:0.78rem;background:#f1f5f9;padding:2px 6px;border-radius:6px">
                                <?php echo h($p['reference_no']); ?>
                            </code>
                        <?php else: ?>
                            —
                        <?php endif; ?>
                    </td>
                    <td>
                        <a href="payment_print.php?id=<?php echo (int)$p['payment_id']; ?>"
                           target="_blank"
                           class="btn-sm primary"
                           style="padding:4px 8px;font-size:0.72rem;text-decoration:none;background:#3b82f6;color:white;border-radius:6px">
                            🖨️ طباعة
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="3">إجمالي المدفوعات</td>
                    <td colspan="4" style="color:#10b981">
                        <?php echo money($summary_current['paid']); ?>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
    <?php else: ?>
        <div class="empty-fin">
            <div class="icon">💵</div>
            <h4>لا توجد مدفوعات مسجلة لهذه السنة</h4>
        </div>
    <?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════
     [5] متأخرات السنين السابقة
     ═══════════════════════════════════════════════════════════ -->
<?php if (!empty($previous_years)): ?>
<div class="fin-card">
    <h4>
        <span class="title">⏰ متأخرات السنين السابقة</span>
        <span class="count"><?php echo count($previous_years); ?> سنة</span>
    </h4>

    <div style="overflow-x:auto">
        <table class="fin-table">
            <thead>
                <tr>
                    <th width="50">#</th>
                    <th>السنة الدراسية</th>
                    <th width="110">المطلوب</th>
                    <th width="110">المدفوع</th>
                    <th width="110">المتبقي</th>
                    <th width="100">عدد الرسوم</th>
                    <th width="140">الحالة</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $i = 1;
                $sorted_prev = $previous_years;
                krsort($sorted_prev);
                foreach ($sorted_prev as $py):
                    $remaining = $py['remaining'];
                    $is_paid = ($remaining <= 0);
                ?>
                <tr>
                    <td><?php echo $i++; ?></td>
                    <td>
                        <strong>📅 <?php echo h($py['year_name']); ?></strong>
                    </td>
                    <td><?php echo money($py['net']); ?></td>
                    <td style="color:#10b981"><?php echo money($py['paid']); ?></td>
                    <td style="color:<?php echo $remaining > 0 ? '#ef4444' : '#10b981'; ?>">
                        <strong><?php echo money($remaining); ?></strong>
                    </td>
                    <td><?php echo $py['count']; ?></td>
                    <td>
                        <?php if ($is_paid): ?>
                            <span class="st-badge st-paid">✅ مسددة</span>
                        <?php else: ?>
                            <span class="st-badge st-overdue">⏰ متأخرة</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="2">إجمالي المتأخرات</td>
                    <td>
                        <?php 
                        $total_prev_net = 0;
                        foreach ($previous_years as $py) $total_prev_net += $py['net'];
                        echo money($total_prev_net); 
                        ?>
                    </td>
                    <td>
                        <?php 
                        $total_prev_paid = 0;
                        foreach ($previous_years as $py) $total_prev_paid += $py['paid'];
                        echo money($total_prev_paid); 
                        ?>
                    </td>
                    <td colspan="3" style="color:#ef4444;font-size:1rem">
                        <?php echo money($total_arrears); ?> ر.س
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════
     [6] الملخص الشامل (كل السنوات)
     ═══════════════════════════════════════════════════════════ -->
<div class="fin-card">
    <h4>
        <span class="title">📊 الملخص المالي الشامل (كل السنوات)</span>
    </h4>

    <div class="summary-grid">
        <div class="summary-card blue">
            <div class="icon">💵</div>
            <div class="value"><?php echo money($grand_total['net']); ?></div>
            <div class="label">إجمالي المطلوب</div>
        </div>

        <div class="summary-card green">
            <div class="icon">✅</div>
            <div class="value" style="color:#10b981"><?php echo money($grand_total['paid']); ?></div>
            <div class="label">إجمالي المدفوع</div>
        </div>

        <div class="summary-card <?php echo $grand_total['remaining'] > 0 ? 'red' : 'green'; ?>">
            <div class="icon">⏰</div>
            <div class="value" style="color:<?php echo $grand_total['remaining'] > 0 ? '#ef4444' : '#10b981'; ?>">
                <?php echo money($grand_total['remaining']); ?>
            </div>
            <div class="label">إجمالي المتبقي</div>
        </div>

        <?php if ($total_arrears > 0): ?>
        <div class="summary-card red">
            <div class="icon">⚠️</div>
            <div class="value" style="color:#991b1b"><?php echo money($total_arrears); ?></div>
            <div class="label">متأخرات سابقة</div>
        </div>
        <?php endif; ?>
    </div>

    <?php if ($grand_total['net'] > 0): 
        $pct_all = round(($grand_total['paid'] / $grand_total['net']) * 100, 1);
        $cls_all = $pct_all >= 100 ? '' : ($pct_all >= 50 ? 'partial' : 'low');
    ?>
    <div style="margin-top:15px">
        <div style="display:flex;justify-content:space-between;font-size:0.85rem;color:#64748b;margin-bottom:6px">
            <span>نسبة السداد الإجمالية</span>
            <span><strong><?php echo $pct_all; ?>%</strong></span>
        </div>
        <div class="progress-bar-wrap">
            <div class="progress-bar-fill <?php echo $cls_all; ?>" style="width:<?php echo min(100, $pct_all); ?>%">
                <?php echo $pct_all >= 15 ? $pct_all . '%' : ''; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════
     JavaScript
     ═══════════════════════════════════════════════════════════ -->
<script>
(function () {
    'use strict';

    var studentId = <?php echo (int)$student_id; ?>;
    var currentYear = <?php echo (int)$display_year_id; ?>;

    window.finChangeYear = function (yearId) {
        var url = 'student_view_finance.php?id=' + studentId + '&year_id=' + yearId;

        /* إذا داخل AJAX → اطلب الجزء فقط */
        var container = document.getElementById('finTabContent');
        if (container) {
            container.innerHTML = '<div style="text-align:center;padding:40px;color:#94a3b8">⏳ جاري التحميل...</div>';
            fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                .then(function (r) { return r.text(); })
                .then(function (html) {
                    container.innerHTML = html;
                    /* إعادة تنفيذ السكريبتات داخل الـ HTML المُحمّل */
                    var scripts = container.querySelectorAll('script');
                    scripts.forEach(function (old) {
                        var s = document.createElement('script');
                        s.textContent = old.textContent;
                        old.parentNode.replaceChild(s, old);
                    });
                })
                .catch(function () {
                    container.innerHTML = '<div style="color:#ef4444;padding:20px">⚠️ فشل التحميل</div>';
                });
        } else {
            /* صفحة كاملة */
            window.location.href = url;
        }
    };

    window.finRefresh = function () {
        finChangeYear(currentYear);
    };

    window.finAddPayment = function () {
        var url = 'payment_add.php?student_id=' + studentId;
        if (typeof openModal === 'function') {
            openModal(url);
        } else {
            window.location.href = url;
        }
    };
})();
</script>

<?php if (!$is_ajax): ?>
</div>
<?php require_once('includes/footer.php'); ?>
</html>
<?php endif; ?>