<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>اشتراكات العضو: <?= e($member['full_name_ar']) ?><?php $__template->endSection(); ?>
<?php $__template->section('page_actions'); ?><a href="/members/<?= (int) $member['id'] ?>" class="btn btn-outline">← العودة للعضو</a><?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>

<?php
$totalDebt = '0.00';
foreach ($yearTotals as $yf => $yt) {
    if ($yt['year_status'] !== 'paid') {
        $remaining = bcsub(bcadd($yt['total_amount'], $yt['total_fine'], 2), $yt['total_paid'], 2);
        $remaining = bcadd($remaining, $yt['total_dev'], 2);
        $totalDebt = bcadd($totalDebt, $remaining, 2);
    }
}
$fineDetailsByYear = [];
foreach ($lateFine['details'] ?? [] as $d) {
    $fineDetailsByYear[$d['financial_year']] = $d;
}
?>

<?php if ($lateFine['should_drop']): ?>
<div style="padding:18px;background:#FEF2F2;border:2px solid #DC2626;border-radius:10px;margin-bottom:20px;">
    <div style="display:flex;align-items:center;gap:10px;">
        <span style="font-size:28px;">⛔</span>
        <div>
            <strong style="color:#DC2626;font-size:16px;">تحذير: هذا العضو متأخر <?= (int) $lateFine['years_overdue'] ?> سنوات — يجب إسقاط العضوية</strong>
            <p style="margin:4px 0 0;color:#991B1B;font-size:13px;">تجاوز الحد الأقصى للتأخير (<?= (int) $lateFine['max_years'] ?> سنوات)</p>
        </div>
    </div>
</div>
<?php endif; ?>

<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:15px;margin-bottom:20px;">
    <div class="card" style="padding:18px;text-align:center;background:#FFF7ED;border:1px solid #FED7AA;">
        <div style="font-size:12px;color:#92400E;margin-bottom:4px;">إجمالي المديونية</div>
        <div style="font-size:22px;font-weight:700;color:#D97706;"><?= money($totalDebt) ?></div>
    </div>
    <div class="card" style="padding:18px;text-align:center;background:#FEF2F2;border:1px solid #FECACA;">
        <div style="font-size:12px;color:#991B1B;margin-bottom:4px;">إجمالي الغرامات</div>
        <div style="font-size:22px;font-weight:700;color:#DC2626;"><?= money($lateFine['total_fine']) ?></div>
    </div>
    <div class="card" style="padding:18px;text-align:center;background:#EFF6FF;border:1px solid #BFDBFE;">
        <div style="font-size:12px;color:#1E40AF;margin-bottom:4px;">سنوات متأخرة</div>
        <div style="font-size:22px;font-weight:700;color:#1D4ED8;"><?= (int) $lateFine['years_unpaid'] ?></div>
    </div>
</div>

<?php if (!empty($lateFine['details'])): ?>
<div class="card" style="padding:12px 18px;margin-bottom:20px;background:#FFFBEB;border:1px solid #FDE68A;">
    <div style="font-size:12px;color:#92400E;margin-bottom:6px;font-weight:600;">📐 سلم الغرامات (من محرك القواعد)</div>
    <div style="display:flex;gap:12px;flex-wrap:wrap;font-size:12px;color:#78350F;">
        <span>السنة 1: <strong>10%</strong></span>
        <span>السنة 2: <strong>50%</strong></span>
        <span>السنة 3: <strong>100%</strong></span>
        <span>السنة 4: <strong>200%</strong></span>
        <span>السنة 5: <strong>300%</strong></span>
        <span style="color:#DC2626;">بعد 5 سنوات: إسقاط</span>
    </div>
</div>
<?php endif; ?>

<?php foreach ($grouped as $fy => $rows):
    $yt = $yearTotals[$fy] ?? null;
    if (!$yt) continue;
    $yearId = str_replace('/', '-', $fy);
    $isPayable = ($oldestUnpaidYear === $fy);
    $isPaid = ($yt['year_status'] === 'paid');
    $fineDetail = $fineDetailsByYear[$fy] ?? null;
    $yearRemaining = bcsub(bcadd(bcadd($yt['total_amount'], $yt['total_fine'], 2), $yt['total_dev'], 2), $yt['total_paid'], 2);

    $borderColor = $isPaid ? '#059669' : ($isPayable ? '#D97706' : '#D1D5DB');
    $headerBg = $isPaid ? '#F0FDF4' : ($isPayable ? '#FFF7ED' : '#F9FAFB');
    $statusColor = match($yt['year_status']) { 'paid' => '#059669', 'partial' => '#0284C7', default => '#DC2626' };
    $statusLabel = match($yt['year_status']) { 'paid' => 'مدفوع بالكامل', 'partial' => 'مدفوع جزئياً', default => 'متأخر' };
?>
<div class="card" style="margin-bottom:16px;border:2px solid <?= $borderColor ?>;border-radius:10px;overflow:hidden;">
    <div onclick="toggleYear('<?= $yearId ?>')" style="cursor:pointer;padding:16px 20px;background:<?= $headerBg ?>;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;">
        <div style="display:flex;align-items:center;gap:10px;">
            <span id="year-arrow-<?= $yearId ?>" style="font-size:14px;color:#6B7280;"><?= $isPaid ? '◀' : '▼' ?></span>
            <strong style="font-size:16px;color:#1F2937;"><?= e($fy) ?></strong>
            <span style="font-size:12px;color:<?= $statusColor ?>;font-weight:600;">● <?= $statusLabel ?></span>
            <?php if ($isPayable && !$isPaid): ?>
            <span style="font-size:11px;background:#FEF3C7;color:#92400E;padding:2px 8px;border-radius:4px;">الأولوية</span>
            <?php endif; ?>
        </div>
        <div style="display:flex;gap:16px;font-size:13px;color:#4B5563;">
            <span>المبلغ: <strong><?= money($yt['total_amount']) ?></strong></span>
            <?php if (bccomp($yt['total_fine'], '0', 2) > 0): ?>
            <span style="color:#DC2626;">الغرامة: <strong><?= money($yt['total_fine']) ?></strong></span>
            <?php endif; ?>
            <?php if (bccomp($yt['total_paid'], '0', 2) > 0): ?>
            <span style="color:#059669;">المدفوع: <strong><?= money($yt['total_paid']) ?></strong></span>
            <?php endif; ?>
            <?php if (!$isPaid): ?>
            <span style="color:#D97706;">المتبقي: <strong><?= money($yearRemaining) ?></strong></span>
            <?php endif; ?>
        </div>
    </div>

    <div id="year-body-<?= $yearId ?>" style="<?= $isPaid ? 'display:none;' : '' ?>">
        <?php if ($fineDetail && bccomp($fineDetail['fine_amount'], '0', 2) > 0): ?>
        <div style="padding:12px 20px;background:#FEF2F2;border-top:1px solid <?= $borderColor ?>;">
            <div onclick="toggleFineDetail('<?= $yearId ?>')" style="cursor:pointer;display:flex;align-items:center;gap:8px;">
                <span style="font-size:14px;">📊</span>
                <span style="font-size:13px;font-weight:600;color:#991B1B;">تفاصيل غرامة هذه السنة</span>
                <span style="font-size:11px;color:#6B7280;">(اضغط للتفاصيل)</span>
            </div>
            <div id="fine-detail-<?= $yearId ?>" style="display:none;margin-top:10px;padding:10px;background:#fff;border-radius:6px;border:1px solid #FECACA;">
                <table style="width:100%;font-size:13px;color:#374151;">
                    <tr><td style="padding:4px 8px;color:#6B7280;">سنوات التأخير:</td><td style="padding:4px 8px;font-weight:600;"><?= (int) $fineDetail['years_overdue'] ?> سنة</td></tr>
                    <tr><td style="padding:4px 8px;color:#6B7280;">نسبة الغرامة:</td><td style="padding:4px 8px;font-weight:600;"><?= $fineDetail['fine_percentage'] ?>% <span style="font-size:11px;color:#9CA3AF;">(من قيمة الاشتراك الإجمالي)</span></td></tr>
                    <tr><td style="padding:4px 8px;color:#6B7280;">قيمة الاشتراك:</td><td style="padding:4px 8px;"><?= money($fineDetail['subscription_total'] ?? $fineDetail['unpaid']) ?></td></tr>
                    <tr style="background:#FEF2F2;"><td style="padding:4px 8px;color:#991B1B;font-weight:600;">الحساب:</td><td style="padding:4px 8px;font-weight:700;color:#DC2626;"><?= money($fineDetail['subscription_total'] ?? $fineDetail['unpaid']) ?> × <?= $fineDetail['fine_percentage'] ?>% = <?= money($fineDetail['fine_amount']) ?></td></tr>
                    <tr><td style="padding:4px 8px;color:#6B7280;">المرجع:</td><td style="padding:4px 8px;font-size:11px;font-family:monospace;">LATE_SUB_FINE_YEAR_<?= (int) $fineDetail['years_overdue'] + 1 ?></td></tr>
                </table>
            </div>
        </div>
        <?php elseif ($fineDetail && ($fineDetail['in_grace'] ?? false)): ?>
        <div style="padding:10px 20px;background:#F0FDF4;border-top:1px solid <?= $borderColor ?>;font-size:12px;color:#065F46;">
            ✓ ضمن فترة السماح (<?= (int) $lateFine['grace_months'] ?> أشهر من بداية السنة المالية) — لا توجد غرامة
        </div>
        <?php endif; ?>

        <div style="padding:0 20px 16px;">
            <?php
            $yearDevFee = '0.00';
            foreach ($rows as $r) {
                if (bccomp($r['development_fee'] ?? '0', '0', 2) > 0) {
                    $yearDevFee = $r['development_fee'];
                    break;
                }
            }
            $invoiceTotal = bcadd($yt['total_amount'], $yearDevFee, 2);
            $invoiceGrand = bcadd(bcadd($invoiceTotal, $yt['total_fine'], 2), '0', 2);
            $invoiceRemaining = bcsub($invoiceGrand, $yt['total_paid'], 2);
            ?>
            <table class="data-table" style="margin-top:12px;">
                <thead><tr>
                    <th>النوع</th>
                    <th>الاسم</th>
                    <th>الاشتراك</th>
                    <th>خصم</th>
                    <th>الصافي</th>
                    <th>غرامة</th>
                    <th>الحالة</th>
                    <th>بيانات السداد</th>
                </tr></thead>
                <tbody>
                <?php foreach ($rows as $s):
                    $personLabel = match($s['person_type']) { 'member' => 'عضو', 'spouse' => 'زوجة', 'child' => 'ابن', 'temporary' => 'مؤقت', default => $s['person_type'] };
                    $rowStatusColor = match($s['status']) { 'paid' => '#059669', 'exempt' => '#0284C7', 'overdue' => '#DC2626', default => '#D97706' };
                    $rowStatusLabel = match($s['status']) { 'paid' => 'مدفوع', 'pending' => 'معلق', 'overdue' => 'متأخر', 'exempt' => 'معفى', default => $s['status'] };
                ?>
                <tr>
                    <td><span style="font-weight:600;"><?= $personLabel ?></span></td>
                    <td style="font-size:13px;"><?= e($s['person_name'] ?? '—') ?></td>
                    <td><?= money($s['base_amount']) ?></td>
                    <td style="font-size:12px;color:#7C3AED;"><?= bccomp($s['discount_amount'] ?? '0', '0', 2) > 0 ? '-' . money($s['discount_amount']) : '—' ?></td>
                    <td style="font-weight:600;"><?= money($s['total_amount']) ?></td>
                    <td style="color:#DC2626;"><?= bccomp($s['fine_amount'] ?? '0', '0', 2) > 0 ? money($s['fine_amount']) : '—' ?></td>
                    <td><span style="color:<?= $rowStatusColor ?>;font-weight:600;">● <?= $rowStatusLabel ?></span></td>
                    <td style="font-size:11px;color:#6B7280;line-height:1.6;">
                        <?php if ($s['status'] === 'paid' && !empty($s['paid_at'])): ?>
                            <div><?= arabic_date(substr($s['paid_at'], 0, 10)) ?></div>
                            <?php if (!empty($s['receipt_number'])): ?>
                                <div style="direction:ltr;text-align:right;font-weight:600;color:#1E293B;"><?= e($s['receipt_number']) ?></div>
                            <?php endif; ?>
                            <?php if (!empty($s['paid_by_name'])): ?>
                                <div style="color:#0D9488;"><?= e($s['paid_by_name']) ?></div>
                            <?php endif; ?>
                        <?php else: ?>
                            —
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
                <tfoot>
                <tr style="background:#F9FAFB;font-weight:600;">
                    <td colspan="2" style="text-align:center;">إجمالي الاشتراكات</td>
                    <td><?= money(array_reduce($rows, fn($c, $r) => bcadd($c, $r['base_amount'], 2), '0.00')) ?></td>
                    <td style="font-size:12px;color:#7C3AED;"><?php $totalDisc = array_reduce($rows, fn($c, $r) => bcadd($c, $r['discount_amount'] ?? '0', 2), '0.00'); echo bccomp($totalDisc, '0', 2) > 0 ? '-' . money($totalDisc) : '—'; ?></td>
                    <td><?= money($yt['total_amount']) ?></td>
                    <td style="color:#DC2626;"><?= bccomp($yt['total_fine'], '0', 2) > 0 ? money($yt['total_fine']) : '—' ?></td>
                    <td colspan="2"></td>
                </tr>
                <?php if (bccomp($yearDevFee, '0', 2) > 0): ?>
                <tr style="background:#F0F9FF;font-weight:600;">
                    <td colspan="4" style="text-align:center;color:#0369A1;">مصاريف تنمية (رسم ثابت)</td>
                    <td style="color:#0369A1;"><?= money($yearDevFee) ?></td>
                    <td colspan="3"></td>
                </tr>
                <?php endif; ?>
                <tr style="background:#1E293B;color:#fff;font-weight:700;">
                    <td colspan="4" style="text-align:center;font-size:14px;">إجمالي الفاتورة</td>
                    <td style="font-size:14px;"><?= money($invoiceGrand) ?></td>
                    <td colspan="3" style="font-size:12px;"><?= bccomp($yt['total_paid'], '0', 2) > 0 ? 'المدفوع: ' . money($yt['total_paid']) : '' ?></td>
                </tr>
                </tfoot>
            </table>

            <?php if (!$isPaid): ?>
            <div style="margin-top:16px;padding:16px;background:#F8FAFC;border:1px solid #E2E8F0;border-radius:8px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px;">
                <div>
                    <div style="font-size:13px;color:#64748B;">المطلوب لسداد اشتراك <?= e($fy) ?> بالكامل:</div>
                    <div style="font-size:24px;font-weight:700;color:#1E293B;margin-top:4px;"><?= money($invoiceRemaining) ?></div>
                    <div style="font-size:11px;color:#94A3B8;margin-top:2px;">
                        (اشتراكات: <?= money($yt['total_amount']) ?>
                        <?= bccomp($yearDevFee, '0', 2) > 0 ? ' + تنمية: ' . money($yearDevFee) : '' ?>
                        <?= bccomp($yt['total_fine'], '0', 2) > 0 ? ' + غرامة: ' . money($yt['total_fine']) : '' ?>
                        <?= bccomp($yt['total_paid'], '0', 2) > 0 ? ' − مدفوع: ' . money($yt['total_paid']) : '' ?>)
                    </div>
                </div>
                <div style="display:flex;gap:8px;align-items:center;">
                    <?php if (can('subscription.collect')): ?>
                        <?php if ($isPayable): ?>
                        <form method="POST" action="/members/<?= (int) $member['id'] ?>/subscriptions/<?= str_replace('/', '-', $fy) ?>/pay">
                            <?= csrf_field() ?>
                            <input type="hidden" name="payment_method" value="cash">
                            <button type="submit" class="btn btn-primary" style="font-size:15px;padding:10px 28px;" onclick="return confirm('تسجيل سداد اشتراك <?= e($fy) ?> بالكامل\n\nالمبلغ: <?= money($invoiceRemaining) ?>\nعدد الأفراد: <?= (int) $yt['count'] ?>\n\nمتأكد؟')">
                                💰 سداد اشتراك <?= e($fy) ?> بالكامل
                            </button>
                        </form>
                        <?php else: ?>
                        <button class="btn btn-outline" disabled style="opacity:0.5;cursor:not-allowed;font-size:14px;padding:10px 24px;" title="يجب سداد اشتراكات <?= e($oldestUnpaidYear ?? '') ?> أولاً">
                            🔒 يجب سداد <?= e($oldestUnpaidYear ?? '') ?> أولاً
                        </button>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endforeach; ?>

<?php if (empty($grouped)): ?>
<div class="card" style="padding:40px;text-align:center;color:#6B7280;">لا توجد اشتراكات</div>
<?php endif; ?>

<script>
function toggleYear(id) {
    var el = document.getElementById('year-body-' + id);
    if (!el) return;
    var show = el.style.display === 'none';
    el.style.display = show ? '' : 'none';
    var arrow = document.getElementById('year-arrow-' + id);
    if (arrow) arrow.textContent = show ? '▼' : '◀';
}
function toggleFineDetail(id) {
    var el = document.getElementById('fine-detail-' + id);
    if (!el) return;
    el.style.display = el.style.display === 'none' ? '' : 'none';
}
</script>
<?php $__template->endSection(); ?>
