<?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 ?>" data-gender="<?= e($c['gender']) ?>"><?= 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>

    <!-- فصل أبناء — Employment & Date Fields (MALE path) -->
    <div id="child-separation-section" style="display:none;">
        <div class="card" style="margin-bottom:20px;border:2px solid #0D9488;">
            <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;background:#F0FDF4;">
                <h3 style="margin:0;color:#0D9488;font-size:15px;">بيانات فصل الأبناء</h3>
                <p style="margin:5px 0 0;font-size:12px;color:#6B7280;" id="child-sep-subtitle">يتم احتساب تاريخ الفصل الفعلي تلقائياً بناءً على حالة التوظيف وتاريخ بلوغ الـ 25</p>
            </div>
            <div style="padding:20px;display:grid;grid-template-columns:1fr 1fr;gap:15px;">

                <!-- Form Number (manual input) -->
                <div class="form-group" style="grid-column:1/-1;margin-bottom:15px;">
                    <label class="form-label">رقم الاستمارة <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="form_number" id="form_number" class="form-input" required placeholder="أدخل رقم الاستمارة" style="max-width:300px;">
                </div>

                <!-- MALE-only fields -->
                <div id="male-separation-fields">
                    <!-- Employment Status -->
                    <div class="form-group" style="grid-column:1/-1;margin-bottom:15px;">
                        <label class="form-label">الحالة الوظيفية <span style="color:#DC2626;">*</span></label>
                        <div style="display:flex;gap:20px;margin-top:6px;">
                            <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                                <input type="radio" name="is_employed" id="is_employed_no" value="0">
                                <span>غير موظف</span>
                            </label>
                            <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                                <input type="radio" name="is_employed" id="is_employed_yes" value="1">
                                <span>موظف</span>
                            </label>
                        </div>
                    </div>

                    <!-- Graduation Date (required when employed) -->
                    <div class="form-group" id="graduation-date-group" style="margin-bottom:15px;">
                        <label class="form-label">تاريخ التخرج <span id="grad-required-mark" style="color:#DC2626;display:none;">*</span></label>
                        <input type="date" name="graduation_date" id="graduation_date" class="form-input">
                    </div>

                    <!-- Work Date (shown only when employed) -->
                    <div class="form-group" id="work-date-group" style="display:none;margin-bottom:15px;">
                        <label class="form-label">تاريخ مباشرة العمل <span style="color:#DC2626;">*</span></label>
                        <input type="date" name="work_date" id="work_date" class="form-input">
                        <small style="color:#6B7280;font-size:11px;">الفصل يتم عند أبكر التاريخين: اكتمال العمل والتخرج أو بلوغ الـ 25</small>
                    </div>

                    <!-- date_turned_25 — auto-computed, editable override -->
                    <div class="form-group" style="margin-bottom:15px;">
                        <label class="form-label">تاريخ بلوغ الـ 25 <span style="font-size:11px;color:#6B7280;">(محسوب تلقائياً — قابل للتعديل)</span></label>
                        <input type="date" name="date_turned_25" id="date_turned_25" class="form-input" style="background:#F9FAFB;">
                        <small id="date25-auto-note" style="color:#059669;font-size:11px;display:none;">محسوب تلقائياً من تاريخ الميلاد</small>
                    </div>
                </div>

                <!-- FEMALE-only fields -->
                <div id="female-separation-fields" style="display:none;">
                    <div class="form-group" style="margin-bottom:15px;">
                        <label class="form-label">تاريخ الزواج <span style="color:#DC2626;">*</span></label>
                        <input type="date" name="marriage_date" id="marriage_date" class="form-input">
                        <small style="color:#6B7280;font-size:11px;">يتم احتساب سنوات الاكتساب من تاريخ الزواج</small>
                    </div>
                </div>

                <!-- Effective Transfer Date (read-only display) -->
                <div class="form-group">
                    <label class="form-label">تاريخ الفصل الفعلي</label>
                    <input type="text" id="effective_transfer_date_display" class="form-input" readonly style="background:#F9FAFB;font-weight:600;color:#0D9488;">
                    <small style="color:#6B7280;font-size:11px;" id="effective-basis-note"></small>
                </div>

                <!-- Elapsed years display -->
                <div class="form-group" id="elapsed-years-group" style="display:none;">
                    <label class="form-label">سنوات الاكتساب المكتملة</label>
                    <div id="elapsed-years-display" style="padding:10px 14px;background:#FEF9C3;border-radius:6px;font-size:14px;font-weight:600;color:#92400E;"></div>
                    <small style="color:#6B7280;font-size:11px;">محسوب بالتمام فقط — لا يُقرَّب للأعلى</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Dependents for new membership (child_separation) -->
    <div id="child-sep-dependents-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;">حدد التابعين الذين سيُضافون للعضوية الجديدة — سيتم احتساب اشتراكاتهم السنوية ضمن الرسوم</p>
            </div>
            <div style="padding:20px;display:grid;grid-template-columns:1fr 1fr 1fr;gap:15px;">
                <div class="form-group">
                    <label class="form-label">عدد الزوجات</label>
                    <input type="number" name="dep_spouses_count" id="dep_spouses_count" class="form-input" value="0" min="0" max="4">
                </div>
                <div class="form-group">
                    <label class="form-label">عدد الأبناء</label>
                    <input type="number" name="dep_children_count" id="dep_children_count" class="form-input" value="0" min="0" max="20">
                </div>
                <div class="form-group">
                    <label class="form-label">عدد الأعضاء المؤقتين</label>
                    <input type="number" name="dep_temps_count" id="dep_temps_count" class="form-input" value="0" min="0" max="10">
                </div>
            </div>
            <!-- Dynamic dependent detail rows -->
            <div id="dep-details-container" style="padding:0 20px 20px;display:none;">
                <div id="dep-spouses-details"></div>
                <div id="dep-children-details"></div>
                <div id="dep-temps-details"></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><td id="fp-annual-note" style="font-size:11px;color:#059669;padding-right:8px;display:none;">✅ مشمول في العضوية</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 childSeparationSection = document.getElementById('child-separation-section');
    var childSepDepsSection = document.getElementById('child-sep-dependents-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) ?>;

    // فصل أبناء elements
    var isEmployedYes = document.getElementById('is_employed_yes');
    var isEmployedNo  = document.getElementById('is_employed_no');
    var workDateGroup = document.getElementById('work-date-group');
    var workDateInput = document.getElementById('work_date');
    var gradDateInput = document.getElementById('graduation_date');
    var gradRequiredMark = document.getElementById('grad-required-mark');
    var date25Input   = document.getElementById('date_turned_25');
    var date25Note    = document.getElementById('date25-auto-note');
    var effectiveDisplay = document.getElementById('effective_transfer_date_display');
    var effectiveBasis   = document.getElementById('effective-basis-note');
    var elapsedGroup     = document.getElementById('elapsed-years-group');
    var elapsedDisplay   = document.getElementById('elapsed-years-display');
    var maleFields   = document.getElementById('male-separation-fields');
    var femaleFields  = document.getElementById('female-separation-fields');
    var marriageDateInput = document.getElementById('marriage_date');
    var childSepSubtitle = document.getElementById('child-sep-subtitle');

    // Dependents for new membership (child_separation)
    var depSpousesCount = document.getElementById('dep_spouses_count');
    var depChildrenCount = document.getElementById('dep_children_count');
    var depTempsCount = document.getElementById('dep_temps_count');
    var depDetailsContainer = document.getElementById('dep-details-container');

    // child DOB lookup — keyed by child_id
    var childDobMap = {};
    <?php foreach ($children as $c): if (empty($c['date_of_birth'])) continue; ?>
    childDobMap[<?= (int)$c['id'] ?>] = '<?= htmlspecialchars(substr($c['date_of_birth'], 0, 10)) ?>';
    <?php endforeach; ?>

    function addYears(dateStr, years) {
        var d = new Date(dateStr);
        d.setFullYear(d.getFullYear() + years);
        return d.toISOString().slice(0, 10);
    }

    function isEmployed() {
        return isEmployedYes && isEmployedYes.checked;
    }

    function getSelectedChildGender() {
        var sel = childSelect.options[childSelect.selectedIndex];
        if (!sel || !sel.value) return null;
        return sel.getAttribute('data-gender') || null;
    }

    function isFemaleChild() {
        return getSelectedChildGender() === 'female';
    }

    function updateGenderFieldsVisibility() {
        var female = isFemaleChild();
        maleFields.style.display = female ? 'none' : '';
        femaleFields.style.display = female ? '' : 'none';
        if (female) {
            childSepSubtitle.textContent = 'للإناث: يتم احتساب تاريخ الفصل بناءً على تاريخ الزواج فقط';
        } else {
            childSepSubtitle.textContent = 'يتم احتساب تاريخ الفصل الفعلي تلقائياً بناءً على حالة التوظيف وتاريخ بلوغ الـ 25';
        }
    }

    function updateDate25FromChild() {
        var cid = parseInt(childSelect.value, 10);
        var dob = childDobMap[cid] || null;
        if (!dob) { date25Input.value = ''; date25Note.style.display = 'none'; return; }
        var d25 = addYears(dob, 25);
        if (!date25Input.dataset.userOverride) {
            date25Input.value = d25;
            date25Note.style.display = 'block';
        }
        updateGenderFieldsVisibility();
        updateEffectiveDate();
    }

    function updateEffectiveDate() {
        // Female path: use marriage_date only
        if (isFemaleChild()) {
            var mDate = marriageDateInput.value;
            if (!mDate) {
                effectiveDisplay.value = '';
                effectiveBasis.textContent = 'أدخل تاريخ الزواج لتحديد تاريخ الفصل';
                elapsedGroup.style.display = 'none';
                return;
            }
            effectiveDisplay.value = mDate;
            effectiveBasis.textContent = 'الفصل يتم عند تاريخ الزواج';
            fetchFeePreview();
            return;
        }

        // Male path: work + graduation + date_turned_25
        var d25 = date25Input.value;
        var wDate = workDateInput.value;
        var gDate = gradDateInput.value;
        var emp = isEmployed();

        workDateGroup.style.display = emp ? 'block' : 'none';
        gradRequiredMark.style.display = emp ? 'inline' : 'none';

        if (!d25) { effectiveDisplay.value = ''; effectiveBasis.textContent = ''; elapsedGroup.style.display = 'none'; return; }

        var effective;
        if (emp && wDate && gDate) {
            var conditionMet = wDate > gDate ? wDate : gDate;
            effective = conditionMet < d25 ? conditionMet : d25;
            if (conditionMet <= d25) {
                effectiveBasis.textContent = 'الفصل يتم عند اكتمال العمل والتخرج (' + conditionMet + ')';
            } else {
                effectiveBasis.textContent = 'الفصل يتم عند بلوغ 25 سنة (أبكر من اكتمال الشرطين)';
            }
        } else if (emp) {
            effective = d25;
            effectiveBasis.textContent = 'أدخل تاريخ العمل وتاريخ التخرج لتحديد التاريخ الفعلي';
        } else {
            effective = d25;
            effectiveBasis.textContent = 'الفصل يتم عند بلوغ 25 سنة';
        }
        effectiveDisplay.value = effective;

        fetchFeePreview();
    }

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

        childGroup.style.display = isChildType ? 'block' : 'none';
        childSeparationSection.style.display = isChildSeparation ? 'block' : 'none';
        childSepDepsSection.style.display = isChildSeparation ? '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) {
                if (type === 'child_separation') {
                    // All children are eligible: males >= 25 (age), males < 25 (work/graduation), females (marriage)
                    opt.style.display = '';
                    opt.disabled = false;
                } else {
                    opt.style.display = '';
                    opt.disabled = false;
                }
            });
        }

        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 updateDepDetailRows() {
        var spCount = parseInt(depSpousesCount.value || '0', 10);
        var chCount = parseInt(depChildrenCount.value || '0', 10);
        var tmCount = parseInt(depTempsCount.value || '0', 10);
        var hasAny = (spCount + chCount + tmCount) > 0;
        depDetailsContainer.style.display = hasAny ? 'block' : 'none';

        document.getElementById('dep-spouses-details').innerHTML = buildDepRows('dep_spouses', spCount, 'زوجة', ['full_name_ar', 'national_id']);
        document.getElementById('dep-children-details').innerHTML = buildDepRows('dep_children', chCount, 'ابن/ابنة', ['full_name_ar', 'national_id', 'gender']);
        document.getElementById('dep-temps-details').innerHTML = buildDepRows('dep_temps', tmCount, 'عضو مؤقت', ['full_name_ar', 'national_id']);

        fetchFeePreview();
    }

    function buildDepRows(prefix, count, label, fields) {
        if (count === 0) return '';
        var html = '<div style="margin-bottom:12px;"><strong style="font-size:13px;color:#7C3AED;">' + label + ' (' + count + ')</strong></div>';
        for (var i = 0; i < count; i++) {
            html += '<div style="border:1px solid #E5E7EB;border-radius:8px;padding:12px;margin-bottom:10px;">';
            html += '<div style="font-size:12px;color:#6B7280;margin-bottom:8px;font-weight:600;">' + (i+1) + '. ' + label + '</div>';
            html += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">';
            html += '<input type="text" name="' + prefix + '[' + i + '][full_name_ar]" class="form-input" placeholder="الاسم بالكامل *" required>';
            html += '<input type="text" name="' + prefix + '[' + i + '][national_id]" class="form-input" style="direction:ltr;text-align:left;" placeholder="الرقم القومي (14 رقم)" maxlength="14">';
            if (prefix === 'dep_spouses') {
                html += '<div class="form-group" style="margin:0;"><label style="font-size:11px;color:#6B7280;">تاريخ الميلاد *</label><input type="date" name="' + prefix + '[' + i + '][date_of_birth]" class="form-input" required></div>';
                html += '<div class="form-group" style="margin:0;"><label style="font-size:11px;color:#6B7280;">الجنسية *</label><select name="' + prefix + '[' + i + '][nationality]" class="form-select"><option value="مصري">مصري</option><option value="أجنبي">أجنبي (غير مصري)</option></select></div>';
                html += '<div class="form-group" style="margin:0;"><label style="font-size:11px;color:#6B7280;">تاريخ الزواج *</label><input type="date" name="' + prefix + '[' + i + '][marriage_date]" class="form-input" required></div>';
                html += '<div class="form-group" style="margin:0;"><label style="font-size:11px;color:#6B7280;">تاريخ الانضمام *</label><input type="date" name="' + prefix + '[' + i + '][join_date]" class="form-input" value="' + (new Date().toISOString().split('T')[0]) + '" required></div>';
                html += '<div class="form-group" style="margin:0;"><label style="font-size:11px;color:#6B7280;">تاريخ السداد</label><input type="date" name="' + prefix + '[' + i + '][payment_date]" class="form-input" value="' + (new Date().toISOString().split('T')[0]) + '"></div>';
            } else if (prefix === 'dep_children') {
                html += '<div class="form-group" style="margin:0;"><label style="font-size:11px;color:#6B7280;">تاريخ الميلاد *</label><input type="date" name="' + prefix + '[' + i + '][date_of_birth]" class="form-input" required></div>';
                html += '<div class="form-group" style="margin:0;"><label style="font-size:11px;color:#6B7280;">النوع *</label><select name="' + prefix + '[' + i + '][gender]" class="form-select"><option value="male">ذكر</option><option value="female">أنثى</option></select></div>';
                html += '<div class="form-group" style="margin:0;"><label style="font-size:11px;color:#6B7280;">تاريخ الانضمام</label><input type="date" name="' + prefix + '[' + i + '][join_date]" class="form-input" value="' + (new Date().toISOString().split('T')[0]) + '"></div>';
            } else {
                html += '<div class="form-group" style="margin:0;"><label style="font-size:11px;color:#6B7280;">تاريخ الميلاد</label><input type="date" name="' + prefix + '[' + i + '][date_of_birth]" class="form-input"></div>';
                html += '<div class="form-group" style="margin:0;"><label style="font-size:11px;color:#6B7280;">النوع</label><select name="' + prefix + '[' + i + '][gender]" class="form-select"><option value="male">ذكر</option><option value="female">أنثى</option></select></div>';
            }
            html += '</div></div>';
        }
        return html;
    }

    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 || '';

        var body = 'member_id=' + memberId + '&child_id=' + childId + '&transfer_type=' + encodeURIComponent(type);

        if (type === 'child_separation') {
            var childGender = getSelectedChildGender() || 'male';
            body += '&child_gender=' + childGender;
            if (childGender === 'female') {
                if (marriageDateInput.value) body += '&marriage_date=' + encodeURIComponent(marriageDateInput.value);
            } else {
                var emp = isEmployed() ? '1' : '0';
                body += '&is_employed=' + emp;
                if (workDateInput.value) body += '&work_date=' + encodeURIComponent(workDateInput.value);
                if (gradDateInput.value) body += '&graduation_date=' + encodeURIComponent(gradDateInput.value);
                if (date25Input.value)   body += '&date_turned_25=' + encodeURIComponent(date25Input.value);
            }
            body += '&dep_spouses_count=' + (depSpousesCount.value || '0');
            body += '&dep_children_count=' + (depChildrenCount.value || '0');
            body += '&dep_temps_count=' + (depTempsCount.value || '0');
        }

        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: body
        })
        .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;
                var annualNote = document.getElementById('fp-annual-note');
                if (d.annual_sub_covered) {
                    document.getElementById('fp-annual').textContent = '0.00';
                    annualNote.style.display = '';
                } else {
                    document.getElementById('fp-annual').textContent = d.annual_subscription_fee;
                    annualNote.style.display = 'none';
                }
                document.getElementById('fp-total').textContent = d.total_fee;
                document.getElementById('fee-preview').style.display = 'block';
                document.getElementById('fp-surcharge-row').style.display = 'none';

                if (type === 'child_separation' && d.years_since_acquisition) {
                    elapsedGroup.style.display = 'block';
                    elapsedDisplay.textContent = d.years_since_acquisition + ' سنة — نسبة ' + d.fee_percentage + '%';
                } else {
                    elapsedGroup.style.display = 'none';
                }
            }
        })
        .catch(function() {});
    }

    transferType.addEventListener('change', updateUI);
    childSelect.addEventListener('change', function() {
        date25Input.removeAttribute('data-user-override');
        updateDate25FromChild();
        fetchFeePreview();
    });
    targetSpouses.addEventListener('change', updateChildrenAgeInputs);
    targetChildren.addEventListener('change', updateChildrenAgeInputs);

    // فصل أبناء listeners
    if (isEmployedYes) {
        isEmployedYes.addEventListener('change', updateEffectiveDate);
        isEmployedNo.addEventListener('change', updateEffectiveDate);
    }
    if (workDateInput) workDateInput.addEventListener('change', updateEffectiveDate);
    if (gradDateInput) gradDateInput.addEventListener('change', updateEffectiveDate);
    if (marriageDateInput) marriageDateInput.addEventListener('change', updateEffectiveDate);
    if (date25Input) {
        date25Input.addEventListener('change', function() {
            this.dataset.userOverride = '1';
            updateEffectiveDate();
        });
    }

    // Dependent count listeners (child_separation)
    if (depSpousesCount) depSpousesCount.addEventListener('change', updateDepDetailRows);
    if (depChildrenCount) depChildrenCount.addEventListener('change', updateDepDetailRows);
    if (depTempsCount) depTempsCount.addEventListener('change', updateDepDetailRows);

    // 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; }
        var formData = new FormData();
        formData.append('national_id', val);
        var csrfToken = document.querySelector('input[name="_csrf_token"]');
        if (csrfToken) formData.append('_csrf_token', csrfToken.value);

        fetch('/api/members/parse-nid', {method: 'POST', body: formData})
        .then(function(r){ return r.json(); })
        .then(function(d){
            var p = d.parsed;
            if (p && p.is_valid) {
                rDob.value = p.dob || '';
                rDob.readOnly = true;
                rDob.style.background = '#F9FAFB';
                var g = p.gender || '';
                rGenderSelect.value = g;
                rGenderSelect.disabled = true;
                rGenderHidden.value = g;
                rStatus.style.display = 'block';
                rStatus.style.color = '#059669';
                rStatus.textContent = (p.governorate_name_ar || '') + ' — ' + (p.age_years || '') + ' سنة';
            } else {
                rStatus.style.display = 'block';
                rStatus.style.color = '#DC2626';
                rStatus.textContent = (p && p.errors) ? p.errors[0] : 'رقم قومي غير صحيح';
            }
        }).catch(function(){});
    }

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