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

<?php
$statusColors = [
    'board_review'   => '#D97706',
    'board_approved' => '#2563EB',
    'fee_paid'       => '#7C3AED',
    'completed'      => '#059669',
    'rejected'       => '#DC2626',
];
$statusLabels = [
    'board_review'   => 'في انتظار مجلس الأمناء',
    'board_approved' => 'تم اعتماد مجلس الأمناء — في انتظار السداد',
    'fee_paid'       => 'تم السداد — في انتظار الإتمام',
    'completed'      => 'مكتمل',
    'rejected'       => 'مرفوض',
    'submitted'      => 'مقدّم',
];
$statusColor = $statusColors[$case['status']] ?? '#6B7280';
$statusLabel = $statusLabels[$case['status']] ?? $case['status'];
?>

<!-- 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;"><a href="/members/<?= (int) $case['member_id'] ?>" style="color:#0D7377;font-weight:600;"><?= e($case['member_name']) ?></a> — رقم <?= e($case['membership_number']) ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">الزوج/ة</td><td style="padding:6px 0;font-weight:600;"><?= e($case['spouse_name']) ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الطلاق</td><td style="padding:6px 0;"><?= e($case['divorce_date']) ?></td></tr>
            <?php if (!empty($case['qualification_name'])): ?>
            <tr><td style="padding:6px 0;color:#6B7280;">المؤهل</td><td style="padding:6px 0;font-weight:600;"><?= e($case['qualification_name']) ?></td></tr>
            <?php endif; ?>
            <?php if (!empty($case['divorce_certificate_path'])): ?>
            <tr><td style="padding:6px 0;color:#6B7280;">قسيمة الطلاق</td><td style="padding:6px 0;"><a href="/<?= e($case['divorce_certificate_path']) ?>" target="_blank" style="color:#2563EB;">عرض المستند</a></td></tr>
            <?php endif; ?>
            <tr><td style="padding:6px 0;color:#6B7280;">قيمة العضوية</td><td style="padding:6px 0;font-weight:700;color:#0D7377;"><?= money($case['membership_value'] ?? '0') ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">الحالة</td><td style="padding:6px 0;font-weight:700;color:<?= $statusColor ?>;">● <?= $statusLabel ?></td></tr>
            <?php if ($case['spouse_new_membership_number']): ?>
            <tr><td style="padding:6px 0;color:#6B7280;">رقم العضوية الجديد</td><td style="padding:6px 0;"><a href="/members/<?= (int) $case['spouse_new_member_id'] ?>" style="font-weight:800;font-size:20px;color:#0D7377;"><?= e($case['spouse_new_membership_number']) ?></a></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">محوّل من عضوية</td><td style="padding:6px 0;font-weight:600;"><?= e($case['original_membership_number'] ?? $case['membership_number']) ?></td></tr>
            <?php endif; ?>
        </table>
        <a href="/divorce" class="btn btn-outline" style="white-space:nowrap;">← قائمة الطلاق</a>
    </div>
</div>

<!-- Workflow Progress -->
<div class="card" style="margin-bottom:20px;padding:20px;">
    <div style="display:flex;gap:5px;align-items:center;font-size:12px;">
        <?php
        $steps = [
            ['key' => 'board_review', 'label' => 'تقديم الطلب'],
            ['key' => 'board_approved', 'label' => 'قرار مجلس الأمناء'],
            ['key' => 'fee_paid', 'label' => 'السداد'],
            ['key' => 'completed', 'label' => 'إتمام العضوية'],
        ];
        $statusOrder = ['board_review' => 1, 'board_approved' => 2, 'fee_paid' => 3, 'completed' => 4, 'rejected' => 0];
        $currentOrder = $statusOrder[$case['status']] ?? 0;
        foreach ($steps as $i => $step):
            $stepOrder = $statusOrder[$step['key']] ?? 0;
            $done = $currentOrder >= $stepOrder;
            $bg = $done ? '#059669' : '#E5E7EB';
            $color = $done ? '#FFF' : '#6B7280';
        ?>
        <div style="flex:1;text-align:center;padding:8px 4px;background:<?= $bg ?>;color:<?= $color ?>;border-radius:6px;font-weight:<?= $done ? '600' : '400' ?>;"><?= $step['label'] ?></div>
        <?php if ($i < count($steps) - 1): ?><div style="color:#9CA3AF;">→</div><?php endif; ?>
        <?php endforeach; ?>
    </div>
</div>

<?php if ($case['status'] === 'board_review'): ?>
<!-- Board Approval Panel -->
<div class="card" style="margin-bottom:20px;border:2px solid #F59E0B;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;background:#FEF3C7;">
        <h3 style="margin:0;color:#D97706;font-size:15px;">قرار مجلس الأمناء</h3>
        <p style="margin:5px 0 0;font-size:12px;color:#6B7280;">حدد النسبة من قيمة العضوية التي ستدفعها المطلقة حسب المؤهل</p>
    </div>
    <div style="padding:20px;">
        <form method="POST" action="/divorce/<?= (int) $case['id'] ?>/board-approve">
            <?= csrf_field() ?>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:15px;margin-bottom:15px;">
                <div class="form-group">
                    <label class="form-label">النسبة من قيمة العضوية (%) <span style="color:#DC2626;">*</span></label>
                    <input type="number" name="fee_percentage" class="form-input" required min="0" max="100" step="0.01" style="font-size:18px;font-weight:700;" placeholder="مثال: 50">
                    <small style="color:#6B7280;">قيمة العضوية: <?= money($case['membership_value'] ?? '0') ?></small>
                </div>
                <div class="form-group">
                    <label class="form-label">رقم قرار المجلس</label>
                    <input type="text" name="board_decision_number" class="form-input">
                </div>
                <div class="form-group">
                    <label class="form-label">تاريخ القرار</label>
                    <input type="date" name="board_decision_date" class="form-input" value="<?= e(date('Y-m-d')) ?>">
                </div>
            </div>
            <div class="form-group" style="margin-bottom:15px;">
                <label class="form-label">ملاحظات المجلس</label>
                <textarea name="board_notes" class="form-textarea" rows="2"></textarea>
            </div>

            <div id="fee-preview" style="background:#F0FDF4;border:1px solid #059669;border-radius:8px;padding:15px;margin-bottom:15px;display:none;">
                <strong style="color:#059669;">معاينة الرسوم:</strong>
                <div style="margin-top:8px;font-size:13px;" id="fee-preview-content"></div>
            </div>

            <div style="display:flex;gap:10px;">
                <button type="submit" class="btn btn-primary" onclick="return confirm('تأكيد اعتماد مجلس الأمناء وإرسال طلب الدفع للخزينة؟')">اعتماد وإرسال للخزينة</button>
            </div>
        </form>

        <hr style="margin:20px 0;border-color:#FDE68A;">

        <form method="POST" action="/divorce/<?= (int) $case['id'] ?>/board-reject">
            <?= csrf_field() ?>
            <div class="form-group" style="margin-bottom:10px;">
                <label class="form-label" style="color:#DC2626;">سبب الرفض</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; ?>

<?php if (!empty($case['fee_percentage']) && in_array($case['status'], ['board_approved', 'fee_paid', 'completed'], true)): ?>
<!-- Fee Breakdown -->
<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;direction:ltr;text-align:left;"><?= money($case['membership_value'] ?? '0') ?></td>
            </tr>
            <tr>
                <td style="padding:8px 0;color:#6B7280;">النسبة المقررة من المجلس</td>
                <td style="padding:8px 0;font-weight:700;color:#D97706;"><?= e($case['fee_percentage']) ?>%</td>
            </tr>
            <tr style="border-top:1px solid #E5E7EB;">
                <td style="padding:8px 0;color:#6B7280;">رسوم الطلاق (<?= e($case['fee_percentage']) ?>% × قيمة العضوية)</td>
                <td style="padding:8px 0;font-weight:600;direction:ltr;text-align:left;"><?= money($case['fee_amount'] ?? '0') ?></td>
            </tr>
            <tr>
                <td style="padding:8px 0;color:#6B7280;">رسوم استمارة (570)</td>
                <td style="padding:8px 0;font-weight:600;direction:ltr;text-align:left;"><?= money($case['form_fee'] ?? '0') ?></td>
            </tr>
            <tr>
                <td style="padding:8px 0;color:#6B7280;">اشتراك سنوي</td>
                <td style="padding:8px 0;font-weight:600;direction:ltr;text-align:left;"><?= money($case['annual_subscription_fee'] ?? '0') ?></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:#DC2626;direction:ltr;text-align:left;"><?= money($case['total_fee'] ?? '0') ?></td>
            </tr>
        </table>
        <?php if (!empty($case['board_decision_number'])): ?>
        <div style="margin-top:15px;font-size:12px;color:#6B7280;">
            قرار رقم: <?= e($case['board_decision_number']) ?>
            <?php if (!empty($case['board_decision_date'])): ?> — بتاريخ: <?= e($case['board_decision_date']) ?><?php endif; ?>
        </div>
        <?php endif; ?>
        <?php if (!empty($case['board_notes'])): ?>
        <div style="margin-top:8px;font-size:12px;color:#6B7280;">ملاحظات المجلس: <?= e($case['board_notes']) ?></div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<?php if ($case['status'] === 'board_approved'): ?>
<!-- Pay button -->
<div class="card" style="padding:20px;margin-bottom:20px;background:#FFF7ED;border:2px solid #F59E0B;">
    <h4 style="margin:0 0 15px;color:#D97706;">دفع رسوم الطلاق</h4>
    <form method="POST" action="/divorce/<?= (int) $case['id'] ?>/pay">
        <?= csrf_field() ?>
        <div style="display:flex;gap:10px;align-items:end;">
            <div class="form-group"><label class="form-label">المبلغ</label><input type="text" value="<?= money($case['total_fee'] ?? '0') ?>" class="form-input" style="background:#F3F4F6;font-weight:700;font-size:18px;" readonly></div>
            <div class="form-group"><label class="form-label">طريقة الدفع</label><select name="payment_method" class="form-select"><option value="cash">نقدي</option><option value="visa">فيزا</option><option value="bank_transfer">تحويل</option></select></div>
            <button type="submit" class="btn btn-primary" style="padding:10px 25px;" onclick="return confirm('تأكيد الدفع؟')">ادفع</button>
        </div>
    </form>
</div>
<?php endif; ?>

<?php if ($case['status'] === 'fee_paid'): ?>
<!-- Complete button -->
<div class="card" style="padding:20px;margin-bottom:20px;background:#F0FDF4;border:2px solid #059669;">
    <h4 style="margin:0 0 10px;color:#059669;">إتمام حالة الطلاق</h4>
    <p style="font-size:13px;color:#6B7280;margin-bottom:15px;">سيتم إنشاء عضوية جديدة مستقلة وأرشفة الزوج/ة من العضوية الأصلية.</p>
    <form method="POST" action="/divorce/<?= (int) $case['id'] ?>/complete">
        <?= csrf_field() ?>
        <button type="submit" class="btn btn-primary" onclick="return confirm('سيتم إنشاء عضوية جديدة مستقلة. متأكد؟')">إتمام حالة الطلاق وإنشاء العضوية</button>
    </form>
</div>
<?php endif; ?>

<?php if ($case['status'] === 'rejected'): ?>
<div class="card" style="padding:20px;margin-bottom:20px;background:#FEF2F2;border:2px solid #DC2626;">
    <h4 style="margin:0 0 5px;color:#DC2626;">تم رفض الطلب</h4>
    <?php if (!empty($case['board_notes'])): ?><p style="margin:0;font-size:13px;color:#6B7280;"><?= e($case['board_notes']) ?></p><?php endif; ?>
</div>
<?php endif; ?>

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

<?php $__template->section('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var percInput = document.querySelector('input[name="fee_percentage"]');
    if (!percInput) return;
    <?php
    $__formFeeData = \App\Modules\Rules\Services\RuleEngine::get('FORM_TRANSFER_FEE');
    $__devFeeData = \App\Modules\Rules\Services\RuleEngine::get('DEVELOPMENT_FEE');
    $__db = \App\Core\App::getInstance()->db();
    $__childRate = $__db->selectOne("SELECT base_amount FROM service_catalog WHERE service_code LIKE 'SVC_ANNUAL_CHILD%' AND is_active = 1 ORDER BY effective_from DESC LIMIT 1");
    ?>
    var membershipValue = <?= json_encode((float) ($case['membership_value'] ?? 0)) ?>;
    var formFee = <?= json_encode((float) ($__formFeeData['amount'] ?? '570')) ?>;
    var annualSub = <?= json_encode((float) ($__childRate['base_amount'] ?? '222') + (float) ($__devFeeData['amount'] ?? '35')) ?>;

    percInput.addEventListener('input', function() {
        var perc = parseFloat(this.value) || 0;
        var percFee = (membershipValue * perc / 100);
        var total = percFee + formFee + annualSub;
        var preview = document.getElementById('fee-preview');
        var content = document.getElementById('fee-preview-content');
        if (perc > 0) {
            preview.style.display = 'block';
            content.innerHTML =
                'رسوم الطلاق (' + perc + '% × ' + membershipValue.toLocaleString() + '): <strong>' + percFee.toLocaleString() + ' ج.م</strong><br>' +
                'رسوم استمارة: <strong>' + formFee.toLocaleString() + ' ج.م</strong><br>' +
                'اشتراك سنوي: <strong>' + annualSub.toLocaleString() + ' ج.م</strong><br>' +
                '<hr style="margin:5px 0;border-color:#059669;"><strong style="font-size:16px;color:#DC2626;">الإجمالي: ' + total.toLocaleString() + ' ج.م</strong>';
        } else {
            preview.style.display = 'none';
        }
    });
});
</script>
<?php $__template->endSection(); ?>
