<?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;display:flex;justify-content:space-between;align-items:center;">
    <div><strong>العضو:</strong> <?= e($member['full_name_ar']) ?> &nbsp;|&nbsp; <strong>رقم العضوية:</strong> <?= e($member['membership_number'] ?? '—') ?></div>
    <a href="/members/<?= (int) $member['id'] ?>" class="btn btn-outline">← العودة</a>
</div>

<form method="POST" action="/members/<?= (int) $member['id'] ?>/seasonal" id="seasonalForm">
    <?= csrf_field() ?>

    <div class="card" style="padding:20px;margin-bottom:20px;">
        <h3 style="margin:0 0 15px;color:#0D7377;">1. نوع العضوية والمدة</h3>
        <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:15px;">
            <div class="form-group">
                <label class="form-label">نوع الجنسية <span style="color:#DC2626;">*</span></label>
                <select name="nationality_type" id="nationalityType" class="form-select" required onchange="updatePricing()">
                    <option value="egyptian">مصري (جنيه مصري)</option>
                    <option value="foreign">أجنبي (دولار أمريكي)</option>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">المدة <span style="color:#DC2626;">*</span></label>
                <select name="duration_months" id="durationMonths" class="form-select" required onchange="updatePricing()">
                    <option value="6">6 أشهر</option>
                    <option value="12">سنة</option>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">الفرع <span style="color:#DC2626;">*</span></label>
                <select name="branch_id" class="form-select" required>
                    <option value="">-- اختر --</option>
                    <?php foreach ($branches as $b): ?><option value="<?= (int) $b['id'] ?>"><?= e($b['name_ar']) ?></option><?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">تاريخ البداية <span style="color:#DC2626;">*</span></label>
                <input type="date" name="start_date" value="<?= e(date('Y-m-d')) ?>" class="form-input" required>
            </div>
        </div>
        <div style="margin-top:10px;">
            <label style="display:flex;align-items:center;gap:8px;font-size:13px;color:#6B7280;">
                <input type="checkbox" name="has_qualification" value="1" checked onchange="updatePricing()">
                العضو حاصل على مؤهل عالي / متوسط (عدم التفعيل = خصم 10%)
            </label>
        </div>
    </div>

    <!-- Family Members Selection -->
    <div class="card" style="padding:20px;margin-bottom:20px;">
        <h3 style="margin:0 0 15px;color:#0D7377;">2. أفراد الأسرة المشتركون</h3>
        <p style="color:#6B7280;font-size:13px;margin:0 0 15px;">العضو نفسه مشمول تلقائياً. أضف أفراد الأسرة للاشتراك معه — سيتم حساب الرسوم لكل فرد حسب فئته العمرية.</p>

        <?php if (!empty($spouses)): ?>
        <div style="margin-bottom:15px;">
            <div style="font-size:12px;color:#0D7377;font-weight:700;margin-bottom:8px;">الزوجات المسجلة</div>
            <?php foreach ($spouses as $sp): ?>
            <label style="display:flex;align-items:center;gap:8px;padding:8px 12px;background:#F9FAFB;border-radius:8px;margin-bottom:4px;cursor:pointer;">
                <input type="checkbox" name="spouses[]" value="<?= (int) $sp['id'] ?>" onchange="updatePricing()">
                <span><?= e($sp['full_name_ar']) ?></span>
            </label>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <?php if (!empty($children)): ?>
        <div style="margin-bottom:15px;">
            <div style="font-size:12px;color:#0D7377;font-weight:700;margin-bottom:8px;">الأبناء المسجلون</div>
            <?php foreach ($children as $ch): ?>
            <label style="display:flex;align-items:center;gap:8px;padding:8px 12px;background:#F9FAFB;border-radius:8px;margin-bottom:4px;cursor:pointer;">
                <input type="checkbox" name="children[]" value="<?= (int) $ch['id'] ?>" onchange="updatePricing()">
                <span><?= e($ch['full_name_ar']) ?> (<?= (int) $ch['age'] ?> سنة — <?= $ch['gender'] === 'male' ? 'ذكر' : 'أنثى' ?>)</span>
            </label>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Add New Spouses -->
        <div style="margin-bottom:15px;border-top:1px solid #E5E7EB;padding-top:15px;">
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;">
                <div style="font-size:12px;color:#0D7377;font-weight:700;">إضافة زوجة جديدة</div>
                <button type="button" onclick="addNewSpouse()" class="btn btn-outline" style="font-size:12px;padding:4px 12px;">+ إضافة زوجة</button>
            </div>
            <div id="newSpousesContainer"></div>
        </div>

        <!-- Add New Children -->
        <div style="margin-bottom:15px;border-top:1px solid #E5E7EB;padding-top:15px;">
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;">
                <div style="font-size:12px;color:#0D7377;font-weight:700;">إضافة أبناء جدد</div>
                <button type="button" onclick="addNewChild()" class="btn btn-outline" style="font-size:12px;padding:4px 12px;">+ إضافة ابن/ة</button>
            </div>
            <div id="newChildrenContainer"></div>
        </div>

        <!-- Add New Temporary Members -->
        <div style="border-top:1px solid #E5E7EB;padding-top:15px;">
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;">
                <div style="font-size:12px;color:#0D7377;font-weight:700;">إضافة أعضاء مؤقتين</div>
                <button type="button" onclick="addNewTemp()" class="btn btn-outline" style="font-size:12px;padding:4px 12px;">+ إضافة مؤقت</button>
            </div>
            <div id="newTempsContainer"></div>
        </div>
    </div>

    <!-- Pricing Preview -->
    <div class="card" style="padding:20px;margin-bottom:20px;border:2px solid #0D7377;" id="pricingPreview">
        <h3 style="margin:0 0 15px;color:#0D7377;">3. ملخص الرسوم</h3>
        <div id="pricingBody">
            <p style="color:#6B7280;text-align:center;">جاري حساب الرسوم...</p>
        </div>
    </div>

    <!-- Pricing Tables Reference -->
    <div class="card" style="padding:20px;margin-bottom:20px;">
        <h3 style="margin:0 0 15px;color:#6B7280;font-size:14px;">جدول الأسعار المرجعي</h3>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
            <!-- Egyptian -->
            <div>
                <h4 style="margin:0 0 10px;color:#0D7377;font-size:13px;">مصريين (ج.م) — شامل حمام السباحة</h4>
                <table style="width:100%;font-size:12px;border-collapse:collapse;">
                    <thead><tr style="background:#F3F4F6;"><th style="padding:6px;text-align:right;">الفئة</th><th style="padding:6px;">6 أشهر</th><th style="padding:6px;">سنة</th></tr></thead>
                    <tbody>
                    <?php
                    $catOrder = ['member', 'spouse', 'under_15', '15_to_21', 'over_21', 'over_60'];
                    foreach ($catOrder as $cat):
                        $label = \App\Modules\Seasonal\Services\SeasonalPricingService::getCategoryLabel($cat);
                    ?>
                    <tr style="border-bottom:1px solid #F3F4F6;">
                        <td style="padding:5px;"><?= e($label) ?></td>
                        <td style="padding:5px;text-align:center;"><?= number_format((float)($egyptianPrices[6][$cat] ?? 0)) ?></td>
                        <td style="padding:5px;text-align:center;"><?= number_format((float)($egyptianPrices[12][$cat] ?? 0)) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <!-- Foreign -->
            <div>
                <h4 style="margin:0 0 10px;color:#0D7377;font-size:13px;">أجانب (دولار) — شامل حمام السباحة</h4>
                <table style="width:100%;font-size:12px;border-collapse:collapse;">
                    <thead><tr style="background:#F3F4F6;"><th style="padding:6px;text-align:right;">الفئة</th><th style="padding:6px;">3 شهور</th><th style="padding:6px;">6 أشهر</th><th style="padding:6px;">سنة</th></tr></thead>
                    <tbody>
                    <?php
                    $foreignCats = ['member', 'spouse', 'under_15', '15_to_21', 'over_21'];
                    foreach ($foreignCats as $cat):
                        $label = \App\Modules\Seasonal\Services\SeasonalPricingService::getCategoryLabel($cat);
                    ?>
                    <tr style="border-bottom:1px solid #F3F4F6;">
                        <td style="padding:5px;"><?= e($label) ?></td>
                        <td style="padding:5px;text-align:center;">$<?= number_format((float)($foreignPrices[3][$cat] ?? 0)) ?></td>
                        <td style="padding:5px;text-align:center;">$<?= number_format((float)($foreignPrices[6][$cat] ?? 0)) ?></td>
                        <td style="padding:5px;text-align:center;">$<?= number_format((float)($foreignPrices[12][$cat] ?? 0)) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <div style="margin-top:15px;padding:10px;background:#FFF7ED;border:1px solid #FED7AA;border-radius:8px;font-size:12px;color:#92400E;">
            <strong>الخصومات المتاحة (خصم واحد فقط):</strong><br>
            • والد/ة مع ابن أقل من 15 سنة في نفس الفترة: خصم 500 ج.م<br>
            • زوج وزوجة في نفس الفترة: خصم 1000 ج.م<br>
            • أسرة 5 أفراد (زوج + زوجة + 3 أبناء): خصم 1000 ج.م<br>
            • بدون مؤهل عالي/متوسط: خصم 10% من قيمة الاشتراك<br>
            <strong style="color:#DC2626;">• يُضاف ضريبة القيمة المضافة على جميع المبالغ</strong>
        </div>
    </div>

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

    <button type="submit" class="btn btn-primary" style="padding:12px 30px;">إنشاء العضوية الموسمية وإرسال للخزينة</button>
    <a href="/members/<?= (int) $member['id'] ?>" class="btn btn-outline">إلغاء</a>
</form>

<script>
const memberId = <?= (int) $member['id'] ?>;
const qualificationsJson = <?= json_encode($qualifications ?? [], JSON_UNESCAPED_UNICODE) ?>;
let debounceTimer = null;
let spouseCount = 0;
let childCount = 0;
let tempCount = 0;

function qualOptions() {
    let opts = '<option value="">-- اختر --</option>';
    qualificationsJson.forEach(q => { opts += '<option value="' + q.id + '">' + q.name_ar + '</option>'; });
    return opts;
}

function addNewSpouse() {
    spouseCount++;
    const i = spouseCount;
    const html = `<div class="card" style="padding:15px;margin-bottom:10px;background:#F0FDF4;border:1px solid #BBF7D0;" id="new-spouse-${i}">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
            <strong style="color:#0D7377;">زوجة جديدة #${i}</strong>
            <button type="button" onclick="removeRow('new-spouse-${i}')" style="background:#FEE2E2;border:1px solid #FECACA;border-radius:6px;padding:4px 10px;cursor:pointer;color:#DC2626;font-weight:700;">✕ حذف</button>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
            <div class="form-group"><label class="form-label">الاسم بالعربية <span style="color:#DC2626;">*</span></label>
                <input type="text" name="new_spouses[${i}][full_name_ar]" class="form-input" required></div>
            <div class="form-group"><label class="form-label">الاسم بالإنجليزية</label>
                <input type="text" name="new_spouses[${i}][full_name_en]" class="form-input"></div>
            <div class="form-group"><label class="form-label">الرقم القومي</label>
                <input type="text" name="new_spouses[${i}][national_id]" class="form-input nid-field" maxlength="14" style="direction:ltr;text-align:left;letter-spacing:2px;" placeholder="14 رقم" data-target="spouse-${i}" oninput="parseNID(this,'spouse-${i}')"></div>
            <div class="form-group"><label class="form-label"><input type="checkbox" name="new_spouses[${i}][is_non_egyptian]" value="1" onchange="togglePassport(this,'sp-passport-${i}')"> غير مصرية</label>
                <input type="text" name="new_spouses[${i}][passport_number]" id="sp-passport-${i}" class="form-input" style="display:none;direction:ltr;margin-top:6px;" placeholder="رقم جواز السفر"></div>
            <div class="form-group"><label class="form-label">تاريخ الميلاد <span style="color:#DC2626;">*</span></label>
                <input type="date" name="new_spouses[${i}][date_of_birth]" id="spouse-${i}-dob" class="form-input" required></div>
            <div class="form-group"><label class="form-label">تاريخ الزواج</label>
                <input type="date" name="new_spouses[${i}][marriage_date]" class="form-input"></div>
            <div class="form-group"><label class="form-label">الجنسية</label>
                <select name="new_spouses[${i}][nationality]" class="form-select"><option value="egyptian">مصرية</option><option value="foreign">أجنبية</option></select></div>
            <div class="form-group"><label class="form-label">النوع</label>
                <select name="new_spouses[${i}][gender]" id="spouse-${i}-gender" class="form-select"><option value="female">أنثى</option><option value="male">ذكر</option></select></div>
            <div class="form-group"><label class="form-label">المؤهل</label>
                <select name="new_spouses[${i}][qualification_id]" class="form-select">${qualOptions()}</select></div>
            <div class="form-group"><label class="form-label">الوظيفة</label>
                <input type="text" name="new_spouses[${i}][occupation]" class="form-input"></div>
            <div class="form-group"><label class="form-label">الموبايل</label>
                <input type="tel" name="new_spouses[${i}][mobile]" class="form-input" style="direction:ltr;text-align:left;"></div>
            <div class="form-group"><label class="form-label">تليفون العمل</label>
                <input type="tel" name="new_spouses[${i}][work_phone]" class="form-input" style="direction:ltr;text-align:left;"></div>
        </div>
        <div class="form-group" style="margin-top:10px;"><label class="form-label">عنوان العمل</label>
            <textarea name="new_spouses[${i}][work_address]" class="form-textarea" rows="1"></textarea></div>
    </div>`;
    document.getElementById('newSpousesContainer').insertAdjacentHTML('beforeend', html);
    updatePricing();
}

function addNewChild() {
    childCount++;
    const i = childCount;
    const html = `<div class="card" style="padding:15px;margin-bottom:10px;background:#EFF6FF;border:1px solid #BFDBFE;" id="new-child-${i}">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
            <strong style="color:#0D7377;">ابن/ة جديد/ة #${i}</strong>
            <button type="button" onclick="removeRow('new-child-${i}')" style="background:#FEE2E2;border:1px solid #FECACA;border-radius:6px;padding:4px 10px;cursor:pointer;color:#DC2626;font-weight:700;">✕ حذف</button>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
            <div class="form-group"><label class="form-label">الاسم بالعربية <span style="color:#DC2626;">*</span></label>
                <input type="text" name="new_children[${i}][full_name_ar]" class="form-input" required></div>
            <div class="form-group"><label class="form-label">الاسم بالإنجليزية</label>
                <input type="text" name="new_children[${i}][full_name_en]" class="form-input"></div>
            <div class="form-group"><label class="form-label">الرقم القومي</label>
                <input type="text" name="new_children[${i}][national_id]" class="form-input nid-field" maxlength="14" style="direction:ltr;text-align:left;letter-spacing:2px;" placeholder="14 رقم" oninput="parseNID(this,'child-${i}')"></div>
            <div class="form-group"><label class="form-label"><input type="checkbox" name="new_children[${i}][is_non_egyptian]" value="1" onchange="togglePassport(this,'ch-passport-${i}')"> غير مصري/ة</label>
                <input type="text" name="new_children[${i}][passport_number]" id="ch-passport-${i}" class="form-input" style="display:none;direction:ltr;margin-top:6px;" placeholder="رقم جواز السفر"></div>
            <div class="form-group"><label class="form-label">رقم شهادة الميلاد</label>
                <input type="text" name="new_children[${i}][birth_certificate_number]" class="form-input" style="direction:ltr;text-align:left;"></div>
            <div class="form-group"><label class="form-label">تاريخ الميلاد <span style="color:#DC2626;">*</span></label>
                <input type="date" name="new_children[${i}][date_of_birth]" id="child-${i}-dob" class="form-input" required onchange="updatePricing()"></div>
            <div class="form-group"><label class="form-label">النوع <span style="color:#DC2626;">*</span></label>
                <select name="new_children[${i}][gender]" id="child-${i}-gender" class="form-select" required onchange="syncRelationship(this, 'child-${i}-rel')">
                    <option value="male">ذكر</option><option value="female">أنثى</option></select></div>
            <div class="form-group"><label class="form-label">صلة القرابة</label>
                <select name="new_children[${i}][relationship]" id="child-${i}-rel" class="form-select">
                    <option value="son">ابن</option><option value="daughter">ابنة</option></select></div>
            <div class="form-group"><label class="form-label">الجنسية</label>
                <select name="new_children[${i}][nationality]" class="form-select"><option value="egyptian">مصري/ة</option><option value="foreign">أجنبي/ة</option></select></div>
            <div class="form-group"><label class="form-label">المدرسة / الكلية</label>
                <input type="text" name="new_children[${i}][school_faculty]" class="form-input"></div>
        </div>
    </div>`;
    document.getElementById('newChildrenContainer').insertAdjacentHTML('beforeend', html);
    updatePricing();
}

function addNewTemp() {
    tempCount++;
    const i = tempCount;
    const html = `<div class="card" style="padding:15px;margin-bottom:10px;background:#FFF7ED;border:1px solid #FED7AA;" id="new-temp-${i}">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
            <strong style="color:#92400E;">عضو مؤقت جديد #${i}</strong>
            <button type="button" onclick="removeRow('new-temp-${i}')" style="background:#FEE2E2;border:1px solid #FECACA;border-radius:6px;padding:4px 10px;cursor:pointer;color:#DC2626;font-weight:700;">✕ حذف</button>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
            <div class="form-group"><label class="form-label">الاسم بالعربية <span style="color:#DC2626;">*</span></label>
                <input type="text" name="new_temps[${i}][full_name_ar]" class="form-input" required></div>
            <div class="form-group"><label class="form-label">الاسم بالإنجليزية</label>
                <input type="text" name="new_temps[${i}][full_name_en]" class="form-input"></div>
            <div class="form-group"><label class="form-label">التصنيف <span style="color:#DC2626;">*</span></label>
                <select name="new_temps[${i}][category]" class="form-select" required>
                    <option value="relative">قريب</option><option value="nanny">مربية</option><option value="driver">سائق</option><option value="other">أخرى</option></select></div>
            <div class="form-group"><label class="form-label">الرقم القومي</label>
                <input type="text" name="new_temps[${i}][national_id]" class="form-input nid-field" maxlength="14" style="direction:ltr;text-align:left;letter-spacing:2px;" placeholder="14 رقم" oninput="parseNID(this,'temp-${i}')"></div>
            <div class="form-group"><label class="form-label"><input type="checkbox" name="new_temps[${i}][is_non_egyptian]" value="1" onchange="togglePassport(this,'tm-passport-${i}')"> غير مصري/ة</label>
                <input type="text" name="new_temps[${i}][passport_number]" id="tm-passport-${i}" class="form-input" style="display:none;direction:ltr;margin-top:6px;" placeholder="رقم جواز السفر"></div>
            <div class="form-group"><label class="form-label">تاريخ الميلاد <span style="color:#DC2626;">*</span></label>
                <input type="date" name="new_temps[${i}][date_of_birth]" id="temp-${i}-dob" class="form-input" required onchange="updatePricing()"></div>
            <div class="form-group"><label class="form-label">النوع</label>
                <select name="new_temps[${i}][gender]" id="temp-${i}-gender" class="form-select">
                    <option value="male">ذكر</option><option value="female">أنثى</option></select></div>
            <div class="form-group"><label class="form-label">الجنسية</label>
                <select name="new_temps[${i}][nationality]" class="form-select"><option value="egyptian">مصري/ة</option><option value="foreign">أجنبي/ة</option></select></div>
            <div class="form-group"><label class="form-label">صلة القرابة بالعضو</label>
                <input type="text" name="new_temps[${i}][relationship_to_member]" class="form-input"></div>
            <div class="form-group" style="display:flex;gap:15px;align-items:center;padding-top:20px;">
                <label><input type="checkbox" name="new_temps[${i}][has_championship]" value="1"> بطولة رياضية</label>
                <label><input type="checkbox" name="new_temps[${i}][disability_documentation]" value="1"> إعاقة موثقة</label>
            </div>
        </div>
        <div class="form-group" style="margin-top:10px;"><label class="form-label">ملاحظات</label>
            <textarea name="new_temps[${i}][notes]" class="form-textarea" rows="1"></textarea></div>
    </div>`;
    document.getElementById('newTempsContainer').insertAdjacentHTML('beforeend', html);
    updatePricing();
}

function removeRow(id) {
    document.getElementById(id).remove();
    updatePricing();
}

function togglePassport(checkbox, passportId) {
    document.getElementById(passportId).style.display = checkbox.checked ? 'block' : 'none';
}

function syncRelationship(genderSelect, relId) {
    const rel = document.getElementById(relId);
    if (rel) rel.value = genderSelect.value === 'female' ? 'daughter' : 'son';
}

function parseNID(input, prefix) {
    const nid = input.value.replace(/\D/g, '');
    if (nid.length !== 14) return;
    const century = nid[0] === '2' ? '19' : '20';
    const year = century + nid.substring(1, 3);
    const month = nid.substring(3, 5);
    const day = nid.substring(5, 7);
    const dob = year + '-' + month + '-' + day;
    const dobField = document.getElementById(prefix + '-dob');
    if (dobField && !isNaN(Date.parse(dob))) dobField.value = dob;
    const genderDigit = parseInt(nid[12]);
    const gender = (genderDigit % 2 === 0) ? 'female' : 'male';
    const genderField = document.getElementById(prefix + '-gender');
    if (genderField) {
        genderField.value = gender;
        const relId = prefix.replace('child-', 'child-') + '-rel';
        const relField = document.getElementById(relId);
        if (relField) relField.value = gender === 'female' ? 'daughter' : 'son';
    }
    updatePricing();
}

function updatePricing() {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(fetchPricing, 300);
    updateDurationOptions();
}

function updateDurationOptions() {
    const nat = document.getElementById('nationalityType').value;
    const sel = document.getElementById('durationMonths');
    const current = sel.value;
    sel.innerHTML = '';
    if (nat === 'foreign') {
        sel.innerHTML = '<option value="3">3 شهور</option><option value="6">6 أشهر</option><option value="12">سنة</option>';
    } else {
        sel.innerHTML = '<option value="6">6 أشهر</option><option value="12">سنة</option>';
    }
    if ([...sel.options].some(o => o.value === current)) sel.value = current;
}

function fetchPricing() {
    const nat = document.getElementById('nationalityType').value;
    const dur = document.getElementById('durationMonths').value;
    const hasQual = document.querySelector('[name="has_qualification"]').checked ? '1' : '0';
    const spouses = [...document.querySelectorAll('[name="spouses[]"]:checked')].map(e => e.value).join(',');
    const children = [...document.querySelectorAll('[name="children[]"]:checked')].map(e => e.value).join(',');

    // Collect new inline spouses count
    const newSpouseInputs = [...document.querySelectorAll('[name$="[full_name_ar]"]')].filter(e => e.name.startsWith('new_spouses'));
    const newSpousesCount = newSpouseInputs.filter(e => e.value.trim()).length;

    // Collect new inline children DOBs
    const newChildDobInputs = [...document.querySelectorAll('[name$="[date_of_birth]"]')].filter(e => e.name.startsWith('new_children'));
    const newChildDobs = newChildDobInputs.map(e => e.value).filter(d => d);

    // Collect new temp DOBs (treated as children for pricing)
    const newTempDobInputs = [...document.querySelectorAll('[name$="[date_of_birth]"]')].filter(e => e.name.startsWith('new_temps'));
    const newTempDobs = newTempDobInputs.map(e => e.value).filter(d => d);

    const allChildDobs = newChildDobs.concat(newTempDobs);

    const url = '/api/seasonal/price-preview?nationality_type=' + nat + '&duration_months=' + dur
        + '&member_id=' + memberId + '&has_qualification=' + hasQual
        + '&spouses=' + spouses + '&children=' + children
        + '&new_spouses_count=' + newSpousesCount
        + '&new_children_dobs=' + encodeURIComponent(allChildDobs.join(','));

    fetch(url, {credentials: 'same-origin'})
        .then(r => r.json())
        .then(data => renderPricing(data))
        .catch(() => {
            document.getElementById('pricingBody').innerHTML = '<p style="color:#DC2626;">خطأ في حساب الرسوم</p>';
        });
}

function renderPricing(p) {
    if (p.error) {
        document.getElementById('pricingBody').innerHTML = '<p style="color:#DC2626;">' + p.error + '</p>';
        return;
    }
    const cur = p.currency;
    let html = '<table style="width:100%;font-size:14px;border-collapse:collapse;">';
    html += '<thead><tr style="border-bottom:2px solid #E5E7EB;"><th style="padding:8px;text-align:right;">الفرد</th><th style="padding:8px;text-align:left;">المبلغ</th></tr></thead><tbody>';
    p.items.forEach(item => {
        html += '<tr style="border-bottom:1px solid #F3F4F6;"><td style="padding:8px;">' + item.person_name + '</td><td style="padding:8px;text-align:left;font-weight:600;">' + parseFloat(item.base_price).toLocaleString() + ' ' + cur + '</td></tr>';
    });
    html += '</tbody></table>';

    html += '<div style="margin-top:15px;padding:12px;background:#F9FAFB;border-radius:8px;">';
    html += '<div style="display:flex;justify-content:space-between;padding:4px 0;"><span>المجموع</span><strong>' + parseFloat(p.subtotal).toLocaleString() + ' ' + cur + '</strong></div>';

    if (parseFloat(p.total_discount) > 0) {
        const discLabel = p.family_discount.label || 'خصم عدم وجود مؤهل';
        html += '<div style="display:flex;justify-content:space-between;padding:4px 0;color:#059669;"><span>🏷️ ' + discLabel + '</span><strong>-' + parseFloat(p.total_discount).toLocaleString() + ' ' + cur + '</strong></div>';
    }

    html += '<div style="display:flex;justify-content:space-between;padding:4px 0;color:#6B7280;"><span>ضريبة القيمة المضافة (' + p.vat_rate + '%)</span><span>' + parseFloat(p.vat_amount).toLocaleString() + ' ' + cur + '</span></div>';
    html += '<div style="display:flex;justify-content:space-between;padding:8px 0;border-top:2px solid #0D7377;margin-top:8px;font-size:18px;"><span style="font-weight:700;color:#0D7377;">الإجمالي</span><strong style="color:#0D7377;">' + parseFloat(p.grand_total).toLocaleString() + ' ' + cur + '</strong></div>';
    html += '</div>';

    document.getElementById('pricingBody').innerHTML = html;
}

document.addEventListener('DOMContentLoaded', fetchPricing);
</script>
<?php $__template->endSection(); ?>
