<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>تنازل #<?= (int) $waiver['id'] ?><?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>

<?php
$statusColor = match($waiver['status']) { 'completed' => '#059669', 'fee_paid' => '#2563EB', 'approved' => '#0284C7', 'rejected' => '#DC2626', default => '#D97706' };
$statusLabel = match($waiver['status']) { 'requested' => 'مقدم — في انتظار اعتماد مجلس الأمناء', 'approved' => 'معتمد — في انتظار إرسال للخزينة ودفع الرسوم', 'fee_paid' => '🟢 تم الدفع — بانتظار استكمال المتطلبات لاعتماد التنازل تلقائياً', 'completed' => 'مكتمل — تم نقل العضوية بنجاح', 'rejected' => 'مرفوض', default => $waiver['status'] };
$statusIcon = match($waiver['status']) { 'requested' => '⏳', 'approved' => '📋', 'fee_paid' => '🟢', 'completed' => '✅', 'rejected' => '❌', default => '●' };
?>

<!-- Status Banner -->
<div style="padding:14px 20px;background:<?= $statusColor ?>15;border:2px solid <?= $statusColor ?>;border-radius:10px;margin-bottom:20px;display:flex;align-items:center;gap:12px;">
    <span style="font-size:22px;"><?= $statusIcon ?></span>
    <div style="flex:1;">
        <span style="font-weight:700;font-size:16px;color:<?= $statusColor ?>;"><?= $statusLabel ?></span>
        <?php if ($waiver['status'] === 'fee_paid'): ?>
        <div style="margin-top:4px;font-size:12px;color:#059669;font-weight:600;">تم السداد — سيتم اعتماد التنازل تلقائياً فور استيفاء جميع الشروط</div>
        <?php endif; ?>
    </div>
    <?php if ($waiver['approved_by_name']): ?>
        <span style="font-size:12px;color:#6B7280;">بواسطة: <?= e($waiver['approved_by_name']) ?> — <?= arabic_date($waiver['approved_at'] ?? '') ?></span>
    <?php endif; ?>
</div>

<!-- SECTION 1: Detailed Debt Status -->
<?php if ($waiver['status'] !== 'completed' && $waiver['status'] !== 'rejected'): ?>
<?php if (!$source_debt_check['clear'] || ($target_debt_check && !$target_debt_check['clear'])): ?>
<div style="padding:18px;background:#FEF2F2;border:2px solid #DC2626;border-radius:10px;margin-bottom:20px;">
    <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">
        <span style="font-size:20px;">🚫</span>
        <strong style="color:#DC2626;font-size:15px;">يوجد مديونيات تمنع إتمام التنازل</strong>
    </div>

    <?php if (!$source_debt_check['clear']): ?>
    <div style="margin-bottom:15px;padding:12px;background:#fff;border:1px solid #FECACA;border-radius:8px;">
        <strong style="color:#7F1D1D;display:block;margin-bottom:8px;">المتنازل: <?= e($waiver['source_name'] ?? '') ?></strong>
        <table style="width:100%;font-size:13px;border-collapse:collapse;">
            <thead>
                <tr style="background:#FEE2E2;">
                    <th style="padding:6px 8px;text-align:right;">الشخص</th>
                    <th style="padding:6px 8px;text-align:right;">النوع</th>
                    <th style="padding:6px 8px;text-align:right;">نوع المديونية</th>
                    <th style="padding:6px 8px;text-align:center;">الفترة</th>
                    <th style="padding:6px 8px;text-align:left;">المبلغ</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($source_debt_check['debts'] as $debt): ?>
                <tr style="border-bottom:1px solid #FECACA;">
                    <td style="padding:6px 8px;font-weight:600;"><?= e($debt['person_name'] ?? '') ?></td>
                    <td style="padding:6px 8px;"><span style="background:#FEE2E2;color:#991B1B;padding:1px 6px;border-radius:3px;font-size:11px;"><?= e($debt['person_label'] ?? '') ?></span></td>
                    <td style="padding:6px 8px;"><?= e($debt['debt_type'] ?? '') ?></td>
                    <td style="padding:6px 8px;text-align:center;font-size:12px;color:#6B7280;"><?= e($debt['period'] ?? '') ?></td>
                    <td style="padding:6px 8px;text-align:left;color:#DC2626;font-weight:700;"><?= money($debt['amount']) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr style="border-top:2px solid #DC2626;background:#FEE2E2;">
                    <td colspan="4" style="padding:8px;font-weight:700;">إجمالي مديونية المتنازل</td>
                    <td style="padding:8px;font-weight:700;color:#DC2626;text-align:left;font-size:15px;"><?= money($source_debt_check['total']) ?></td>
                </tr>
            </tfoot>
        </table>
        <div style="margin-top:10px;text-align:left;">
            <a href="/payments/process/<?= (int) $waiver['source_member_id'] ?>" class="btn btn-outline" style="padding:6px 14px;font-size:12px;color:#DC2626;border-color:#DC2626;">
                الانتقال إلى السداد ←
            </a>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($target_debt_check && !$target_debt_check['clear']): ?>
    <div style="padding:12px;background:#fff;border:1px solid #FECACA;border-radius:8px;">
        <strong style="color:#7F1D1D;display:block;margin-bottom:8px;">المتنازل إليه: <?= e($waiver['target_name'] ?? '') ?></strong>
        <table style="width:100%;font-size:13px;border-collapse:collapse;">
            <thead>
                <tr style="background:#FEE2E2;">
                    <th style="padding:6px 8px;text-align:right;">الشخص</th>
                    <th style="padding:6px 8px;text-align:right;">النوع</th>
                    <th style="padding:6px 8px;text-align:right;">نوع المديونية</th>
                    <th style="padding:6px 8px;text-align:center;">الفترة</th>
                    <th style="padding:6px 8px;text-align:left;">المبلغ</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($target_debt_check['debts'] as $debt): ?>
                <tr style="border-bottom:1px solid #FECACA;">
                    <td style="padding:6px 8px;font-weight:600;"><?= e($debt['person_name'] ?? '') ?></td>
                    <td style="padding:6px 8px;"><span style="background:#FEE2E2;color:#991B1B;padding:1px 6px;border-radius:3px;font-size:11px;"><?= e($debt['person_label'] ?? '') ?></span></td>
                    <td style="padding:6px 8px;"><?= e($debt['debt_type'] ?? '') ?></td>
                    <td style="padding:6px 8px;text-align:center;font-size:12px;color:#6B7280;"><?= e($debt['period'] ?? '') ?></td>
                    <td style="padding:6px 8px;text-align:left;color:#DC2626;font-weight:700;"><?= money($debt['amount']) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr style="border-top:2px solid #DC2626;background:#FEE2E2;">
                    <td colspan="4" style="padding:8px;font-weight:700;">إجمالي مديونية المتنازل إليه</td>
                    <td style="padding:8px;font-weight:700;color:#DC2626;text-align:left;font-size:15px;"><?= money($target_debt_check['total']) ?></td>
                </tr>
            </tfoot>
        </table>
        <div style="margin-top:10px;text-align:left;">
            <a href="/payments/process/<?= (int) $waiver['target_member_id'] ?>" class="btn btn-outline" style="padding:6px 14px;font-size:12px;color:#DC2626;border-color:#DC2626;">
                الانتقال إلى السداد ←
            </a>
        </div>
    </div>
    <?php endif; ?>

    <p style="margin:12px 0 0;font-size:12px;color:#7F1D1D;">يجب سداد جميع المديونيات على الطرفين (بما فيها مديونيات التابعين) قبل إتمام التنازل.</p>
</div>
<?php else: ?>
<div style="padding:10px 15px;background:#F0FDF4;border:1px solid #BBF7D0;border-radius:8px;margin-bottom:20px;font-size:13px;color:#166534;display:flex;align-items:center;gap:8px;">
    <span style="font-size:16px;">✅</span>
    <span>لا توجد مديونيات على أي من الطرفين (بما فيها التابعين) — الوضع المالي سليم</span>
</div>
<?php endif; ?>
<?php endif; ?>

<!-- SECTION 2: Main Info -->
<div class="card" style="padding:20px;margin-bottom:20px;">
    <table style="width:100%;max-width:700px;font-size:14px;">
        <tr><td style="padding:8px 0;color:#6B7280;width:30%;">المتنازل</td><td style="padding:8px 0;"><a href="/members/<?= (int) $waiver['source_member_id'] ?>" style="color:#0D7377;font-weight:600;"><?= e($waiver['source_name'] ?? '') ?></a></td></tr>
        <tr><td style="padding:8px 0;color:#6B7280;">رقم العضوية</td><td style="padding:8px 0;font-weight:700;font-size:16px;"><?= e($waiver['membership_number'] ?? '—') ?></td></tr>
        <?php if ($waiver['target_member_id']): ?>
        <tr><td style="padding:8px 0;color:#6B7280;">المتنازل إليه (المشتري)</td><td style="padding:8px 0;"><a href="/members/<?= (int) $waiver['target_member_id'] ?>" style="color:#0D7377;font-weight:600;"><?= e($waiver['target_name'] ?? '') ?></a></td></tr>
        <?php endif; ?>
        <tr><td style="padding:8px 0;color:#6B7280;">تاريخ الطلب</td><td style="padding:8px 0;"><?= arabic_date($waiver['created_at'] ?? '') ?></td></tr>
        <?php if ($waiver['board_decision_reference']): ?>
        <tr><td style="padding:8px 0;color:#6B7280;">مرجع قرار مجلس الأمناء</td><td style="padding:8px 0;font-weight:600;"><?= e($waiver['board_decision_reference']) ?></td></tr>
        <?php endif; ?>
        <?php if ($waiver['notes']): ?>
        <tr><td style="padding:8px 0;color:#6B7280;">ملاحظات</td><td style="padding:8px 0;"><?= e($waiver['notes']) ?></td></tr>
        <?php endif; ?>
    </table>
</div>

<!-- SECTION 3: Dependents Comparison (counts) -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;font-size:15px;color:#0369A1;">👥 مقارنة التابعين (لكل فئة على حدة)</h3>
    </div>
    <div style="padding:20px;">
        <table style="width:100%;font-size:14px;border-collapse:collapse;">
            <thead>
                <tr style="background:#F0F9FF;border-bottom:2px solid #BAE6FD;">
                    <th style="padding:10px;text-align:right;color:#0369A1;">الفئة</th>
                    <th style="padding:10px;text-align:center;color:#0369A1;">المتنازل (الأصلي)</th>
                    <th style="padding:10px;text-align:center;color:#0369A1;">المتنازل إليه</th>
                    <th style="padding:10px;text-align:center;color:#0369A1;">الزيادة</th>
                    <th style="padding:10px;text-align:center;color:#0369A1;">الحالة</th>
                </tr>
            </thead>
            <tbody>
                <tr style="border-bottom:1px solid #E5E7EB;">
                    <td style="padding:10px;font-weight:600;">👩 الزوجات</td>
                    <td style="padding:10px;text-align:center;font-weight:700;"><?= (int) $original_deps['spouses'] ?></td>
                    <td style="padding:10px;text-align:center;font-weight:700;"><?= $target_deps ? $target_deps['spouses'] : '—' ?></td>
                    <?php $exSpouses = $target_deps ? max(0, $target_deps['spouses'] - $original_deps['spouses']) : 0; ?>
                    <td style="padding:10px;text-align:center;font-weight:700;color:<?= $exSpouses > 0 ? '#DC2626' : '#059669' ?>;"><?= $target_deps ? ($exSpouses > 0 ? '+' . $exSpouses : '0') : '—' ?></td>
                    <td style="padding:10px;text-align:center;"><?= $target_deps ? ($exSpouses > 0 ? '<span style="background:#FEF2F2;color:#DC2626;padding:2px 8px;border-radius:4px;font-size:12px;font-weight:600;">زائد</span>' : '<span style="background:#F0FDF4;color:#059669;padding:2px 8px;border-radius:4px;font-size:12px;font-weight:600;">ضمن الحد</span>') : '—' ?></td>
                </tr>
                <tr style="border-bottom:1px solid #E5E7EB;">
                    <td style="padding:10px;font-weight:600;">👶 الأبناء</td>
                    <td style="padding:10px;text-align:center;font-weight:700;"><?= (int) $original_deps['children'] ?></td>
                    <td style="padding:10px;text-align:center;font-weight:700;"><?= $target_deps ? $target_deps['children'] : '—' ?></td>
                    <?php $exChildren = $target_deps ? max(0, $target_deps['children'] - $original_deps['children']) : 0; ?>
                    <td style="padding:10px;text-align:center;font-weight:700;color:<?= $exChildren > 0 ? '#DC2626' : '#059669' ?>;"><?= $target_deps ? ($exChildren > 0 ? '+' . $exChildren : '0') : '—' ?></td>
                    <td style="padding:10px;text-align:center;"><?= $target_deps ? ($exChildren > 0 ? '<span style="background:#FEF2F2;color:#DC2626;padding:2px 8px;border-radius:4px;font-size:12px;font-weight:600;">زائد</span>' : '<span style="background:#F0FDF4;color:#059669;padding:2px 8px;border-radius:4px;font-size:12px;font-weight:600;">ضمن الحد</span>') : '—' ?></td>
                </tr>
                <tr style="border-bottom:1px solid #E5E7EB;">
                    <td style="padding:10px;font-weight:600;">👤 الأعضاء المؤقتون</td>
                    <td style="padding:10px;text-align:center;font-weight:700;"><?= (int) $original_deps['temporary'] ?></td>
                    <td style="padding:10px;text-align:center;font-weight:700;"><?= $target_deps ? $target_deps['temporary'] : '—' ?></td>
                    <?php $exTemp = $target_deps ? max(0, $target_deps['temporary'] - $original_deps['temporary']) : 0; ?>
                    <td style="padding:10px;text-align:center;font-weight:700;color:<?= $exTemp > 0 ? '#DC2626' : '#059669' ?>;"><?= $target_deps ? ($exTemp > 0 ? '+' . $exTemp : '0') : '—' ?></td>
                    <td style="padding:10px;text-align:center;"><?= $target_deps ? ($exTemp > 0 ? '<span style="background:#FEF2F2;color:#DC2626;padding:2px 8px;border-radius:4px;font-size:12px;font-weight:600;">زائد</span>' : '<span style="background:#F0FDF4;color:#059669;padding:2px 8px;border-radius:4px;font-size:12px;font-weight:600;">ضمن الحد</span>') : '—' ?></td>
                </tr>
                <tr style="border-top:2px solid #0D7377;background:#F0FDFA;">
                    <td style="padding:10px;font-weight:700;color:#0D7377;">الإجمالي</td>
                    <td style="padding:10px;text-align:center;font-weight:700;font-size:16px;color:#0D7377;"><?= (int) $original_deps['total'] ?></td>
                    <td style="padding:10px;text-align:center;font-weight:700;font-size:16px;color:#0D7377;"><?= $target_deps ? $target_deps['total'] : '—' ?></td>
                    <?php $exTotal = $exSpouses + $exChildren + $exTemp; ?>
                    <td style="padding:10px;text-align:center;font-weight:700;font-size:16px;color:<?= $exTotal > 0 ? '#DC2626' : '#059669' ?>;"><?= $target_deps ? ($exTotal > 0 ? '+' . $exTotal : '0') : '—' ?></td>
                    <td style="padding:10px;text-align:center;">
                        <?php if ($target_deps && $exTotal > 0): ?>
                            <span style="background:#FEF2F2;color:#DC2626;padding:3px 10px;border-radius:4px;font-size:12px;font-weight:700;">يتطلب رسوم إضافية</span>
                        <?php elseif ($target_deps): ?>
                            <span style="background:#F0FDF4;color:#059669;padding:3px 10px;border-radius:4px;font-size:12px;font-weight:700;">ضمن الحد المسموح</span>
                        <?php endif; ?>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<!-- SECTION 4: Children Details (name, age, DOB, category) -->
<?php if (($source_details && !empty($source_details['children'])) || ($target_details && !empty($target_details['children']))): ?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;font-size:15px;color:#7C3AED;">👶 تفاصيل الأبناء (مقارنة بالاسم والسن)</h3>
    </div>
    <div style="padding:20px;display:grid;grid-template-columns:1fr 1fr;gap:20px;">
        <!-- Source children -->
        <div>
            <h4 style="margin:0 0 10px;font-size:13px;color:#6B7280;">أبناء المتنازل (<?= e($waiver['source_name'] ?? '') ?>)</h4>
            <?php if (!empty($source_details['children'])): ?>
            <table style="width:100%;font-size:12px;border-collapse:collapse;">
                <thead><tr style="background:#F5F3FF;"><th style="padding:6px;text-align:right;">الاسم</th><th style="padding:6px;text-align:center;">تاريخ الميلاد</th><th style="padding:6px;text-align:center;">السن</th><th style="padding:6px;text-align:center;">الفئة العمرية</th></tr></thead>
                <tbody>
                <?php foreach ($source_details['children'] as $child): ?>
                <tr style="border-bottom:1px solid #EDE9FE;">
                    <td style="padding:6px;font-weight:600;"><?= e($child['full_name_ar'] ?? '') ?></td>
                    <td style="padding:6px;text-align:center;"><?= e($child['date_of_birth'] ?? '—') ?></td>
                    <td style="padding:6px;text-align:center;"><?= e($child['age_display'] ?? '—') ?></td>
                    <td style="padding:6px;text-align:center;">
                        <?php
                        $catColor = match($child['age_category_code'] ?? '') {
                            'under_12' => '#059669', '12_to_16' => '#0284C7', '16_to_18' => '#D97706', '18_plus' => '#DC2626', default => '#6B7280'
                        };
                        ?>
                        <span style="background:<?= $catColor ?>15;color:<?= $catColor ?>;padding:2px 6px;border-radius:3px;font-size:11px;font-weight:600;"><?= e($child['age_category'] ?? '') ?></span>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <p style="color:#9CA3AF;font-size:12px;">لا يوجد أبناء</p>
            <?php endif; ?>
        </div>

        <!-- Target children -->
        <div>
            <h4 style="margin:0 0 10px;font-size:13px;color:#6B7280;">أبناء المتنازل إليه (<?= e($waiver['target_name'] ?? '') ?>)</h4>
            <?php if ($target_details && !empty($target_details['children'])): ?>
            <table style="width:100%;font-size:12px;border-collapse:collapse;">
                <thead><tr style="background:#F5F3FF;"><th style="padding:6px;text-align:right;">الاسم</th><th style="padding:6px;text-align:center;">تاريخ الميلاد</th><th style="padding:6px;text-align:center;">السن</th><th style="padding:6px;text-align:center;">الفئة العمرية</th></tr></thead>
                <tbody>
                <?php foreach ($target_details['children'] as $child): ?>
                <tr style="border-bottom:1px solid #EDE9FE;">
                    <td style="padding:6px;font-weight:600;"><?= e($child['full_name_ar'] ?? '') ?></td>
                    <td style="padding:6px;text-align:center;"><?= e($child['date_of_birth'] ?? '—') ?></td>
                    <td style="padding:6px;text-align:center;"><?= e($child['age_display'] ?? '—') ?></td>
                    <td style="padding:6px;text-align:center;">
                        <?php
                        $catColor = match($child['age_category_code'] ?? '') {
                            'under_12' => '#059669', '12_to_16' => '#0284C7', '16_to_18' => '#D97706', '18_plus' => '#DC2626', default => '#6B7280'
                        };
                        ?>
                        <span style="background:<?= $catColor ?>15;color:<?= $catColor ?>;padding:2px 6px;border-radius:3px;font-size:11px;font-weight:600;"><?= e($child['age_category'] ?? '') ?></span>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <p style="color:#9CA3AF;font-size:12px;"><?= $target_details ? 'لا يوجد أبناء' : 'لم يُحدد المتنازل إليه بعد' ?></p>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- SECTION 5: Fee Breakdown -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:8px;">
        <i data-lucide="receipt" style="width:18px;height:18px;color:#D97706;"></i>
        <h3 style="margin:0;color:#D97706;font-size:15px;">تفصيل الرسوم</h3>
    </div>
    <div style="padding:20px;">
        <table style="width:100%;max-width:700px;font-size:14px;">
            <tr>
                <td style="padding:8px 0;color:#6B7280;">قيمة العضوية وقت التنازل</td>
                <td style="padding:8px 0;font-weight:600;text-align:left;" colspan="2"><?= money($waiver['membership_value_at_waiver'] ?? '0') ?></td>
            </tr>
            <tr>
                <td style="padding:8px 0;color:#6B7280;">نسبة رسوم التنازل</td>
                <td style="padding:8px 0;font-weight:600;" colspan="2"><?= e($waiver['waiver_fee_percentage'] ?? '30') ?>%</td>
            </tr>
            <tr style="border-bottom:1px dashed #E5E7EB;">
                <td style="padding:8px 0;color:#374151;font-weight:600;">رسوم التنازل الأساسية</td>
                <td style="padding:8px 0;font-size:12px;color:#6B7280;"><?= e($waiver['waiver_fee_percentage'] ?? '30') ?>% x <?= money($waiver['membership_value_at_waiver'] ?? '0') ?></td>
                <td style="padding:8px 0;font-weight:700;text-align:left;"><?= money($waiver['waiver_fee_amount'] ?? '0') ?></td>
            </tr>

            <?php
            $spouseFeeTotal = $waiver['spouse_fee_total'] ?? '0.00';
            $childFeeTotal = $waiver['child_fee_total'] ?? '0.00';
            $tempFeeTotal = $waiver['temporary_fee_total'] ?? '0.00';
            $hasPerCategoryFees = bccomp(bcadd(bcadd($spouseFeeTotal, $childFeeTotal, 2), $tempFeeTotal, 2), '0', 2) > 0;
            $hasIndividualFees = !empty($individual_fees);
            ?>

            <?php if ($hasIndividualFees): ?>
            <!-- Per-individual fee breakdown -->
            <?php
            $indSpouses = array_filter($individual_fees, fn($f) => $f['person_type'] === 'spouse');
            $indChildren = array_filter($individual_fees, fn($f) => $f['person_type'] === 'child');
            $indTemps = array_filter($individual_fees, fn($f) => $f['person_type'] === 'temporary');
            ?>
            <?php if (!empty($indSpouses)): ?>
            <tr style="background:#FDF2F8;"><td colspan="3" style="padding:6px 0;color:#9D174D;font-weight:700;font-size:12px;">👩 رسوم الزوجات الإضافيات</td></tr>
            <?php foreach ($indSpouses as $fee): ?>
            <tr style="background:#FEF2F2;">
                <td style="padding:6px 0;color:#DC2626;font-weight:600;font-size:13px;"><?= e($fee['person_name']) ?></td>
                <td style="padding:6px 0;font-size:12px;color:#7F1D1D;">
                    <?= ($fee['fee_type'] ?? '') === 'percentage' ? e($fee['fee_rate'] ?? '0') . '% من قيمة العضوية' : money($fee['fee_rate'] ?? '0') . ' (ثابت)' ?>
                </td>
                <td style="padding:6px 0;font-weight:700;color:#DC2626;text-align:left;"><?= money($fee['fee_amount'] ?? '0') ?></td>
            </tr>
            <?php endforeach; ?>
            <tr style="border-bottom:1px dashed #FECACA;"><td colspan="2" style="padding:4px 0;font-size:12px;color:#7F1D1D;font-weight:600;">إجمالي الزوجات</td><td style="padding:4px 0;font-weight:700;color:#DC2626;text-align:left;"><?= money($spouseFeeTotal) ?></td></tr>
            <?php endif; ?>

            <?php if (!empty($indChildren)): ?>
            <tr style="background:#EFF6FF;"><td colspan="3" style="padding:6px 0;color:#1E40AF;font-weight:700;font-size:12px;">👶 رسوم الأبناء الإضافيين</td></tr>
            <?php foreach ($indChildren as $fee): ?>
            <tr style="background:#FEF2F2;">
                <td style="padding:6px 0;color:#DC2626;font-weight:600;font-size:13px;"><?= e($fee['person_name']) ?> <?= $fee['age_years'] ? '(' . (int) $fee['age_years'] . ' سنة)' : '' ?></td>
                <td style="padding:6px 0;font-size:12px;color:#7F1D1D;">
                    <?= ($fee['fee_type'] ?? '') === 'percentage' ? e($fee['fee_rate'] ?? '0') . '% من قيمة العضوية' : money($fee['fee_rate'] ?? '0') . ' (ثابت)' ?>
                </td>
                <td style="padding:6px 0;font-weight:700;color:#DC2626;text-align:left;"><?= money($fee['fee_amount'] ?? '0') ?></td>
            </tr>
            <?php endforeach; ?>
            <tr style="border-bottom:1px dashed #FECACA;"><td colspan="2" style="padding:4px 0;font-size:12px;color:#7F1D1D;font-weight:600;">إجمالي الأبناء</td><td style="padding:4px 0;font-weight:700;color:#DC2626;text-align:left;"><?= money($childFeeTotal) ?></td></tr>
            <?php endif; ?>

            <?php if (!empty($indTemps)): ?>
            <tr style="background:#F0FDF4;"><td colspan="3" style="padding:6px 0;color:#166534;font-weight:700;font-size:12px;">👤 رسوم الأعضاء المؤقتين</td></tr>
            <?php foreach ($indTemps as $fee): ?>
            <tr style="background:#FEF2F2;">
                <td style="padding:6px 0;color:#DC2626;font-weight:600;font-size:13px;"><?= e($fee['person_name']) ?></td>
                <td style="padding:6px 0;font-size:12px;color:#7F1D1D;">
                    <?= ($fee['fee_type'] ?? '') === 'percentage' ? e($fee['fee_rate'] ?? '0') . '% من قيمة العضوية' : money($fee['fee_rate'] ?? '0') . ' (ثابت)' ?>
                </td>
                <td style="padding:6px 0;font-weight:700;color:#DC2626;text-align:left;"><?= money($fee['fee_amount'] ?? '0') ?></td>
            </tr>
            <?php endforeach; ?>
            <tr style="border-bottom:1px dashed #FECACA;"><td colspan="2" style="padding:4px 0;font-size:12px;color:#7F1D1D;font-weight:600;">إجمالي المؤقتين</td><td style="padding:4px 0;font-weight:700;color:#DC2626;text-align:left;"><?= money($tempFeeTotal) ?></td></tr>
            <?php endif; ?>

            <?php elseif ($hasPerCategoryFees): ?>
            <?php if (bccomp($spouseFeeTotal, '0', 2) > 0): ?>
            <tr style="background:#FEF2F2;"><td style="padding:8px 0;color:#DC2626;font-weight:600;">👩 رسوم زوجات إضافيات (<?= (int) ($waiver['excess_spouses_count'] ?? 0) ?>)</td><td style="padding:8px 0;font-size:12px;color:#7F1D1D;"><?= (int) ($waiver['excess_spouses_count'] ?? 0) ?> شخص</td><td style="padding:8px 0;font-weight:700;color:#DC2626;text-align:left;"><?= money($spouseFeeTotal) ?></td></tr>
            <?php endif; ?>
            <?php if (bccomp($childFeeTotal, '0', 2) > 0): ?>
            <tr style="background:#FEF2F2;"><td style="padding:8px 0;color:#DC2626;font-weight:600;">👶 رسوم أبناء إضافيين (<?= (int) ($waiver['excess_children_count'] ?? 0) ?>)</td><td style="padding:8px 0;font-size:12px;color:#7F1D1D;"><?= (int) ($waiver['excess_children_count'] ?? 0) ?> شخص</td><td style="padding:8px 0;font-weight:700;color:#DC2626;text-align:left;"><?= money($childFeeTotal) ?></td></tr>
            <?php endif; ?>
            <?php if (bccomp($tempFeeTotal, '0', 2) > 0): ?>
            <tr style="background:#FEF2F2;"><td style="padding:8px 0;color:#DC2626;font-weight:600;">👤 رسوم أعضاء مؤقتين (<?= (int) ($waiver['excess_temporary_count'] ?? 0) ?>)</td><td style="padding:8px 0;font-size:12px;color:#7F1D1D;"><?= (int) ($waiver['excess_temporary_count'] ?? 0) ?> شخص</td><td style="padding:8px 0;font-weight:700;color:#DC2626;text-align:left;"><?= money($tempFeeTotal) ?></td></tr>
            <?php endif; ?>

            <?php elseif (bccomp($waiver['excess_fee_amount'] ?? '0', '0', 2) > 0): ?>
            <tr style="background:#FEF2F2;">
                <td style="padding:8px 0;color:#DC2626;">رسوم تابعين إضافيين (<?= (int) ($waiver['excess_dependent_count'] ?? 0) ?> عضو)</td>
                <td style="padding:8px 0;"></td>
                <td style="padding:8px 0;font-weight:700;color:#DC2626;text-align:left;"><?= money($waiver['excess_fee_amount']) ?></td>
            </tr>
            <?php endif; ?>

            <?php
            $totalExcess = $hasPerCategoryFees
                ? bcadd(bcadd($spouseFeeTotal, $childFeeTotal, 2), $tempFeeTotal, 2)
                : ($waiver['excess_fee_amount'] ?? '0.00');
            $grandTotal = bcadd($waiver['waiver_fee_amount'] ?? '0', $totalExcess, 2);
            ?>
            <tr style="border-top:2px solid #0D7377;">
                <td style="padding:12px 0;font-weight:700;font-size:16px;" colspan="2">الإجمالي النهائي (يدفعه المتنازل إليه / المشتري)</td>
                <td style="padding:12px 0;font-weight:800;font-size:20px;color:#0D7377;text-align:left;">
                    <?= money($grandTotal) ?>
                </td>
            </tr>
        </table>
    </div>
</div>

<!-- Documents -->
<?php if (!empty($waiver['waiver_request_doc_path']) || !empty($waiver['target_form_doc_path'])): ?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;font-size:15px;color:#374151;">📄 المستندات المرفقة</h3>
    </div>
    <div style="padding:20px;display:flex;gap:20px;flex-wrap:wrap;">
        <?php if (!empty($waiver['waiver_request_doc_path'])): ?>
        <a href="/<?= e($waiver['waiver_request_doc_path']) ?>" target="_blank" style="display:flex;align-items:center;gap:8px;padding:10px 16px;background:#F3F4F6;border-radius:8px;text-decoration:none;color:#374151;">
            <i data-lucide="file-text" style="width:20px;height:20px;color:#0D7377;"></i>
            <span>استمارة طلب التنازل</span>
        </a>
        <?php endif; ?>
        <?php if (!empty($waiver['target_form_doc_path'])): ?>
        <a href="/<?= e($waiver['target_form_doc_path']) ?>" target="_blank" style="display:flex;align-items:center;gap:8px;padding:10px 16px;background:#F3F4F6;border-radius:8px;text-decoration:none;color:#374151;">
            <i data-lucide="file-text" style="width:20px;height:20px;color:#0D7377;"></i>
            <span>استمارة عضوية المتنازل إليه</span>
        </a>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<!-- SECTION 6: Send to Cashier (approved status, has target) -->
<?php if ($waiver['status'] === 'approved' && $waiver['target_member_id'] && bccomp($grandTotal, '0', 2) > 0 && can('waiver.approve')): ?>
<div class="card" style="padding:20px;margin-bottom:20px;background:#FFF7ED;border:2px solid #F59E0B;">
    <div style="display:flex;align-items:center;gap:10px;margin-bottom:12px;">
        <span style="font-size:20px;">💰</span>
        <h4 style="margin:0;color:#D97706;">إرسال طلب الدفع إلى الخزينة</h4>
    </div>
    <p style="font-size:13px;color:#92400E;margin:0 0 12px;">سيتم إنشاء طلب دفع باسم <strong>المتنازل إليه (المشتري): <?= e($waiver['target_name'] ?? '') ?></strong> بإجمالي <strong><?= money($grandTotal) ?></strong></p>
    <div style="padding:10px;background:#FFFBEB;border:1px solid #FDE68A;border-radius:6px;margin-bottom:12px;font-size:12px;color:#92400E;">
        <strong>سيتضمن الإيصال:</strong> رسوم التنازل<?= $hasPerCategoryFees ? ' + رسوم التابعين الإضافيين لكل فئة' : '' ?> + اسم المتنازل والمتنازل إليه + رقم العضوية
    </div>
    <form method="POST" action="/waivers/<?= (int) $waiver['id'] ?>/send-to-cashier" style="display:inline;">
        <?= csrf_field() ?>
        <button type="submit" class="btn btn-primary" style="background:#D97706;padding:10px 25px;" onclick="return confirm('إرسال طلب دفع <?= money($grandTotal) ?> باسم <?= e($waiver['target_name'] ?? '') ?> إلى الخزينة؟')">
            💰 إرسال للخزينة باسم المتنازل إليه
        </button>
    </form>
</div>
<?php endif; ?>

<!-- SECTION 7: Board Approval (per-individual fee assignment) -->
<?php if ($waiver['status'] === 'requested' && can('waiver.approve')): ?>
<div class="card" style="padding:20px;margin-bottom:20px;background:#EFF6FF;border:2px solid #3B82F6;">
    <h4 style="margin:0 0 15px;color:#1D4ED8;">🏛 اعتماد مجلس الأمناء</h4>
    <form method="POST" action="/waivers/<?= (int) $waiver['id'] ?>/approve" id="approve-form">
        <?= csrf_field() ?>

        <div class="form-group" style="margin-bottom:15px;">
            <label class="form-label">مرجع قرار مجلس الأمناء</label>
            <input type="text" name="board_decision_reference" class="form-input" placeholder="مثال: قرار جلسة 2026/06/15">
        </div>

        <?php if (!empty($excess_individuals)): ?>
        <div style="padding:15px;background:#FEF2F2;border:1px solid #FECACA;border-radius:8px;margin-bottom:15px;">
            <strong style="color:#DC2626;">⚠ يوجد تابعين زائدين — يجب تحديد الرسوم لكل فرد على حدة:</strong>
            <p style="font-size:12px;color:#7F1D1D;margin:5px 0 0;">قيمة العضوية الحالية: <strong><?= money($waiver['membership_value_at_waiver'] ?? '0') ?></strong> — يمكن تحديد مبلغ ثابت أو نسبة من قيمة العضوية لكل شخص بشكل مستقل</p>
        </div>

        <?php
        $spouseExcess = array_filter($excess_individuals, fn($p) => $p['person_type'] === 'spouse');
        $childExcess = array_filter($excess_individuals, fn($p) => $p['person_type'] === 'child');
        $tempExcess = array_filter($excess_individuals, fn($p) => $p['person_type'] === 'temporary');
        $indIdx = 0;
        ?>

        <!-- Spouse individuals -->
        <?php if (!empty($spouseExcess)): ?>
        <div style="margin-bottom:20px;">
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;padding:8px 12px;background:#FDF2F8;border-radius:6px;">
                <span style="font-size:18px;">👩</span>
                <strong style="color:#9D174D;">الزوجات الإضافيات (<?= count($spouseExcess) ?>)</strong>
            </div>
            <?php foreach ($spouseExcess as $person): ?>
            <div style="padding:14px;background:#fff;border:1px solid #E5E7EB;border-radius:8px;margin-bottom:10px;" class="ind-fee-card" data-idx="<?= $indIdx ?>">
                <div style="display:flex;align-items:center;gap:10px;margin-bottom:10px;">
                    <strong style="color:#374151;font-size:14px;"><?= e($person['person_name']) ?></strong>
                    <?php if (!empty($person['national_id'])): ?>
                    <span style="font-size:11px;color:#6B7280;">رقم قومي: <?= e($person['national_id']) ?></span>
                    <?php endif; ?>
                    <span style="background:#F0FDF4;color:#059669;padding:2px 6px;border-radius:3px;font-size:11px;"><?= e($person['status'] ?? 'active') ?></span>
                </div>
                <input type="hidden" name="ind_person_type[]" value="spouse">
                <input type="hidden" name="ind_person_id[]" value="<?= (int) $person['person_id'] ?>">
                <input type="hidden" name="ind_person_name[]" value="<?= e($person['person_name']) ?>">
                <input type="hidden" name="ind_person_order[]" value="<?= (int) $person['person_order'] ?>">
                <input type="hidden" name="ind_age_years[]" value="">
                <input type="hidden" name="ind_age_category_code[]" value="">
                <input type="hidden" name="ind_date_of_birth[]" value="">
                <input type="hidden" name="ind_relationship[]" value="">
                <input type="hidden" name="ind_status[]" value="<?= e($person['status'] ?? '') ?>">
                <div style="display:grid;grid-template-columns:1fr 1fr 120px;gap:10px;align-items:end;">
                    <div class="form-group" style="margin:0;">
                        <label class="form-label" style="font-size:12px;">طريقة الاحتساب</label>
                        <select name="ind_fee_type[]" class="form-select" required onchange="calcIndFee(<?= $indIdx ?>)">
                            <option value="">— اختر —</option>
                            <option value="fixed">مبلغ ثابت</option>
                            <option value="percentage">نسبة من قيمة العضوية</option>
                        </select>
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label class="form-label" style="font-size:12px;">القيمة</label>
                        <input type="number" name="ind_fee_rate[]" class="form-input" step="0.01" min="0" required oninput="calcIndFee(<?= $indIdx ?>)" data-idx="<?= $indIdx ?>">
                    </div>
                    <div style="text-align:center;padding:8px 0;">
                        <span style="font-size:12px;color:#6B7280;">= </span>
                        <strong class="ind-fee-result" id="ind-result-<?= $indIdx ?>" style="color:#0D7377;">0.00</strong>
                        <span style="font-size:11px;color:#6B7280;"> ج.م</span>
                    </div>
                </div>
            </div>
            <?php $indIdx++; endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Child individuals -->
        <?php if (!empty($childExcess)): ?>
        <div style="margin-bottom:20px;">
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;padding:8px 12px;background:#EFF6FF;border-radius:6px;">
                <span style="font-size:18px;">👶</span>
                <strong style="color:#1E40AF;">الأبناء الإضافيون (<?= count($childExcess) ?>)</strong>
            </div>
            <?php foreach ($childExcess as $person): ?>
            <?php
            $catColor = match($person['age_category_code'] ?? '') {
                'under_12' => '#059669', '12_to_16' => '#0284C7', '16_to_18' => '#D97706', '18_to_25' => '#EA580C', '25_plus' => '#DC2626', default => '#6B7280'
            };
            $is25Plus = ($person['age_category_code'] ?? '') === '25_plus';
            ?>
            <div style="padding:14px;background:<?= $is25Plus ? '#FEF2F2' : '#fff' ?>;border:1px solid <?= $is25Plus ? '#FECACA' : '#E5E7EB' ?>;border-radius:8px;margin-bottom:10px;" class="ind-fee-card" data-idx="<?= $indIdx ?>">
                <div style="display:flex;align-items:center;gap:10px;margin-bottom:10px;flex-wrap:wrap;">
                    <strong style="color:#374151;font-size:14px;"><?= e($person['person_name']) ?></strong>
                    <?php if ($person['date_of_birth']): ?>
                    <span style="font-size:11px;color:#6B7280;">م: <?= e($person['date_of_birth']) ?></span>
                    <?php endif; ?>
                    <?php if ($person['age_years'] !== null): ?>
                    <span style="font-size:12px;font-weight:600;color:#374151;">(<?= (int) $person['age_years'] ?> سنة)</span>
                    <?php endif; ?>
                    <span style="background:<?= $catColor ?>15;color:<?= $catColor ?>;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600;"><?= e($person['age_category'] ?? '') ?></span>
                    <?php if ($person['relationship']): ?>
                    <span style="font-size:11px;color:#6B7280;"><?= $person['relationship'] === 'son' ? 'ابن' : 'ابنة' ?></span>
                    <?php endif; ?>
                </div>
                <?php if ($is25Plus): ?>
                <div style="padding:8px 12px;background:#FEE2E2;border:1px solid #FECACA;border-radius:6px;margin-bottom:10px;display:flex;align-items:center;gap:8px;">
                    <span style="color:#DC2626;font-size:12px;font-weight:700;">⚠ تجاوز السن المسموح (25 سنة فأكثر) — قد يتطلب فصل العضوية</span>
                    <a href="/members/<?= (int) $waiver['target_member_id'] ?>" class="btn btn-outline" style="padding:4px 10px;font-size:11px;color:#DC2626;border-color:#DC2626;margin-right:auto;">فصل العضوية</a>
                </div>
                <?php endif; ?>
                <input type="hidden" name="ind_person_type[]" value="child">
                <input type="hidden" name="ind_person_id[]" value="<?= (int) $person['person_id'] ?>">
                <input type="hidden" name="ind_person_name[]" value="<?= e($person['person_name']) ?>">
                <input type="hidden" name="ind_person_order[]" value="<?= (int) $person['person_order'] ?>">
                <input type="hidden" name="ind_age_years[]" value="<?= $person['age_years'] !== null ? (int) $person['age_years'] : '' ?>">
                <input type="hidden" name="ind_age_category_code[]" value="<?= e($person['age_category_code'] ?? '') ?>">
                <input type="hidden" name="ind_date_of_birth[]" value="<?= e($person['date_of_birth'] ?? '') ?>">
                <input type="hidden" name="ind_relationship[]" value="<?= e($person['relationship'] ?? '') ?>">
                <input type="hidden" name="ind_status[]" value="<?= e($person['status'] ?? '') ?>">
                <div style="display:grid;grid-template-columns:1fr 1fr 120px;gap:10px;align-items:end;">
                    <div class="form-group" style="margin:0;">
                        <label class="form-label" style="font-size:12px;">طريقة الاحتساب</label>
                        <select name="ind_fee_type[]" class="form-select" required onchange="calcIndFee(<?= $indIdx ?>)">
                            <option value="">— اختر —</option>
                            <option value="fixed">مبلغ ثابت</option>
                            <option value="percentage">نسبة من قيمة العضوية</option>
                        </select>
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label class="form-label" style="font-size:12px;">القيمة</label>
                        <input type="number" name="ind_fee_rate[]" class="form-input" step="0.01" min="0" required oninput="calcIndFee(<?= $indIdx ?>)" data-idx="<?= $indIdx ?>">
                    </div>
                    <div style="text-align:center;padding:8px 0;">
                        <span style="font-size:12px;color:#6B7280;">= </span>
                        <strong class="ind-fee-result" id="ind-result-<?= $indIdx ?>" style="color:#0D7377;">0.00</strong>
                        <span style="font-size:11px;color:#6B7280;"> ج.م</span>
                    </div>
                </div>
            </div>
            <?php $indIdx++; endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Temporary individuals -->
        <?php if (!empty($tempExcess)): ?>
        <div style="margin-bottom:20px;">
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;padding:8px 12px;background:#F0FDF4;border-radius:6px;">
                <span style="font-size:18px;">👤</span>
                <strong style="color:#166534;">الأعضاء المؤقتون الإضافيون (<?= count($tempExcess) ?>)</strong>
            </div>
            <?php foreach ($tempExcess as $person): ?>
            <div style="padding:14px;background:#fff;border:1px solid #E5E7EB;border-radius:8px;margin-bottom:10px;" class="ind-fee-card" data-idx="<?= $indIdx ?>">
                <div style="display:flex;align-items:center;gap:10px;margin-bottom:10px;">
                    <strong style="color:#374151;font-size:14px;"><?= e($person['person_name']) ?></strong>
                    <?php if (!empty($person['national_id'])): ?>
                    <span style="font-size:11px;color:#6B7280;">رقم قومي: <?= e($person['national_id']) ?></span>
                    <?php endif; ?>
                    <span style="background:#F0FDF4;color:#059669;padding:2px 6px;border-radius:3px;font-size:11px;"><?= e($person['status'] ?? 'active') ?></span>
                </div>
                <input type="hidden" name="ind_person_type[]" value="temporary">
                <input type="hidden" name="ind_person_id[]" value="<?= (int) $person['person_id'] ?>">
                <input type="hidden" name="ind_person_name[]" value="<?= e($person['person_name']) ?>">
                <input type="hidden" name="ind_person_order[]" value="<?= (int) $person['person_order'] ?>">
                <input type="hidden" name="ind_age_years[]" value="">
                <input type="hidden" name="ind_age_category_code[]" value="">
                <input type="hidden" name="ind_date_of_birth[]" value="">
                <input type="hidden" name="ind_relationship[]" value="">
                <input type="hidden" name="ind_status[]" value="<?= e($person['status'] ?? '') ?>">
                <div style="display:grid;grid-template-columns:1fr 1fr 120px;gap:10px;align-items:end;">
                    <div class="form-group" style="margin:0;">
                        <label class="form-label" style="font-size:12px;">طريقة الاحتساب</label>
                        <select name="ind_fee_type[]" class="form-select" required onchange="calcIndFee(<?= $indIdx ?>)">
                            <option value="">— اختر —</option>
                            <option value="fixed">مبلغ ثابت</option>
                            <option value="percentage">نسبة من قيمة العضوية</option>
                        </select>
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label class="form-label" style="font-size:12px;">القيمة</label>
                        <input type="number" name="ind_fee_rate[]" class="form-input" step="0.01" min="0" required oninput="calcIndFee(<?= $indIdx ?>)" data-idx="<?= $indIdx ?>">
                    </div>
                    <div style="text-align:center;padding:8px 0;">
                        <span style="font-size:12px;color:#6B7280;">= </span>
                        <strong class="ind-fee-result" id="ind-result-<?= $indIdx ?>" style="color:#0D7377;">0.00</strong>
                        <span style="font-size:11px;color:#6B7280;"> ج.م</span>
                    </div>
                </div>
            </div>
            <?php $indIdx++; endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Live Total Summary -->
        <div id="fee-summary" style="padding:15px;background:#F0FDF4;border:2px solid #BBF7D0;border-radius:8px;margin-bottom:15px;">
            <strong style="color:#166534;display:block;margin-bottom:8px;">📊 ملخص الرسوم الإضافية:</strong>
            <div id="fee-summary-content" style="font-size:13px;color:#166534;">
                <div id="sum-spouses" style="display:none;margin-bottom:4px;"></div>
                <div id="sum-children" style="display:none;margin-bottom:4px;"></div>
                <div id="sum-temporary" style="display:none;margin-bottom:4px;"></div>
                <hr style="margin:8px 0;border:none;border-top:1px dashed #BBF7D0;">
                <div style="font-weight:700;">إجمالي الرسوم الإضافية: <span id="sum-excess-total">0.00</span> ج.م</div>
                <div style="font-weight:700;">+ رسوم التنازل الأساسية: <?= money($waiver['waiver_fee_amount'] ?? '0') ?></div>
                <div style="font-weight:700;font-size:16px;color:#0D7377;margin-top:4px;">= الإجمالي النهائي: <span id="sum-grand-total"><?= money($waiver['waiver_fee_amount'] ?? '0') ?></span></div>
            </div>
        </div>

        <?php else: ?>
        <div style="padding:12px;background:#F0FDF4;border:1px solid #BBF7D0;border-radius:8px;margin-bottom:15px;">
            <span style="color:#059669;font-weight:600;">✅ لا يوجد تابعين زائدين — لا تُفرض رسوم إضافية</span>
        </div>
        <?php endif; ?>

        <div style="display:flex;gap:10px;">
            <button type="submit" class="btn btn-primary" onclick="return confirm('اعتماد طلب التنازل؟')">✅ اعتماد</button>
            <button type="button" class="btn btn-outline" style="color:#DC2626;" onclick="document.getElementById('reject-modal').style.display='flex'">❌ رفض</button>
        </div>
    </form>
</div>

<!-- Reject modal -->
<div id="reject-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:1000;align-items:center;justify-content:center;">
    <div style="background:#fff;padding:30px;border-radius:12px;max-width:450px;width:90%;">
        <h4 style="margin:0 0 15px;color:#DC2626;">❌ رفض طلب التنازل</h4>
        <form method="POST" action="/waivers/<?= (int) $waiver['id'] ?>/reject">
            <?= csrf_field() ?>
            <div class="form-group">
                <label class="form-label">سبب الرفض</label>
                <textarea name="rejection_reason" class="form-textarea" rows="3" placeholder="أدخل سبب الرفض..."></textarea>
            </div>
            <div style="display:flex;gap:10px;margin-top:15px;">
                <button type="submit" class="btn btn-primary" style="background:#DC2626;">تأكيد الرفض</button>
                <button type="button" class="btn btn-outline" onclick="document.getElementById('reject-modal').style.display='none'">إلغاء</button>
            </div>
        </form>
    </div>
</div>

<?php if (!empty($excess_individuals)): ?>
<script>
var membershipValue = <?= (float) ($waiver['membership_value_at_waiver'] ?? 0) ?>;
var waiverBaseFee = <?= (float) ($waiver['waiver_fee_amount'] ?? 0) ?>;
var totalCards = <?= count($excess_individuals) ?>;

function calcIndFee(idx) {
    var card = document.querySelector('.ind-fee-card[data-idx="' + idx + '"]');
    if (!card) return;
    var typeEl = card.querySelector('select[name="ind_fee_type[]"]');
    var rateEl = card.querySelector('input[name="ind_fee_rate[]"]');
    var resultEl = document.getElementById('ind-result-' + idx);
    if (!typeEl || !rateEl || !resultEl) return;

    var type = typeEl.value;
    var rate = parseFloat(rateEl.value) || 0;
    var amount = 0;

    if (type === 'percentage') {
        amount = membershipValue * rate / 100;
    } else if (type === 'fixed') {
        amount = rate;
    }
    resultEl.textContent = amount.toLocaleString('en', {minimumFractionDigits: 2, maximumFractionDigits: 2});
    updateSummary();
}

function updateSummary() {
    var cards = document.querySelectorAll('.ind-fee-card');
    var totals = {spouse: 0, child: 0, temporary: 0};
    var names = {spouse: [], child: [], temporary: []};

    cards.forEach(function(card) {
        var idx = parseInt(card.dataset.idx);
        var resultEl = document.getElementById('ind-result-' + idx);
        var amount = parseFloat((resultEl ? resultEl.textContent : '0').replace(/,/g, '')) || 0;
        var personType = card.querySelector('input[name="ind_person_type[]"]').value;
        var personName = card.querySelector('input[name="ind_person_name[]"]').value;
        totals[personType] = (totals[personType] || 0) + amount;
        if (amount > 0) names[personType].push(personName + ': ' + amount.toLocaleString('en', {minimumFractionDigits: 2}) + ' ج.م');
    });

    var sumSpouses = document.getElementById('sum-spouses');
    var sumChildren = document.getElementById('sum-children');
    var sumTemp = document.getElementById('sum-temporary');

    if (totals.spouse > 0) { sumSpouses.innerHTML = '<strong>👩 الزوجات:</strong> ' + names.spouse.join(' | ') + ' = <strong>' + totals.spouse.toLocaleString('en', {minimumFractionDigits: 2}) + ' ج.م</strong>'; sumSpouses.style.display = 'block'; } else { sumSpouses.style.display = 'none'; }
    if (totals.child > 0) { sumChildren.innerHTML = '<strong>👶 الأبناء:</strong> ' + names.child.join(' | ') + ' = <strong>' + totals.child.toLocaleString('en', {minimumFractionDigits: 2}) + ' ج.م</strong>'; sumChildren.style.display = 'block'; } else { sumChildren.style.display = 'none'; }
    if (totals.temporary > 0) { sumTemp.innerHTML = '<strong>👤 المؤقتون:</strong> ' + names.temporary.join(' | ') + ' = <strong>' + totals.temporary.toLocaleString('en', {minimumFractionDigits: 2}) + ' ج.م</strong>'; sumTemp.style.display = 'block'; } else { sumTemp.style.display = 'none'; }

    var excessTotal = totals.spouse + totals.child + totals.temporary;
    document.getElementById('sum-excess-total').textContent = excessTotal.toLocaleString('en', {minimumFractionDigits: 2});
    document.getElementById('sum-grand-total').textContent = (excessTotal + waiverBaseFee).toLocaleString('en', {minimumFractionDigits: 2}) + ' ج.م';
}
</script>
<?php endif; ?>
<?php endif; ?>

<!-- SECTION 8: Fee paid but auto-complete didn't fire (edge case — debts remain or missing target) -->
<?php if ($waiver['status'] === 'fee_paid'): ?>
<div class="card" style="padding:20px;margin-bottom:20px;background:#FEF3C7;border:2px solid #F59E0B;">
    <div style="display:flex;align-items:center;gap:10px;margin-bottom:8px;">
        <span style="font-size:22px;">⏳</span>
        <div>
            <h4 style="margin:0;color:#D97706;">تم السداد — بانتظار استكمال المتطلبات</h4>
            <p style="margin:4px 0 0;font-size:12px;color:#92400E;">سيتم اعتماد التنازل تلقائياً فور استيفاء جميع الشروط التالية:</p>
        </div>
    </div>
    <ul style="margin:10px 0 0;padding:0 20px;font-size:13px;color:#92400E;list-style:disc;">
        <li style="margin-bottom:4px;">✅ سداد رسوم التنازل</li>
        <?php if (!$waiver['target_member_id']): ?>
        <li style="margin-bottom:4px;color:#DC2626;font-weight:700;">❌ لم يتم تحديد المتنازل إليه بعد</li>
        <?php else: ?>
        <li style="margin-bottom:4px;">✅ تحديد المتنازل إليه: <?= e($waiver['target_name'] ?? '') ?></li>
        <?php endif; ?>
        <?php if (!$source_debt_check['clear']): ?>
        <li style="margin-bottom:4px;color:#DC2626;font-weight:700;">❌ مديونيات على المتنازل: <?= money($source_debt_check['total']) ?></li>
        <?php else: ?>
        <li style="margin-bottom:4px;">✅ لا مديونيات على المتنازل</li>
        <?php endif; ?>
        <?php if ($target_debt_check && !$target_debt_check['clear']): ?>
        <li style="margin-bottom:4px;color:#DC2626;font-weight:700;">❌ مديونيات على المتنازل إليه: <?= money($target_debt_check['total']) ?></li>
        <?php elseif ($waiver['target_member_id']): ?>
        <li style="margin-bottom:4px;">✅ لا مديونيات على المتنازل إليه</li>
        <?php endif; ?>
    </ul>
    <?php
    $allClear = $waiver['target_member_id'] && $source_debt_check['clear'] && (!$target_debt_check || $target_debt_check['clear']);
    ?>
    <?php if ($allClear && can('waiver.approve')): ?>
    <div style="margin-top:15px;padding:12px;background:#ECFDF5;border:1px solid #BBF7D0;border-radius:8px;">
        <p style="margin:0 0 10px;font-size:13px;color:#166534;font-weight:600;">✅ جميع الشروط مستوفاة — يمكن إتمام التنازل الآن</p>
        <form method="POST" action="/waivers/<?= (int) $waiver['id'] ?>/complete" style="display:inline;">
            <?= csrf_field() ?>
            <input type="hidden" name="target_member_id" value="<?= (int) $waiver['target_member_id'] ?>">
            <button type="submit" class="btn btn-primary" style="padding:10px 25px;" onclick="return confirm('إتمام التنازل ونقل العضوية؟')">✅ إتمام التنازل يدوياً</button>
        </form>
        <span style="font-size:11px;color:#6B7280;margin-right:10px;">(كان يُفترض أن يتم تلقائياً — اضغط هنا لإتمامه يدوياً)</span>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- Info for approved (still needs payment) -->
<?php if ($waiver['status'] === 'approved' && can('waiver.approve')): ?>
<div style="padding:12px 16px;background:#FEF3C7;border:1px solid #FDE68A;border-radius:8px;margin-bottom:20px;font-size:13px;color:#92400E;">
    ⏳ لإتمام التنازل: يجب إرسال طلب الدفع للخزينة وسداد الرسوم. بعد السداد سيتم اعتماد التنازل ونقل العضوية تلقائياً.
</div>
<?php endif; ?>

<div style="margin-top:20px;">
    <a href="/waivers" class="btn btn-outline">← رجوع للقائمة</a>
</div>

<?php if (!$waiver['target_member_id'] && $waiver['status'] === 'requested'): ?>
<script>
(function() {
    var searchInput = document.getElementById('target-search');
    if (!searchInput) return;
    var resultsDiv = document.getElementById('target-results');
    var selectedDiv = document.getElementById('target-selected');
    var hiddenInput = document.getElementById('target-member-id');
    var timer = null;

    searchInput.addEventListener('input', function() {
        clearTimeout(timer);
        var q = this.value.trim();
        if (q.length < 2) { resultsDiv.style.display = 'none'; return; }
        timer = setTimeout(function() {
            fetch('/api/members/search?q=' + encodeURIComponent(q) + '&exclude=<?= (int) $waiver['source_member_id'] ?>&limit=10')
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (!data.length) {
                        resultsDiv.innerHTML = '<div style="padding:12px;color:#6B7280;font-size:13px;">لا توجد نتائج</div>';
                    } else {
                        resultsDiv.innerHTML = data.map(function(m) {
                            return '<div class="target-option" data-id="' + m.id + '" data-name="' + (m.full_name_ar || '') + '" data-info="' + (m.national_id || '') + ' — ' + (m.membership_number ? 'عضوية #' + m.membership_number : 'بدون رقم عضوية') + '" style="padding:10px 14px;cursor:pointer;border-bottom:1px solid #F3F4F6;transition:background .1s;">' +
                                '<div style="font-weight:600;font-size:13px;">' + (m.full_name_ar || '') + '</div>' +
                                '<div style="font-size:11px;color:#6B7280;">' + (m.national_id || '—') + ' — ' + (m.phone_mobile || '') + (m.membership_number ? ' — عضوية #' + m.membership_number : '') + '</div></div>';
                        }).join('');
                    }
                    resultsDiv.style.display = 'block';
                });
        }, 300);
    });

    resultsDiv.addEventListener('click', function(e) {
        var opt = e.target.closest('.target-option');
        if (!opt) return;
        hiddenInput.value = opt.dataset.id;
        document.getElementById('target-name').textContent = opt.dataset.name;
        document.getElementById('target-info').textContent = opt.dataset.info;
        selectedDiv.style.display = 'block';
        resultsDiv.style.display = 'none';
        searchInput.value = '';
    });

    document.addEventListener('click', function(e) {
        if (!resultsDiv.contains(e.target) && e.target !== searchInput) resultsDiv.style.display = 'none';
    });

    resultsDiv.addEventListener('mouseover', function(e) {
        var opt = e.target.closest('.target-option');
        if (opt) opt.style.background = '#F0FDF4';
    });
    resultsDiv.addEventListener('mouseout', function(e) {
        var opt = e.target.closest('.target-option');
        if (opt) opt.style.background = '';
    });
})();

function clearTarget() {
    document.getElementById('target-member-id').value = '';
    document.getElementById('target-selected').style.display = 'none';
}

function validateComplete() {
    var tid = document.getElementById('target-member-id');
    if (!tid || !tid.value || tid.value === '0') {
        alert('يجب تحديد المستفيد (المتنازل إليه) أولاً');
        return false;
    }
    return confirm('⚠ إتمام التنازل — سيتم نقل العضوية رقم <?= e($waiver['membership_number'] ?? '') ?> للمستفيد وأرشفة العضو الأصلي نهائياً. هل أنت متأكد؟');
}
</script>
<?php endif; ?>

<script>document.addEventListener('DOMContentLoaded', function() { if (typeof lucide !== 'undefined') lucide.createIcons(); });</script>
<?php $__template->endSection(); ?>
