<?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; ?>
                <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>
            <div style="margin-top:10px;font-size:12px;color:#9CA3AF;">تاريخ: <?= e(substr($member->created_at, 0, 10)) ?></div>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════ -->
<!-- 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>

    <!-- Payment Section -->
    <?php if (bccomp($bill['total_pending'], '0', 2) > 0 && in_array($member->status, ['accepted', 'payment_pending'])): ?>
    <?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 else: ?>
    <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: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="membership_fee">
                    <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>
            <!-- Installment -->
            <div style="background:#fff;border:2px solid #0284C7;border-radius:12px;padding:20px;">
                <h5 style="margin:0 0 10px;color:#0284C7;">&#x1f4c5; تقسيط</h5>
                <p style="font-size:13px;color:#6B7280;margin:0 0 5px;">مقدم 25% على الأقل + باقي على أقساط</p>
                <p style="font-size:12px;color:#D97706;margin:0 0 10px;">فائدة 22% سنوياً — حتى 30 شهر</p>
                <?php
                $minDown = bcdiv(bcmul($bill['total_pending'], '25', 2), '100', 2);
                $remaining = bcsub($bill['total_pending'], $minDown, 2);
                $interest = bcdiv(bcmul($remaining, '22', 2), '100', 2);
                $totalWithInterest = bcadd($remaining, $interest, 2);
                $monthlyEst = bcdiv($totalWithInterest, '30', 2);
                ?>
                <table style="width:100%;font-size:13px;margin-bottom:10px;">
                    <tr><td style="color:#6B7280;">المقدم (25%)</td><td style="text-align:left;font-weight:600;"><?= money($minDown) ?></td></tr>
                    <tr><td style="color:#6B7280;">الفائدة (22%)</td><td style="text-align:left;color:#D97706;"><?= money($interest) ?></td></tr>
                    <tr><td style="color:#6B7280;">القسط (~30 شهر)</td><td style="text-align:left;font-weight:600;"><?= money($monthlyEst) ?></td></tr>
                </table>
                <form method="POST" action="/members/<?= (int) $member->id ?>/pay-membership">
                    <?= csrf_field() ?>
                    <input type="hidden" name="payment_type" value="down_payment">
                    <div class="form-group" style="margin-bottom:10px;">
                        <label class="form-label" style="font-size:12px;">المقدم (&#x2265; <?= money($minDown) ?>)</label>
                        <input type="number" name="amount" value="<?= e($minDown) ?>" min="<?= e($minDown) ?>" step="0.01" class="form-input" style="direction:ltr;text-align:left;" required>
                    </div>
                    <div class="form-group" style="margin-bottom:10px;">
                        <label class="form-label" style="font-size:12px;">عدد الأشهر (حتى 30)</label>
                        <input type="number" name="installment_months" value="30" min="1" max="30" class="form-input" style="direction:ltr;text-align:left;">
                    </div>
                    <button type="submit" class="btn btn-primary" style="width:100%;background:#D97706;border-color:#D97706;" onclick="return confirm('إرسال طلب تقسيط للخزينة؟')">&#x1f4e4; إرسال للخزينة</button>
                </form>
            </div>
        </div>
        <div style="margin-top:15px;padding:10px;background:#FEF2F2;border-radius:8px;font-size:12px;color:#DC2626;">
            &#x26a0;&#xfe0f; مهلة السداد: 15 يوم من تاريخ القبول — بعدها تنتهي الاستمارة
        </div>
    </div>
    <?php endif; ?>
    <?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];
}

if ($formFilled && !$bill['membership_paid'] && !in_array($member->status, ['active'], true)) {
    if (!empty($bill['membership_pending']) || !empty($pendingMembership)) {
        $missingSteps[] = ['icon' => '&#x1f4b3;', 'text' => 'رسوم العضوية في انتظار الخزينة', 'color' => '#D97706', 'done' => false];
    } elseif (in_array($member->status, ['accepted', 'payment_pending'], true)) {
        $missingSteps[] = ['icon' => '&#x23f3;', 'text' => 'لم يتم سداد رسوم العضوية', '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' => 'رسوم العضوية', '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;">
                <div style="background:#F0FDF4;padding:15px;border-radius:8px;text-align:center;"><div style="font-size:20px;font-weight:700;color:#059669;"><?= money($member->membership_value ?? '0') ?></div><div style="color:#6B7280;font-size:11px;">قيمة العضوية</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>
        </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; ?>

        <!-- Special Memberships (active members only) -->
        <?php if ($isActive): ?>
        <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 ?>/seasonal/create" class="btn btn-sm btn-outline">☀️ عضوية موسمية</a>
                <a href="/members/<?= (int) $member->id ?>/sports/create" class="btn btn-sm btn-outline">🏆 عضوية رياضية</a>
                <a href="/members/<?= (int) $member->id ?>/honorary/create" class="btn btn-sm btn-outline">⭐ عضوية شرفية</a>
                <a href="/members/<?= (int) $member->id ?>/foreign/create" class="btn btn-sm btn-outline">🌍 عضوية أجنبية</a>
            </div>
        </div>
        <?php endif; ?>

        <!-- 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="/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>
        <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><?= (int) ($c['age_years'] ?? 0) ?></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', default => '#DC2626' } ?>;font-weight:600;font-size:12px;">&#x25cf; <?= match($c['status'] ?? '') { 'active' => 'نشط', 'pending_payment' => 'لم يتم السداد', 'frozen' => 'مجمد', '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; ?>

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