<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?><?= e($member->full_name_ar) ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<?php if (can('member.edit') && (empty($member->membership_number) || ($isSuperAdmin ?? false))): ?>
<a href="/members/<?= (int) $member->id ?>/edit" class="btn btn-outline">✏️ تعديل</a>
<?php endif; ?>
<a href="/members/<?= (int) $member->id ?>/changelog" class="btn btn-outline">📜 سجل التعديلات</a>
<a href="/members" class="btn btn-outline">← العودة</a>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<?php
$statusLabel = $member->getStatusLabel();
$statusColor = $member->getStatusColor();
$isInitialPhase = in_array($member->status, ['potential', 'under_review', 'interview_scheduled', 'accepted', 'payment_pending']);
$isActive = ($member->status === 'active');
$pendingAdditions ??= [];
$isLocked = !empty($member->membership_number);
$canEdit = can('member.edit') && (!$isLocked || ($isSuperAdmin ?? false));
?>

<!-- ═══════════════════════════════════════ -->
<!-- STEP 1: Form Fee Not Paid -->
<!-- ═══════════════════════════════════════ -->
<?php if (!$bill['form_fee_paid'] && $member->status === 'potential'): ?>
<?php if (!empty($pendingFormFee)): ?>
<div class="card" style="margin-bottom:20px;padding:30px;background:linear-gradient(135deg, #FFF7ED, #FEF3C7);border:2px solid #F59E0B;">
    <div style="text-align:center;">
        <div style="font-size:48px;">&#x23F3;</div>
        <h2 style="color:#D97706;margin:10px 0 5px;">في انتظار الخزينة</h2>
        <p style="color:#6B7280;margin:0 0 15px;">تم إرسال طلب دفع رسوم الاستمارة للخزينة</p>
        <div style="background:#fff;display:inline-block;padding:15px 30px;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,0.08);">
            <div style="font-size:12px;color:#6B7280;">رقم الطلب</div>
            <div style="font-size:20px;font-weight:700;color:#D97706;direction:ltr;"><?= e($pendingFormFee['request_number']) ?></div>
            <div style="font-size:14px;color:#6B7280;margin-top:5px;">المبلغ: <strong style="color:#059669;"><?= money($pendingFormFee['amount']) ?></strong></div>
        </div>
        <?php
        $ffNotes = $pendingFormFee['notes'] ? json_decode($pendingFormFee['notes'], true) : null;
        $ffBreakdown = $ffNotes['fee_breakdown'] ?? null;
        if (is_array($ffBreakdown) && !empty($ffBreakdown)): ?>
        <div style="margin-top:15px;background:#FFFBEB;border:1px solid #FCD34D;border-radius:8px;padding:10px 14px;text-align:right;max-width:350px;display:inline-block;">
            <div style="font-weight:700;color:#92400E;margin-bottom:6px;font-size:12px;">📊 تفصيل:</div>
            <?php foreach ($ffBreakdown as $ffLine): ?>
                <?php if (str_contains($ffLine, '═══')): ?>
                    <hr style="border:0;border-top:1px solid #FCD34D;margin:4px 0;">
                <?php elseif (str_starts_with($ffLine, '💵')): ?>
                    <div style="font-weight:700;color:#059669;font-size:13px;"><?= e($ffLine) ?></div>
                <?php else: ?>
                    <div style="font-size:12px;color:#374151;padding:1px 0;"><?= e($ffLine) ?></div>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php else: ?>
<div class="card" style="margin-bottom:20px;padding:30px;background:linear-gradient(135deg, #FEF2F2, #FEE2E2);border:2px solid #DC2626;">
    <div style="text-align:center;margin-bottom:20px;">
        <div style="font-size:48px;">&#x1f512;</div>
        <h2 style="color:#DC2626;margin:10px 0 5px;">يجب دفع رسوم الاستمارة أولاً</h2>
    </div>
    <div style="max-width:500px;margin:0 auto;background:#fff;border-radius:12px;padding:25px;box-shadow:0 4px 12px rgba(0,0,0,0.1);">
        <table style="width:100%;font-size:15px;margin-bottom:20px;">
            <tr><td style="padding:8px 0;color:#6B7280;">رقم الاستمارة</td><td style="padding:8px 0;text-align:left;font-weight:700;font-size:20px;color:#0D7377;"><?= e($member->form_number ?? '—') ?></td></tr>
            <tr><td style="padding:8px 0;color:#6B7280;">رسوم الاستمارة</td><td style="padding:8px 0;text-align:left;font-weight:700;font-size:24px;color:#DC2626;"><?= money($formFee) ?></td></tr>
        </table>
        <?php if (can('member.pay_form_fee')): ?>
        <form method="POST" action="/members/<?= (int) $member->id ?>/pay-form-fee">
            <?= csrf_field() ?>
            <button type="submit" class="btn btn-primary" style="width:100%;padding:15px;font-size:18px;background:#D97706;border-color:#D97706;" onclick="return confirm('إرسال طلب دفع <?= money($formFee) ?> للخزينة؟')">&#x1f4b0; إرسال للخزينة</button>
        </form>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════ -->
<!-- STEP 2: Fee Paid, Form Not Filled -->
<!-- ═══════════════════════════════════════ -->
<?php elseif ($bill['form_fee_paid'] && !$formFilled && $member->status === 'potential'): ?>
<div class="card" style="margin-bottom:20px;padding:25px;background:#F0FDF4;border:2px solid #059669;">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
        <div>
            <h3 style="color:#059669;margin:0 0 8px;">✅ تم دفع رسوم الاستمارة — الآن قم بملء البيانات وإضافة الأسرة</h3>
            <p style="color:#6B7280;margin:0;font-size:14px;">استمارة رقم <strong><?= e($member->form_number) ?></strong> — يمكنك إضافة أفراد الأسرة الآن بدون رسوم إضافية</p>
        </div>
        <?php if (can('member.fill_form')): ?>
        <a href="/members/<?= (int) $member->id ?>/fill-form" class="btn btn-primary" style="padding:15px 30px;font-size:18px;">📝 ملء الاستمارة</a>
        <?php endif; ?>
    </div>
    <div style="display:flex;gap:8px;flex-wrap:wrap;padding-top:12px;border-top:1px solid #A7F3D0;">
        <a href="/members/<?= (int) $member->id ?>/spouses/create" class="btn btn-sm btn-outline">💍 إضافة زوج/ة</a>
        <a href="/members/<?= (int) $member->id ?>/children/create" class="btn btn-sm btn-outline">👶 إضافة ابن/ة</a>
        <a href="/members/<?= (int) $member->id ?>/temporary/create" class="btn btn-sm btn-outline">👤 إضافة عضو مؤقت</a>
    </div>
</div>
<?php endif; ?>

<!-- Member Header -->
<div class="card" style="margin-bottom:20px;padding:25px;">
    <div style="display:flex;justify-content:space-between;align-items:start;">
        <div>
            <h2 style="margin:0 0 5px;color:#1A1A2E;font-size:22px;"><?= e($member->full_name_ar) ?></h2>
            <?php if ($member->full_name_en): ?><div style="color:#6B7280;font-size:14px;margin-bottom:8px;"><?= e($member->full_name_en) ?></div><?php endif; ?>
            <div style="display:flex;gap:15px;flex-wrap:wrap;font-size:13px;color:#6B7280;margin-top:10px;">
                <?php if ($member->membership_number): ?><span>🪪 عضوية: <strong style="color:#0D7377;font-size:16px;"><?= e($member->membership_number) ?></strong></span><?php endif; ?>
                <?php if (!empty($divorceTransfer)): ?>
                <span style="background:#FEF3C7;padding:2px 8px;border-radius:10px;font-size:11px;">محوّل من عضوية: <a href="/members/<?= (int) $divorceTransfer['original_member_id'] ?>" style="color:#D97706;font-weight:700;"><?= e($divorceTransfer['original_membership_number']) ?></a> (<?= e($divorceTransfer['original_member_name'] ?? '') ?>)</span>
                <?php endif; ?>
                <?php if (!empty($member->transferred_from_death_id)): ?>
                <span style="background:#DBEAFE;padding:2px 8px;border-radius:10px;font-size:11px;">أُنشئت من <a href="/death/<?= (int) $member->transferred_from_death_id ?>" style="color:#2563EB;font-weight:700;">حالة وفاة #<?= (int) $member->transferred_from_death_id ?></a><?php if (!empty($member->deceased_member_name)): ?> (<?= e($member->deceased_member_name) ?>)<?php endif; ?></span>
                <?php if (!empty($deathTransfer['deceased_member_id'])): ?>
                <a href="/members/archive/<?= (int) $deathTransfer['deceased_member_id'] ?>" style="background:#FEF3C7;padding:2px 8px;border-radius:10px;font-size:11px;color:#92400E;font-weight:600;text-decoration:none;">&#x1f4e6; عرض العضوية الأصلية (المؤرشفة)</a>
                <?php endif; ?>
                <?php endif; ?>
                <?php if (!empty($waiverTransfer)): ?>
                <span style="background:#F3E8FF;padding:2px 8px;border-radius:10px;font-size:11px;">تنازل من: <a href="/waivers/<?= (int) $waiverTransfer['id'] ?>" style="color:#7C3AED;font-weight:700;"><?= e($waiverTransfer['source_member_name'] ?? $member->waived_from_member_name ?? '—') ?></a></span>
                <?php if (!empty($waiverTransfer['source_member_id_ref'])): ?>
                <a href="/members/archive/<?= (int) $waiverTransfer['source_member_id_ref'] ?>" style="background:#FEF3C7;padding:2px 8px;border-radius:10px;font-size:11px;color:#92400E;font-weight:600;text-decoration:none;">&#x1f4e6; عرض العضوية المؤرشفة</a>
                <?php endif; ?>
                <?php endif; ?>
                <?php if (!empty($member->ownership_transfer_date)): ?>
                <span style="background:#ECFDF5;padding:2px 8px;border-radius:10px;font-size:11px;">تاريخ انتقال الملكية: <strong style="color:#059669;"><?= arabic_date($member->ownership_transfer_date) ?></strong></span>
                <?php endif; ?>
                <span>📋 استمارة: <strong style="color:#D97706;"><?= e($member->form_number ?? '—') ?></strong></span>
                <span>🏢 <?= e($branchName) ?></span>
                <span><?= $member->gender === 'male' ? '👨' : '👩' ?> <?= $member->getGenderLabel() ?></span>
                <?php if ($member->age_years): ?><span>🎂 <?= (int) $member->age_years ?> سنة</span><?php endif; ?>
            </div>
        </div>
        <div style="text-align:left;">
            <span style="display:inline-block;padding:6px 16px;border-radius:20px;font-weight:700;font-size:14px;color:#fff;background:<?= $statusColor ?>;"><?= e($statusLabel) ?></span>
            <?php if ($member->status === 'active'): ?>
                <?php if (!empty($overdueSubscriptions)): ?>
                <div style="margin-top:8px;"><span style="display:inline-block;padding:4px 12px;border-radius:12px;font-size:12px;font-weight:600;background:#FEF2F2;color:#DC2626;border:1px solid #FECACA;">⚠️ اشتراكات متأخرة</span></div>
                <?php elseif (!empty($subscriptionStatus) && $subscriptionStatus['status'] === 'paid'): ?>
                <div style="margin-top:8px;"><span style="display:inline-block;padding:4px 12px;border-radius:12px;font-size:12px;font-weight:600;background:#ECFDF5;color:#059669;border:1px solid #A7F3D0;">✓ العضوية سارية</span></div>
                <?php else: ?>
                <div style="margin-top:8px;"><span style="display:inline-block;padding:4px 12px;border-radius:12px;font-size:12px;font-weight:600;background:#FEF9C3;color:#92400E;border:1px solid #FDE68A;">⏳ في انتظار التجديد</span></div>
                <?php endif; ?>
            <?php endif; ?>
            <div style="margin-top:10px;font-size:12px;color:#9CA3AF;">تاريخ: <?= e(substr($member->membership_origin_date ?? $member->activated_at ?? $member->created_at, 0, 10)) ?></div>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════ -->
<!-- OVERDUE SUBSCRIPTIONS WARNING -->
<!-- ═══════════════════════════════════════════════ -->
<?php if (!empty($overdueSubscriptions)): ?>
<div class="card" style="margin-bottom:20px;padding:16px 20px;background:#FEF2F2;border:1px solid #FECACA;display:flex;align-items:center;justify-content:space-between;">
    <div style="display:flex;align-items:center;gap:10px;">
        <span style="font-size:18px;">⚠️</span>
        <span style="font-weight:700;color:#DC2626;font-size:14px;">يوجد اشتراكات متأخرة يجب سدادها</span>
    </div>
    <a href="/members/<?= (int) $member->id ?>/subscriptions" class="btn btn-sm" style="background:#DC2626;color:#fff;padding:6px 14px;border-radius:6px;font-size:12px;font-weight:600;text-decoration:none;">عرض الاشتراكات</a>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════ -->
<!-- TRANSFER ORIGIN DETAILS -->
<!-- ═══════════════════════════════════════════════ -->
<?php if (!empty($deathTransfer) || !empty($waiverTransfer) || !empty($divorceTransfer) || !empty($separationTransfer)): ?>
<div class="card" style="margin-bottom:20px;padding:20px;background:#F0F9FF;border:1px solid #BAE6FD;">
    <div style="display:flex;align-items:center;gap:10px;margin-bottom:12px;">
        <span style="font-size:18px;">🔄</span>
        <h3 style="margin:0;color:#0369A1;font-size:15px;">بيانات انتقال العضوية</h3>
    </div>
    <table style="width:100%;font-size:13px;border-collapse:collapse;">
        <?php if (!empty($deathTransfer)): ?>
        <tr><td style="padding:6px 0;color:#6B7280;width:160px;">انتقلت من</td><td style="padding:6px 0;font-weight:600;"><a href="/members/archive/<?= (int) $deathTransfer['deceased_member_id'] ?>" style="color:#2563EB;"><?= e($deathTransfer['deceased_member_name'] ?? '—') ?></a> (وفاة)</td></tr>
        <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الانتقال</td><td style="padding:6px 0;font-weight:600;"><?= e($member->ownership_transfer_date ?? substr($deathTransfer['transfer_date'] ?? '', 0, 10)) ?></td></tr>
        <?php if (!empty($deathTransfer['paid_amount'])): ?>
        <tr><td style="padding:6px 0;color:#6B7280;">المبلغ المدفوع فعلياً</td><td style="padding:6px 0;font-weight:700;color:#059669;font-size:15px;"><?= number_format((float) $deathTransfer['paid_amount'], 2) ?> ج.م</td></tr>
        <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الدفع</td><td style="padding:6px 0;"><?= e($deathTransfer['payment_date'] ?? '—') ?></td></tr>
        <?php endif; ?>
        <?php elseif (!empty($waiverTransfer)): ?>
        <tr><td style="padding:6px 0;color:#6B7280;width:160px;">انتقلت من</td><td style="padding:6px 0;font-weight:600;"><a href="/members/archive/<?= (int) ($waiverTransfer['source_member_id_ref'] ?? 0) ?>" style="color:#7C3AED;"><?= e($waiverTransfer['source_member_name'] ?? $member->waived_from_member_name ?? '—') ?></a> (تنازل)</td></tr>
        <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الانتقال</td><td style="padding:6px 0;font-weight:600;"><?= e($member->ownership_transfer_date ?? substr($waiverTransfer['waiver_date'] ?? '', 0, 10)) ?></td></tr>
        <?php if (!empty($transferFeePayment)): ?>
        <tr><td style="padding:6px 0;color:#6B7280;">المبلغ المدفوع فعلياً</td><td style="padding:6px 0;font-weight:700;color:#059669;font-size:15px;"><?= number_format((float) $transferFeePayment['amount'], 2) ?> ج.م</td></tr>
        <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الدفع</td><td style="padding:6px 0;"><?= e($transferFeePayment['payment_date'] ?? '—') ?></td></tr>
        <?php endif; ?>
        <?php elseif (!empty($divorceTransfer)): ?>
        <tr><td style="padding:6px 0;color:#6B7280;width:160px;">انتقلت من</td><td style="padding:6px 0;font-weight:600;"><a href="/members/<?= (int) $divorceTransfer['original_member_id'] ?>" style="color:#D97706;"><?= e($divorceTransfer['original_member_name'] ?? '—') ?></a> (فصل/طلاق)</td></tr>
        <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الانتقال</td><td style="padding:6px 0;font-weight:600;"><?= e($member->ownership_transfer_date ?? '—') ?></td></tr>
        <?php if (!empty($transferFeePayment)): ?>
        <tr><td style="padding:6px 0;color:#6B7280;">المبلغ المدفوع فعلياً</td><td style="padding:6px 0;font-weight:700;color:#059669;font-size:15px;"><?= number_format((float) $transferFeePayment['amount'], 2) ?> ج.م</td></tr>
        <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الدفع</td><td style="padding:6px 0;"><?= e($transferFeePayment['payment_date'] ?? '—') ?></td></tr>
        <?php endif; ?>
        <?php elseif (!empty($separationTransfer)): ?>
        <tr><td style="padding:6px 0;color:#6B7280;width:160px;">فُصل من عضوية</td><td style="padding:6px 0;font-weight:600;"><a href="/members/<?= (int) $separationTransfer['source_member_id'] ?>" style="color:#14B8A6;"><?= e($separationTransfer['source_member_name'] ?? '—') ?></a> (<?= e($separationTransfer['source_number'] ?? '') ?>)</td></tr>
        <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الفصل</td><td style="padding:6px 0;font-weight:600;"><?= e(substr($separationTransfer['transfer_date'] ?? '', 0, 10)) ?></td></tr>
        <tr><td style="padding:6px 0;color:#6B7280;">رسوم الفصل المدفوعة</td><td style="padding:6px 0;font-weight:700;color:#059669;font-size:15px;"><?= number_format((float) ($transferFeePayment['amount'] ?? $separationTransfer['total_fee'] ?? 0), 2) ?> ج.م</td></tr>
        <?php if (!empty($transferFeePayment['payment_date'])): ?>
        <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الدفع</td><td style="padding:6px 0;"><?= e($transferFeePayment['payment_date']) ?></td></tr>
        <?php endif; ?>
        <tr><td style="padding:6px 0;color:#6B7280;">تفاصيل الطلب</td><td style="padding:6px 0;"><a href="/transfers/<?= (int) $separationTransfer['id'] ?>" style="color:#0D7377;font-weight:600;">عرض طلب الفصل #<?= (int) $separationTransfer['id'] ?></a></td></tr>
        <?php endif; ?>
    </table>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════ -->
<!-- PENDING CHEQUES — member paid down payment but hasn't submitted cheques yet -->
<!-- ═══════════════════════════════════════════════ -->
<?php if ($member->status === 'pending_cheques' && !empty($installmentPlan)): ?>
<div class="card" style="margin-bottom:20px;padding:25px;background:linear-gradient(135deg,#FFF7ED,#FEF3C7);border:2px solid #EA580C;">
    <div style="display:flex;align-items:center;gap:15px;">
        <div style="font-size:40px;">📝</div>
        <div style="flex:1;">
            <h3 style="margin:0 0 5px;color:#9A3412;">في انتظار تسليم شيكات الأقساط</h3>
            <p style="margin:0;color:#78350F;font-size:14px;">لا يمكن تفعيل العضوية أو إصدار رقم عضوية حتى يتم رفع جميع الشيكات المطلوبة (<?= (int) $installmentPlan['number_of_months'] ?> شيك)</p>
        </div>
        <a href="/installments/<?= (int) $installmentPlan['id'] ?>/cheques" class="btn btn-primary" style="white-space:nowrap;">رفع الشيكات</a>
    </div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════ -->
<!-- BILL / INVOICE — visible during initial phase -->
<!-- ═══════════════════════════════════════════════ -->
<?php if ($isInitialPhase && $formFilled): ?>
<div class="card" style="margin-bottom:20px;border:2px solid #0D7377;">
    <div style="padding:15px 20px;background:#0D7377;color:#fff;display:flex;justify-content:space-between;align-items:center;">
        <h3 style="margin:0;">🧾 فاتورة العضوية</h3>
        <div style="text-align:left;">
            <div style="font-size:12px;opacity:0.8;">الإجمالي المطلوب</div>
            <div style="font-size:28px;font-weight:700;"><?= money($bill['total_pending']) ?></div>
        </div>
    </div>

    <div style="padding:20px;">
        <table style="width:100%;font-size:14px;border-collapse:collapse;">
            <thead>
                <tr style="border-bottom:2px solid #E5E7EB;">
                    <th style="padding:10px;text-align:right;color:#6B7280;">البند</th>
                    <th style="padding:10px;text-align:left;color:#6B7280;width:140px;">المبلغ</th>
                    <th style="padding:10px;text-align:center;color:#6B7280;width:100px;">الحالة</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($bill['items'] as $bIdx => $item): ?>
                <tr style="border-bottom:1px solid #F3F4F6;<?= !empty($item['breakdown']) ? 'cursor:pointer;' : '' ?>" <?= !empty($item['breakdown']) ? 'onclick="toggleBillDetail(' . $bIdx . ')"' : '' ?>>
                    <td style="padding:10px;">
                        <?= e($item['label']) ?>
                        <?php if (!empty($item['included_note'])): ?>
                            <small style="display:block;color:#059669;font-size:11px;"><?= e($item['included_note']) ?></small>
                        <?php endif; ?>
                        <?php if (!empty($item['breakdown'])): ?>
                            <small style="display:block;color:#0D7377;font-size:11px;">&#x25BC; اضغط لعرض التفاصيل</small>
                        <?php endif; ?>
                    </td>
                    <td style="padding:10px;text-align:left;font-weight:600;direction:ltr;<?= $item['included'] ? 'color:#9CA3AF;text-decoration:line-through;' : '' ?>">
                        <?= money($item['amount']) ?>
                    </td>
                    <td style="padding:10px;text-align:center;">
                        <?php if ($item['paid']): ?>
                            <span style="color:#059669;font-weight:700;">&#x2705; مدفوع</span>
                        <?php elseif (!empty($item['in_queue'])): ?>
                            <span style="color:#D97706;font-weight:600;">&#x1f4b3; في الخزينة</span>
                        <?php elseif ($item['included']): ?>
                            <span style="color:#0284C7;font-size:12px;">مشمول</span>
                        <?php else: ?>
                            <span style="color:#DC2626;font-weight:600;">&#x23f3; معلق</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php if (!empty($item['breakdown'])): ?>
                <tr id="bill-detail-<?= $bIdx ?>" style="display:none;">
                    <td colspan="3" style="padding:0 10px 10px;">
                        <div style="background:#F9FAFB;border:1px solid #E5E7EB;border-radius:8px;padding:10px 14px;font-size:12px;">
                            <?php foreach ($item['breakdown'] as $line): ?>
                                <?php if (str_contains($line, '═══')): ?>
                                    <hr style="border:0;border-top:1px solid #D1D5DB;margin:4px 0;">
                                <?php elseif (str_starts_with($line, '💵')): ?>
                                    <div style="font-weight:700;color:#059669;font-size:13px;"><?= e($line) ?></div>
                                <?php else: ?>
                                    <div style="color:#374151;padding:1px 0;"><?= e($line) ?></div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                    </td>
                </tr>
                <?php endif; ?>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <?php if (bccomp($bill['total_included'], '0', 2) > 0): ?>
                <tr style="background:#EFF6FF;">
                    <td style="padding:10px;font-weight:600;color:#0284C7;">بنود مشمولة في قيمة العضوية</td>
                    <td style="padding:10px;text-align:left;color:#0284C7;"><?= money($bill['total_included']) ?></td>
                    <td></td>
                </tr>
                <?php endif; ?>
                <tr style="background:#F0FDF4;">
                    <td style="padding:10px;font-weight:600;color:#059669;">إجمالي المدفوع</td>
                    <td style="padding:10px;text-align:left;font-weight:700;color:#059669;"><?= money($bill['total_paid']) ?></td>
                    <td></td>
                </tr>
                <tr style="background:#FEF2F2;">
                    <td style="padding:12px;font-weight:700;font-size:16px;color:#DC2626;">المتبقي للسداد</td>
                    <td style="padding:12px;text-align:left;font-weight:700;font-size:20px;color:#DC2626;"><?= money($bill['total_pending']) ?></td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    </div>

    <!-- Add Family Before Paying -->
    <div style="padding:0 20px 15px;display:flex;gap:10px;flex-wrap:wrap;border-top:1px solid #E5E7EB;padding-top:15px;">
        <span style="color:#6B7280;font-size:13px;padding:8px 0;">أضف أفراد الأسرة (بدون رسوم استمارة إضافية):</span>
        <a href="/members/<?= (int) $member->id ?>/spouses/create" class="btn btn-sm btn-outline">💍 إضافة زوج/ة</a>
        <a href="/members/<?= (int) $member->id ?>/children/create" class="btn btn-sm btn-outline">👶 إضافة ابن/ابنة</a>
        <a href="/members/<?= (int) $member->id ?>/temporary/create" class="btn btn-sm btn-outline">👤 عضو مؤقت</a>
    </div>

    <!-- Special Discount Section -->
    <?php if (!empty($availableDiscounts) && in_array($member->status, ['accepted', 'payment_pending']) && empty($pendingMembership)): ?>
    <div style="padding:15px 20px;border-top:1px solid #E5E7EB;">
        <?php if (!empty($specialDiscount)): ?>
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
            <span style="color:#059669;font-weight:600;font-size:13px;">&#x2705; خصم مُطبق: <?= e($specialDiscount['name_ar']) ?> (<?= e($specialDiscount['discount_percentage']) ?>%) = -<?= money($member->discount_amount ?? '0') ?></span>
            <form method="POST" action="/members/<?= (int) $member->id ?>/apply-discount" style="display:inline;">
                <?= csrf_field() ?>
                <input type="hidden" name="special_discount_id" value="0">
                <button type="submit" class="btn btn-sm btn-outline" style="color:#DC2626;border-color:#DC2626;" onclick="return confirm('إزالة الخصم؟')">&#x274c; إزالة</button>
            </form>
        </div>
        <?php else: ?>
        <form method="POST" action="/members/<?= (int) $member->id ?>/apply-discount" enctype="multipart/form-data" style="display:flex;align-items:end;gap:10px;flex-wrap:wrap;">
            <?= csrf_field() ?>
            <div class="form-group" style="margin:0;">
                <label class="form-label" style="font-size:12px;">&#x1f3f7;&#xfe0f; خصم خاص</label>
                <select name="special_discount_id" class="form-select" style="min-width:200px;" id="discountSelect" onchange="document.getElementById('discountDoc').style.display = this.selectedOptions[0].dataset.doc === '1' ? 'block' : 'none'">
                    <option value="">-- اختر خصم --</option>
                    <?php foreach ($availableDiscounts as $disc): ?>
                    <option value="<?= (int) $disc['id'] ?>" data-doc="<?= $disc['requires_document'] ? '1' : '0' ?>"><?= e($disc['name_ar']) ?> (<?= e($disc['discount_percentage']) ?>%)</option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group" style="margin:0;display:none;" id="discountDoc">
                <label class="form-label" style="font-size:12px;">مستند الإثبات</label>
                <input type="file" name="discount_document" class="form-input" accept="image/*,.pdf">
            </div>
            <button type="submit" class="btn btn-sm btn-primary">تطبيق الخصم</button>
        </form>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- Type-specific registration CTA (seasonal/foreign/sports) -->
    <?php
    $typeDetailExists = match ($member->membership_type ?? 'working') {
        'foreign'  => (bool) \App\Core\App::getInstance()->db()->selectOne("SELECT 1 FROM foreign_member_details WHERE member_id = ? AND is_archived = 0 LIMIT 1", [(int) $member->id]),
        'sports'   => (bool) \App\Core\App::getInstance()->db()->selectOne("SELECT 1 FROM sports_members WHERE member_id = ? AND is_archived = 0 LIMIT 1", [(int) $member->id]),
        'seasonal' => (bool) \App\Core\App::getInstance()->db()->selectOne("SELECT 1 FROM seasonal_memberships WHERE member_id = ? AND person_type = 'member' AND is_archived = 0 LIMIT 1", [(int) $member->id]),
        'honorary' => (bool) \App\Core\App::getInstance()->db()->selectOne("SELECT 1 FROM honorary_members WHERE member_id = ? AND is_archived = 0 LIMIT 1", [(int) $member->id]),
        default    => false,
    };
    ?>
    <?php if ($member->status === 'potential' && ($member->membership_type ?? 'working') !== 'working' && $bill['form_fee_paid'] && !$typeDetailExists && empty($pendingMembership) && !($bill['membership_pending'] ?? false) && !($bill['membership_paid'] ?? false)): ?>
    <?php
    $typeFormRoutes = [
        'seasonal' => ['route' => '/members/' . (int) $member->id . '/seasonal/create', 'label' => 'تسجيل بيانات العضوية الموسمية', 'icon' => '📋', 'desc' => 'سجّل بيانات المدة والأسرة — سيتم حساب الرسوم وإرسالها للخزينة تلقائياً'],
        'foreign'  => ['route' => '/members/' . (int) $member->id . '/foreign/create', 'label' => 'تسجيل بيانات العضوية الأجنبية', 'icon' => '🛂', 'desc' => 'سجّل بيانات جواز السفر وسعر الصرف قبل السداد'],
        'sports'   => ['route' => '/members/' . (int) $member->id . '/sports/create', 'label' => 'تسجيل بيانات العضوية الرياضية', 'icon' => '🏅', 'desc' => 'سجّل بيانات الرياضة والاتحاد قبل السداد'],
        'honorary' => ['route' => '/members/' . (int) $member->id . '/honorary/create', 'label' => 'تسجيل بيانات العضوية الشرفية', 'icon' => '🏆', 'desc' => 'سجّل سبب منح العضوية الشرفية — سيتم التفعيل فوراً بدون رسوم'],
    ];
    $typeForm = $typeFormRoutes[$member->membership_type] ?? null;
    ?>
    <?php if ($typeForm): ?>
    <div style="padding:20px;background:#EFF6FF;border-top:2px solid #3B82F6;text-align:center;">
        <div style="font-size:36px;"><?= $typeForm['icon'] ?></div>
        <h4 style="margin:10px 0 5px;color:#1D4ED8;"><?= e($typeForm['label']) ?></h4>
        <p style="color:#6B7280;margin:0 0 15px;font-size:14px;"><?= e($typeForm['desc']) ?></p>
        <a href="<?= $typeForm['route'] ?>" class="btn btn-primary" style="padding:12px 30px;font-size:16px;"><?= $typeForm['icon'] ?> <?= e($typeForm['label']) ?></a>
    </div>
    <?php endif; ?>
    <?php endif; ?>

    <!-- Payment Section -->
    <?php
    $canShowPayment = in_array($member->status, ['accepted', 'payment_pending']);
    if (!$canShowPayment && $member->status === 'potential' && ($member->membership_type ?? 'working') !== 'working' && $bill['form_fee_paid']) {
        $canShowPayment = true;
    }
    ?>
    <?php if (!empty($pendingMembership)): ?>
    <div style="padding:20px;background:#FFF7ED;border-top:2px solid #F59E0B;text-align:center;">
        <div style="font-size:36px;">&#x23F3;</div>
        <h4 style="margin:10px 0 5px;color:#D97706;">في انتظار الخزينة</h4>
        <p style="color:#6B7280;margin:0 0 15px;">تم إرسال طلب دفع العضوية للخزينة</p>
        <div style="background:#fff;display:inline-block;padding:15px 30px;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,0.08);">
            <div style="font-size:12px;color:#6B7280;">رقم الطلب</div>
            <div style="font-size:20px;font-weight:700;color:#D97706;direction:ltr;"><?= e($pendingMembership['request_number']) ?></div>
            <div style="font-size:14px;color:#6B7280;margin-top:5px;">المبلغ: <strong style="color:#059669;"><?= money($pendingMembership['amount']) ?></strong></div>
            <div style="font-size:12px;color:#6B7280;margin-top:5px;">النوع: <?= \App\Modules\Cashier\Services\PaymentRequestService::getPaymentTypeLabel($pendingMembership['payment_type']) ?></div>
        </div>
        <?php
        $pmNotes = $pendingMembership['notes'] ? json_decode($pendingMembership['notes'], true) : null;
        $pmBreakdown = $pmNotes['fee_breakdown'] ?? null;
        if (is_array($pmBreakdown) && !empty($pmBreakdown)): ?>
        <div style="margin-top:15px;background:#FFFBEB;border:1px solid #FCD34D;border-radius:8px;padding:12px 16px;text-align:right;max-width:400px;display:inline-block;">
            <div style="font-weight:700;color:#92400E;margin-bottom:6px;font-size:12px;">📊 تفصيل المبلغ:</div>
            <?php foreach ($pmBreakdown as $pmLine): ?>
                <?php if (str_contains($pmLine, '═══')): ?>
                    <hr style="border:0;border-top:1px solid #FCD34D;margin:4px 0;">
                <?php elseif (str_starts_with($pmLine, '💵')): ?>
                    <div style="font-weight:700;color:#059669;font-size:13px;"><?= e($pmLine) ?></div>
                <?php else: ?>
                    <div style="font-size:12px;color:#374151;padding:1px 0;"><?= e($pmLine) ?></div>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
    <?php elseif (bccomp($bill['total_pending'], '0', 2) > 0 && $canShowPayment): ?>
    <?php
    $paymentTypeForType = match ($member->membership_type ?? 'working') {
        'foreign'  => 'foreign_membership_fee',
        'sports'   => 'sports_membership_fee',
        'seasonal' => 'seasonal_fee',
        default    => 'membership_fee',
    };
    $allowInstallment = in_array($member->membership_type ?? 'working', ['working', 'sports'], true);
    ?>
    <div style="padding:20px;background:#FFF7ED;border-top:2px solid #F59E0B;">
        <h4 style="margin:0 0 15px;color:#D97706;">&#x1f4b0; اختر طريقة السداد وأرسل للخزينة</h4>
        <div style="display:grid;grid-template-columns:<?= $allowInstallment ? '1fr 1fr' : '1fr' ?>;gap:20px;">
            <!-- Cash Full -->
            <div style="background:#fff;border:2px solid #059669;border-radius:12px;padding:20px;">
                <h5 style="margin:0 0 10px;color:#059669;">&#x1f4b5; كاش كامل</h5>
                <p style="font-size:13px;color:#6B7280;margin:0 0 10px;">ادفع المبلغ كاملاً — بدون فوائد</p>
                <div style="font-size:24px;font-weight:700;color:#059669;margin-bottom:15px;"><?= money($bill['total_pending']) ?></div>
                <form method="POST" action="/members/<?= (int) $member->id ?>/pay-membership">
                    <?= csrf_field() ?>
                    <input type="hidden" name="payment_type" value="<?= e($paymentTypeForType) ?>">
                    <input type="hidden" name="amount" value="<?= e($bill['total_pending']) ?>">
                    <button type="submit" class="btn btn-primary" style="width:100%;background:#D97706;border-color:#D97706;" onclick="return confirm('إرسال طلب دفع <?= money($bill['total_pending']) ?> للخزينة؟')">&#x1f4e4; إرسال للخزينة</button>
                </form>
            </div>
            <?php if ($allowInstallment): ?>
            <?php
            $instRate     = $installInterestRate ?? 22;
            $instMaxMos   = $installMaxMonths    ?? 30;
            $minDown      = bcdiv(bcmul($bill['total_pending'], '25', 2), '100', 2);
            // Default preview: min down, max months
            $instRem      = bcsub($bill['total_pending'], $minDown, 2);
            $instInterest = bcmul(bcmul($instRem, bcdiv((string) $instRate, '100', 8), 8), bcdiv((string) $instMaxMos, '12', 8), 2);
            $instTotalWI  = bcadd($instRem, $instInterest, 2);
            $instMonthly  = bcdiv($instTotalWI, (string) $instMaxMos, 2);
            ?>
            <!-- Installment -->
            <div style="background:#fff;border:2px solid #0284C7;border-radius:12px;padding:20px;">
                <h5 style="margin:0 0 4px;color:#0284C7;">&#x1f4c5; تقسيط</h5>
                <p style="font-size:12px;color:#6B7280;margin:0 0 2px;">مقدم 25% على الأقل + باقي على أقساط</p>
                <p style="font-size:11px;color:#D97706;margin:0 0 12px;">فائدة <?= (float) $instRate ?>% سنوياً — حتى <?= $instMaxMos ?> شهر</p>

                <!-- Live breakdown (updates with JS) -->
                <div style="background:#EFF6FF;border:1px solid #BFDBFE;border-radius:8px;padding:10px 12px;margin-bottom:12px;font-size:12px;">
                    <table style="width:100%;border-collapse:collapse;">
                        <tr>
                            <td style="color:#6B7280;padding:3px 0;">سعر العضوية</td>
                            <td style="text-align:left;font-weight:600;" id="inst_price_disp"><?= money($bill['total_pending']) ?></td>
                        </tr>
                        <tr>
                            <td style="color:#6B7280;padding:3px 0;">المقدم</td>
                            <td style="text-align:left;font-weight:600;color:#059669;" id="inst_down_disp"><?= money($minDown) ?></td>
                        </tr>
                        <tr style="border-top:1px solid #BFDBFE;">
                            <td style="color:#374151;font-weight:700;padding:4px 0;">المبلغ المتبقي</td>
                            <td style="text-align:left;font-weight:800;color:#0284C7;" id="inst_remaining_disp"><?= money($instRem) ?></td>
                        </tr>
                        <tr>
                            <td style="color:#6B7280;padding:3px 0;" id="inst_interest_label">الفائدة (<?= (float) $instRate ?>% × <?= $instMaxMos ?> شهر)</td>
                            <td style="text-align:left;color:#D97706;font-weight:600;" id="inst_interest_disp"><?= money($instInterest) ?></td>
                        </tr>
                        <tr>
                            <td style="color:#6B7280;padding:3px 0;">الإجمالي مع الفائدة</td>
                            <td style="text-align:left;font-weight:600;" id="inst_totalwi_disp"><?= money($instTotalWI) ?></td>
                        </tr>
                        <tr style="border-top:2px solid #93C5FD;">
                            <td style="font-weight:700;color:#0D7377;padding:5px 0;" id="inst_monthly_label">القسط الشهري (÷ <?= $instMaxMos ?>)</td>
                            <td style="text-align:left;font-weight:900;color:#0D7377;font-size:16px;" id="inst_monthly_disp"><?= money($instMonthly) ?></td>
                        </tr>
                    </table>
                </div>

                <form method="POST" action="/members/<?= (int) $member->id ?>/pay-membership" novalidate>
                    <?= csrf_field() ?>
                    <input type="hidden" name="payment_type" value="down_payment">
                    <div class="form-group" style="margin-bottom:8px;">
                        <label class="form-label" style="font-size:12px;">المقدم (&#x2265; <?= money($minDown) ?>)</label>
                        <input type="number" id="inst_down_input" name="amount"
                               value="<?= e($minDown) ?>" min="<?= e($minDown) ?>" step="0.01"
                               class="form-input" style="direction:ltr;text-align:left;"
                               oninput="instRecalc()" required>
                    </div>
                    <div class="form-group" style="margin-bottom:12px;">
                        <label class="form-label" style="font-size:12px;">عدد الأشهر (1 – <?= $instMaxMos ?>)</label>
                        <input type="number" id="inst_months_input" name="installment_months"
                               value="<?= $instMaxMos ?>" min="1" max="<?= $instMaxMos ?>"
                               class="form-input" style="direction:ltr;text-align:left;"
                               oninput="instRecalc()">
                    </div>
                    <button type="submit" class="btn btn-primary"
                            style="width:100%;background:#D97706;border-color:#D97706;"
                            onclick="return confirm('إرسال طلب تقسيط للخزينة؟')">
                        &#x1f4e4; إرسال للخزينة
                    </button>
                </form>
            </div>
            <script>
            (function () {
                var TOTAL     = <?= json_encode((float) $bill['total_pending']) ?>;
                var RATE      = <?= json_encode((float) $instRate) ?>;
                var MIN_DOWN  = <?= json_encode((float) $minDown) ?>;
                var fmt = function(v) { return v.toLocaleString('ar-EG', {minimumFractionDigits:2, maximumFractionDigits:2}) + ' ج.م'; };

                window.instRecalc = function () {
                    var down   = parseFloat(document.getElementById('inst_down_input').value)   || MIN_DOWN;
                    var months = parseInt(document.getElementById('inst_months_input').value,10) || <?= $instMaxMos ?>;
                    if (down < MIN_DOWN) down = MIN_DOWN;
                    if (months < 1) months = 1;

                    var remaining     = Math.round((TOTAL - down) * 100) / 100;
                    var totalInterest = Math.round(remaining * (RATE / 100) * (months / 12) * 100) / 100;
                    var totalWI       = Math.round((remaining + totalInterest) * 100) / 100;
                    var monthly       = Math.round((totalWI / months) * 100) / 100;

                    document.getElementById('inst_down_disp').textContent      = fmt(down);
                    document.getElementById('inst_remaining_disp').textContent  = fmt(remaining);
                    document.getElementById('inst_interest_disp').textContent   = fmt(totalInterest);
                    document.getElementById('inst_totalwi_disp').textContent    = fmt(totalWI);
                    document.getElementById('inst_monthly_disp').textContent    = fmt(monthly);
                    document.getElementById('inst_interest_label').textContent  = 'الفائدة (' + RATE + '% × ' + months + ' شهر)';
                    document.getElementById('inst_monthly_label').textContent   = 'القسط الشهري (÷ ' + months + ')';
                };
            })();
            </script>
            <?php endif; ?>
        </div>
        <div style="margin-top:15px;padding:10px;background:#FEF2F2;border-radius:8px;font-size:12px;color:#DC2626;">
            &#x26a0;&#xfe0f; مهلة السداد: 15 يوم من تاريخ القبول — بعدها تنتهي الاستمارة
        </div>
    </div>
    <?php elseif ($formFilled && in_array($member->status, ['under_review', 'interview_scheduled'])): ?>
    <div style="padding:20px;background:#EFF6FF;border-top:2px solid #0284C7;">
        <p style="margin:0;color:#0284C7;font-size:14px;">📋 الفاتورة جاهزة — في انتظار قرار مجلس الأمناء قبل السداد</p>
        <p style="margin:5px 0 0;color:#6B7280;font-size:13px;">يمكنك إضافة أفراد الأسرة الآن وستُضاف رسومهم تلقائياً</p>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════ -->
<!-- POST-ACTIVATION PENDING ADDITIONS (for active members) -->
<!-- ═══════════════════════════════════════════════ -->
<?php if ($isActive && !empty($pendingAdditions)): ?>
<div class="card" style="margin-bottom:20px;border:2px solid #F59E0B;">
    <div style="padding:15px 20px;background:#FFFBEB;border-bottom:1px solid #FDE68A;">
        <h3 style="margin:0;color:#D97706;font-size:16px;">&#x23f3; إضافات في انتظار السداد</h3>
    </div>
    <div style="padding:20px;">
        <table style="width:100%;font-size:14px;border-collapse:collapse;">
            <thead>
                <tr style="border-bottom:2px solid #E5E7EB;">
                    <th style="padding:10px;text-align:right;color:#6B7280;">البند</th>
                    <th style="padding:10px;text-align:left;color:#6B7280;width:120px;">المبلغ</th>
                    <th style="padding:10px;text-align:center;color:#6B7280;width:150px;">رقم الطلب</th>
                    <th style="padding:10px;text-align:center;color:#6B7280;width:100px;">الحالة</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($pendingAdditions as $paKey => $pa): ?>
                <?php
                    $paNotes = $pa['notes'] ? json_decode($pa['notes'], true) : null;
                    $paBreakdown = $paNotes['fee_breakdown'] ?? null;
                    $paIdx = 'pa-' . (int) $pa['id'];
                ?>
                <tr style="border-bottom:1px solid #F3F4F6;<?= !empty($paBreakdown) ? 'cursor:pointer;' : '' ?>" <?= !empty($paBreakdown) ? 'onclick="toggleBillDetail(\'' . $paIdx . '\')"' : '' ?>>
                    <td style="padding:10px;">
                        <?= e($pa['description_ar'] ?? 'رسوم إضافة') ?>
                        <?php if (!empty($paBreakdown)): ?>
                            <small style="display:block;color:#0D7377;font-size:11px;">&#x25BC; اضغط لعرض التفاصيل</small>
                        <?php endif; ?>
                    </td>
                    <td style="padding:10px;text-align:left;font-weight:700;direction:ltr;color:#DC2626;"><?= money($pa['amount']) ?></td>
                    <td style="padding:10px;text-align:center;direction:ltr;font-size:12px;color:#6B7280;"><?= e($pa['request_number']) ?></td>
                    <td style="padding:10px;text-align:center;">
                        <span style="color:#D97706;font-weight:600;font-size:12px;">&#x1f4b3; في الخزينة</span>
                    </td>
                </tr>
                <?php if (!empty($paBreakdown)): ?>
                <tr id="bill-detail-<?= $paIdx ?>" style="display:none;">
                    <td colspan="4" style="padding:0 10px 10px;">
                        <div style="background:#F9FAFB;border:1px solid #E5E7EB;border-radius:8px;padding:10px 14px;font-size:12px;">
                            <?php foreach ($paBreakdown as $line): ?>
                                <?php if (str_contains($line, '═══')): ?>
                                    <hr style="border:0;border-top:1px solid #D1D5DB;margin:4px 0;">
                                <?php elseif (str_starts_with($line, '💵')): ?>
                                    <div style="font-weight:700;color:#059669;font-size:13px;"><?= e($line) ?></div>
                                <?php else: ?>
                                    <div style="color:#374151;padding:1px 0;"><?= e($line) ?></div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                    </td>
                </tr>
                <?php endif; ?>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════ -->
<!-- CANCELLED REQUESTS — can be re-queued -->
<!-- ═══════════════════════════════════════════════ -->
<?php $cancelledRequests ??= []; ?>
<?php if (!empty($cancelledRequests)): ?>
<div class="card" style="margin-bottom:20px;border:2px solid #DC2626;">
    <div style="padding:15px 20px;background:#FEF2F2;border-bottom:1px solid #FECACA;">
        <h3 style="margin:0;color:#DC2626;font-size:16px;">&#x274c; طلبات ملغاة (يمكن إعادتها لطابور الدفع)</h3>
    </div>
    <div style="padding:20px;">
        <table style="width:100%;font-size:14px;border-collapse:collapse;">
            <thead>
                <tr style="border-bottom:2px solid #E5E7EB;">
                    <th style="padding:10px;text-align:right;color:#6B7280;">البند</th>
                    <th style="padding:10px;text-align:left;color:#6B7280;width:120px;">المبلغ</th>
                    <th style="padding:10px;text-align:center;color:#6B7280;width:150px;">رقم الطلب</th>
                    <th style="padding:10px;text-align:right;color:#6B7280;width:180px;">سبب الإلغاء</th>
                    <th style="padding:10px;text-align:center;color:#6B7280;width:130px;">إجراء</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($cancelledRequests as $cr): ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:10px;">
                        <?= e($cr['description_ar'] ?? \App\Modules\Cashier\Services\PaymentRequestService::getPaymentTypeLabel($cr['payment_type'])) ?>
                        <small style="display:block;color:#DC2626;font-size:11px;">ملغى <?= e(substr($cr['voided_at'] ?? $cr['updated_at'], 0, 16)) ?></small>
                    </td>
                    <td style="padding:10px;text-align:left;font-weight:700;direction:ltr;color:#6B7280;text-decoration:line-through;"><?= money($cr['amount']) ?></td>
                    <td style="padding:10px;text-align:center;direction:ltr;font-size:12px;color:#9CA3AF;"><?= e($cr['request_number']) ?></td>
                    <td style="padding:10px;font-size:12px;color:#6B7280;"><?= e($cr['void_reason'] ?? '—') ?></td>
                    <td style="padding:10px;text-align:center;">
                        <form method="POST" action="/cashier/<?= (int) $cr['id'] ?>/requeue" style="display:inline;">
                            <?= csrf_field() ?>
                            <input type="hidden" name="return_to" value="/members/<?= (int) $member->id ?>">
                            <button type="submit" class="btn btn-sm btn-primary" style="background:#D97706;border-color:#D97706;font-size:12px;" onclick="return confirm('إعادة هذا الطلب لطابور الدفع؟')">&#x1f504; إعادة للطابور</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════ -->
<!-- MISSING STEPS — shows what still needs to happen -->
<!-- ═══════════════════════════════════════════════ -->
<?php
$missingSteps = [];

if (!$bill['form_fee_paid'] && $member->status === 'potential') {
    if (!empty($bill['form_fee_pending']) || !empty($pendingFormFee)) {
        $missingSteps[] = ['icon' => '&#x1f4b3;', 'text' => 'رسوم الاستمارة في انتظار الخزينة', 'color' => '#D97706', 'done' => false];
    } else {
        $missingSteps[] = ['icon' => '&#x1f512;', 'text' => 'لم يتم دفع رسوم الاستمارة', 'color' => '#DC2626', 'done' => false];
    }
} else {
    $missingSteps[] = ['icon' => '&#x2705;', 'text' => 'رسوم الاستمارة', 'color' => '#059669', 'done' => true];
}

if ($bill['form_fee_paid'] && !$formFilled) {
    $missingSteps[] = ['icon' => '&#x1f4dd;', 'text' => 'لم يتم ملء الاستمارة بعد', 'color' => '#DC2626', 'done' => false];
} elseif ($formFilled) {
    $missingSteps[] = ['icon' => '&#x2705;', 'text' => 'الاستمارة مكتملة', 'color' => '#059669', 'done' => true];
}

$membershipFeeLabel = match ($member->membership_type ?? 'working') {
    'foreign'  => 'رسوم العضوية الأجنبية',
    'sports'   => 'رسوم العضوية الرياضية',
    'seasonal' => 'رسوم العضوية الموسمية',
    'honorary' => 'تفعيل العضوية الشرفية',
    default    => 'رسوم العضوية',
};

if (($member->membership_type ?? 'working') === 'honorary') {
    if ($member->status !== 'active') {
        $missingSteps[] = ['icon' => '&#x1f4cb;', 'text' => 'في انتظار تسجيل بيانات العضوية الشرفية والتفعيل', 'color' => '#3B82F6', 'done' => false];
    } else {
        $missingSteps[] = ['icon' => '&#x2705;', 'text' => $membershipFeeLabel, 'color' => '#059669', 'done' => true];
    }
} elseif ($formFilled && !$bill['membership_paid'] && !in_array($member->status, ['active'], true)) {
    if (!empty($bill['membership_pending']) || !empty($pendingMembership)) {
        $missingSteps[] = ['icon' => '&#x1f4b3;', 'text' => $membershipFeeLabel . ' في انتظار الخزينة', 'color' => '#D97706', 'done' => false];
    } elseif (in_array($member->status, ['accepted', 'payment_pending'], true) || ($member->status === 'potential' && ($member->membership_type ?? 'working') !== 'working' && $bill['form_fee_paid'])) {
        $missingSteps[] = ['icon' => '&#x23f3;', 'text' => 'لم يتم سداد ' . $membershipFeeLabel, 'color' => '#DC2626', 'done' => false];
    } elseif (in_array($member->status, ['under_review', 'interview_scheduled'], true)) {
        $missingSteps[] = ['icon' => '&#x1f4cb;', 'text' => 'في انتظار قرار مجلس الأمناء', 'color' => '#3B82F6', 'done' => false];
    }
} elseif ($bill['membership_paid'] || $member->status === 'active') {
    $missingSteps[] = ['icon' => '&#x2705;', 'text' => $membershipFeeLabel, 'color' => '#059669', 'done' => true];
}

foreach ($bill['items'] as $item) {
    if (in_array($item['type'] ?? '', ['spouse_fee', 'child_fee', 'temp_fee'], true) && !$item['included'] && !$item['paid']) {
        $inQueue = !empty($item['in_queue']) || !empty($pendingMembership);
        $statusText = $inQueue ? ' — في انتظار الخزينة' : ' — سيتم تحصيلها ضمن الفاتورة المجمعة';
        $statusColor = $inQueue ? '#D97706' : '#DC2626';
        $missingSteps[] = ['icon' => $inQueue ? '&#x1f4b3;' : '&#x26a0;', 'text' => $item['label'] . $statusText, 'color' => $statusColor, 'done' => false];
    }
}

$hasIncomplete = !empty(array_filter($missingSteps, fn($s) => !$s['done']));
?>
<?php if ($hasIncomplete): ?>
<div class="card" style="margin-bottom:20px;border:2px solid #F59E0B;">
    <div style="padding:15px 20px;background:#FFFBEB;border-bottom:1px solid #FDE68A;">
        <h3 style="margin:0;color:#D97706;font-size:15px;">&#x1f4cb; الخطوات الناقصة</h3>
    </div>
    <div style="padding:15px 20px;">
        <?php foreach ($missingSteps as $step): ?>
        <div style="display:flex;align-items:center;gap:10px;padding:8px 0;<?= $step['done'] ? 'opacity:0.5;' : '' ?>border-bottom:1px solid #F9FAFB;">
            <span style="font-size:18px;"><?= $step['icon'] ?></span>
            <span style="flex:1;color:<?= $step['color'] ?>;font-weight:<?= $step['done'] ? '400' : '600' ?>;font-size:14px;<?= $step['done'] ? 'text-decoration:line-through;' : '' ?>"><?= e($step['text']) ?></span>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- Info Grid -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px;">
    <div class="card">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;"><h3 style="margin:0;color:#0D7377;font-size:15px;">👤 البيانات الشخصية</h3></div>
        <div style="padding:15px 20px;">
            <table style="width:100%;font-size:13px;">
                <tr><td style="padding:5px 0;color:#6B7280;width:40%;">الرقم القومي</td><td style="padding:5px 0;direction:ltr;text-align:right;font-weight:600;"><?= e($member->national_id ?? '—') ?></td></tr>
                <tr><td style="padding:5px 0;color:#6B7280;">تاريخ الميلاد</td><td style="padding:5px 0;"><?= e($member->date_of_birth ?? '—') ?></td></tr>
                <tr><td style="padding:5px 0;color:#6B7280;">المحمول</td><td style="padding:5px 0;direction:ltr;text-align:right;"><?= e($member->phone_mobile ?? '—') ?></td></tr>
                <tr><td style="padding:5px 0;color:#6B7280;">الجنسية</td><td style="padding:5px 0;"><?= e($member->nationality ?? '—') ?></td></tr>
                <tr><td style="padding:5px 0;color:#6B7280;">المؤهل</td><td style="padding:5px 0;"><?= e($qualificationName) ?></td></tr>
                <tr><td style="padding:5px 0;color:#6B7280;">الحالة الاجتماعية</td><td style="padding:5px 0;"><?= e($member->marital_status ?? '—') ?></td></tr>
                <?php if ($member->email): ?><tr><td style="padding:5px 0;color:#6B7280;">البريد</td><td style="padding:5px 0;direction:ltr;text-align:right;"><?= e($member->email) ?></td></tr><?php endif; ?>
                <?php if ($member->residence_address): ?><tr><td style="padding:5px 0;color:#6B7280;">العنوان</td><td style="padding:5px 0;"><?= e($member->residence_address) ?></td></tr><?php endif; ?>
                <?php if ($member->occupation): ?><tr><td style="padding:5px 0;color:#6B7280;">المهنة</td><td style="padding:5px 0;"><?= e($member->occupation) ?></td></tr><?php endif; ?>
            </table>
        </div>
    </div>
    <div class="card">
        <?php if (can('member.view_financial')): ?>
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;"><h3 style="margin:0;color:#0D7377;font-size:15px;">💰 الملخص المالي</h3></div>
        <div style="padding:15px 20px;">
            <div style="display:grid;grid-template-columns:<?= !empty($specialDiscount) ? '1fr 1fr 1fr' : '1fr 1fr' ?>;gap:15px;">
                <?php
                    $isTransferred = !empty($member->transferred_from_death_id) || !empty($member->transferred_from_waiver_id) || !empty($member->transferred_from_divorce_id) || !empty($member->transferred_from_transfer_id);
                    $displayValue = $member->membership_value ?? '0';
                    $valueLabel = 'قيمة العضوية';
                    if (!empty($member->transferred_from_transfer_id) && !empty($separationTransfer)) {
                        $displayValue = $transferFeePayment['amount'] ?? $separationTransfer['total_fee'] ?? $displayValue;
                        $valueLabel = 'رسوم الفصل المدفوعة';
                    } elseif ($isTransferred && !empty($transferFeePayment)) {
                        $displayValue = $transferFeePayment['amount'];
                        $valueLabel = 'المبلغ المدفوع عند الانتقال';
                    } elseif ($isTransferred && !empty($deathTransfer['paid_amount'])) {
                        $displayValue = $deathTransfer['paid_amount'];
                        $valueLabel = 'المبلغ المدفوع عند الانتقال';
                    }
                ?>
                <div style="background:#F0FDF4;padding:15px;border-radius:8px;text-align:center;"><div style="font-size:20px;font-weight:700;color:#059669;"><?= money($displayValue) ?></div><div style="color:#6B7280;font-size:11px;"><?= $valueLabel ?></div></div>
                <?php if (!empty($specialDiscount)): ?>
                <div style="background:#FFF7ED;padding:15px;border-radius:8px;text-align:center;">
                    <div style="font-size:20px;font-weight:700;color:#D97706;">-<?= money($member->discount_amount ?? '0') ?></div>
                    <div style="color:#6B7280;font-size:11px;">خصم: <?= e($specialDiscount['name_ar']) ?> (<?= e($specialDiscount['discount_percentage']) ?>%)</div>
                    <?php if ($specialDiscount['requires_document'] && !empty($member->special_discount_document)): ?>
                    <a href="/<?= e($member->special_discount_document) ?>" target="_blank" style="font-size:11px;color:#0D7377;">📄 عرض الإثبات</a>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <div style="background:#EFF6FF;padding:15px;border-radius:8px;text-align:center;"><div style="font-size:20px;font-weight:700;color:#0284C7;"><?= money($bill['total_paid']) ?></div><div style="color:#6B7280;font-size:11px;">إجمالي المدفوع</div></div>
            </div>
            <a href="/payments/member/<?= (int) $member->id ?>" class="btn btn-outline" style="width:100%;text-align:center;margin-top:10px;">📜 سجل المدفوعات</a>
            <?php if (!empty($deathTransfer['deceased_member_id'])): ?>
            <a href="/payments/member/<?= (int) $deathTransfer['deceased_member_id'] ?>" class="btn btn-outline" style="width:100%;text-align:center;margin-top:6px;color:#6B7280;border-color:#D1D5DB;">📋 سجل مدفوعات العضو المتوفي (<?= e($deathTransfer['deceased_member_name'] ?? '') ?>)</a>
            <?php endif; ?>
        </div>
        <?php else: ?>
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;"><h3 style="margin:0;color:#0D7377;font-size:15px;">💰 الملخص المالي</h3></div>
        <div style="padding:30px;text-align:center;color:#9CA3AF;">🔒 لا تملك صلاحية عرض البيانات المالية</div>
        <?php endif; ?>
    </div>
</div>

<!-- ═══════════════════════════════════════════════ -->
<!-- ALL ACTIONS — organized by category -->
<!-- ═══════════════════════════════════════════════ -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#0D7377;font-size:15px;">⚡ الإجراءات</h3>
    </div>
    <div style="padding:15px 20px;">

        <!-- Registration & Form -->
        <?php if ($bill['form_fee_paid'] && !$formFilled && can('member.fill_form')): ?>
        <div style="margin-bottom:15px;">
            <div style="font-size:12px;color:#6B7280;font-weight:600;margin-bottom:8px;text-transform:uppercase;">📋 الاستمارة</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <a href="/members/<?= (int) $member->id ?>/fill-form" class="btn btn-primary">📝 ملء الاستمارة</a>
            </div>
        </div>
        <?php endif; ?>

        <!-- Family Management — available once form fee is paid (during filling) or after -->
        <?php if (($bill['form_fee_paid'] || $formFilled || $isActive) && $canEdit): ?>
        <div style="margin-bottom:15px;">
            <div style="font-size:12px;color:#6B7280;font-weight:600;margin-bottom:8px;text-transform:uppercase;">👨‍👩‍👧‍👦 الأسرة</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <?php if (can('spouse.add')): ?>
                <a href="/members/<?= (int) $member->id ?>/spouses/create" class="btn btn-sm btn-outline">💍 إضافة زوج/ة</a>
                <?php endif; ?>
                <?php if (can('child.add')): ?>
                <a href="/members/<?= (int) $member->id ?>/children/create" class="btn btn-sm btn-outline">👶 إضافة ابن/ة</a>
                <?php endif; ?>
                <?php if (can('temp.add')): ?>
                <a href="/members/<?= (int) $member->id ?>/temporary/create" class="btn btn-sm btn-outline">👤 إضافة عضو مؤقت</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Interview & Review -->
        <?php if (in_array($member->status, ['under_review', 'interview_scheduled', 'potential']) && can('interview.schedule')): ?>
        <div style="margin-bottom:15px;">
            <div style="font-size:12px;color:#6B7280;font-weight:600;margin-bottom:8px;text-transform:uppercase;">🗓️ المقابلة والمراجعة</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <a href="/interviews/schedule/<?= (int) $member->id ?>" class="btn btn-sm btn-outline">🗓️ تحديد مقابلة</a>
            </div>
        </div>
        <?php endif; ?>

        <!-- Financial -->
        <?php if (canAny(['payment.view', 'member.view_financial'])): ?>
        <div style="margin-bottom:15px;">
            <div style="font-size:12px;color:#6B7280;font-weight:600;margin-bottom:8px;text-transform:uppercase;">💰 المالية</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <?php if (can('payment.process_cash')): ?>
                <a href="/payments/process/<?= (int) $member->id ?>" class="btn btn-sm btn-outline">💰 تسجيل دفعة</a>
                <?php endif; ?>
                <?php if (can('payment.view')): ?>
                <a href="/payments/member/<?= (int) $member->id ?>" class="btn btn-sm btn-outline">📜 سجل المدفوعات</a>
                <?php endif; ?>
                <?php if ($isActive): ?>
                    <?php if (can('installment.create_plan')): ?>
                    <a href="/installments/create/<?= (int) $member->id ?>" class="btn btn-sm btn-outline">📅 خطة تقسيط</a>
                    <?php endif; ?>
                    <?php if (can('subscription.view')): ?>
                    <a href="/members/<?= (int) $member->id ?>/subscriptions" class="btn btn-sm btn-outline">🔄 الاشتراكات</a>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Documents & Carnet -->
        <?php if (($bill['form_fee_paid'] || $formFilled || $isActive) && canAny(['document.view', 'document.upload', 'carnet.issue'])): ?>
        <div style="margin-bottom:15px;">
            <div style="font-size:12px;color:#6B7280;font-weight:600;margin-bottom:8px;text-transform:uppercase;">📁 المستندات والكارنيه</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <?php if (can('document.upload')): ?>
                <a href="/documents/upload/<?= (int) $member->id ?>" class="btn btn-sm btn-outline">📁 رفع مستندات</a>
                <?php endif; ?>
                <?php if (can('document.view')): ?>
                <a href="/documents/member/<?= (int) $member->id ?>" class="btn btn-sm btn-outline">📂 عرض المستندات</a>
                <?php endif; ?>
                <?php if ($isActive && can('carnet.issue')): ?>
                    <a href="/carnets/issue/<?= (int) $member->id ?>" class="btn btn-sm btn-outline">🪪 إصدار كارنيه</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Membership Type Badge -->
        <?php
            $typeLabels = [
                'working' => ['label' => 'عضوية عاملة', 'color' => '#0D7377', 'bg' => '#E6FFFA'],
                'seasonal' => ['label' => 'عضوية موسمية', 'color' => '#D97706', 'bg' => '#FFF7ED'],
                'sports' => ['label' => 'عضوية رياضية', 'color' => '#7C3AED', 'bg' => '#F5F3FF'],
                'honorary' => ['label' => 'عضوية شرفية', 'color' => '#059669', 'bg' => '#ECFDF5'],
                'foreign' => ['label' => 'عضوية أجنبية', 'color' => '#2563EB', 'bg' => '#EFF6FF'],
            ];
            $mType = $member->membership_type ?? 'working';
            $typeInfo = $typeLabels[$mType] ?? $typeLabels['working'];
        ?>
        <div style="margin-bottom:15px;">
            <div style="font-size:12px;color:#6B7280;font-weight:600;margin-bottom:8px;">نوع العضوية</div>
            <span style="display:inline-block;padding:6px 14px;border-radius:20px;font-size:13px;font-weight:700;color:<?= $typeInfo['color'] ?>;background:<?= $typeInfo['bg'] ?>;border:1px solid <?= $typeInfo['color'] ?>30;">
                <?= e($typeInfo['label']) ?>
            </span>
            <?php if ($mType !== 'working' && $isActive): ?>
                <?php
                    $detailRoutes = [
                        'seasonal' => '/members/' . (int) $member->id . '/seasonal/create',
                        'sports' => '/members/' . (int) $member->id . '/sports/create',
                        'honorary' => '/members/' . (int) $member->id . '/honorary/create',
                        'foreign' => '/members/' . (int) $member->id . '/foreign/create',
                    ];
                ?>
                <a href="<?= $detailRoutes[$mType] ?? '#' ?>" class="btn btn-sm btn-outline" style="margin-right:8px;">تفاصيل النوع</a>
            <?php endif; ?>
        </div>

        <!-- Violations & Fines (active members only) -->
        <?php if ($isActive && can('fine.impose')): ?>
        <div style="margin-bottom:15px;">
            <div style="font-size:12px;color:#6B7280;font-weight:600;margin-bottom:8px;text-transform:uppercase;">⚠️ المخالفات والغرامات</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <a href="/violations/create/<?= (int) $member->id ?>" class="btn btn-sm btn-outline" style="color:#DC2626;border-color:#DC2626;">⚠️ تسجيل مخالفة</a>
            </div>
        </div>
        <?php endif; ?>

        <!-- Life Events (active members only) -->
        <?php if ($isActive && canAny(['transfer.initiate', 'waiver.initiate', 'member.change_status'])): ?>
        <div style="margin-bottom:15px;">
            <div style="font-size:12px;color:#6B7280;font-weight:600;margin-bottom:8px;text-transform:uppercase;">🔀 التحويلات وأحداث الحياة</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <?php if (can('transfer.initiate')): ?>
                <a href="/transfers/create/<?= (int) $member->id ?>" class="btn btn-sm btn-outline">🔀 طلب تحويل/فصل</a>
                <?php endif; ?>
                <?php if (can('member.change_status')): ?>
                <a href="/divorce/create/<?= (int) $member->id ?>" class="btn btn-sm btn-outline">💔 تسجيل طلاق</a>
                <a href="/death/create/<?= (int) $member->id ?>" class="btn btn-sm btn-outline" style="color:#6B7280;">🕊️ تسجيل وفاة</a>
                <?php endif; ?>
                <?php if (can('waiver.initiate')): ?>
                <a href="/waivers/create/<?= (int) $member->id ?>" class="btn btn-sm btn-outline">📤 طلب تنازل</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Archive & Audit -->
        <div style="margin-bottom:0;">
            <div style="font-size:12px;color:#6B7280;font-weight:600;margin-bottom:8px;text-transform:uppercase;">🗄️ الأرشيف والمراجعة</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <a href="/members/<?= (int) $member->id ?>/insurance-record" class="btn btn-sm btn-outline" style="color:#1E40AF;border-color:#1E40AF;">&#x1f4cb; السجل التأميني</a>
                <a href="/audit/entity/members/<?= (int) $member->id ?>" class="btn btn-sm btn-outline">📜 سجل المراجعة</a>
                <a href="/archive/entity/members/<?= (int) $member->id ?>" class="btn btn-sm btn-outline">🗄️ اللقطات الأرشيفية</a>
                <?php if ($member->membership_number): ?>
                    <a href="/archive/number-chain/<?= urlencode($member->membership_number) ?>" class="btn btn-sm btn-outline">🔗 سلسلة رقم العضوية</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════ -->
<!-- FAMILY TREE — unified display of all dependants -->
<!-- ═══════════════════════════════════════════════ -->
<?php
$totalDependants = count($spouses) + count($children) + count($temporaries ?? []);
$categoryLabels = [
    'parent' => 'والد/ة', 'special_needs' => 'ذوي احتياجات خاصة', 'unmarried_daughter' => 'ابنة غير متزوجة',
    'sister' => 'شقيقة', 'stepchild' => 'ابن/ة زوج', 'orphan' => 'يتيم', 'disabled_sibling' => 'شقيق معاق', 'nanny' => 'مربية',
];
$childClassLabels = ['included' => 'تابع مشمول', 'dependent_with_fee' => 'تابع برسوم', 'temporary' => 'تابع مؤقت', 'frozen' => 'مجمد'];
?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;background:linear-gradient(135deg, #F0FDF4, #ECFDF5);border-bottom:2px solid #A7F3D0;display:flex;justify-content:space-between;align-items:center;">
        <h3 style="margin:0;color:#065F46;font-size:16px;">&#x1f468;&#x200d;&#x1f469;&#x200d;&#x1f467;&#x200d;&#x1f466; الشجرة العائلية (<?= $totalDependants ?> تابع)</h3>
        <?php if ($canEdit): ?>
        <div style="display:flex;gap:8px;">
            <a href="/members/<?= (int) $member->id ?>/spouses/create" class="btn btn-sm btn-outline">+ زوج/ة</a>
            <a href="/members/<?= (int) $member->id ?>/children/create" class="btn btn-sm btn-outline">+ ابن/ة</a>
            <a href="/members/<?= (int) $member->id ?>/temporary/create" class="btn btn-sm btn-outline">+ عضو مؤقت</a>
        </div>
        <?php elseif ($isLocked): ?>
        <span style="font-size:12px;color:#6B7280;">🔒 البيانات مقفلة بعد تفعيل العضوية</span>
        <?php endif; ?>
    </div>

    <?php if ($totalDependants === 0): ?>
    <div style="padding:30px;text-align:center;color:#9CA3AF;">
        <div style="font-size:36px;margin-bottom:10px;">&#x1f465;</div>
        <p style="margin:0;">لا يوجد تابعون مسجلون — يمكنك إضافة زوج/ة، أبناء، أو أعضاء مؤقتين</p>
    </div>
    <?php else: ?>

    <?php if (!empty($spouses)): ?>
    <!-- Spouses -->
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <div style="font-size:12px;color:#0D7377;font-weight:700;margin-bottom:10px;text-transform:uppercase;">&#x1f48d; الزوجات (<?= count($spouses) ?>)</div>
        <div class="table-responsive"><table class="data-table" style="margin:0;"><thead><tr><th>#</th><th>الاسم</th><th>نوع العضوية</th><th>الرقم القومي</th><th>تاريخ الالتحاق</th><th>تاريخ الاستحقاق</th><th>تاريخ السداد</th><th>الرسوم</th><th>الحالة</th><th></th></tr></thead><tbody>
        <?php foreach ($spouses as $sIdx => $s): ?>
        <?php
            $sFee = $s['addition_fee'] ?? '0.00';
            $sHasBreakdown = !empty($s['fee_breakdown_json']);
            $sBreakdown = $sHasBreakdown ? json_decode($s['fee_breakdown_json'], true) : null;
            if (!is_array($sBreakdown)) $sBreakdown = null;
        ?>
        <tr <?= $sBreakdown ? 'style="cursor:pointer;" onclick="toggleBillDetail(\'spouse-' . $sIdx . '\')"' : '' ?>>
            <td><?= (int) $s['spouse_order'] ?></td>
            <td style="font-weight:600;"><?= e($s['full_name_ar']) ?></td>
            <td><?php
                $sClassification = $s['classification'] ?? 'working';
                $sTypeLabel = match($sClassification) { 'dependent' => 'عضو تابع', 'working' => 'عضو عامل', default => 'عضو عامل' };
            ?><span style="background:#E0F2FE;color:#0369A1;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:600;"><?= $sTypeLabel ?></span></td>
            <td style="direction:ltr;text-align:right;font-size:12px;"><?= e($s['national_id'] ?? '—') ?></td>
            <td style="font-size:12px;"><?= $s['join_date'] ? e($s['join_date']) : '<span style="color:#D97706;">لم يُحدد بعد</span>' ?></td>
            <td style="font-size:12px;"><?= !empty($s['due_date']) ? e(substr($s['due_date'], 0, 10)) : '<span style="color:#9CA3AF;">—</span>' ?></td>
            <td style="font-size:12px;"><?= !empty($s['payment_date']) ? e($s['payment_date']) : '<span style="color:#9CA3AF;">—</span>' ?></td>
            <td style="font-weight:600;"><?php
                $fee = $s['addition_fee'] ?? '0.00';
                if (bccomp($fee, '0', 2) <= 0 && (int) $s['spouse_order'] === 1) echo '<span style="color:#059669;">مشمولة</span>';
                else echo money($fee);
                if ($sBreakdown) echo ' <small style="color:#0D7377;font-size:10px;">&#x25BC;</small>';
            ?></td>
            <td><?php
                $sKey = 'spouses:' . (int) $s['id'];
                $sInQueue = isset($pendingAdditions[$sKey]);
                $sInCombined = ($s['status'] === 'pending_payment' && !empty($pendingMembership));
                if ($sInQueue || $sInCombined): ?>
                    <span style="color:#D97706;font-weight:600;font-size:12px;">&#x1f4b3; في الخزينة</span>
                <?php else: ?>
                    <span style="color:<?= match($s['status']) { 'active' => '#059669', 'pending_payment' => '#D97706', default => '#DC2626' } ?>;font-weight:600;font-size:12px;">&#x25cf; <?= match($s['status']) { 'active' => 'نشط', 'pending_payment' => 'لم يتم السداد', 'inactive' => 'غير نشط', default => $s['status'] } ?></span>
                <?php endif; ?>
            </td>
            <td style="white-space:nowrap;">
                <a href="/members/<?= (int) $member->id ?>/spouses/<?= (int) $s['id'] ?>" class="btn btn-sm btn-outline">عرض</a>
            </td>
        </tr>
        <?php if ($sBreakdown): ?>
        <tr id="bill-detail-spouse-<?= $sIdx ?>" style="display:none;">
            <td colspan="10" style="padding:5px 10px 10px;">
                <div style="background:#F9FAFB;border:1px solid #E5E7EB;border-radius:8px;padding:10px 14px;font-size:12px;">
                    <?php foreach ($sBreakdown as $line): ?>
                        <?php if (str_contains($line, '═══')): ?>
                            <hr style="border:0;border-top:1px solid #D1D5DB;margin:4px 0;">
                        <?php elseif (str_starts_with($line, '💵')): ?>
                            <div style="font-weight:700;color:#059669;font-size:13px;"><?= e($line) ?></div>
                        <?php else: ?>
                            <div style="color:#374151;padding:1px 0;"><?= e($line) ?></div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            </td>
        </tr>
        <?php endif; ?>
        <?php endforeach; ?>
        </tbody></table></div>
    </div>
    <?php endif; ?>

    <?php if (!empty($children)): ?>
    <!-- Children -->
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <div style="font-size:12px;color:#0D7377;font-weight:700;margin-bottom:10px;text-transform:uppercase;">&#x1f476; الأبناء (<?= count($children) ?>)</div>
        <?php
        $childrenOver25Male = array_filter($children, function($c) {
            return ($c['gender'] ?? '') === 'male'
                && ($c['status'] ?? '') === 'active'
                && (int) ($c['age_years'] ?? 0) >= 25;
        });
        ?>
        <?php if (!empty($childrenOver25Male)): ?>
        <div style="margin-bottom:12px;padding:12px 15px;background:#FFF7ED;border:2px solid #F59E0B;border-radius:8px;">
            <div style="font-weight:700;color:#D97706;margin-bottom:8px;font-size:13px;">&#x26a0;&#xfe0f; أبناء ذكور بلغوا 25 سنة — يجب تجميد عضوياتهم</div>
            <div style="display:flex;flex-direction:column;gap:6px;">
            <?php foreach ($childrenOver25Male as $c25): ?>
                <div style="display:flex;align-items:center;justify-content:space-between;background:#fff;border:1px solid #FDE68A;border-radius:6px;padding:8px 12px;">
                    <span style="font-size:13px;color:#374151;">
                        <strong><?= e($c25['full_name_ar']) ?></strong>
                        — عمره <strong style="color:#DC2626;"><?= (int) $c25['age_years'] ?> سنة</strong>
                    </span>
                    <?php if (can('child.freeze')): ?>
                    <form method="POST" action="/members/<?= (int) $member->id ?>/children/<?= (int) $c25['id'] ?>/freeze" style="display:inline;">
                        <?= csrf_field() ?>
                        <input type="hidden" name="freeze_reason" value="بلوغ سن 25 — تجميد تلقائي">
                        <button type="submit" class="btn btn-sm" style="background:#D97706;color:#fff;border-color:#D97706;font-size:12px;"
                            onclick="return confirm('تجميد عضوية <?= e($c25['full_name_ar']) ?>؟')">
                            &#x1f9ca; تجميد العضوية
                        </button>
                    </form>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        <div class="table-responsive"><table class="data-table" style="margin:0;"><thead><tr><th>#</th><th>الاسم</th><th>نوع العضوية</th><th>النوع</th><th>السن</th><th>تاريخ الالتحاق</th><th>تاريخ الاستحقاق</th><th>تاريخ السداد</th><th>الرسوم</th><th>الحالة</th><th></th></tr></thead><tbody>
        <?php foreach ($children as $cIdx => $c): ?>
        <?php
            $cFee = $c['addition_fee'] ?? '0.00';
            $cBreakdown = !empty($c['fee_breakdown_json']) ? json_decode($c['fee_breakdown_json'], true) : null;
            if (!is_array($cBreakdown)) $cBreakdown = null;
        ?>
        <tr <?= $cBreakdown ? 'style="cursor:pointer;" onclick="toggleBillDetail(\'child-' . $cIdx . '\')"' : '' ?>>
            <td><?= (int) $c['child_order'] ?></td>
            <td style="font-weight:600;"><?= e($c['full_name_ar']) ?></td>
            <td><span style="background:#E0F2FE;color:#0369A1;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:600;"><?= $childClassLabels[$c['classification'] ?? 'included'] ?? 'تابع' ?></span></td>
            <td><?= $c['gender'] === 'male' ? 'ذكر' : 'أنثى' ?></td>
            <td><?php
                $cDob = $c['date_of_birth'] ?? null;
                $cAge = ($c['age_years'] ?? 0);
                if (!$cAge && $cDob && strtotime($cDob) > 0) {
                    $cAge = (int) ((time() - strtotime($cDob)) / 31557600);
                }
                echo (int) $cAge;
            ?></td>
            <td style="font-size:12px;"><?= !empty($c['join_date']) ? e($c['join_date']) : '<span style="color:#D97706;">—</span>' ?></td>
            <td style="font-size:12px;"><?= !empty($c['due_date']) ? e(substr($c['due_date'], 0, 10)) : '<span style="color:#9CA3AF;">—</span>' ?></td>
            <td style="font-size:12px;"><?= !empty($c['payment_date']) ? e($c['payment_date']) : '<span style="color:#9CA3AF;">—</span>' ?></td>
            <td style="font-weight:600;"><?php
                $fee = $c['addition_fee'] ?? '0.00';
                echo bccomp($fee, '0', 2) <= 0 ? '<span style="color:#059669;">مشمول</span>' : money($fee);
                if ($cBreakdown) echo ' <small style="color:#0D7377;font-size:10px;">&#x25BC;</small>';
            ?></td>
            <td><?php
                $cKey = 'children:' . (int) $c['id'];
                $cInQueue = isset($pendingAdditions[$cKey]);
                $cInCombined = (($c['status'] ?? '') === 'pending_payment' && !empty($pendingMembership));
                if ($cInQueue || $cInCombined): ?>
                    <span style="color:#D97706;font-weight:600;font-size:12px;">&#x1f4b3; في الخزينة</span>
                <?php else: ?>
                    <span style="color:<?= match($c['status'] ?? '') { 'active' => '#059669', 'pending_payment' => '#D97706', 'frozen' => '#6B7280', 'separated' => '#6B7280', default => '#DC2626' } ?>;font-weight:600;font-size:12px;">&#x25cf; <?= match($c['status'] ?? '') { 'active' => 'نشط', 'pending_payment' => 'لم يتم السداد', 'frozen' => 'مجمد', 'separated' => 'منفصل', 'inactive' => 'غير نشط', default => $c['status'] ?? '—' } ?></span>
                <?php endif; ?>
            </td>
            <td style="white-space:nowrap;">
                <a href="/members/<?= (int) $member->id ?>/children/<?= (int) $c['id'] ?>" class="btn btn-sm btn-outline">عرض</a></td>
        </tr>
        <?php if ($cBreakdown): ?>
        <tr id="bill-detail-child-<?= $cIdx ?>" style="display:none;">
            <td colspan="11" style="padding:5px 10px 10px;">
                <div style="background:#F9FAFB;border:1px solid #E5E7EB;border-radius:8px;padding:10px 14px;font-size:12px;">
                    <?php foreach ($cBreakdown as $line): ?>
                        <?php if (str_contains($line, '═══')): ?>
                            <hr style="border:0;border-top:1px solid #D1D5DB;margin:4px 0;">
                        <?php elseif (str_starts_with($line, '💵')): ?>
                            <div style="font-weight:700;color:#059669;font-size:13px;"><?= e($line) ?></div>
                        <?php else: ?>
                            <div style="color:#374151;padding:1px 0;"><?= e($line) ?></div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            </td>
        </tr>
        <?php endif; ?>
        <?php endforeach; ?>
        </tbody></table></div>
    </div>
    <?php endif; ?>

    <?php if (!empty($temporaries)): ?>
    <!-- Temporary Members -->
    <div style="padding:15px 20px;">
        <div style="font-size:12px;color:#0D7377;font-weight:700;margin-bottom:10px;text-transform:uppercase;">&#x1f464; الأعضاء المؤقتون (<?= count($temporaries) ?>)</div>
        <div class="table-responsive"><table class="data-table" style="margin:0;"><thead><tr><th>الاسم</th><th>نوع العضوية</th><th>الصلة</th><th>النوع</th><th>السن</th><th>تاريخ الالتحاق</th><th>تاريخ الاستحقاق</th><th>تاريخ السداد</th><th>الرسوم</th><th>الحالة</th><th></th></tr></thead><tbody>
        <?php foreach ($temporaries as $tIdx => $t): ?>
        <?php
            $tFee = $t['addition_fee'] ?? '0.00';
            $tBreakdown = !empty($t['fee_breakdown_json']) ? json_decode($t['fee_breakdown_json'], true) : null;
            if (!is_array($tBreakdown)) $tBreakdown = null;
        ?>
        <tr <?= $tBreakdown ? 'style="cursor:pointer;" onclick="toggleBillDetail(\'temp-' . $tIdx . '\')"' : '' ?>>
            <td style="font-weight:600;"><?= e($t['full_name_ar']) ?></td>
            <td><span style="background:#E0F2FE;color:#0369A1;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:600;">عضو مؤقت</span></td>
            <td style="font-size:12px;"><?= $categoryLabels[$t['category']] ?? e($t['category']) ?></td>
            <td><?= $t['gender'] === 'male' ? 'ذكر' : 'أنثى' ?></td>
            <td><?= (int) ($t['age_years'] ?? 0) ?></td>
            <td style="font-size:12px;"><?= !empty($t['join_date']) ? e($t['join_date']) : '<span style="color:#D97706;">—</span>' ?></td>
            <td style="font-size:12px;"><?= !empty($t['due_date']) ? e(substr($t['due_date'], 0, 10)) : '<span style="color:#9CA3AF;">—</span>' ?></td>
            <td style="font-size:12px;"><?= !empty($t['payment_date']) ? e($t['payment_date']) : '<span style="color:#9CA3AF;">—</span>' ?></td>
            <td style="font-weight:600;"><?php
                $fee = $t['addition_fee'] ?? '0.00';
                echo bccomp($fee, '0', 2) <= 0 ? '<span style="color:#059669;">مشمول</span>' : money($fee);
                if ($tBreakdown) echo ' <small style="color:#0D7377;font-size:10px;">&#x25BC;</small>';
            ?></td>
            <td><?php
                $tKey = 'temporary_members:' . (int) $t['id'];
                $tInQueue = isset($pendingAdditions[$tKey]);
                $tInCombined = (($t['status'] ?? '') === 'pending_payment' && !empty($pendingMembership));
                if ($tInQueue || $tInCombined): ?>
                    <span style="color:#D97706;font-weight:600;font-size:12px;">&#x1f4b3; في الخزينة</span>
                <?php else: ?>
                    <span style="color:<?= match($t['status'] ?? '') { 'active' => '#059669', 'pending_payment' => '#D97706', default => '#DC2626' } ?>;font-weight:600;font-size:12px;">&#x25cf; <?= match($t['status'] ?? '') { 'active' => 'نشط', 'pending_payment' => 'لم يتم السداد', 'frozen' => 'مجمد', 'inactive' => 'غير نشط', default => $t['status'] ?? '—' } ?></span>
                <?php endif; ?>
            </td>
            <td style="white-space:nowrap;">
                <a href="/members/<?= (int) $member->id ?>/temporary/<?= (int) $t['id'] ?>" class="btn btn-sm btn-outline">عرض</a>
            </td>
        </tr>
        <?php if ($tBreakdown): ?>
        <tr id="bill-detail-temp-<?= $tIdx ?>" style="display:none;">
            <td colspan="11" style="padding:5px 10px 10px;">
                <div style="background:#F9FAFB;border:1px solid #E5E7EB;border-radius:8px;padding:10px 14px;font-size:12px;">
                    <?php foreach ($tBreakdown as $line): ?>
                        <?php if (str_contains($line, '═══')): ?>
                            <hr style="border:0;border-top:1px solid #D1D5DB;margin:4px 0;">
                        <?php elseif (str_starts_with($line, '💵')): ?>
                            <div style="font-weight:700;color:#059669;font-size:13px;"><?= e($line) ?></div>
                        <?php else: ?>
                            <div style="color:#374151;padding:1px 0;"><?= e($line) ?></div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            </td>
        </tr>
        <?php endif; ?>
        <?php endforeach; ?>
        </tbody></table></div>
    </div>
    <?php endif; ?>

    <?php endif; ?>
</div>

<?php if (can('member.change_status')): ?>
<!-- Status Change -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;"><h3 style="margin:0;color:#0D7377;font-size:15px;">🔄 تغيير الحالة</h3></div>
    <div style="padding:15px 20px;">
        <form method="POST" action="/members/<?= (int) $member->id ?>/status" style="display:flex;gap:10px;align-items:center;">
            <?= csrf_field() ?>
            <select name="status" class="form-select" style="width:auto;">
                <?php foreach (\App\Modules\Members\Models\Member::getStatusOptions() as $val => $label): ?>
                    <option value="<?= e($val) ?>" <?= $member->status === $val ? 'selected' : '' ?>><?= e($label) ?></option>
                <?php endforeach; ?>
            </select>
            <button type="submit" class="btn btn-outline" onclick="return confirm('تغيير حالة العضو؟')">تحديث</button>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════ -->
<!-- WAIVER TRANSFER SOURCE & ARCHIVE -->
<!-- ═══════════════════════════════════════════════ -->
<?php if (!empty($waiverTransfer)): ?>
<div class="card" style="margin-bottom:20px;border:2px solid #7C3AED;">
    <div style="padding:15px 20px;border-bottom:1px solid #DDD6FE;background:#F5F3FF;display:flex;justify-content:space-between;align-items:center;">
        <h3 style="margin:0;color:#7C3AED;font-size:15px;">📤 هذه العضوية ناتجة عن تنازل</h3>
        <a href="/waivers/<?= (int) $waiverTransfer['id'] ?>" class="btn btn-sm btn-outline" style="color:#7C3AED;border-color:#7C3AED;">عرض طلب التنازل</a>
    </div>
    <div style="padding:20px;">
        <table style="width:100%;max-width:600px;font-size:14px;">
            <tr>
                <td style="padding:6px 0;color:#6B7280;width:35%;">العضو المتنازل</td>
                <td style="padding:6px 0;font-weight:700;"><?= e($waiverTransfer['source_member_name'] ?? $member->waived_from_member_name ?? '—') ?></td>
            </tr>
            <tr>
                <td style="padding:6px 0;color:#6B7280;">رقم العضوية المنقول</td>
                <td style="padding:6px 0;font-weight:600;color:#0D7377;"><?= e($waiverTransfer['membership_number'] ?? $member->membership_number ?? '—') ?></td>
            </tr>
            <?php if (!empty($waiverTransfer['waiver_fee_amount']) && bccomp($waiverTransfer['waiver_fee_amount'], '0', 2) > 0): ?>
            <tr>
                <td style="padding:6px 0;color:#6B7280;">رسوم التنازل</td>
                <td style="padding:6px 0;font-weight:600;"><?= money($waiverTransfer['waiver_fee_amount']) ?> (<?= e($waiverTransfer['waiver_fee_percentage'] ?? '30') ?>%)</td>
            </tr>
            <?php endif; ?>
            <tr>
                <td style="padding:6px 0;color:#6B7280;">تاريخ التنازل</td>
                <td style="padding:6px 0;"><?= e(substr($waiverTransfer['waiver_date'] ?? '', 0, 10)) ?></td>
            </tr>
        </table>

        <?php if (!empty($waiverArchiveSnapshot)): ?>
        <hr style="border:none;border-top:1px solid #E5E7EB;margin:20px 0;">
        <div style="margin-bottom:10px;">
            <button type="button" onclick="document.getElementById('waiver-archive-detail').style.display = document.getElementById('waiver-archive-detail').style.display === 'none' ? 'block' : 'none';"
                class="btn btn-sm btn-outline" style="color:#7C3AED;border-color:#7C3AED;">
                🗄️ عرض أرشيف العضو السابق
            </button>
            <span style="font-size:12px;color:#9CA3AF;margin-right:10px;">لقطة كاملة من تاريخ <?= e(substr($waiverArchiveSnapshot['snapshot_taken_at'] ?? '', 0, 10)) ?></span>
        </div>
        <div id="waiver-archive-detail" style="display:none;background:#FAFAFA;border:1px solid #E5E7EB;border-radius:8px;padding:20px;margin-top:10px;">
            <?php
            $archiveData = $waiverArchiveSnapshot['full_data'] ?? [];
            $archiveRelated = $waiverArchiveSnapshot['related_data'] ?? [];
            ?>

            <!-- Personal Data -->
            <h4 style="margin:0 0 10px;color:#374151;font-size:14px;border-bottom:1px solid #E5E7EB;padding-bottom:8px;">البيانات الشخصية للعضو السابق</h4>
            <table style="width:100%;font-size:13px;margin-bottom:20px;">
                <?php
                $archiveFields = [
                    'full_name_ar' => 'الاسم بالعربي',
                    'full_name_en' => 'الاسم بالإنجليزي',
                    'national_id' => 'الرقم القومي',
                    'date_of_birth' => 'تاريخ الميلاد',
                    'gender' => 'النوع',
                    'nationality' => 'الجنسية',
                    'phone_mobile' => 'الهاتف المحمول',
                    'email' => 'البريد الإلكتروني',
                    'residence_address' => 'العنوان',
                    'membership_number' => 'رقم العضوية',
                    'membership_type' => 'نوع العضوية',
                    'membership_value' => 'قيمة العضوية',
                    'status' => 'الحالة',
                    'activated_at' => 'تاريخ التفعيل',
                ];
                foreach ($archiveFields as $key => $label):
                    if (!empty($archiveData[$key])):
                ?>
                <tr>
                    <td style="padding:4px 0;color:#6B7280;width:30%;"><?= e($label) ?></td>
                    <td style="padding:4px 0;"><?= e((string) $archiveData[$key]) ?></td>
                </tr>
                <?php endif; endforeach; ?>
            </table>

            <!-- Dependents -->
            <?php if (!empty($archiveRelated['spouses'])): ?>
            <h4 style="margin:15px 0 8px;color:#374151;font-size:13px;border-bottom:1px solid #E5E7EB;padding-bottom:6px;">الزوجات (<?= count($archiveRelated['spouses']) ?>)</h4>
            <table style="width:100%;font-size:12px;margin-bottom:15px;">
                <thead><tr style="background:#F9FAFB;"><th style="padding:6px;text-align:right;">الاسم</th><th style="padding:6px;">الرقم القومي</th><th style="padding:6px;">الحالة</th></tr></thead>
                <tbody>
                <?php foreach ($archiveRelated['spouses'] as $as): ?>
                <tr style="border-bottom:1px solid #F3F4F6;"><td style="padding:5px;"><?= e($as['full_name_ar'] ?? '') ?></td><td style="padding:5px;direction:ltr;"><?= e($as['national_id'] ?? '') ?></td><td style="padding:5px;"><?= e($as['status'] ?? '') ?></td></tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>

            <?php if (!empty($archiveRelated['children'])): ?>
            <h4 style="margin:15px 0 8px;color:#374151;font-size:13px;border-bottom:1px solid #E5E7EB;padding-bottom:6px;">الأبناء (<?= count($archiveRelated['children']) ?>)</h4>
            <table style="width:100%;font-size:12px;margin-bottom:15px;">
                <thead><tr style="background:#F9FAFB;"><th style="padding:6px;text-align:right;">الاسم</th><th style="padding:6px;">تاريخ الميلاد</th><th style="padding:6px;">الرقم القومي</th><th style="padding:6px;">الحالة</th></tr></thead>
                <tbody>
                <?php foreach ($archiveRelated['children'] as $ac): ?>
                <tr style="border-bottom:1px solid #F3F4F6;"><td style="padding:5px;"><?= e($ac['full_name_ar'] ?? '') ?></td><td style="padding:5px;"><?= e($ac['date_of_birth'] ?? '') ?></td><td style="padding:5px;direction:ltr;"><?= e($ac['national_id'] ?? '') ?></td><td style="padding:5px;"><?= e($ac['status'] ?? '') ?></td></tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>

            <?php if (!empty($archiveRelated['temporary_members'])): ?>
            <h4 style="margin:15px 0 8px;color:#374151;font-size:13px;border-bottom:1px solid #E5E7EB;padding-bottom:6px;">الأعضاء المؤقتون (<?= count($archiveRelated['temporary_members']) ?>)</h4>
            <table style="width:100%;font-size:12px;margin-bottom:15px;">
                <thead><tr style="background:#F9FAFB;"><th style="padding:6px;text-align:right;">الاسم</th><th style="padding:6px;">الرقم القومي</th><th style="padding:6px;">الحالة</th></tr></thead>
                <tbody>
                <?php foreach ($archiveRelated['temporary_members'] as $at): ?>
                <tr style="border-bottom:1px solid #F3F4F6;"><td style="padding:5px;"><?= e($at['full_name_ar'] ?? '') ?></td><td style="padding:5px;direction:ltr;"><?= e($at['national_id'] ?? '') ?></td><td style="padding:5px;"><?= e($at['status'] ?? '') ?></td></tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>

            <!-- Payments -->
            <?php if (!empty($archiveRelated['payments'])): ?>
            <h4 style="margin:15px 0 8px;color:#374151;font-size:13px;border-bottom:1px solid #E5E7EB;padding-bottom:6px;">المدفوعات (<?= count($archiveRelated['payments']) ?>)</h4>
            <table style="width:100%;font-size:12px;margin-bottom:15px;">
                <thead><tr style="background:#F9FAFB;"><th style="padding:6px;text-align:right;">النوع</th><th style="padding:6px;">المبلغ</th><th style="padding:6px;">التاريخ</th><th style="padding:6px;">رقم الإيصال</th></tr></thead>
                <tbody>
                <?php foreach (array_slice($archiveRelated['payments'], 0, 20) as $ap): ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:5px;"><?= e($ap['payment_type'] ?? '') ?></td>
                    <td style="padding:5px;font-weight:600;"><?= money($ap['amount'] ?? '0') ?></td>
                    <td style="padding:5px;"><?= e(substr($ap['payment_date'] ?? $ap['created_at'] ?? '', 0, 10)) ?></td>
                    <td style="padding:5px;direction:ltr;"><?= e($ap['receipt_number'] ?? '') ?></td>
                </tr>
                <?php endforeach; ?>
                <?php if (count($archiveRelated['payments']) > 20): ?>
                <tr><td colspan="4" style="padding:5px;color:#6B7280;text-align:center;">... و<?= count($archiveRelated['payments']) - 20 ?> مدفوعات أخرى</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
            <?php endif; ?>

            <!-- Subscriptions -->
            <?php if (!empty($archiveRelated['subscriptions'])): ?>
            <h4 style="margin:15px 0 8px;color:#374151;font-size:13px;border-bottom:1px solid #E5E7EB;padding-bottom:6px;">الاشتراكات السنوية (<?= count($archiveRelated['subscriptions']) ?>)</h4>
            <table style="width:100%;font-size:12px;margin-bottom:15px;">
                <thead><tr style="background:#F9FAFB;"><th style="padding:6px;text-align:right;">السنة المالية</th><th style="padding:6px;">الشخص</th><th style="padding:6px;">المبلغ</th><th style="padding:6px;">الحالة</th></tr></thead>
                <tbody>
                <?php foreach (array_slice($archiveRelated['subscriptions'], 0, 30) as $asub): ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:5px;"><?= e($asub['financial_year'] ?? '') ?></td>
                    <td style="padding:5px;"><?= e($asub['person_name'] ?? 'العضو') ?></td>
                    <td style="padding:5px;"><?= money($asub['total_amount'] ?? '0') ?></td>
                    <td style="padding:5px;"><?= e($asub['status'] ?? '') ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>

            <!-- Fines -->
            <?php if (!empty($archiveRelated['fines'])): ?>
            <h4 style="margin:15px 0 8px;color:#374151;font-size:13px;border-bottom:1px solid #E5E7EB;padding-bottom:6px;">الغرامات (<?= count($archiveRelated['fines']) ?>)</h4>
            <table style="width:100%;font-size:12px;margin-bottom:15px;">
                <thead><tr style="background:#F9FAFB;"><th style="padding:6px;text-align:right;">المبلغ</th><th style="padding:6px;">الحالة</th><th style="padding:6px;">ملاحظات</th></tr></thead>
                <tbody>
                <?php foreach ($archiveRelated['fines'] as $af): ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:5px;"><?= money($af['amount'] ?? '0') ?></td>
                    <td style="padding:5px;"><?= e($af['status'] ?? '') ?></td>
                    <td style="padding:5px;max-width:200px;overflow:hidden;text-overflow:ellipsis;"><?= e($af['notes'] ?? '') ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>

            <!-- Installments -->
            <?php if (!empty($archiveRelated['installment_plans'])): ?>
            <h4 style="margin:15px 0 8px;color:#374151;font-size:13px;border-bottom:1px solid #E5E7EB;padding-bottom:6px;">خطط الأقساط (<?= count($archiveRelated['installment_plans']) ?>)</h4>
            <table style="width:100%;font-size:12px;margin-bottom:15px;">
                <thead><tr style="background:#F9FAFB;"><th style="padding:6px;text-align:right;">المبلغ</th><th style="padding:6px;">عدد الأشهر</th><th style="padding:6px;">الحالة</th></tr></thead>
                <tbody>
                <?php foreach ($archiveRelated['installment_plans'] as $aip): ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:5px;"><?= money($aip['total_amount'] ?? '0') ?></td>
                    <td style="padding:5px;"><?= e($aip['number_of_months'] ?? '') ?></td>
                    <td style="padding:5px;"><?= e($aip['status'] ?? '') ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>

            <!-- Documents -->
            <?php if (!empty($archiveRelated['documents'])): ?>
            <h4 style="margin:15px 0 8px;color:#374151;font-size:13px;border-bottom:1px solid #E5E7EB;padding-bottom:6px;">المستندات (<?= count($archiveRelated['documents']) ?>)</h4>
            <table style="width:100%;font-size:12px;">
                <thead><tr style="background:#F9FAFB;"><th style="padding:6px;text-align:right;">النوع</th><th style="padding:6px;">اسم الملف</th><th style="padding:6px;">تاريخ الرفع</th></tr></thead>
                <tbody>
                <?php foreach ($archiveRelated['documents'] as $adoc): ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:5px;"><?= e($adoc['document_type'] ?? '') ?></td>
                    <td style="padding:5px;"><?= e($adoc['original_filename'] ?? '') ?></td>
                    <td style="padding:5px;"><?= e(substr($adoc['uploaded_at'] ?? '', 0, 10)) ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<script>
function toggleBillDetail(idx) {
    var el = document.getElementById('bill-detail-' + idx);
    if (!el) return;
    el.style.display = el.style.display === 'none' ? '' : 'none';
}
</script>

<?php $__template->endSection(); ?>