<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>أرشيف — <?= e($member['full_name_ar'] ?? '') ?><?php $__template->endSection(); ?>
<?php $__template->section('page_actions'); ?>
<a href="/members/archive" class="btn btn-outline">← رجوع للأرشيف</a>
<?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>

<?php
$statusLabels = ['deceased' => 'وفاة', 'transferred' => 'تحويل', 'waived' => 'تنازل', 'divorced' => 'طلاق', 'cancelled' => 'إلغاء'];
$statusColors = ['deceased' => '#6B7280', 'transferred' => '#0284C7', 'waived' => '#7C3AED', 'divorced' => '#DC2626', 'cancelled' => '#D97706'];
$color = $statusColors[$member['status']] ?? '#6B7280';
$data = $primarySnapshot['full_data'] ?? [];
$related = $primarySnapshot['related_data'] ?? [];
?>

<!-- Status Banner -->
<div style="padding:15px 20px;background:<?= $color ?>15;border:2px solid <?= $color ?>;border-radius:8px;margin-bottom:20px;display:flex;justify-content:space-between;align-items:center;">
    <div style="display:flex;align-items:center;gap:12px;">
        <span style="width:12px;height:12px;border-radius:50%;background:<?= $color ?>;"></span>
        <span style="font-weight:700;font-size:16px;color:<?= $color ?>;">مؤرشف — <?= e($statusLabels[$member['status']] ?? $member['status']) ?></span>
        <?php if ($linkedMember): ?>
        <a href="/members/<?= (int) $linkedMember['id'] ?>" style="background:#059669;color:#fff;padding:4px 12px;border-radius:6px;font-size:12px;font-weight:600;text-decoration:none;">الانتقال إلى العضوية الحالية &#x2192;</a>
        <?php endif; ?>
    </div>
    <div style="text-align:left;font-size:13px;color:#6B7280;">
        <div>تاريخ الأرشفة: <strong><?= $member['archived_at'] ? arabic_date($member['archived_at']) : '—' ?></strong></div>
        <?php if ($operator): ?>
            <div>بواسطة: <strong><?= e($operator['full_name_ar']) ?></strong></div>
        <?php endif; ?>
    </div>
</div>

<div style="display:grid;grid-template-columns:2fr 1fr;gap:20px;">
<div>

<!-- Member Data -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#0D7377;">بيانات العضوية</h3>
    </div>
    <div style="padding:20px;">
        <table style="width:100%;font-size:14px;">
            <tr><td style="padding:6px 0;color:#6B7280;width:30%;">رقم العضوية</td><td style="padding:6px 0;font-weight:700;font-size:16px;"><?= e($membershipNumber ?? ($data['membership_number'] ?? '—')) ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">رقم الاستمارة</td><td style="padding:6px 0;font-weight:600;color:#D97706;"><?= e($member['form_number'] ?? $data['form_number'] ?? '—') ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">الاسم بالكامل</td><td style="padding:6px 0;font-weight:600;"><?= e($member['full_name_ar'] ?? '') ?></td></tr>
            <?php if (!empty($member['full_name_en'])): ?><tr><td style="padding:6px 0;color:#6B7280;">الاسم بالإنجليزية</td><td style="padding:6px 0;"><?= e($member['full_name_en']) ?></td></tr><?php endif; ?>
            <tr><td style="padding:6px 0;color:#6B7280;">الرقم القومي</td><td style="padding:6px 0;font-family:monospace;"><?= e($member['national_id'] ?? '—') ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الميلاد</td><td style="padding:6px 0;"><?= e($member['date_of_birth'] ?? $member['birth_date'] ?? '—') ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">النوع</td><td style="padding:6px 0;"><?= ($member['gender'] ?? '') === 'male' ? 'ذكر' : (($member['gender'] ?? '') === 'female' ? 'أنثى' : '—') ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">نوع العضوية</td><td style="padding:6px 0;"><?= e($member['membership_type'] ?? '—') ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">قيمة العضوية</td><td style="padding:6px 0;font-weight:700;color:#059669;"><?= !empty($member['membership_value']) ? money($member['membership_value']) : '—' ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">الهاتف</td><td style="padding:6px 0;"><?= e($member['phone_mobile'] ?? '—') ?></td></tr>
            <?php if (!empty($member['phone_home'])): ?><tr><td style="padding:6px 0;color:#6B7280;">هاتف المنزل</td><td style="padding:6px 0;"><?= e($member['phone_home']) ?></td></tr><?php endif; ?>
            <?php if (!empty($member['email'])): ?><tr><td style="padding:6px 0;color:#6B7280;">البريد</td><td style="padding:6px 0;"><?= e($member['email']) ?></td></tr><?php endif; ?>
            <?php if (!empty($member['residence_address'])): ?><tr><td style="padding:6px 0;color:#6B7280;">العنوان</td><td style="padding:6px 0;"><?= e($member['residence_address']) ?></td></tr><?php endif; ?>
            <?php if (!empty($member['occupation'])): ?><tr><td style="padding:6px 0;color:#6B7280;">الوظيفة</td><td style="padding:6px 0;"><?= e($member['occupation']) ?></td></tr><?php endif; ?>
            <?php if (!empty($member['job_title'])): ?><tr><td style="padding:6px 0;color:#6B7280;">المسمى الوظيفي</td><td style="padding:6px 0;"><?= e($member['job_title']) ?></td></tr><?php endif; ?>
            <?php if (!empty($member['nationality'])): ?><tr><td style="padding:6px 0;color:#6B7280;">الجنسية</td><td style="padding:6px 0;"><?= e($member['nationality']) ?></td></tr><?php endif; ?>
            <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الإنشاء</td><td style="padding:6px 0;"><?= e($member['created_at'] ?? '—') ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">آخر تعديل</td><td style="padding:6px 0;"><?= e($member['updated_at'] ?? '—') ?></td></tr>
        </table>
    </div>
</div>

<!-- Dependents -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#0D7377;">التابعون (<?= count($dependents['spouses'] ?? []) + count($dependents['children'] ?? []) + count($dependents['temporary'] ?? []) ?>)</h3>
    </div>
    <div style="padding:20px;">
        <?php if (!empty($dependents['spouses'])): ?>
        <h4 style="margin:0 0 10px;font-size:14px;color:#374151;">الزوجات (<?= count($dependents['spouses']) ?>)</h4>
        <table class="data-table" style="margin-bottom:15px;font-size:13px;">
            <thead><tr><th>الاسم</th><th>الرقم القومي</th><th>تاريخ الميلاد</th><th>الجنسية</th><th>الحالة</th></tr></thead>
            <tbody>
            <?php foreach ($dependents['spouses'] as $s): ?>
                <tr>
                    <td style="font-weight:600;"><?= e($s['full_name_ar'] ?? '') ?></td>
                    <td style="font-family:monospace;font-size:12px;"><?= e($s['national_id'] ?? '—') ?></td>
                    <td><?= e($s['date_of_birth'] ?? $s['birth_date'] ?? '—') ?></td>
                    <td><?= e($s['nationality'] ?? '—') ?></td>
                    <td>
                        <?php $st = $s['status'] ?? ($s['is_archived'] ?? 0 ? 'archived' : 'active'); ?>
                        <?php if ($st === 'active'): ?><span style="color:#059669;">فعال</span>
                        <?php elseif ($st === 'transferred'): ?><span style="color:#0284C7;">محوّل</span>
                        <?php elseif ($st === 'deceased'): ?><span style="color:#6B7280;">متوفى</span>
                        <?php else: ?><span style="color:#DC2626;">مؤرشف</span><?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>

        <?php if (!empty($dependents['children'])): ?>
        <h4 style="margin:0 0 10px;font-size:14px;color:#374151;">الأبناء (<?= count($dependents['children']) ?>)</h4>
        <table class="data-table" style="margin-bottom:15px;font-size:13px;">
            <thead><tr><th>الاسم</th><th>تاريخ الميلاد</th><th>النوع</th><th>الحالة</th></tr></thead>
            <tbody>
            <?php foreach ($dependents['children'] as $c): ?>
                <tr>
                    <td style="font-weight:600;"><?= e($c['full_name_ar'] ?? '') ?></td>
                    <td><?= e($c['date_of_birth'] ?? $c['birth_date'] ?? '—') ?></td>
                    <td><?= ($c['gender'] ?? '') === 'male' ? 'ذكر' : 'أنثى' ?></td>
                    <td>
                        <?php $st = $c['status'] ?? ($c['is_archived'] ?? 0 ? 'archived' : 'active'); ?>
                        <?php if ($st === 'active'): ?><span style="color:#059669;">فعال</span>
                        <?php else: ?><span style="color:#DC2626;">مؤرشف</span><?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>

        <?php if (!empty($dependents['temporary'])): ?>
        <h4 style="margin:0 0 10px;font-size:14px;color:#374151;">الأعضاء المؤقتون (<?= count($dependents['temporary']) ?>)</h4>
        <table class="data-table" style="font-size:13px;">
            <thead><tr><th>الاسم</th><th>الرقم القومي</th><th>تاريخ الميلاد</th><th>الحالة</th></tr></thead>
            <tbody>
            <?php foreach ($dependents['temporary'] as $t): ?>
                <tr>
                    <td style="font-weight:600;"><?= e($t['full_name_ar'] ?? '') ?></td>
                    <td style="font-family:monospace;font-size:12px;"><?= e($t['national_id'] ?? '—') ?></td>
                    <td><?= e($t['date_of_birth'] ?? $t['birth_date'] ?? '—') ?></td>
                    <td>
                        <?php $st = $t['status'] ?? ($t['is_archived'] ?? 0 ? 'archived' : 'active'); ?>
                        <?php if ($st === 'active'): ?><span style="color:#059669;">فعال</span>
                        <?php else: ?><span style="color:#DC2626;">مؤرشف</span><?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>

        <?php if (empty($dependents['spouses']) && empty($dependents['children']) && empty($dependents['temporary'])): ?>
            <div style="text-align:center;padding:20px;color:#6B7280;">لا يوجد تابعون مسجلون</div>
        <?php endif; ?>
    </div>
</div>

<!-- Payments -->
<?php if (!empty($payments)): ?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#D97706;">المدفوعات (<?= count($payments) ?>)</h3>
    </div>
    <div style="padding:20px;">
        <table class="data-table" style="font-size:12px;width:100%;">
            <thead><tr><th>التاريخ</th><th>النوع</th><th>المبلغ</th><th>طريقة الدفع</th><th>الإيصال</th></tr></thead>
            <tbody>
            <?php foreach ($payments as $p): ?>
                <tr>
                    <td><?= e($p['payment_date'] ?? $p['created_at'] ?? '—') ?></td>
                    <td><?= e($p['payment_type'] ?? '—') ?></td>
                    <td style="font-weight:700;color:#059669;"><?= money($p['amount'] ?? '0') ?></td>
                    <td><?= e($p['payment_method'] ?? '—') ?></td>
                    <td style="font-family:monospace;font-size:11px;"><?= e($p['receipt_number'] ?? '—') ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- Subscriptions -->
<?php if (!empty($subscriptions)): ?>
<?php
$subStatusLabels = ['paid' => 'مدفوع', 'pending' => 'معلق', 'overdue' => 'متأخر', 'exempted' => 'معفى', 'exempt' => 'معفى'];
$subTypeLabels = ['member' => 'العضو', 'spouse' => 'زوج/ة', 'child' => 'ابن/ابنة', 'temporary' => 'مؤقت', 'temp' => 'مؤقت'];
$groupedSubs = [];
foreach ($subscriptions as $sub) {
    $fy = $sub['financial_year'] ?? $sub['year'] ?? $sub['subscription_year'] ?? '—';
    $groupedSubs[$fy][] = $sub;
}
krsort($groupedSubs);
?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#7C3AED;">الاشتراكات السنوية (<?= count($subscriptions) ?>)</h3>
    </div>
    <div style="padding:20px;">
        <?php foreach ($groupedSubs as $fy => $yearSubs): ?>
        <?php
        $yearTotal = array_sum(array_map(fn($s) => (float) ($s['total_amount'] ?? 0), $yearSubs));
        $yearPaid = array_sum(array_map(fn($s) => (float) ($s['paid_amount'] ?? 0), $yearSubs));
        $allPaid = $yearTotal > 0 && $yearPaid >= $yearTotal;
        $yearColor = $allPaid ? '#059669' : '#D97706';
        ?>
        <div style="border:1px solid #E5E7EB;border-radius:8px;margin-bottom:12px;overflow:hidden;">
            <div style="padding:10px 15px;background:#F9FAFB;border-bottom:1px solid #E5E7EB;display:flex;justify-content:space-between;align-items:center;">
                <span style="font-weight:700;color:#1F2937;font-size:14px;"><?= e($fy) ?></span>
                <span style="font-size:12px;color:<?= $yearColor ?>;font-weight:600;"><?= $allPaid ? 'مدفوع بالكامل' : 'غير مكتمل' ?> — <?= money((string) $yearPaid) ?> / <?= money((string) $yearTotal) ?></span>
            </div>
            <table style="width:100%;font-size:12px;">
                <thead><tr style="background:#F3F4F6;"><th style="padding:6px 10px;text-align:right;">النوع</th><th style="padding:6px 10px;text-align:right;">الاسم</th><th style="padding:6px 10px;text-align:right;">المبلغ</th><th style="padding:6px 10px;text-align:right;">المدفوع</th><th style="padding:6px 10px;text-align:right;">الحالة</th></tr></thead>
                <tbody>
                <?php foreach ($yearSubs as $sub):
                    $subStatus = $sub['status'] ?? '—';
                    $subColor = match($subStatus) {
                        'paid' => '#059669', 'pending' => '#F59E0B', 'overdue' => '#DC2626',
                        'exempted', 'exempt' => '#6B7280', default => '#374151',
                    };
                ?>
                <tr style="border-top:1px solid #F3F4F6;">
                    <td style="padding:5px 10px;"><?= e($subTypeLabels[$sub['person_type'] ?? ''] ?? ($sub['person_type'] ?? '—')) ?></td>
                    <td style="padding:5px 10px;"><?= e($sub['person_name'] ?? '—') ?></td>
                    <td style="padding:5px 10px;font-weight:600;"><?= money($sub['total_amount'] ?? '0') ?></td>
                    <td style="padding:5px 10px;"><?= money($sub['paid_amount'] ?? '0') ?></td>
                    <td style="padding:5px 10px;"><span style="color:<?= $subColor ?>;font-weight:600;"><?= e($subStatusLabels[$subStatus] ?? $subStatus) ?></span></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- Installment Plans -->
<?php if (!empty($installmentPlans)): ?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#0284C7;">خطط الأقساط (<?= count($installmentPlans) ?>)</h3>
    </div>
    <div style="padding:20px;">
        <?php foreach ($installmentPlans as $plan):
            $planStatusLabel = match($plan['status'] ?? '') {
                'active' => 'نشط', 'completed' => 'مكتمل', 'cancelled' => 'ملغى', default => $plan['status'] ?? '—',
            };
            $planStatusColor = match($plan['status'] ?? '') {
                'active' => '#059669', 'completed' => '#6B7280', 'cancelled' => '#DC2626', default => '#374151',
            };
        ?>
        <div style="border:1px solid #E5E7EB;border-radius:8px;padding:15px;margin-bottom:15px;">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
                <span style="font-weight:700;color:#1F2937;">خطة #<?= (int) $plan['id'] ?></span>
                <span style="color:<?= $planStatusColor ?>;font-weight:600;font-size:13px;"><?= $planStatusLabel ?></span>
            </div>
            <table style="width:100%;font-size:13px;">
                <tr><td style="color:#6B7280;width:35%;">إجمالي المبلغ</td><td style="font-weight:600;"><?= money($plan['total_amount'] ?? '0') ?></td></tr>
                <tr><td style="color:#6B7280;">المقدم</td><td><?= money($plan['down_payment'] ?? '0') ?></td></tr>
                <tr><td style="color:#6B7280;">المتبقي</td><td style="color:<?= bccomp($plan['remaining_balance'] ?? '0', '0', 2) <= 0 ? '#059669' : '#DC2626' ?>;font-weight:600;"><?= money($plan['remaining_balance'] ?? '0') ?></td></tr>
                <tr><td style="color:#6B7280;">عدد الأشهر</td><td><?= (int) ($plan['number_of_months'] ?? 0) ?></td></tr>
                <tr><td style="color:#6B7280;">القسط الشهري</td><td><?= money($plan['monthly_payment'] ?? '0') ?></td></tr>
                <tr><td style="color:#6B7280;">تاريخ البدء</td><td><?= e($plan['start_date'] ?? '—') ?></td></tr>
            </table>

            <?php
            $planSchedule = array_filter($installmentSchedules ?? [], fn($s) => (int) $s['installment_plan_id'] === (int) $plan['id']);
            if (!empty($planSchedule)):
            ?>
            <details style="margin-top:10px;">
                <summary style="cursor:pointer;font-size:12px;color:#0284C7;font-weight:600;">عرض جدول الأقساط (<?= count($planSchedule) ?>)</summary>
                <table class="data-table" style="font-size:11px;margin-top:8px;width:100%;">
                    <thead><tr><th>#</th><th>تاريخ الاستحقاق</th><th>المبلغ</th><th>المدفوع</th><th>الحالة</th></tr></thead>
                    <tbody>
                    <?php foreach ($planSchedule as $sched): ?>
                        <tr>
                            <td><?= (int) ($sched['installment_number'] ?? 0) ?></td>
                            <td><?= e($sched['due_date'] ?? '—') ?></td>
                            <td><?= money($sched['amount'] ?? '0') ?></td>
                            <td><?= money($sched['paid_amount'] ?? '0') ?></td>
                            <td>
                                <?php $schedStatus = $sched['status'] ?? 'pending'; ?>
                                <span style="color:<?= $schedStatus === 'paid' ? '#059669' : ($schedStatus === 'overdue' ? '#DC2626' : '#F59E0B') ?>;"><?= $schedStatus === 'paid' ? 'مدفوع' : ($schedStatus === 'overdue' ? 'متأخر' : 'معلق') ?></span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </details>
            <?php endif; ?>

            <?php
            $planCheques = array_filter($installmentCheques ?? [], fn($c) => (int) $c['installment_plan_id'] === (int) $plan['id']);
            if (!empty($planCheques)):
            ?>
            <details style="margin-top:10px;">
                <summary style="cursor:pointer;font-size:12px;color:#7C3AED;font-weight:600;">عرض الشيكات (<?= count($planCheques) ?>)</summary>
                <table class="data-table" style="font-size:11px;margin-top:8px;width:100%;">
                    <thead><tr><th>رقم الشيك</th><th>تاريخ الاستحقاق</th><th>المبلغ</th><th>البنك</th><th>الحالة</th></tr></thead>
                    <tbody>
                    <?php foreach ($planCheques as $cheque): ?>
                        <tr>
                            <td style="font-weight:600;"><?= e($cheque['cheque_number'] ?? '—') ?></td>
                            <td><?= e($cheque['due_date'] ?? '—') ?></td>
                            <td><?= money($cheque['amount'] ?? '0') ?></td>
                            <td><?= e($cheque['bank_name'] ?? '—') ?></td>
                            <td>
                                <?php
                                $chequeStatus = $cheque['status'] ?? 'pending';
                                $chequeStatusLabel = match($chequeStatus) {
                                    'collected' => 'تم التحصيل', 'deposited' => 'مودع', 'bounced' => 'مرتجع',
                                    'replaced' => 'مستبدل', 'cancelled' => 'ملغى', default => 'معلق',
                                };
                                $chequeStatusColor = match($chequeStatus) {
                                    'collected' => '#059669', 'deposited' => '#0284C7', 'bounced' => '#DC2626',
                                    'replaced' => '#F59E0B', 'cancelled' => '#6B7280', default => '#D97706',
                                };
                                ?>
                                <span style="color:<?= $chequeStatusColor ?>;font-weight:600;"><?= $chequeStatusLabel ?></span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </details>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- Fines -->
<?php if (!empty($fines)): ?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#DC2626;">الغرامات (<?= count($fines) ?>)</h3>
    </div>
    <div style="padding:20px;">
        <table class="data-table" style="font-size:12px;width:100%;">
            <thead><tr><th>السبب</th><th>المبلغ</th><th>الحالة</th><th>التاريخ</th></tr></thead>
            <tbody>
            <?php foreach ($fines as $fine): ?>
                <tr>
                    <td><?= e($fine['reason'] ?? '—') ?></td>
                    <td style="font-weight:700;color:#DC2626;"><?= money($fine['amount'] ?? '0') ?></td>
                    <td><?= e($fine['status'] ?? '—') ?></td>
                    <td><?= e($fine['created_at'] ?? '—') ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- Documents -->
<?php if (!empty($documents)): ?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#374151;">المستندات (<?= count($documents) ?>)</h3>
    </div>
    <div style="padding:20px;">
        <table class="data-table" style="font-size:12px;width:100%;">
            <thead><tr><th>النوع</th><th>اسم الملف</th><th>الوصف</th><th>تاريخ الرفع</th></tr></thead>
            <tbody>
            <?php foreach ($documents as $doc): ?>
                <tr>
                    <td style="font-weight:600;"><?= e($doc['document_type'] ?? '—') ?></td>
                    <td><?= e($doc['original_filename'] ?? '—') ?></td>
                    <td style="font-size:11px;color:#6B7280;"><?= e($doc['description'] ?? '—') ?></td>
                    <td><?= e($doc['uploaded_at'] ?? $doc['created_at'] ?? '—') ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- Audit Trail -->
<?php if (!empty($auditTrail)): ?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#1A1A2E;">سجل التعديلات (<?= count($auditTrail) ?>)</h3>
    </div>
    <div style="padding:20px;max-height:400px;overflow-y:auto;">
        <?php foreach ($auditTrail as $log): ?>
        <div style="padding:10px 0;border-bottom:1px solid #F3F4F6;font-size:13px;">
            <div style="display:flex;justify-content:space-between;margin-bottom:4px;">
                <strong style="color:#374151;"><?= e($log['action'] ?? '') ?></strong>
                <span style="font-size:11px;color:#9CA3AF;"><?= e($log['created_at'] ?? '') ?></span>
            </div>
            <div style="color:#6B7280;font-size:12px;">
                <?php if (!empty($log['employee_name'])): ?>
                    بواسطة: <?= e($log['employee_name']) ?>
                <?php endif; ?>
                <?php if (!empty($log['changed_fields_json'])):
                    $changes = json_decode($log['changed_fields_json'], true) ?? [];
                    if (!empty($changes)): ?>
                        <div style="margin-top:4px;padding:6px 10px;background:#F9FAFB;border-radius:4px;">
                            <?php foreach (array_slice($changes, 0, 5) as $field => $vals): ?>
                                <div style="margin-bottom:2px;">
                                    <span style="color:#6B7280;"><?= e($field) ?>:</span>
                                    <span style="color:#DC2626;text-decoration:line-through;"><?= e(is_array($vals) ? ($vals['old'] ?? '') : '') ?></span>
                                    → <span style="color:#059669;"><?= e(is_array($vals) ? ($vals['new'] ?? '') : (string) $vals) ?></span>
                                </div>
                            <?php endforeach; ?>
                            <?php if (count($changes) > 5): ?>
                                <div style="color:#9CA3AF;">+ <?= count($changes) - 5 ?> تعديلات أخرى</div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

</div>
<div>

<!-- Sidebar: Archive Info + Links -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:12px 15px;border-bottom:1px solid #E5E7EB;">
        <h4 style="margin:0;font-size:14px;color:#1A1A2E;">معلومات الأرشفة</h4>
    </div>
    <div style="padding:15px;">
        <table style="width:100%;font-size:13px;">
            <tr><td style="padding:4px 0;color:#6B7280;">السبب</td><td style="padding:4px 0;font-weight:600;color:<?= $color ?>;"><?= e($statusLabels[$member['status']] ?? $member['status']) ?></td></tr>
            <tr><td style="padding:4px 0;color:#6B7280;">التاريخ</td><td style="padding:4px 0;"><?= $member['archived_at'] ? arabic_date($member['archived_at']) : '—' ?></td></tr>
            <tr><td style="padding:4px 0;color:#6B7280;">المنفذ</td><td style="padding:4px 0;"><?= e($operator['full_name_ar'] ?? 'النظام') ?></td></tr>
            <tr><td style="padding:4px 0;color:#6B7280;">عدد اللقطات</td><td style="padding:4px 0;"><?= count($snapshots) ?></td></tr>
        </table>
    </div>
</div>

<!-- Financial Summary Box -->
<div class="card" style="margin-bottom:20px;background:#F9FAFB;">
    <div style="padding:15px;text-align:center;">
        <div style="font-size:12px;color:#6B7280;margin-bottom:8px;">الملخص المالي</div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
            <div style="background:#fff;border:1px solid #E5E7EB;border-radius:8px;padding:10px;">
                <div style="font-size:18px;font-weight:700;color:#059669;"><?= money($member['membership_value'] ?? '0') ?></div>
                <div style="font-size:11px;color:#6B7280;">قيمة العضوية</div>
            </div>
            <div style="background:#fff;border:1px solid #E5E7EB;border-radius:8px;padding:10px;">
                <?php
                $totalPaid = '0.00';
                foreach ($payments as $p) {
                    $totalPaid = bcadd($totalPaid, (string) ($p['amount'] ?? '0'), 2);
                }
                ?>
                <div style="font-size:18px;font-weight:700;color:#0284C7;"><?= money($totalPaid) ?></div>
                <div style="font-size:11px;color:#6B7280;">إجمالي المدفوع</div>
            </div>
        </div>
    </div>
</div>

<!-- Linked Member (who received the number) -->
<?php if ($linkedMember): ?>
<div class="card" style="margin-bottom:20px;border:2px solid #059669;">
    <div style="padding:12px 15px;border-bottom:1px solid #E5E7EB;background:#F0FDF4;">
        <h4 style="margin:0;font-size:14px;color:#059669;">العضو الجديد (المنقول إليه)</h4>
    </div>
    <div style="padding:15px;">
        <div style="font-weight:700;font-size:15px;margin-bottom:5px;"><?= e($linkedMember['full_name_ar']) ?></div>
        <div style="font-size:12px;color:#6B7280;">رقم العضوية: <strong><?= e($linkedMember['membership_number'] ?? '—') ?></strong></div>
        <div style="font-size:12px;color:#6B7280;">الحالة: <?= e($linkedMember['status']) ?></div>
        <a href="/members/<?= (int) $linkedMember['id'] ?>" class="btn btn-sm btn-primary" style="margin-top:10px;width:100%;text-align:center;">الانتقال لسجل العضو الجديد</a>
    </div>
</div>
<?php endif; ?>

<!-- Number Chain -->
<?php if (!empty($numberChain)): ?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:12px 15px;border-bottom:1px solid #E5E7EB;">
        <h4 style="margin:0;font-size:14px;color:#0D7377;">سلسلة رقم العضوية: <?= e($membershipNumber ?? '') ?></h4>
    </div>
    <div style="padding:15px;">
        <?php foreach ($numberChain as $i => $link): ?>
        <div style="padding:8px 0;<?= $i < count($numberChain) - 1 ? 'border-bottom:1px solid #F3F4F6;' : '' ?>display:flex;gap:8px;align-items:start;">
            <div style="flex-shrink:0;width:24px;height:24px;border-radius:50%;background:<?= $link['held_until'] === null ? '#059669' : '#E5E7EB' ?>;display:flex;align-items:center;justify-content:center;color:<?= $link['held_until'] === null ? '#fff' : '#6B7280' ?>;font-weight:700;font-size:11px;"><?= $i + 1 ?></div>
            <div style="flex:1;font-size:12px;">
                <div style="font-weight:600;color:#374151;"><?= e($link['holder_type']) ?></div>
                <div style="color:#6B7280;">عضو #<?= (int) $link['holder_entity_id'] ?></div>
                <div style="color:#9CA3AF;font-size:11px;">من: <?= e(mb_substr($link['held_from'], 0, 10)) ?><?= $link['held_until'] ? ' — إلى: ' . e(mb_substr($link['held_until'], 0, 10)) : ' — حتى الآن' ?></div>
            </div>
        </div>
        <?php endforeach; ?>
        <a href="/archive/number-chain/<?= urlencode($membershipNumber ?? '') ?>" class="btn btn-sm btn-outline" style="width:100%;text-align:center;margin-top:10px;">عرض السلسلة الكاملة</a>
    </div>
</div>
<?php endif; ?>

<!-- Snapshots -->
<?php if (!empty($snapshots)): ?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:12px 15px;border-bottom:1px solid #E5E7EB;">
        <h4 style="margin:0;font-size:14px;color:#1A1A2E;">اللقطات الأرشيفية (<?= count($snapshots) ?>)</h4>
    </div>
    <div style="padding:15px;">
        <?php foreach ($snapshots as $s): ?>
        <div style="padding:8px 0;border-bottom:1px solid #F3F4F6;font-size:12px;">
            <div style="display:flex;justify-content:space-between;align-items:center;">
                <div>
                    <strong style="color:#374151;"><?= e($s['snapshot_reason']) ?></strong>
                    <div style="color:#9CA3AF;margin-top:2px;"><?= e(mb_substr($s['snapshot_taken_at'], 0, 16)) ?></div>
                </div>
                <a href="/archive/<?= (int) $s['id'] ?>" class="btn btn-sm btn-outline">عرض</a>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- Quick Links -->
<div class="card">
    <div style="padding:15px;display:flex;flex-direction:column;gap:8px;">
        <a href="/members/<?= (int) $member['id'] ?>/insurance-record" class="btn btn-outline" style="text-align:center;color:#1E40AF;border-color:#1E40AF;">&#x1f4cb; السجل التأميني</a>
        <?php if (!empty($snapshots[0]['id'])): ?>
        <a href="/archive/<?= (int) $snapshots[0]['id'] ?>" class="btn btn-outline" style="text-align:center;">عرض اللقطة الكاملة (JSON)</a>
        <?php endif; ?>
        <a href="/audit/entity/members/<?= (int) $member['id'] ?>" class="btn btn-outline" style="text-align:center;">سجل المراجعة الكامل</a>
    </div>
</div>

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