<?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'] };
?>

<!-- Status Banner -->
<div style="padding:12px 20px;background:<?= $statusColor ?>15;border:2px solid <?= $statusColor ?>;border-radius:8px;margin-bottom:20px;display:flex;align-items:center;gap:10px;">
    <span style="font-size:20px;">● </span>
    <span style="font-weight:700;font-size:16px;color:<?= $statusColor ?>;"><?= $statusLabel ?></span>
    <?php if ($waiver['approved_by_name']): ?>
        <span style="margin-right:auto;font-size:12px;color:#6B7280;">بواسطة: <?= e($waiver['approved_by_name']) ?> — <?= arabic_date($waiver['approved_at'] ?? '') ?></span>
    <?php endif; ?>
</div>

<!-- 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; ?>
        <tr><td style="padding:8px 0;color:#6B7280;">المديونيات</td><td style="padding:8px 0;"><?= $waiver['debts_cleared'] ? '<span style="color:#059669;font-weight:600;">✅ تم التحقق — لا توجد مديونيات</span>' : '<span style="color:#D97706;">⏳ لم يتم التحقق</span>' ?></td></tr>
        <?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>

<!-- Dependents Comparison -->
<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;">
        <div style="display:grid;grid-template-columns:1fr auto 1fr;gap:15px;align-items:start;">
            <!-- Source dependents -->
            <div style="text-align:center;">
                <div style="font-size:12px;color:#6B7280;margin-bottom:5px;">تابعين المتنازل (الأصلي)</div>
                <div style="font-size:28px;font-weight:700;color:#0D7377;"><?= (int) ($waiver['original_dependent_count'] ?? 0) ?></div>
                <?php if ($source_deps): ?>
                <div style="font-size:11px;color:#6B7280;margin-top:4px;">
                    <?= $source_deps['spouses'] ?> زوجات — <?= $source_deps['children'] ?> أبناء — <?= $source_deps['temporary'] ?> مؤقتين
                </div>
                <?php endif; ?>
            </div>
            <!-- Arrow -->
            <div style="text-align:center;padding-top:15px;font-size:24px;color:#6B7280;">←</div>
            <!-- Target dependents -->
            <div style="text-align:center;">
                <div style="font-size:12px;color:#6B7280;margin-bottom:5px;">تابعين المتنازل إليه</div>
                <?php if ($target_deps): ?>
                    <?php $excess = $target_deps['total'] - (int) ($waiver['original_dependent_count'] ?? 0); ?>
                    <div style="font-size:28px;font-weight:700;color:<?= $excess > 0 ? '#DC2626' : '#059669' ?>;"><?= $target_deps['total'] ?></div>
                    <div style="font-size:11px;color:#6B7280;margin-top:4px;">
                        <?= $target_deps['spouses'] ?> زوجات — <?= $target_deps['children'] ?> أبناء — <?= $target_deps['temporary'] ?> مؤقتين
                    </div>
                    <?php if ($excess > 0): ?>
                    <div style="margin-top:6px;padding:4px 10px;background:#FEF2F2;border:1px solid #FECACA;border-radius:4px;display:inline-block;">
                        <span style="color:#DC2626;font-weight:700;font-size:13px;">+<?= $excess ?> تابع زائد</span>
                    </div>
                    <?php elseif ($excess <= 0): ?>
                    <div style="margin-top:6px;padding:4px 10px;background:#F0FDF4;border:1px solid #BBF7D0;border-radius:4px;display:inline-block;">
                        <span style="color:#059669;font-weight:600;font-size:13px;">ضمن الحد المسموح</span>
                    </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div style="font-size:28px;font-weight:700;color:#9CA3AF;">—</div>
                    <div style="font-size:11px;color:#9CA3AF;">لم يُحدد المتنازل إليه بعد</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- 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:600px;font-size:14px;">
            <tr>
                <td style="padding:8px 0;color:#6B7280;">قيمة العضوية وقت التنازل</td>
                <td style="padding:8px 0;font-weight:600;text-align:left;"><?= 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;"><?= e($waiver['waiver_fee_percentage'] ?? '30') ?>%</td>
            </tr>
            <tr style="border-bottom:1px dashed #E5E7EB;">
                <td style="padding:8px 0;color:#374151;">رسوم التنازل الأساسية</td>
                <td style="padding:8px 0;font-weight:700;text-align:left;"><?= money($waiver['waiver_fee_amount'] ?? '0') ?></td>
            </tr>
            <?php if (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) ?> عضو × <?= e($waiver['excess_fee_percentage'] ?? '0') ?>%)</td>
                <td style="padding:8px 0;font-weight:700;color:#DC2626;text-align:left;"><?= money($waiver['excess_fee_amount']) ?></td>
            </tr>
            <?php endif; ?>
            <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:20px;color:#0D7377;text-align:left;">
                    <?= money(bcadd($waiver['waiver_fee_amount'] ?? '0', $waiver['excess_fee_amount'] ?? '0', 2)) ?>
                </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; ?>

<!-- Payment Section -->
<?php if (in_array($waiver['status'], ['requested', 'approved']) && bccomp(bcadd($waiver['waiver_fee_amount'] ?? '0', $waiver['excess_fee_amount'] ?? '0', 2), '0', 2) > 0 && can('payment.collect')): ?>
<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="/waivers/<?= (int) $waiver['id'] ?>/pay">
        <?= csrf_field() ?>
        <div style="display:flex;gap:10px;align-items:end;flex-wrap:wrap;">
            <div class="form-group">
                <label class="form-label">الإجمالي</label>
                <input type="text" value="<?= money(bcadd($waiver['waiver_fee_amount'] ?? '0', $waiver['excess_fee_amount'] ?? '0', 2)) ?>" class="form-input" style="background:#F3F4F6;font-weight:700;font-size:18px;min-width:180px;" 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('تأكيد دفع <?= money(bcadd($waiver['waiver_fee_amount'] ?? '0', $waiver['excess_fee_amount'] ?? '0', 2)) ?>؟')">💰 دفع</button>
        </div>
    </form>
</div>
<?php endif; ?>

<!-- Board Approval Section (with excess fee input) -->
<?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 style="display:grid;grid-template-columns:1fr 1fr;gap:15px;margin-bottom:15px;">
            <div class="form-group">
                <label class="form-label">مرجع قرار مجلس الأمناء</label>
                <input type="text" name="board_decision_reference" class="form-input" placeholder="مثال: قرار جلسة 2026/06/15">
            </div>
            <?php if ($target_deps && $target_deps['total'] > (int) ($waiver['original_dependent_count'] ?? 0)): ?>
            <div class="form-group">
                <label class="form-label" style="color:#DC2626;">نسبة رسوم التابعين الزائدين (%) <span style="color:#DC2626;">*</span></label>
                <input type="number" name="excess_fee_percentage" class="form-input" step="0.01" min="0" max="100" placeholder="مثال: 30" style="border-color:#DC2626;">
                <small style="color:#DC2626;">
                    يوجد <?= $target_deps['total'] - (int) $waiver['original_dependent_count'] ?> تابع زائد — النسبة × قيمة العضوية (<?= money($waiver['membership_value_at_waiver'] ?? '0') ?>) × عدد الزائدين
                </small>
            </div>
            <?php else: ?>
            <div class="form-group">
                <label class="form-label">نسبة رسوم تابعين إضافية (%)</label>
                <input type="number" name="excess_fee_percentage" class="form-input" step="0.01" min="0" max="100" placeholder="0 إذا لم يوجد زيادة">
                <small style="color:#6B7280;">اتركه فارغاً إذا لم يوجد تابعين زائدين</small>
            </div>
            <?php endif; ?>
        </div>
        <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='block'">❌ رفض</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;display:none;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 endif; ?>

<!-- Complete Section -->
<?php if (in_array($waiver['status'], ['approved', 'fee_paid']) && can('waiver.approve')): ?>
<div class="card" style="padding:20px;margin-bottom:20px;background:#ECFDF5;border:2px solid #059669;">
    <h4 style="margin:0 0 15px;color:#059669;">✅ إتمام التنازل ونقل العضوية</h4>
    <form method="POST" action="/waivers/<?= (int) $waiver['id'] ?>/complete" id="complete-form">
        <?= csrf_field() ?>
        <?php if (!$waiver['target_member_id']): ?>
        <div style="margin-bottom:15px;">
            <label class="form-label">بحث عن المستفيد <span style="color:#DC2626;">*</span></label>
            <div style="position:relative;">
                <input type="text" id="target-search" class="form-input" placeholder="اكتب اسم أو رقم قومي المستفيد..." autocomplete="off" style="padding-left:40px;">
                <i data-lucide="search" style="position:absolute;left:12px;top:50%;transform:translateY(-50%);width:16px;height:16px;color:#9CA3AF;"></i>
            </div>
            <div id="target-results" style="display:none;position:absolute;z-index:100;background:#fff;border:1px solid #E5E7EB;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,0.1);max-height:200px;overflow-y:auto;width:100%;margin-top:4px;"></div>
        </div>
        <div id="target-selected" style="display:none;padding:12px 16px;background:#F0FDF4;border:1px solid #BBF7D0;border-radius:8px;margin-bottom:15px;">
            <div style="display:flex;align-items:center;justify-content:space-between;">
                <div>
                    <span style="font-weight:700;color:#166534;" id="target-name"></span>
                    <span style="color:#6B7280;font-size:12px;margin-right:10px;" id="target-info"></span>
                </div>
                <button type="button" onclick="clearTarget()" style="background:none;border:none;color:#DC2626;cursor:pointer;font-size:18px;">✕</button>
            </div>
        </div>
        <?php else: ?>
        <div style="padding:12px 16px;background:#F0FDF4;border:1px solid #BBF7D0;border-radius:8px;margin-bottom:15px;">
            <span style="font-weight:700;color:#166534;"><?= e($waiver['target_name'] ?? '') ?></span>
            <span style="color:#6B7280;font-size:12px;margin-right:10px;">عضو #<?= (int) $waiver['target_member_id'] ?></span>
        </div>
        <?php endif; ?>
        <input type="hidden" name="target_member_id" id="target-member-id" value="<?= (int) ($waiver['target_member_id'] ?? 0) ?>">
        <div style="display:flex;gap:10px;align-items:center;">
            <button type="submit" class="btn btn-primary" onclick="return validateComplete()">✅ إتمام التنازل ونقل العضوية</button>
            <?php if (!$waiver['target_member_id']): ?>
            <span style="font-size:12px;color:#6B7280;">أو <a href="/members/create" target="_blank" style="color:#0D7377;">أنشئ عضو جديد</a> ثم ارجع هنا</span>
            <?php endif; ?>
        </div>
    </form>
</div>
<?php endif; ?>

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

<?php if (in_array($waiver['status'], ['approved', 'fee_paid']) || (!$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(); ?>
