<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>طلب تحويل/فصل — <?= e($member['full_name_ar']) ?><?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>
<div class="card" style="margin-bottom:15px;padding:15px;">
    <strong>العضو:</strong> <?= e($member['full_name_ar']) ?> — <strong>رقم العضوية:</strong> <?= e($member['membership_number'] ?? '—') ?>
    &nbsp;|&nbsp; <strong>الملحقين:</strong> <?= count($spouses) ?> زوج/ة، <?= count($children) ?> ابن/ابنة
</div>
<form method="POST" action="/transfers/store/<?= (int) $member['id'] ?>">
    <?= csrf_field() ?>
    <div class="card" style="padding:20px;margin-bottom:20px;">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:15px;">
            <div class="form-group">
                <label class="form-label">نوع التحويل <span style="color:#DC2626;">*</span></label>
                <select name="transfer_type" id="transfer_type" class="form-select" required>
                    <option value="">-- اختر --</option>
                    <option value="full_transfer">تحويل العضوية لمستلم جديد</option>
                    <option value="child_separation">فصل أبناء</option>
                    <option value="child_mandatory_25">تحويل وجوبي (25 سنة)</option>
                    <option value="sports_conversion">تحويل رياضي لعامل</option>
                    <option value="cross_branch">تحويل بين فروع</option>
                </select>
            </div>
            <div class="form-group" id="child-select" style="display:none;">
                <label class="form-label">اختيار الابن/الابنة</label>
                <select name="child_id" id="child_id" class="form-select">
                    <option value="">-- اختر --</option>
                    <?php foreach ($children as $c):
                        $dob = $c['date_of_birth'] ?? null;
                        $childAge = 0;
                        if ($dob) {
                            $childAge = (int) (new \DateTime($dob))->diff(new \DateTime())->y;
                        }
                    ?>
                    <option value="<?= (int) $c['id'] ?>" data-age="<?= $childAge ?>"><?= e($c['full_name_ar']) ?> — <?= $childAge ?> سنة (<?= $c['gender'] === 'male' ? 'ذكر' : 'أنثى' ?>)</option>
                    <?php endforeach; ?>
                </select>
                <div id="age-warning" style="display:none;margin-top:6px;padding:8px 12px;background:#FEE2E2;border:1px solid #FECACA;border-radius:6px;font-size:13px;color:#DC2626;">
                    <strong>تنبيه:</strong> لا يمكن فصل الملحقين تحت سن 25 سنة. يتم الفصل الوجوبي فقط عند بلوغ 25 سنة.
                </div>
            </div>
        </div>
    </div>

    <!-- Recipient Data (for full_transfer) -->
    <div id="recipient-section" style="display:none;">
        <div class="card" style="margin-bottom:20px;border:2px solid #0D7377;">
            <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;background:#F0FDFA;">
                <h3 style="margin:0;color:#0D7377;font-size:15px;">بيانات المستلم الجديد</h3>
                <p style="margin:5px 0 0;font-size:12px;color:#6B7280;">المستلم سيحصل على نفس رقم العضوية (<?= e($member['membership_number'] ?? '') ?>)</p>
            </div>
            <div style="padding:20px;display:grid;grid-template-columns:1fr 1fr;gap:15px;">
                <div class="form-group" style="grid-column:1/-1;">
                    <label class="form-label">الاسم بالكامل (عربي) <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="recipient_full_name_ar" class="form-input">
                </div>
                <div class="form-group">
                    <label class="form-label">الاسم بالإنجليزي</label>
                    <input type="text" name="recipient_full_name_en" class="form-input">
                </div>
                <div class="form-group">
                    <label class="form-label">الرقم القومي <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="recipient_national_id" id="recipientNidInput" class="form-input" maxlength="14" style="direction:ltr;text-align:left;">
                    <small id="recipientNidStatus" style="display:none;margin-top:4px;font-size:11px;"></small>
                </div>
                <div class="form-group">
                    <label class="form-label">تاريخ الميلاد</label>
                    <input type="date" name="recipient_date_of_birth" id="recipientDobInput" class="form-input" readonly style="background:#F9FAFB;">
                </div>
                <div class="form-group">
                    <label class="form-label">النوع</label>
                    <select name="recipient_gender" id="recipientGenderSelect" class="form-select" disabled>
                        <option value="male">ذكر</option>
                        <option value="female">أنثى</option>
                    </select>
                    <input type="hidden" name="recipient_gender" id="recipientGenderHidden" value="male">
                </div>
                <div class="form-group">
                    <label class="form-label">الهاتف المحمول</label>
                    <input type="text" name="recipient_phone_mobile" class="form-input">
                </div>
                <div class="form-group">
                    <label class="form-label">الجنسية</label>
                    <input type="text" name="recipient_nationality" class="form-input" value="مصري">
                </div>
            </div>
        </div>
    </div>

    <!-- Companion Validation (for full_transfer) -->
    <div id="companion-section" style="display:none;">
        <div class="card" style="margin-bottom:20px;border:2px solid #7C3AED;">
            <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;background:#F5F3FF;">
                <h3 style="margin:0;color:#7C3AED;font-size:15px;">ملحقين المستلم الجديد</h3>
                <p style="margin:5px 0 0;font-size:12px;color:#6B7280;">العضوية الحالية بها <?= count($spouses) ?> زوج/ة و <?= count($children) ?> ابن/ابنة. إذا كان للمستلم ملحقين أكثر سيتم احتساب رسوم إضافية.</p>
            </div>
            <div style="padding:20px;display:grid;grid-template-columns:1fr 1fr;gap:15px;">
                <div class="form-group">
                    <label class="form-label">عدد الزوجات لدى المستلم</label>
                    <input type="number" name="target_spouses_count" id="target_spouses_count" class="form-input" value="0" min="0" max="4">
                    <small style="color:#6B7280;font-size:11px;">العضوية الحالية: <?= count($spouses) ?> زوج/ة</small>
                </div>
                <div class="form-group">
                    <label class="form-label">عدد الأبناء لدى المستلم</label>
                    <input type="number" name="target_children_count" id="target_children_count" class="form-input" value="0" min="0" max="20">
                    <small style="color:#6B7280;font-size:11px;">العضوية الحالية: <?= count($children) ?> ابن/ابنة</small>
                </div>
            </div>
            <div id="children-ages-section" style="display:none;padding:0 20px 20px;">
                <label class="form-label" style="margin-bottom:8px;">أعمار الأبناء الإضافيين (لحساب الرسوم بدقة)</label>
                <div id="children-ages-inputs" style="display:flex;gap:8px;flex-wrap:wrap;"></div>
            </div>
            <div id="companion-surcharge-preview" style="display:none;padding:0 20px 20px;">
                <div style="padding:12px;background:#FEF3C7;border-radius:6px;font-size:13px;">
                    <strong style="color:#D97706;">رسوم ملحقين إضافيين:</strong>
                    <div id="surcharge-details" style="margin-top:8px;"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Notes -->
    <div class="card" style="padding:20px;margin-bottom:20px;">
        <div class="form-group">
            <label class="form-label">ملاحظات</label>
            <textarea name="notes" class="form-textarea" rows="3"></textarea>
        </div>
    </div>

    <!-- Fee & Payment -->
    <div class="card" style="padding:20px;margin-bottom:20px;background:#FFF7ED;border:2px solid #F59E0B;">
        <h4 style="margin:0 0 15px;color:#D97706;">رسوم الإجراء</h4>
        <p style="font-size:13px;color:#6B7280;margin-bottom:15px;">سيتم احتساب رسوم الفصل/التحويل تلقائياً (نسبة من قيمة العضوية حسب سنوات الاكتساب + رسوم استمارة + اشتراك سنوي + رسوم ملحقين إضافيين إن وجدت).</p>
        <div id="fee-preview" style="display:none;margin-bottom:15px;padding:12px;background:#FEF3C7;border-radius:6px;">
            <table style="font-size:14px;">
                <tr><td style="padding:3px 15px 3px 0;color:#6B7280;">رسوم الفصل</td><td id="fp-separation" style="font-weight:600;">—</td></tr>
                <tr><td style="padding:3px 15px 3px 0;color:#6B7280;">رسوم الاستمارة</td><td id="fp-form" style="font-weight:600;">—</td></tr>
                <tr><td style="padding:3px 15px 3px 0;color:#6B7280;">اشتراك سنوي</td><td id="fp-annual" style="font-weight:600;">—</td></tr>
                <tr id="fp-surcharge-row" style="display:none;"><td style="padding:3px 15px 3px 0;color:#7C3AED;font-weight:600;">رسوم ملحقين إضافيين</td><td id="fp-surcharge" style="font-weight:600;color:#7C3AED;">—</td></tr>
                <tr style="border-top:2px solid #D97706;"><td style="padding:6px 15px 3px 0;font-weight:700;">الإجمالي</td><td id="fp-total" style="font-weight:700;font-size:18px;color:#DC2626;">—</td></tr>
            </table>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:15px;">
            <div class="form-group">
                <label class="form-label">طريقة الدفع <span style="color:#DC2626;">*</span></label>
                <select name="payment_method" class="form-select" required>
                    <option value="cash">نقدي</option>
                    <option value="visa">فيزا</option>
                    <option value="bank_transfer">تحويل بنكي</option>
                </select>
            </div>
        </div>
    </div>

    <button type="submit" class="btn btn-primary" onclick="return confirm('سيتم تقديم الطلب وتحصيل الرسوم. متأكد؟')">تقديم الطلب وتحصيل الرسوم</button>
    <a href="/members/<?= (int) $member['id'] ?>" class="btn btn-outline">إلغاء</a>
</form>
<?php $__template->endSection(); ?>

<?php $__template->section('scripts'); ?>
<script>
(function() {
    var transferType = document.getElementById('transfer_type');
    var childSelect = document.getElementById('child_id');
    var childGroup = document.getElementById('child-select');
    var ageWarning = document.getElementById('age-warning');
    var recipientSection = document.getElementById('recipient-section');
    var companionSection = document.getElementById('companion-section');
    var allOptions = Array.from(childSelect.querySelectorAll('option[data-age]'));
    var targetSpouses = document.getElementById('target_spouses_count');
    var targetChildren = document.getElementById('target_children_count');
    var childrenAgesSection = document.getElementById('children-ages-section');
    var childrenAgesInputs = document.getElementById('children-ages-inputs');
    var sourceSpouses = <?= count($spouses) ?>;
    var sourceChildren = <?= count($children) ?>;

    function updateUI() {
        var type = transferType.value;
        var isChildType = (type === 'child_separation' || type === 'child_mandatory_25');
        var isFullTransfer = (type === 'full_transfer');

        childGroup.style.display = isChildType ? 'block' : 'none';
        recipientSection.style.display = isFullTransfer ? 'block' : 'none';
        companionSection.style.display = isFullTransfer ? 'block' : 'none';

        childSelect.value = '';
        ageWarning.style.display = 'none';

        if (isChildType) {
            allOptions.forEach(function(opt) {
                var age = parseInt(opt.getAttribute('data-age'), 10);
                if (type === 'child_separation') {
                    opt.style.display = age >= 25 ? '' : 'none';
                    opt.disabled = age < 25;
                } else {
                    opt.style.display = '';
                    opt.disabled = false;
                }
            });
            if (type === 'child_separation') {
                var hasEligible = allOptions.some(function(opt) { return parseInt(opt.getAttribute('data-age'), 10) >= 25; });
                if (!hasEligible) ageWarning.style.display = 'block';
            }
        }

        fetchFeePreview();
    }

    function updateChildrenAgeInputs() {
        var extra = Math.max(0, parseInt(targetChildren.value || '0', 10) - sourceChildren);
        childrenAgesSection.style.display = extra > 0 ? 'block' : 'none';
        childrenAgesInputs.innerHTML = '';
        for (var i = 0; i < extra; i++) {
            var inp = document.createElement('input');
            inp.type = 'number';
            inp.name = 'target_children_ages[]';
            inp.className = 'form-input';
            inp.style.width = '80px';
            inp.min = '0';
            inp.max = '30';
            inp.value = '10';
            inp.placeholder = 'سن #' + (i + 1);
            childrenAgesInputs.appendChild(inp);
        }
    }

    function fetchFeePreview() {
        var type = transferType.value;
        if (!type) {
            document.getElementById('fee-preview').style.display = 'none';
            return;
        }
        var memberId = <?= (int) $member['id'] ?>;
        var childId = childSelect.value || '';
        fetch('/api/transfers/calculate-fee', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': document.querySelector('[name=_csrf_token]').value},
            body: 'member_id=' + memberId + '&child_id=' + childId
        })
        .then(function(r) { return r.json(); })
        .then(function(d) {
            if (d.success) {
                document.getElementById('fp-separation').textContent = d.separation_fee;
                document.getElementById('fp-form').textContent = d.form_fee;
                document.getElementById('fp-annual').textContent = d.annual_subscription_fee;
                document.getElementById('fp-total').textContent = d.total_fee;
                document.getElementById('fee-preview').style.display = 'block';
                document.getElementById('fp-surcharge-row').style.display = 'none';
            }
        })
        .catch(function() {});
    }

    transferType.addEventListener('change', updateUI);
    childSelect.addEventListener('change', fetchFeePreview);
    targetSpouses.addEventListener('change', updateChildrenAgeInputs);
    targetChildren.addEventListener('change', updateChildrenAgeInputs);

    // Recipient NID auto-parse
    var rNid = document.getElementById('recipientNidInput');
    var rDob = document.getElementById('recipientDobInput');
    var rGenderSelect = document.getElementById('recipientGenderSelect');
    var rGenderHidden = document.getElementById('recipientGenderHidden');
    var rStatus = document.getElementById('recipientNidStatus');

    function parseRecipientNid(val) {
        if (val.length !== 14) { rStatus.style.display = 'none'; rDob.readOnly = false; rDob.style.background = ''; rGenderSelect.disabled = false; return; }
        fetch('/api/members/parse-nid', {
            method: 'POST',
            headers: {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'},
            body: JSON.stringify({national_id: val})
        })
        .then(function(r){ return r.json(); })
        .then(function(d){
            if (d.success && d.data) {
                rDob.value = d.data.dob || '';
                rDob.readOnly = true;
                rDob.style.background = '#F9FAFB';
                var g = d.data.gender || '';
                rGenderSelect.value = g;
                rGenderSelect.disabled = true;
                rGenderHidden.value = g;
                rStatus.style.display = 'block';
                rStatus.style.color = '#059669';
                rStatus.textContent = (d.data.governorate || '') + ' — ' + (d.data.age || '') + ' سنة';
            } else {
                rStatus.style.display = 'block';
                rStatus.style.color = '#DC2626';
                rStatus.textContent = d.message || 'رقم قومي غير صحيح';
            }
        }).catch(function(){});
    }

    rNid.addEventListener('input', function(){ parseRecipientNid(this.value.trim()); });
    rGenderSelect.addEventListener('change', function(){ rGenderHidden.value = this.value; });
})();
</script>
<?php $__template->endSection(); ?>