<?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"><i data-lucide="pencil" style="width:14px;height:14px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> تعديل</a>
<?php endif; ?>
<a href="/members/<?= (int) $member->id ?>/changelog" class="btn btn-outline"><i data-lucide="history" style="width:14px;height:14px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> سجل التعديلات</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;"><i data-lucide="bar-chart-3" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> تفصيل:</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, 'الإجمالي') || 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;"><i data-lucide="check-circle" style="width:16px;height:16px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> تم دفع رسوم الاستمارة — الآن قم بملء البيانات وإضافة الأسرة</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;"><i data-lucide="file-edit" style="width:14px;height:14px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> ملء الاستمارة</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"><i data-lucide="heart" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> إضافة زوج/ة</a>
        <a href="/members/<?= (int) $member->id ?>/children/create" class="btn btn-sm btn-outline"><i data-lucide="baby" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> إضافة ابن/ة</a>
        <a href="/members/<?= (int) $member->id ?>/temporary/create" class="btn btn-sm btn-outline"><i data-lucide="user-plus" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> إضافة عضو مؤقت</a>
    </div>
</div>
<?php endif; ?>

<!-- Member Header -->
<?php
$_memberHasPhoto = !empty($member->photo_path);
$_memberInitials = mb_substr($member->full_name_ar, 0, 2);
?>
<div class="card" style="margin-bottom:20px;padding:0;overflow:hidden;">
    <div style="background:linear-gradient(135deg, #0D7377 0%, #14919B 50%, #0AA6B7 100%);padding:20px 25px 60px;position:relative;">
        <div style="display:flex;justify-content:space-between;align-items:center;">
            <div style="display:flex;align-items:center;gap:12px;">
                <span style="display:inline-block;padding:6px 16px;border-radius:20px;font-weight:700;font-size:14px;color:#fff;background:<?= $statusColor ?>;box-shadow:0 2px 8px rgba(0,0,0,0.2);"><?= e($statusLabel) ?></span>
                <?php if ($member->status === 'active'): ?>
                    <?php if (!empty($overdueSubscriptions)): ?>
                    <span style="display:inline-block;padding:4px 12px;border-radius:12px;font-size:12px;font-weight:600;background:rgba(220,38,38,0.15);color:#FCA5A5;border:1px solid rgba(220,38,38,0.3);"><i data-lucide="alert-triangle" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> اشتراكات متأخرة</span>
                    <?php elseif (!empty($subscriptionStatus) && $subscriptionStatus['status'] === 'paid'): ?>
                    <span style="display:inline-block;padding:4px 12px;border-radius:12px;font-size:12px;font-weight:600;background:rgba(5,150,105,0.15);color:#6EE7B7;border:1px solid rgba(5,150,105,0.3);">✓ العضوية سارية</span>
                    <?php else: ?>
                    <span style="display:inline-block;padding:4px 12px;border-radius:12px;font-size:12px;font-weight:600;background:rgba(217,119,6,0.15);color:#FCD34D;border:1px solid rgba(217,119,6,0.3);">⏳ في انتظار التجديد</span>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
            <div style="font-size:12px;color:rgba(255,255,255,0.7);"><?php
                $isWaiverAcquired = !empty($member->transferred_from_waiver_id);
                $isDeathAcquired = !empty($member->transferred_from_death_id);
                $isTransferAcquired = !empty($member->transferred_from_transfer_id);
                if ($isWaiverAcquired || $isDeathAcquired || $isTransferAcquired):
                    echo 'تاريخ الانتقال: ' . e(substr($member->ownership_transfer_date ?? $member->activated_at ?? $member->created_at, 0, 10));
                else:
                    echo 'تاريخ: ' . e(substr($member->membership_origin_date ?? $member->activated_at ?? $member->created_at, 0, 10));
                endif;
            ?></div>
        </div>
    </div>
    <div style="padding:0 25px 25px;margin-top:-45px;position:relative;">
        <div style="display:flex;align-items:end;gap:20px;">
            <!-- Member Photo -->
            <div style="position:relative;flex-shrink:0;">
                <div style="width:100px;height:100px;border-radius:50%;overflow:hidden;border:4px solid #fff;box-shadow:0 4px 20px rgba(0,0,0,0.15);background:<?= $_memberHasPhoto ? '#F3F4F6' : 'linear-gradient(135deg, #667EEA, #764BA2)' ?>;display:flex;align-items:center;justify-content:center;">
                    <?php if ($_memberHasPhoto): ?>
                        <img src="/<?= e($member->photo_path) ?>" alt="صورة العضو" style="width:100%;height:100%;object-fit:cover;">
                    <?php else: ?>
                        <span style="font-size:32px;font-weight:700;color:#fff;letter-spacing:-1px;"><?= e($_memberInitials) ?></span>
                    <?php endif; ?>
                </div>
                <?php if ($canEdit): ?>
                <div style="position:absolute;bottom:0;right:0;display:flex;gap:3px;">
                    <label style="width:28px;height:28px;border-radius:50%;background:#0D7377;border:2px solid #fff;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 2px 6px rgba(0,0,0,0.2);" title="<?= $_memberHasPhoto ? 'تغيير الصورة' : 'رفع صورة' ?>">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
                        <form method="POST" action="/members/<?= (int) $member->id ?>/photo" enctype="multipart/form-data" style="display:none;" id="memberPhotoForm">
                            <?= csrf_field() ?>
                            <input type="file" name="photo" accept="image/jpeg,image/png,image/webp" onchange="this.form.submit();">
                        </form>
                    </label>
                    <?php if ($_memberHasPhoto): ?>
                    <form method="POST" action="/members/<?= (int) $member->id ?>/photo/delete" style="display:inline;" onsubmit="return confirm('حذف صورة العضو؟')">
                        <?= csrf_field() ?>
                        <button type="submit" style="width:28px;height:28px;border-radius:50%;background:#DC2626;border:2px solid #fff;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 2px 6px rgba(0,0,0,0.2);padding:0;" title="حذف الصورة">
                            <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                        </button>
                    </form>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
            <div style="flex:1;padding-bottom:5px;">
                <h2 style="margin:0 0 2px;color:#1A1A2E;font-size:24px;font-weight:800;"><?= e($member->full_name_ar) ?></h2>
                <?php if ($member->full_name_en): ?><div style="color:#6B7280;font-size:14px;margin-bottom:4px;"><?= e($member->full_name_en) ?></div><?php endif; ?>
                <?php if (!$_memberHasPhoto): ?>
                <span style="display:inline-block;background:#FEF2F2;color:#DC2626;padding:2px 10px;border-radius:4px;font-size:11px;font-weight:600;margin-bottom:4px;"><i data-lucide="alert-triangle" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> لا توجد صورة — مطلوبة لإصدار الكارنيه</span>
                <?php endif; ?>
            </div>
        </div>
        <div style="display:flex;gap:12px;flex-wrap:wrap;font-size:13px;color:#6B7280;margin-top:14px;padding-top:14px;border-top:1px solid #E5E7EB;">
            <?php if ($member->membership_number): ?><span style="background:#E6FFFA;padding:4px 10px;border-radius:6px;"><i data-lucide="id-card" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> عضوية: <strong style="color:#0D7377;font-size:15px;"><?= e($member->membership_number) ?></strong></span><?php endif; ?>
            <span style="background:#FFF7ED;padding:4px 10px;border-radius:6px;"><i data-lucide="clipboard-list" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> استمارة: <strong style="color:#D97706;"><?= e($member->form_number ?? '—') ?></strong></span>
            <span style="background:#F3F4F6;padding:4px 10px;border-radius:6px;"><i data-lucide="building-2" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> <?= e($branchName) ?></span>
            <span style="background:#F3F4F6;padding:4px 10px;border-radius:6px;"><?= $member->gender === 'male' ? '<i data-lucide="user" style="width:13px;height:13px;display:inline-block;vertical-align:middle;"></i>' : '<i data-lucide="user" style="width:13px;height:13px;display:inline-block;vertical-align:middle;"></i>' ?> <?= $member->getGenderLabel() ?></span>
            <?php if ($member->age_years): ?><span style="background:#F3F4F6;padding:4px 10px;border-radius:6px;"><i data-lucide="cake" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> <?= (int) $member->age_years ?> سنة</span><?php endif; ?>
        </div>
        <?php if (!empty($divorceTransfer) || !empty($member->transferred_from_death_id) || !empty($waiverTransfer) || !empty($member->ownership_transfer_date)): ?>
        <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:10px;">
            <?php if (!empty($divorceTransfer)): ?>
            <span style="background:#FEF3C7;padding:3px 10px;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:3px 10px;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:3px 10px;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:3px 10px;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:3px 10px;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:3px 10px;border-radius:10px;font-size:11px;">تاريخ انتقال الملكية: <strong style="color:#059669;"><?= arabic_date($member->ownership_transfer_date) ?></strong></span>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </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;">
        <i data-lucide="alert-triangle" style="width:18px;height:18px;color:#D97706;"></i>
        <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;">
        <i data-lucide="refresh-cw" style="width:18px;height:18px;color:#0D7377;"></i>
        <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($member->membership_origin_date)): ?>
        <tr><td style="padding:6px 0;color:#6B7280;">تاريخ العضوية الأصلية</td><td style="padding:6px 0;font-weight:600;"><?= e($member->membership_origin_date) ?></td></tr>
        <?php endif; ?>
        <?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;"><i data-lucide="file-text" style="width:40px;height:40px;display:inline-block;color:#EA580C;"></i></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;"><i data-lucide="receipt" style="width:16px;height:16px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> فاتورة العضوية</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, 'الإجمالي') || 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"><i data-lucide="heart" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> إضافة زوج/ة</a>
        <a href="/members/<?= (int) $member->id ?>/children/create" class="btn btn-sm btn-outline"><i data-lucide="baby" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> إضافة ابن/ابنة</a>
        <a href="/members/<?= (int) $member->id ?>/temporary/create" class="btn btn-sm btn-outline"><i data-lucide="user-plus" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> عضو مؤقت</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; ?>

    <!-- Regulatory Discount Status -->
    <?php if (!empty($member->regulatory_discount_id) && !empty($regulatoryDiscount)): ?>
    <div style="padding:15px 20px;border-top:1px solid #E5E7EB;">
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
            <span style="background:#ECFDF5;color:#065F46;padding:4px 10px;border-radius:6px;font-size:12px;font-weight:600;">خصم لائحي</span>
            <span style="color:#0D7377;font-weight:600;font-size:13px;">
                <?= e($regulatoryDiscount['name_ar']) ?> (مادة <?= e($regulatoryDiscount['article_number']) ?> — <?= e($regulatoryDiscount['discount_percentage']) ?>%)
                = -<?= money($member->regulatory_discount_amount ?? '0') ?>
            </span>
            <?php if (!empty($member->regulatory_discount_document)): ?>
            <a href="/<?= e($member->regulatory_discount_document) ?>" target="_blank" style="color:#0D7377;font-size:12px;text-decoration:underline;">عرض المستند</a>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- FYI: All Available Discounts Guide -->
    <?php if ($isInitialPhase): ?>
    <div style="border-top:1px solid #E5E7EB;">
        <div style="padding:12px 20px;cursor:pointer;display:flex;align-items:center;gap:8px;background:#F8FAFC;" onclick="var el=document.getElementById('fyi-discounts');el.style.display=el.style.display==='none'?'block':'none';this.querySelector('.fyi-arrow').textContent=el.style.display==='none'?'▼':'▲';">
            <i data-lucide="info" style="width:16px;height:16px;color:#6366F1;"></i>
            <span style="font-weight:600;font-size:13px;color:#6366F1;">دليل الخصومات المتاحة (للعلم)</span>
            <span class="fyi-arrow" style="margin-right:auto;color:#6366F1;font-size:11px;">&#x25BC;</span>
        </div>
        <div id="fyi-discounts" style="display:none;padding:0 20px 20px;">

            <!-- 1. Special Discounts -->
            <div style="margin-bottom:16px;">
                <h4 style="font-size:13px;color:#D97706;margin:12px 0 8px;border-bottom:1px solid #FEF3C7;padding-bottom:4px;">1. الخصومات الخاصة</h4>
                <p style="font-size:12px;color:#6B7280;margin:0 0 6px;">خصومات نسبة أو مبلغ ثابت تُطبَّق من صفحة التعديل أو صفحة ملء الاستمارة. يمكن أن تتطلب مستند إثبات.</p>
                <?php if (!empty($availableDiscounts)): ?>
                <div style="font-size:12px;color:#374151;">
                    <strong>المتاح حالياً:</strong>
                    <?php foreach ($availableDiscounts as $ad): ?>
                    <span style="background:#FEF3C7;padding:2px 8px;border-radius:4px;margin:0 2px;"><?= e($ad['name_ar']) ?> (<?= e($ad['discount_percentage']) ?>%)</span>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

            <!-- 2. Regulatory Discounts -->
            <div style="margin-bottom:16px;">
                <h4 style="font-size:13px;color:#0D7377;margin:0 0 8px;border-bottom:1px solid #D1FAE5;padding-bottom:4px;">2. الخصومات اللائحية (مواد 97 — 102، 110)</h4>
                <p style="font-size:12px;color:#6B7280;margin:0 0 6px;">خصومات منصوص عليها في لائحة النادي — تُطبَّق أثناء ملء الاستمارة بعد التحقق من الأهلية واعتماد المسؤول.</p>
                <?php if (!empty($regulatoryDiscounts)): ?>
                <table style="width:100%;font-size:11px;border-collapse:collapse;margin-top:4px;">
                    <thead>
                        <tr style="background:#F0FDF4;">
                            <th style="padding:5px 8px;text-align:right;color:#065F46;border:1px solid #D1FAE5;">المادة</th>
                            <th style="padding:5px 8px;text-align:right;color:#065F46;border:1px solid #D1FAE5;">الوصف</th>
                            <th style="padding:5px 8px;text-align:center;color:#065F46;border:1px solid #D1FAE5;">النسبة</th>
                            <th style="padding:5px 8px;text-align:right;color:#065F46;border:1px solid #D1FAE5;">الإثبات المطلوب</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($regulatoryDiscounts as $rd): ?>
                        <tr>
                            <td style="padding:4px 8px;border:1px solid #E5E7EB;font-weight:600;">مادة <?= e($rd['article_number']) ?></td>
                            <td style="padding:4px 8px;border:1px solid #E5E7EB;"><?= e($rd['name_ar']) ?></td>
                            <td style="padding:4px 8px;border:1px solid #E5E7EB;text-align:center;font-weight:600;color:#059669;"><?= e($rd['discount_percentage']) ?>%</td>
                            <td style="padding:4px 8px;border:1px solid #E5E7EB;font-size:10px;color:#6B7280;"><?= e($rd['proof_requirements'] ?? 'حسب نوع الخصم') ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>

            <!-- 3. Board Offers -->
            <div>
                <h4 style="font-size:13px;color:#7C3AED;margin:0 0 8px;border-bottom:1px solid #EDE9FE;padding-bottom:4px;">3. عروض مجلس الإدارة</h4>
                <p style="font-size:12px;color:#6B7280;margin:0 0 6px;">عروض سعرية بقرار مجلس الإدارة (خصم كاش أو شروط تقسيط). تظهر تلقائياً في قسم الدفع عندما تكون مفعّلة.</p>
                <?php if (!empty($boardOffers)): ?>
                <div style="font-size:12px;color:#374151;">
                    <strong>العروض المتاحة:</strong>
                    <?php foreach ($boardOffers as $bo): ?>
                    <span style="background:#EDE9FE;padding:2px 8px;border-radius:4px;margin:0 2px;"><?= e($bo['title_ar']) ?></span>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <p style="font-size:12px;color:#9CA3AF;margin:0;">لا توجد عروض نشطة حالياً.</p>
                <?php endif; ?>
            </div>

        </div>
    </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' => 'clipboard-list', 'desc' => 'سجّل بيانات المدة والأسرة — سيتم حساب الرسوم وإرسالها للخزينة تلقائياً'],
        'foreign'  => ['route' => '/members/' . (int) $member->id . '/foreign/create', 'label' => 'تسجيل بيانات العضوية الأجنبية', 'icon' => 'globe', 'desc' => 'سجّل بيانات جواز السفر وسعر الصرف قبل السداد'],
        'sports'   => ['route' => '/members/' . (int) $member->id . '/sports/create', 'label' => 'تسجيل بيانات العضوية الرياضية', 'icon' => 'medal', 'desc' => 'سجّل بيانات الرياضة والاتحاد قبل السداد'],
        'honorary' => ['route' => '/members/' . (int) $member->id . '/honorary/create', 'label' => 'تسجيل بيانات العضوية الشرفية', 'icon' => 'award', '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;"><i data-lucide="bar-chart-3" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> تفصيل المبلغ:</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, 'الإجمالي') || 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>
        <?php if (!empty($bestOffer)): ?>
        <div style="background:linear-gradient(135deg,#FEF3C7,#FDE68A);border:1px solid #F59E0B;border-radius:8px;padding:10px 15px;margin-bottom:15px;display:flex;align-items:center;gap:10px;">
            <span style="font-size:20px;">&#x1f381;</span>
            <div>
                <strong style="color:#92400E;font-size:13px;">عرض مجلس الإدارة: <?= e($bestOffer['title_ar']) ?></strong>
                <?php if ($bestOffer['board_decision_number']): ?>
                <span style="color:#78350F;font-size:11px;margin-right:8px;">(قرار <?= e($bestOffer['board_decision_number']) ?>)</span>
                <?php endif; ?>
                <div style="font-size:11px;color:#92400E;margin-top:2px;">ساري حتى <?= e($bestOffer['effective_to']) ?></div>
            </div>
        </div>
        <?php endif; ?>

        <?php if (!empty($offerTiers)): ?>
        <!-- ═══ Multi-Tier Payment Options ═══ -->
        <div style="display:grid;grid-template-columns:repeat(<?= min(count($offerTiers), 4) ?>, 1fr);gap:12px;">
        <?php foreach ($offerTiers as $tierIdx => $tier):
            $bd = $tier['breakdown'];
            $isCash = $bd['payment_type'] === 'cash';
            $borderColor = $isCash ? '#059669' : '#0284C7';
            $headerColor = $isCash ? '#059669' : '#0284C7';
        ?>
            <div style="background:#fff;border:2px solid <?= $borderColor ?>;border-radius:12px;padding:16px;display:flex;flex-direction:column;">
                <div style="text-align:center;margin-bottom:10px;">
                    <div style="font-size:11px;color:#6B7280;margin-bottom:2px;">العرض <?= (int) $tier['tier_order'] ?></div>
                    <h5 style="margin:0;color:<?= $headerColor ?>;font-size:13px;"><?= e($tier['tier_name_ar']) ?></h5>
                </div>

                <?php if ($isCash): ?>
                <div style="text-align:center;flex:1;">
                    <div style="font-size:12px;color:#6B7280;text-decoration:line-through;"><?= money($bd['original']) ?></div>
                    <div style="font-size:22px;font-weight:700;color:#059669;margin:4px 0;"><?= money($bd['amount_due']) ?></div>
                    <div style="font-size:11px;color:#059669;background:#ECFDF5;display:inline-block;padding:2px 8px;border-radius:4px;">&#x2714; وفّرت <?= money($bd['savings']) ?></div>
                </div>
                <?php else: ?>
                <div style="background:#EFF6FF;border:1px solid #BFDBFE;border-radius:8px;padding:8px 10px;font-size:11px;flex:1;">
                    <table style="width:100%;border-collapse:collapse;">
                        <tr><td style="color:#6B7280;padding:2px 0;">المقدم (<?= (float) $bd['down_pct'] ?>%)</td><td style="text-align:left;font-weight:600;color:#059669;"><?= money($bd['down_payment']) ?></td></tr>
                        <tr><td style="color:#6B7280;padding:2px 0;">المتبقي</td><td style="text-align:left;font-weight:600;"><?= money($bd['remaining']) ?></td></tr>
                        <?php if (bccomp($bd['interest_rate'], '0', 2) > 0): ?>
                        <tr><td style="color:#6B7280;padding:2px 0;">الفائدة (<?= (float) $bd['interest_rate'] ?>%)</td><td style="text-align:left;color:#D97706;font-weight:600;"><?= money($bd['interest_total']) ?></td></tr>
                        <?php else: ?>
                        <tr><td style="color:#7C3AED;padding:2px 0;">&#x1f389; بدون فوائد</td><td style="text-align:left;color:#7C3AED;font-weight:600;">0 ج.م</td></tr>
                        <?php endif; ?>
                        <tr style="border-top:1px solid #BFDBFE;"><td style="color:#374151;font-weight:700;padding:3px 0;">القسط الشهري</td><td style="text-align:left;font-weight:800;color:#0284C7;font-size:13px;"><?= money($bd['monthly']) ?></td></tr>
                        <tr><td style="color:#6B7280;padding:2px 0;">الإجمالي</td><td style="text-align:left;font-weight:600;"><?= money($bd['grand_total']) ?></td></tr>
                    </table>
                </div>
                <?php endif; ?>

                <form method="POST" action="/members/<?= (int) $member->id ?>/pay-membership" style="margin-top:10px;">
                    <?= csrf_field() ?>
                    <input type="hidden" name="payment_type" value="<?= $isCash ? e($paymentTypeForType) : 'down_payment' ?>">
                    <input type="hidden" name="amount" value="<?= e($isCash ? $bd['amount_due'] : $bd['down_payment']) ?>">
                    <input type="hidden" name="board_offer_id" value="<?= (int) $bestOffer['id'] ?>">
                    <input type="hidden" name="offer_tier_id" value="<?= (int) $tier['id'] ?>">
                    <?php if (!$isCash): ?>
                    <input type="hidden" name="installment_months" value="<?= (int) $bd['months'] ?>">
                    <?php endif; ?>
                    <button type="submit" class="btn btn-primary"
                            style="width:100%;background:#D97706;border-color:#D97706;font-size:12px;padding:8px;"
                            onclick="return confirm('إرسال طلب دفع <?= $isCash ? money($bd['amount_due']) : money($bd['down_payment']) . ' مقدم + ' . $bd['months'] . ' شهر' ?> للخزينة؟')">
                        &#x1f4e4; إرسال للخزينة
                    </button>
                </form>
            </div>
        <?php endforeach; ?>
        </div>

        <?php else: ?>
        <!-- ═══ Legacy Fallback (no tiers configured) ═══ -->
        <?php
        $cashAmount = $bill['total_pending'];
        $cashSavings = '0.00';
        if (!empty($cashDiscount) && bccomp($cashDiscount['savings'], '0', 2) > 0) {
            $cashAmount = $cashDiscount['discounted'];
            $cashSavings = $cashDiscount['savings'];
        }
        ?>
        <div style="display:grid;grid-template-columns:<?= $allowInstallment ? '1fr 1fr' : '1fr' ?>;gap:20px;">
            <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>
                <?php if (bccomp($cashSavings, '0', 2) > 0): ?>
                <div style="font-size:14px;color:#6B7280;text-decoration:line-through;margin-bottom:4px;"><?= money($bill['total_pending']) ?></div>
                <div style="font-size:24px;font-weight:700;color:#059669;margin-bottom:4px;"><?= money($cashAmount) ?></div>
                <div style="font-size:12px;color:#059669;background:#ECFDF5;display:inline-block;padding:2px 8px;border-radius:4px;margin-bottom:15px;">&#x2714; وفّرت <?= money($cashSavings) ?></div>
                <?php else: ?>
                <div style="font-size:24px;font-weight:700;color:#059669;margin-bottom:15px;"><?= money($cashAmount) ?></div>
                <?php endif; ?>
                <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($cashAmount) ?>">
                    <?php if (!empty($bestOffer)): ?><input type="hidden" name="board_offer_id" value="<?= (int) $bestOffer['id'] ?>"><?php endif; ?>
                    <button type="submit" class="btn btn-primary" style="width:100%;background:#D97706;border-color:#D97706;" onclick="return confirm('إرسال طلب دفع <?= money($cashAmount) ?> للخزينة؟')">&#x1f4e4; إرسال للخزينة</button>
                </form>
            </div>
            <?php if ($allowInstallment): ?>
            <?php
            $instRate     = (float) ($installmentTerms['interest_rate'] ?? $installInterestRate ?? 22);
            $instMaxMos   = (int) ($installmentTerms['max_months'] ?? $installMaxMonths ?? 30);
            $instDownPct  = (float) ($installmentTerms['down_pct'] ?? 25);
            $instGraceType = $installmentTerms['grace_type'] ?? null;
            $instGraceMonths = (int) ($installmentTerms['grace_months'] ?? 0);
            $minDown      = bcdiv(bcmul($bill['total_pending'], (string) $instDownPct, 2), '100', 2);
            $instRem      = bcsub($bill['total_pending'], $minDown, 2);
            $instInterest = bcmul(bcmul($instRem, bcdiv((string) $instRate, '100', 8), 8), bcdiv((string) $instMaxMos, '12', 8), 2);
            if ($instGraceType === 'full_free_under_n' && $instMaxMos <= $instGraceMonths) {
                $instInterest = '0.00';
            }
            $instTotalWI  = bcadd($instRem, $instInterest, 2);
            $instMonthly  = bcdiv($instTotalWI, (string) $instMaxMos, 2);
            ?>
            <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;">مقدم <?= $instDownPct ?>% + باقي على أقساط</p>
                <p style="font-size:11px;color:#D97706;margin:0 0 12px;">فائدة <?= $instRate ?>% سنوياً — حتى <?= $instMaxMos ?> شهر</p>
                <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;color:#059669;" id="inst_down_disp"><?= money($minDown) ?></td></tr>
                        <tr><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 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">
                    <?php if (!empty($bestOffer)): ?><input type="hidden" name="board_offer_id" value="<?= (int) $bestOffer['id'] ?>"><?php endif; ?>
                    <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']) ?>, RATE = <?= json_encode((float) $instRate) ?>, MIN_DOWN = <?= json_encode((float) $minDown) ?>;
                var GRACE_TYPE = <?= json_encode($instGraceType) ?>, GRACE_MOS = <?= json_encode($instGraceMonths) ?>;
                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 effectiveRate = RATE;
                    if (GRACE_TYPE === 'full_free_under_n' && months <= GRACE_MOS) effectiveRate = 0;
                    var totalInterest = Math.round(remaining * (effectiveRate / 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_monthly_disp').textContent = fmt(monthly);
                    document.getElementById('inst_interest_label').textContent = 'الفائدة (' + effectiveRate + '% × ' + months + ' شهر)';
                    document.getElementById('inst_monthly_label').textContent = 'القسط الشهري (÷ ' + months + ')';
                };
            })();
            </script>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <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;"><i data-lucide="clipboard-check" style="width:14px;height:14px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> الفاتورة جاهزة — في انتظار قرار مجلس الأمناء قبل السداد</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, 'الإجمالي') || 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;"><i data-lucide="user" style="width:14px;height:14px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> البيانات الشخصية</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>
    <?php if (can('member.view_financial')): ?>
    <div class="card">
        <div style="padding:15px 20px;">
            <a href="/payments/member/<?= (int) $member->id ?>" class="btn btn-outline" style="width:100%;text-align:center;"><i data-lucide="scroll-text" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> سجل المدفوعات</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;"><i data-lucide="clipboard-list" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> سجل مدفوعات العضو المتوفي (<?= e($deathTransfer['deceased_member_name'] ?? '') ?>)</a>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</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;"><i data-lucide="zap" style="width:14px;height:14px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> الإجراءات</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;"><i data-lucide="clipboard-list" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> الاستمارة</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <a href="/members/<?= (int) $member->id ?>/fill-form" class="btn btn-primary"><i data-lucide="file-edit" style="width:14px;height:14px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> ملء الاستمارة</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;"><i data-lucide="users" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> الأسرة</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"><i data-lucide="heart" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> إضافة زوج/ة</a>
                <?php endif; ?>
                <?php if (can('child.add')): ?>
                <a href="/members/<?= (int) $member->id ?>/children/create" class="btn btn-sm btn-outline"><i data-lucide="baby" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> إضافة ابن/ة</a>
                <?php endif; ?>
                <?php if (can('temp.add')): ?>
                <a href="/members/<?= (int) $member->id ?>/temporary/create" class="btn btn-sm btn-outline"><i data-lucide="user-plus" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> إضافة عضو مؤقت</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;"><i data-lucide="calendar" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> المقابلة والمراجعة</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <a href="/interviews/schedule/<?= (int) $member->id ?>" class="btn btn-sm btn-outline"><i data-lucide="calendar" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> تحديد مقابلة</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;"><i data-lucide="wallet" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> المالية</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"><i data-lucide="wallet" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> تسجيل دفعة</a>
                <?php endif; ?>
                <?php if (can('payment.view')): ?>
                <a href="/payments/member/<?= (int) $member->id ?>" class="btn btn-sm btn-outline"><i data-lucide="scroll-text" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> سجل المدفوعات</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"><i data-lucide="calendar-range" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> خطة تقسيط</a>
                    <?php endif; ?>
                    <?php if (can('subscription.view')): ?>
                    <a href="/members/<?= (int) $member->id ?>/subscriptions" class="btn btn-sm btn-outline"><i data-lucide="refresh-cw" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> الاشتراكات</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;"><i data-lucide="folder" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> المستندات والكارنيه</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"><i data-lucide="upload" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> رفع مستندات</a>
                <?php endif; ?>
                <?php if (can('document.view')): ?>
                <a href="/documents/member/<?= (int) $member->id ?>" class="btn btn-sm btn-outline"><i data-lucide="folder-open" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> عرض المستندات</a>
                <?php endif; ?>
                <?php if ($isActive && can('carnet.issue')): ?>
                    <a href="/carnets/issue/<?= (int) $member->id ?>" class="btn btn-sm btn-outline"><i data-lucide="id-card" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> إصدار كارنيه</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;"><i data-lucide="alert-triangle" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> المخالفات والغرامات</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;"><i data-lucide="alert-triangle" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> تسجيل مخالفة</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;"><i data-lucide="arrow-right-left" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> التحويلات وأحداث الحياة</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"><i data-lucide="arrow-right-left" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> طلب تحويل/فصل</a>
                <?php endif; ?>
                <?php if (can('member.change_status')): ?>
                <a href="/divorce/create/<?= (int) $member->id ?>" class="btn btn-sm btn-outline"><i data-lucide="heart-crack" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> تسجيل طلاق</a>
                <a href="/death/create/<?= (int) $member->id ?>" class="btn btn-sm btn-outline" style="color:#6B7280;"><i data-lucide="cloud" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> تسجيل وفاة</a>
                <?php endif; ?>
                <?php if (can('waiver.initiate')): ?>
                <a href="/waivers/create/<?= (int) $member->id ?>" class="btn btn-sm btn-outline"><i data-lucide="send" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> طلب تنازل</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;"><i data-lucide="archive" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> الأرشيف والمراجعة</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;"><i data-lucide="clipboard-list" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> السجل التأميني</a>
                <a href="/audit/entity/members/<?= (int) $member->id ?>" class="btn btn-sm btn-outline"><i data-lucide="scroll-text" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> سجل المراجعة</a>
                <a href="/archive/entity/members/<?= (int) $member->id ?>" class="btn btn-sm btn-outline"><i data-lucide="archive" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> اللقطات الأرشيفية</a>
                <?php if ($member->membership_number): ?>
                    <a href="/archive/number-chain/<?= urlencode($member->membership_number) ?>" class="btn btn-sm btn-outline"><i data-lucide="link" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> سلسلة رقم العضوية</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════ -->
<!-- FAMILY TREE — unified display of all dependants -->
<!-- ═══════════════════════════════════════════════ -->
<?php
$activeChildrenCount = count(array_filter($children, fn($c) => empty($c['is_archived']) && !in_array($c['status'] ?? '', ['separated', 'deceased'])));
$totalDependants = count($spouses) + $activeChildrenCount + 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;"><i data-lucide="lock" style="width:12px;height:12px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> البيانات مقفلة بعد تفعيل العضوية</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;
            $_sHasPhoto = !empty($s['photo_path']);
            $_sInitials = mb_substr($s['full_name_ar'], 0, 2);
            $_sIsDeceased = ($s['status'] ?? '') === 'deceased';
        ?>
        <tr <?php if ($_sIsDeceased): ?>style="opacity:0.5;background:#F9FAFB;"<?php elseif ($sBreakdown): ?>style="cursor:pointer;" onclick="toggleBillDetail('spouse-<?= $sIdx ?>')"<?php endif; ?>>
            <td><?= (int) $s['spouse_order'] ?></td>
            <td style="font-weight:600;"><div style="display:flex;align-items:center;gap:8px;">
                <div style="position:relative;flex-shrink:0;" class="dep-photo-wrap">
                    <div style="width:36px;height:36px;border-radius:50%;overflow:hidden;background:<?= $_sHasPhoto ? '#F3F4F6' : 'linear-gradient(135deg, #EC4899, #F472B6)' ?>;display:flex;align-items:center;justify-content:center;border:2px solid <?= $_sHasPhoto ? '#0D7377' : '#F9A8D4' ?>;box-shadow:0 1px 4px rgba(0,0,0,0.08);"><?php if ($_sHasPhoto): ?><img src="/<?= e($s['photo_path']) ?>" style="width:100%;height:100%;object-fit:cover;"><?php else: ?><span style="font-size:13px;font-weight:700;color:#fff;"><?= e($_sInitials) ?></span><?php endif; ?></div>
                    <?php if ($canEdit): ?>
                    <label class="dep-photo-btn" style="position:absolute;bottom:-4px;right:-4px;width:18px;height:18px;border-radius:50%;background:#0D7377;border:1.5px solid #fff;display:none;align-items:center;justify-content:center;cursor:pointer;" title="رفع صورة">
                        <svg xmlns="http://www.w3.org/2000/svg" width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="3"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
                        <form method="POST" action="/members/<?= (int) $member->id ?>/spouses/<?= (int) $s['id'] ?>/photo" enctype="multipart/form-data" style="display:none;">
                            <?= csrf_field() ?>
                            <input type="file" name="photo" accept="image/jpeg,image/png,image/webp" onchange="this.form.submit();">
                        </form>
                    </label>
                    <?php if ($_sHasPhoto): ?>
                    <form method="POST" action="/members/<?= (int) $member->id ?>/spouses/<?= (int) $s['id'] ?>/photo/delete" class="dep-photo-del" style="position:absolute;top:-4px;right:-4px;display:none;" onsubmit="return confirm('حذف الصورة؟')">
                        <?= csrf_field() ?>
                        <button type="submit" style="width:16px;height:16px;border-radius:50%;background:#DC2626;border:1.5px solid #fff;display:flex;align-items:center;justify-content:center;cursor:pointer;padding:0;" title="حذف">
                            <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="3"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                        </button>
                    </form>
                    <?php endif; ?>
                    <?php endif; ?>
                </div>
                <span><?= e($s['full_name_ar']) ?></span>
            </div></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
                $sIsDeceased = ($s['status'] ?? '') === 'deceased';
                $sKey = 'spouses:' . (int) $s['id'];
                $sInQueue = isset($pendingAdditions[$sKey]);
                $sInCombined = ($s['status'] === 'pending_payment' && !empty($pendingMembership));
                if ($sIsDeceased): ?>
                    <span style="color:#DC2626;font-weight:600;font-size:12px;">&#x25cf; متوفية</span>
                <?php elseif ($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;">
                <?php if ($sIsDeceased && isset($dependentDeathCases['spouse:' . (int) $s['id']])): ?>
                    <?php $spouseDeath = $dependentDeathCases['spouse:' . (int) $s['id']]; ?>
                    <a href="/death/<?= (int) $spouseDeath['id'] ?>" class="btn btn-sm" style="background:#DC2626;color:#fff;border-color:#DC2626;font-size:11px;" title="تاريخ الوفاة: <?= e($spouseDeath['death_date']) ?>">حالة الوفاة</a>
                <?php else: ?>
                    <a href="/members/<?= (int) $member->id ?>/spouses/<?= (int) $s['id'] ?>" class="btn btn-sm btn-outline">عرض</a>
                <?php endif; ?>
            </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, 'الإجمالي') || 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;">
        <?php
        $activeChildren = array_filter($children, fn($c) => empty($c['is_archived']) && !in_array($c['status'] ?? '', ['separated', 'deceased']));
        $inactiveChildren = array_filter($children, fn($c) => !empty($c['is_archived']) || in_array($c['status'] ?? '', ['separated', 'deceased']));
        ?>
        <div style="font-size:12px;color:#0D7377;font-weight:700;margin-bottom:10px;text-transform:uppercase;">&#x1f476; الأبناء (<?= count($activeChildren) ?><?= !empty($inactiveChildren) ? ' <span style="color:#6B7280;font-weight:500;">+ ' . count($inactiveChildren) . ' سابق</span>' : '' ?>)</div>
        <?php
        $childrenOver25Male = array_filter($children, function($c) {
            return ($c['gender'] ?? '') === 'male'
                && ($c['status'] ?? '') === 'active'
                && empty($c['is_archived'])
                && (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;
            $cIsSeparated = ($c['status'] ?? '') === 'separated';
            $cIsDeceased = ($c['status'] ?? '') === 'deceased';
            $cIsArchived = !empty($c['is_archived']) && !$cIsSeparated && !$cIsDeceased;
            $cIsInactive = $cIsArchived || $cIsSeparated || $cIsDeceased;
            $_cHasPhoto = !empty($c['photo_path']);
            $_cInitials = mb_substr($c['full_name_ar'], 0, 2);
            $_cGradient = ($c['gender'] === 'male') ? 'linear-gradient(135deg, #3B82F6, #60A5FA)' : 'linear-gradient(135deg, #EC4899, #F472B6)';
            $_cBorder = ($c['gender'] === 'male') ? '#93C5FD' : '#F9A8D4';
        ?>
        <tr <?= $cBreakdown && !$cIsInactive ? 'style="cursor:pointer;" onclick="toggleBillDetail(\'child-' . $cIdx . '\')"' : '' ?> <?= $cIsInactive ? 'style="opacity:0.5;background:#F9FAFB;"' : '' ?>>
            <td><?= (int) $c['child_order'] ?></td>
            <td style="font-weight:600;"><div style="display:flex;align-items:center;gap:8px;">
                <div style="position:relative;flex-shrink:0;" class="dep-photo-wrap">
                    <div style="width:36px;height:36px;border-radius:50%;overflow:hidden;background:<?= $_cHasPhoto ? '#F3F4F6' : $_cGradient ?>;display:flex;align-items:center;justify-content:center;border:2px solid <?= $_cHasPhoto ? '#0D7377' : $_cBorder ?>;box-shadow:0 1px 4px rgba(0,0,0,0.08);"><?php if ($_cHasPhoto): ?><img src="/<?= e($c['photo_path']) ?>" style="width:100%;height:100%;object-fit:cover;"><?php else: ?><span style="font-size:13px;font-weight:700;color:#fff;"><?= e($_cInitials) ?></span><?php endif; ?></div>
                    <?php if ($canEdit && !$cIsInactive): ?>
                    <label class="dep-photo-btn" style="position:absolute;bottom:-4px;right:-4px;width:18px;height:18px;border-radius:50%;background:#0D7377;border:1.5px solid #fff;display:none;align-items:center;justify-content:center;cursor:pointer;" title="رفع صورة">
                        <svg xmlns="http://www.w3.org/2000/svg" width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="3"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
                        <form method="POST" action="/members/<?= (int) $member->id ?>/children/<?= (int) $c['id'] ?>/photo" enctype="multipart/form-data" style="display:none;">
                            <?= csrf_field() ?>
                            <input type="file" name="photo" accept="image/jpeg,image/png,image/webp" onchange="this.form.submit();">
                        </form>
                    </label>
                    <?php if ($_cHasPhoto): ?>
                    <form method="POST" action="/members/<?= (int) $member->id ?>/children/<?= (int) $c['id'] ?>/photo/delete" class="dep-photo-del" style="position:absolute;top:-4px;right:-4px;display:none;" onsubmit="return confirm('حذف الصورة؟')">
                        <?= csrf_field() ?>
                        <button type="submit" style="width:16px;height:16px;border-radius:50%;background:#DC2626;border:1.5px solid #fff;display:flex;align-items:center;justify-content:center;cursor:pointer;padding:0;" title="حذف">
                            <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="3"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                        </button>
                    </form>
                    <?php endif; ?>
                    <?php endif; ?>
                </div>
                <div><?= e($c['full_name_ar']) ?>
                <?php if ($cIsSeparated && !empty($c['separated_membership_number'])): ?>
                    <a href="/members/<?= (int) $c['separated_member_id'] ?>" style="display:block;font-size:11px;color:#0D7377;font-weight:600;margin-top:2px;">عضوية #<?= e($c['separated_membership_number']) ?></a>
                <?php endif; ?>
            </div></div></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
                if ($cIsInactive) {
                    echo '<span style="color:#9CA3AF;">—</span>';
                } else {
                    $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 if ($cIsDeceased): ?>
                    <span style="color:#DC2626;font-weight:600;font-size:12px;">&#x25cf; متوفي</span>
                <?php elseif ($cIsSeparated): ?>
                    <span style="color:#6B7280;font-weight:600;font-size:12px;">&#x25cf; مفصول</span>
                <?php elseif ($cIsArchived): ?>
                    <span style="color:#6B7280;font-weight:600;font-size:12px;">&#x25cf; محذوف</span>
                <?php else:
                    $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;
                endif; ?>
            </td>
            <td style="white-space:nowrap;">
                <?php if ($cIsSeparated && !empty($c['separated_member_id'])): ?>
                    <a href="/members/<?= (int) $c['separated_member_id'] ?>" class="btn btn-sm btn-outline" style="color:#0D7377;">الملف</a>
                <?php elseif ($cIsDeceased && isset($dependentDeathCases['child:' . (int) $c['id']])): ?>
                    <?php $childDeath = $dependentDeathCases['child:' . (int) $c['id']]; ?>
                    <a href="/death/<?= (int) $childDeath['id'] ?>" class="btn btn-sm" style="background:#DC2626;color:#fff;border-color:#DC2626;font-size:11px;" title="تاريخ الوفاة: <?= e($childDeath['death_date']) ?>">حالة الوفاة</a>
                <?php elseif (!$cIsInactive): ?>
                    <a href="/members/<?= (int) $member->id ?>/children/<?= (int) $c['id'] ?>" class="btn btn-sm btn-outline">عرض</a>
                <?php endif; ?>
            </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, 'الإجمالي') || 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;
            $_tHasPhoto = !empty($t['photo_path']);
            $_tInitials = mb_substr($t['full_name_ar'], 0, 2);
            $_tGradient = ($t['gender'] === 'male') ? 'linear-gradient(135deg, #8B5CF6, #A78BFA)' : 'linear-gradient(135deg, #F59E0B, #FBBF24)';
            $_tBorder = ($t['gender'] === 'male') ? '#C4B5FD' : '#FDE68A';
        ?>
        <tr <?= $tBreakdown ? 'style="cursor:pointer;" onclick="toggleBillDetail(\'temp-' . $tIdx . '\')"' : '' ?>>
            <td style="font-weight:600;"><div style="display:flex;align-items:center;gap:8px;">
                <div style="position:relative;flex-shrink:0;" class="dep-photo-wrap">
                    <div style="width:36px;height:36px;border-radius:50%;overflow:hidden;background:<?= $_tHasPhoto ? '#F3F4F6' : $_tGradient ?>;display:flex;align-items:center;justify-content:center;border:2px solid <?= $_tHasPhoto ? '#0D7377' : $_tBorder ?>;box-shadow:0 1px 4px rgba(0,0,0,0.08);"><?php if ($_tHasPhoto): ?><img src="/<?= e($t['photo_path']) ?>" style="width:100%;height:100%;object-fit:cover;"><?php else: ?><span style="font-size:13px;font-weight:700;color:#fff;"><?= e($_tInitials) ?></span><?php endif; ?></div>
                    <?php if ($canEdit): ?>
                    <label class="dep-photo-btn" style="position:absolute;bottom:-4px;right:-4px;width:18px;height:18px;border-radius:50%;background:#0D7377;border:1.5px solid #fff;display:none;align-items:center;justify-content:center;cursor:pointer;" title="رفع صورة">
                        <svg xmlns="http://www.w3.org/2000/svg" width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="3"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
                        <form method="POST" action="/members/<?= (int) $member->id ?>/temporary/<?= (int) $t['id'] ?>/photo" enctype="multipart/form-data" style="display:none;">
                            <?= csrf_field() ?>
                            <input type="file" name="photo" accept="image/jpeg,image/png,image/webp" onchange="this.form.submit();">
                        </form>
                    </label>
                    <?php if ($_tHasPhoto): ?>
                    <form method="POST" action="/members/<?= (int) $member->id ?>/temporary/<?= (int) $t['id'] ?>/photo/delete" class="dep-photo-del" style="position:absolute;top:-4px;right:-4px;display:none;" onsubmit="return confirm('حذف الصورة؟')">
                        <?= csrf_field() ?>
                        <button type="submit" style="width:16px;height:16px;border-radius:50%;background:#DC2626;border:1.5px solid #fff;display:flex;align-items:center;justify-content:center;cursor:pointer;padding:0;" title="حذف">
                            <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="3"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                        </button>
                    </form>
                    <?php endif; ?>
                    <?php endif; ?>
                </div>
                <span><?= e($t['full_name_ar']) ?></span>
            </div></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, 'الإجمالي') || 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;"><i data-lucide="refresh-cw" style="width:14px;height:14px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> تغيير الحالة</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;"><i data-lucide="send" style="width:14px;height:14px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> هذه العضوية ناتجة عن تنازل</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;">
                <i data-lucide="archive" style="width:13px;height:13px;display:inline-block;vertical-align:middle;margin-left:3px;"></i> عرض أرشيف العضو السابق
            </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; ?>

<style>
.dep-photo-wrap:hover .dep-photo-btn,
.dep-photo-wrap:hover .dep-photo-del { display: flex !important; }
</style>
<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(); ?>