<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>حالة وفاة #<?= (int) $case['id'] ?><?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>

<?php
$statusLabels = [
    'recorded'          => 'مسجّل — في انتظار مراجعة مجلس الإدارة',
    'board_review'      => 'قيد مراجعة مجلس الإدارة',
    'board_approved'    => 'معتمد من مجلس الإدارة — في انتظار الدفع',
    'rejected'          => 'مرفوض من مجلس الإدارة',
    'fee_paid'          => 'تم الدفع',
    'pending_form_fill' => 'في انتظار ملء الاستمارة',
    'completed'         => 'مكتمل',
];
$statusColors = [
    'recorded'          => '#9CA3AF',
    'board_review'      => '#D97706',
    'board_approved'    => '#2563EB',
    'rejected'          => '#DC2626',
    'fee_paid'          => '#0D7377',
    'pending_form_fill' => '#7C3AED',
    'completed'         => '#059669',
];
$statusLabel = $statusLabels[$case['status']] ?? $case['status'];
$statusColor = $statusColors[$case['status']] ?? '#6B7280';
$deceasedLabel = match($case['deceased_type']) {
    'primary_member' => 'العضو الرئيسي',
    'spouse'         => 'الزوج/ة',
    'child'          => 'ابن/ابنة',
    default          => $case['deceased_type'],
};
$canApprove = can('transfer.approve');
?>

<!-- Case Info -->
<div class="card" style="padding:20px;margin-bottom:20px;">
    <div style="display:flex;justify-content:space-between;align-items:start;">
        <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:600;"><?= e($case['member_name']) ?> (<?= e($case['membership_number'] ?? '—') ?>)</td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">المتوفى</td><td style="padding:6px 0;font-weight:600;"><?= $deceasedLabel ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الوفاة</td><td style="padding:6px 0;"><?= e($case['death_date']) ?></td></tr>
            <?php if ($case['death_certificate_number']): ?>
            <tr><td style="padding:6px 0;color:#6B7280;">رقم شهادة الوفاة</td><td style="padding:6px 0;"><?= e($case['death_certificate_number']) ?></td></tr>
            <?php endif; ?>
            <tr><td style="padding:6px 0;color:#6B7280;">الحالة</td><td style="padding:6px 0;font-weight:700;color:<?= $statusColor ?>;">● <?= $statusLabel ?></td></tr>
            <?php if ($primarySpouse): ?>
            <tr><td style="padding:6px 0;color:#6B7280;">الزوجة الأساسية</td><td style="padding:6px 0;font-weight:600;"><?= e($primarySpouse['full_name_ar']) ?></td></tr>
            <?php endif; ?>
            <?php if ($newMember): ?>
            <tr><td style="padding:6px 0;color:#6B7280;">نُقلت العضوية إلى</td><td style="padding:6px 0;"><a href="/members/<?= (int) $newMember['id'] ?>" style="color:#0D7377;font-weight:700;font-size:16px;"><?= e($newMember['full_name_ar']) ?> — رقم <?= e($newMember['membership_number'] ?? '—') ?></a></td></tr>
            <?php endif; ?>
        </table>
        <a href="/death" class="btn btn-outline">← القائمة</a>
    </div>
</div>

<?php if (!empty($secondarySpouses)): ?>
<div class="card" style="margin-bottom:20px;padding:20px;">
    <h4 style="margin:0 0 10px;color:#6B7280;font-size:14px;">الزوجات الإضافيات (عضويات منفصلة)</h4>
    <?php foreach ($secondarySpouses as $ss): ?>
    <div style="padding:5px 0;font-size:14px;">• <?= e($ss['full_name_ar']) ?></div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Documents Section -->
<?php if ($case['deceased_type'] === 'primary_member'): ?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#1F2937;font-size:15px;">المستندات المرفوعة</h3>
    </div>
    <div style="padding:20px;display:grid;grid-template-columns:1fr 1fr;gap:15px;">
        <div>
            <div style="font-size:13px;color:#6B7280;margin-bottom:6px;">شهادة الوفاة</div>
            <?php if ($case['death_certificate_path']): ?>
            <a href="/death/<?= (int) $case['id'] ?>/document/cert" target="_blank" class="btn btn-outline btn-sm" style="font-size:12px;">📄 عرض / تنزيل</a>
            <?php else: ?>
            <span style="color:#DC2626;font-size:13px;">لم يُرفع بعد</span>
            <?php endif; ?>
        </div>
        <div>
            <div style="font-size:13px;color:#6B7280;margin-bottom:6px;">إعلام الوراثة</div>
            <?php if ($case['inheritance_notice_path']): ?>
            <a href="/death/<?= (int) $case['id'] ?>/document/inheritance" target="_blank" class="btn btn-outline btn-sm" style="font-size:12px;">📄 عرض / تنزيل</a>
            <?php else: ?>
            <span style="color:#DC2626;font-size:13px;">لم يُرفع بعد</span>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Board Review Form (visible when status = board_review and user has approve permission) -->
<?php if ($case['status'] === 'board_review' && $canApprove): ?>
<div class="card" style="margin-bottom:20px;border:2px solid #D97706;">
    <div style="padding:15px 20px;border-bottom:1px solid #FDE68A;background:#FFFBEB;">
        <h3 style="margin:0;color:#D97706;font-size:15px;">مراجعة مجلس الإدارة</h3>
        <p style="margin:4px 0 0;font-size:12px;color:#6B7280;">حدد رسوم مجلس الأمناء وقرار المجلس لإرسال طلب الدفع للخزينة</p>
    </div>
    <div style="padding:20px;">
        <form method="POST" action="/death/<?= (int) $case['id'] ?>/board-approve">
            <?= csrf_field() ?>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:15px;margin-bottom:15px;">
                <div class="form-group">
                    <label class="form-label">طريقة احتساب رسوم مجلس الأمناء <span style="color:#DC2626;">*</span></label>
                    <select name="fee_method" id="board_fee_method" class="form-select" required>
                        <option value="">-- اختر --</option>
                        <option value="percentage">نسبة مئوية من قيمة العضوية (%)</option>
                        <option value="fixed">مبلغ ثابت (ج.م)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label" id="fee_value_label">القيمة <span style="color:#DC2626;">*</span></label>
                    <input type="number" name="fee_value" id="board_fee_value" class="form-input" min="0" step="0.01" required placeholder="0.00">
                    <p id="fee_calc_hint" style="font-size:11px;color:#9CA3AF;margin:4px 0 0;"></p>
                </div>
                <div class="form-group">
                    <label class="form-label">رقم قرار المجلس</label>
                    <input type="text" name="board_decision_reference" class="form-input" placeholder="مثال: قرار ٢٠٢٦/١٥">
                </div>
                <div class="form-group">
                    <label class="form-label">تاريخ قرار المجلس</label>
                    <input type="date" name="board_decision_date" class="form-input" max="<?= date('Y-m-d') ?>">
                </div>
                <div class="form-group" style="grid-column:1/-1;">
                    <label class="form-label">ملاحظات المجلس</label>
                    <textarea name="board_notes" class="form-textarea" rows="2"></textarea>
                </div>
            </div>
            <div style="display:flex;gap:10px;">
                <button type="submit" class="btn btn-primary" onclick="return confirm('تأكيد اعتماد القضية وإرسال طلب الدفع للخزينة؟')">اعتماد وإرسال للخزينة</button>
            </div>
        </form>

        <hr style="border:none;border-top:1px solid #E5E7EB;margin:20px 0;">

        <form method="POST" action="/death/<?= (int) $case['id'] ?>/board-reject">
            <?= csrf_field() ?>
            <div class="form-group" style="margin-bottom:10px;">
                <label class="form-label">سبب الرفض</label>
                <textarea name="board_notes" class="form-textarea" rows="2" placeholder="اذكر سبب الرفض..."></textarea>
            </div>
            <button type="submit" class="btn" style="background:#DC2626;color:#fff;" onclick="return confirm('تأكيد رفض القضية؟')">رفض القضية</button>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- Board Decision Display (status >= board_approved or rejected) -->
<?php if ($case['board_approved_at'] && $case['status'] !== 'board_review'): ?>
<div class="card" style="margin-bottom:20px;border:1px solid <?= $case['status'] === 'rejected' ? '#DC2626' : '#2563EB' ?>;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;background:<?= $case['status'] === 'rejected' ? '#FEF2F2' : '#EFF6FF' ?>;">
        <h3 style="margin:0;color:<?= $case['status'] === 'rejected' ? '#DC2626' : '#2563EB' ?>;font-size:15px;">
            <?= $case['status'] === 'rejected' ? 'قرار الرفض' : 'قرار مجلس الإدارة' ?>
        </h3>
    </div>
    <div style="padding:20px;font-size:14px;">
        <table style="width:100%;max-width:500px;">
            <?php if ($case['board_decision_reference']): ?>
            <tr><td style="padding:5px 0;color:#6B7280;width:40%;">رقم القرار</td><td style="padding:5px 0;font-weight:600;"><?= e($case['board_decision_reference']) ?></td></tr>
            <?php endif; ?>
            <?php if ($case['board_decision_date']): ?>
            <tr><td style="padding:5px 0;color:#6B7280;">تاريخ القرار</td><td style="padding:5px 0;"><?= e($case['board_decision_date']) ?></td></tr>
            <?php endif; ?>
            <?php if ($boardApprover): ?>
            <tr><td style="padding:5px 0;color:#6B7280;">بواسطة</td><td style="padding:5px 0;"><?= e($boardApprover['full_name_ar']) ?></td></tr>
            <?php endif; ?>
            <tr><td style="padding:5px 0;color:#6B7280;">وقت القرار</td><td style="padding:5px 0;"><?= e($case['board_approved_at']) ?></td></tr>
            <?php if ($case['board_notes']): ?>
            <tr><td style="padding:5px 0;color:#6B7280;vertical-align:top;">ملاحظات</td><td style="padding:5px 0;"><?= e($case['board_notes']) ?></td></tr>
            <?php endif; ?>
        </table>

        <?php if ($case['board_fee_amount'] !== null && $case['status'] !== 'rejected'): ?>
        <hr style="border:none;border-top:1px solid #E5E7EB;margin:15px 0;">
        <div style="font-weight:600;margin-bottom:8px;color:#1F2937;">تفصيل الرسوم المعتمدة</div>
        <?php
        $secondaryCount = 0;
        if (!empty($case['secondary_spouses_json'])) {
            $secondaryCount = count(json_decode($case['secondary_spouses_json'], true));
        }
        $multiplier = 1 + $secondaryCount;
        ?>
        <table style="font-size:13px;max-width:500px;">
            <tr><td style="padding:4px 20px 4px 0;color:#6B7280;">رسوم استمارة (<?= $multiplier ?> × <?= money($fees['formFee']) ?>)</td><td style="font-weight:600;"><?= money(bcmul($fees['formFee'], (string) $multiplier, 2)) ?></td></tr>
            <tr><td style="padding:4px 20px 4px 0;color:#6B7280;">اشتراك سنوي (العضوية الجديدة) × <?= $multiplier ?></td><td style="font-weight:600;"><?= money(bcmul($familySub['annual_sub_total'], (string) $multiplier, 2)) ?></td></tr>
            <?php if ($familySub['child_count'] > 0 || $familySub['temp_count'] > 0 || $familySub['spouse_count'] > 0): ?>
            <tr><td colspan="2" style="padding:2px 40px 2px 0;color:#9CA3AF;font-size:11px;">
                (العضو الجديد: <?= money($familySub['member_sub']) ?>
                <?php if ($familySub['spouse_count'] > 0): ?> + <?= $familySub['spouse_count'] ?> زوجة إضافية: <?= money(bcmul($familySub['spouse_sub'], (string) $familySub['spouse_count'], 2)) ?><?php endif; ?>
                <?php if ($familySub['child_count'] > 0): ?> + <?= $familySub['child_count'] ?> أبناء: <?= money(bcmul($familySub['child_sub'], (string) $familySub['child_count'], 2)) ?><?php endif; ?>
                <?php if ($familySub['temp_count'] > 0): ?> + <?= $familySub['temp_count'] ?> مؤقتين: <?= money(bcmul($familySub['temp_sub'], (string) $familySub['temp_count'], 2)) ?><?php endif; ?>
                + تنمية: <?= money($familySub['dev_fee']) ?>)
            </td></tr>
            <?php endif; ?>
            <tr>
                <td style="padding:4px 20px 4px 0;color:#6B7280;">
                    رسوم مجلس الأمناء
                    (<?= $case['board_fee_method'] === 'percentage' ? $case['board_fee_value'] . '% من قيمة العضوية' : 'مبلغ ثابت' ?>)
                </td>
                <td style="font-weight:600;"><?= money($case['board_fee_amount']) ?></td>
            </tr>
            <tr style="border-top:2px solid #0D7377;">
                <td style="padding:10px 20px 4px 0;font-weight:700;font-size:15px;">الإجمالي</td>
                <td style="padding:10px 0 4px;font-weight:800;font-size:20px;color:#DC2626;"><?= money($case['fee_amount']) ?></td>
            </tr>
        </table>
        <?php endif; ?>

        <?php if ($paymentRequest): ?>
        <div style="margin-top:15px;padding:10px 15px;background:#F0FDF4;border:1px solid #86EFAC;border-radius:6px;font-size:13px;">
            طلب الدفع #<?= (int) $paymentRequest['id'] ?> —
            الحالة: <strong><?= e($paymentRequest['status']) ?></strong>
            <?php if (!empty($paymentRequest['request_number'])): ?> — رقم: <?= e($paymentRequest['request_number']) ?><?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<!-- Fee Breakdown (legacy: for cases before board flow, status fee_paid/pending_form_fill) -->
<?php if (in_array($case['status'], ['fee_paid', 'pending_form_fill', 'completed'], true) && !$case['board_approved_at'] && bccomp($case['fee_amount'] ?? '0', '0', 2) > 0): ?>
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#D97706;font-size:15px;">تفصيل الرسوم</h3>
    </div>
    <div style="padding:20px;">
        <table style="width:100%;max-width:500px;font-size:14px;">
            <tr><td style="padding:8px 0;color:#6B7280;">رسوم الاستمارة</td><td style="padding:8px 0;font-weight:600;"><?= money($fees['formFee']) ?></td></tr>
            <tr><td style="padding:8px 0;color:#6B7280;">اشتراك سنوي</td><td style="padding:8px 0;font-weight:600;"><?= money($fees['annualSubBase']) ?></td></tr>
            <tr><td style="padding:8px 0;color:#6B7280;">رسوم تنمية</td><td style="padding:8px 0;font-weight:600;"><?= money($fees['devFee']) ?></td></tr>
            <tr style="border-top:2px solid #0D7377;">
                <td style="padding:12px 0;font-weight:700;font-size:16px;">الإجمالي المدفوع</td>
                <td style="padding:12px 0;font-weight:800;font-size:22px;color:#059669;"><?= money($case['fee_amount']) ?></td>
            </tr>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- Form Fill Section -->
<?php if ($case['status'] === 'pending_form_fill'): ?>
<div class="card" style="padding:20px;margin-bottom:20px;background:#F5F3FF;border:2px solid #7C3AED;">
    <h4 style="margin:0 0 10px;color:#7C3AED;">ملء استمارة العضوية الجديدة</h4>
    <p style="font-size:13px;color:#6B7280;margin-bottom:15px;">يجب ملء استمارة العضوية الكاملة للزوجة قبل إتمام نقل العضوية.</p>
    <?php if ($case['primary_spouse_form_filled']): ?>
    <p style="color:#059669;font-weight:600;margin-bottom:10px;">✓ تم ملء الاستمارة — يمكن إتمام النقل</p>
    <?php else: ?>
    <a href="/death/<?= (int) $case['id'] ?>/fill-form" class="btn btn-primary">ملء الاستمارة الآن</a>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- Action Buttons -->
<?php if ($case['status'] === 'pending_form_fill' && $case['primary_spouse_form_filled']): ?>
<form method="POST" action="/death/<?= (int) $case['id'] ?>/complete">
    <?= csrf_field() ?>
    <button type="submit" class="btn btn-primary" onclick="return confirm('سيتم نقل العضوية بنفس الرقم. متأكد؟')">إتمام نقل العضوية</button>
</form>
<?php elseif ($case['status'] === 'fee_paid' && $case['deceased_type'] !== 'primary_member'): ?>
<form method="POST" action="/death/<?= (int) $case['id'] ?>/complete">
    <?= csrf_field() ?>
    <button type="submit" class="btn btn-primary" onclick="return confirm('إتمام حالة الوفاة؟')">إتمام الإجراء</button>
</form>
<?php elseif ($case['status'] === 'recorded' && bccomp($case['fee_amount'] ?? '0', '0', 2) <= 0): ?>
<form method="POST" action="/death/<?= (int) $case['id'] ?>/complete">
    <?= csrf_field() ?>
    <button type="submit" class="btn btn-primary" onclick="return confirm('إتمام حالة الوفاة؟')">إتمام الإجراء</button>
</form>
<?php endif; ?>

<!-- Audit Trail (displayed when case is completed) -->
<?php
$notesData = !empty($case['notes']) ? json_decode($case['notes'], true) : [];
$auditLog = is_array($notesData) ? ($notesData['audit_log'] ?? []) : [];
?>
<?php if (!empty($auditLog)): ?>
<div class="card" style="margin-bottom:20px;margin-top:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;background:#F9FAFB;">
        <h3 style="margin:0;color:#1F2937;font-size:15px;">سجل العمليات (Audit Trail)</h3>
    </div>
    <div style="padding:20px;">
        <?php foreach ($auditLog as $entry): ?>
        <div style="padding:6px 0;font-size:13px;border-bottom:1px solid #F3F4F6;display:flex;align-items:start;gap:8px;">
            <span style="color:#0D7377;font-size:11px;margin-top:2px;">●</span>
            <span><?= e($entry) ?></span>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

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

<?php $__template->section('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var feeMethod = document.getElementById('board_fee_method');
    var feeValue  = document.getElementById('board_fee_value');
    var feeLabel  = document.getElementById('fee_value_label');
    var feeHint   = document.getElementById('fee_calc_hint');
    var currentPlanPrice = <?= (float) ($currentPlanPrice ?? 0) ?>;

    if (feeMethod) {
        feeMethod.addEventListener('change', function() {
            if (this.value === 'percentage') {
                feeLabel.innerHTML = 'النسبة المئوية (%) <span style="color:#DC2626;">*</span>';
                feeValue.placeholder = 'مثال: 8';
                feeValue.step = '0.01';
                feeHint.textContent = currentPlanPrice > 0
                    ? 'النسبة تُحسب من قيمة الخطة الحالية: ' + currentPlanPrice.toLocaleString('ar-EG') + ' ج.م — مثال: 8% = ' + (currentPlanPrice * 0.08).toFixed(2)
                    : 'أدخل النسبة المئوية';
            } else if (this.value === 'fixed') {
                feeLabel.innerHTML = 'المبلغ الثابت (ج.م) <span style="color:#DC2626;">*</span>';
                feeValue.placeholder = '0.00';
                feeValue.step = '0.01';
                feeHint.textContent = '';
            }
        });

        feeValue.addEventListener('input', function() {
            if (feeMethod.value === 'percentage' && currentPlanPrice > 0) {
                var pct = parseFloat(this.value) || 0;
                var calc = (currentPlanPrice * pct / 100).toFixed(2);
                feeHint.textContent = pct + '% من ' + currentPlanPrice.toLocaleString('ar-EG') + ' = ' + parseFloat(calc).toLocaleString('ar-EG') + ' ج.م';
            }
        });
    }
});
</script>
<?php $__template->endSection(); ?>
