<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>تنازل #<?= (int) $waiver['id'] ?><?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>
<div class="card" style="padding:20px;margin-bottom:20px;">
    <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) $waiver['source_member_id'] ?>" style="color:#0D7377;font-weight:600;"><?= e($waiver['source_name'] ?? '') ?></a></td></tr>
        <tr><td style="padding:6px 0;color:#6B7280;">رقم العضوية</td><td style="padding:6px 0;font-weight:700;"><?= e($waiver['membership_number'] ?? '—') ?></td></tr>
        <tr><td style="padding:6px 0;color:#6B7280;">الحالة</td><td style="padding:6px 0;font-weight:700;color:<?= match($waiver['status']) { 'completed' => '#059669', 'fee_paid' => '#2563EB', 'approved' => '#0284C7', 'rejected' => '#DC2626', default => '#D97706' } ?>;">● <?= match($waiver['status']) { 'requested' => 'مقدم', 'approved' => 'معتمد — في انتظار الدفع', 'fee_paid' => 'تم الدفع', 'completed' => 'مكتمل', 'rejected' => 'مرفوض', default => $waiver['status'] } ?></td></tr>
        <?php if ($waiver['target_member_id']): ?><tr><td style="padding:6px 0;color:#6B7280;">المتنازل إليه</td><td style="padding:6px 0;"><a href="/members/<?= (int) $waiver['target_member_id'] ?>" style="color:#0D7377;font-weight:600;">عضو #<?= (int) $waiver['target_member_id'] ?></a></td></tr><?php endif; ?>
    </table>
</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: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($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-top:2px solid #0D7377;">
                <td style="padding:12px 0;font-weight:700;font-size:16px;">رسوم التنازل (<?= e($waiver['waiver_fee_percentage'] ?? '30') ?>% من قيمة العضوية)</td>
                <td style="padding:12px 0;font-weight:800;font-size:22px;color:#DC2626;direction:ltr;text-align:left;"><?= money($waiver['waiver_fee_amount'] ?? '0') ?></td>
            </tr>
        </table>
    </div>
</div>

<?php if (in_array($waiver['status'], ['requested', 'approved']) && bccomp($waiver['waiver_fee_amount'] ?? '0', '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;">💰 دفع رسوم التنازل (<?= e($waiver['waiver_fee_percentage'] ?? '30') ?>% من قيمة العضوية)</h4>
    <form method="POST" action="/waivers/<?= (int) $waiver['id'] ?>/pay">
        <?= csrf_field() ?>
        <input type="hidden" name="amount" value="<?= e($waiver['waiver_fee_amount']) ?>">
        <div style="display:flex;gap:10px;align-items:end;">
            <div class="form-group"><label class="form-label">المبلغ</label><input type="text" value="<?= money($waiver['waiver_fee_amount']) ?>" 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('تأكيد دفع <?= money($waiver['waiver_fee_amount']) ?>؟')">💰 ادفع</button>
        </div>
    </form>
</div>
<?php endif; ?>

<?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() ?>
        <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>
        <input type="hidden" name="target_member_id" id="target-member-id" value="<?= (int) ($waiver['target_member_id'] ?? 0) ?>">
        <?php if (!empty($waiver['target_member_id']) && !empty($waiver['target_name'])): ?>
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('target-name').textContent = <?= json_encode($waiver['target_name'], JSON_UNESCAPED_UNICODE) ?>;
            document.getElementById('target-info').textContent = 'عضو #<?= (int) $waiver['target_member_id'] ?>';
            document.getElementById('target-selected').style.display = 'block';
        });
        </script>
        <?php endif; ?>
        <div style="display:flex;gap:10px;align-items:center;">
            <button type="submit" class="btn btn-primary" onclick="return validateComplete()">✅ إتمام التنازل ونقل العضوية</button>
            <span style="font-size:12px;color:#6B7280;">أو <a href="/members/create?waiver_id=<?= (int) $waiver['id'] ?>" style="color:#0D7377;">أنشئ عضو جديد</a> ثم ارجع هنا</span>
        </div>
    </form>
</div>
<script>
(function() {
    var searchInput = document.getElementById('target-search');
    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() {
    if (!document.getElementById('target-member-id').value || document.getElementById('target-member-id').value === '0') {
        alert('يجب تحديد المستفيد (المتنازل إليه) أولاً');
        return false;
    }
    return confirm('⚠ إتمام التنازل — سيتم نقل العضوية رقم <?= e($waiver['membership_number'] ?? '') ?> للمستفيد. هل أنت متأكد؟');
}
</script>
<?php endif; ?>

<?php if ($waiver['status'] === 'requested'): ?>
<div style="margin-top:15px;display:flex;gap:10px;">
    <form method="POST" action="/waivers/<?= (int) $waiver['id'] ?>/approve"><?= csrf_field() ?><button type="submit" class="btn btn-primary" onclick="return confirm('اعتماد التنازل؟')">✅ اعتماد مجلس الأمناء</button></form>
    <form method="POST" action="/waivers/<?= (int) $waiver['id'] ?>/reject"><?= csrf_field() ?><button type="submit" class="btn btn-outline" style="color:#DC2626;" onclick="return confirm('رفض التنازل؟')">❌ رفض</button></form>
</div>
<?php endif; ?>
<script>document.addEventListener('DOMContentLoaded', function() { if (typeof lucide !== 'undefined') lucide.createIcons(); });</script>
<?php $__template->endSection(); ?>