<?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'] ?? 'لم يُحدد') ?>
        &nbsp;|&nbsp; <strong>ترتيب الابن:</strong> #<?= (int) $childOrder ?>
    </div>
    <a href="/members/<?= (int) $member['id'] ?>" class="btn btn-outline">← العودة للعضو</a>
</div>

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

    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;"><h3 style="margin:0;color:#0D7377;">بيانات الابن/الابنة</h3></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="full_name_ar" value="<?= e(old('full_name_ar')) ?>" class="form-input" required minlength="5" maxlength="200">
            </div>
            <div class="form-group">
                <label class="form-label">الاسم بالإنجليزي</label>
                <input type="text" name="full_name_en" value="<?= e(old('full_name_en')) ?>" class="form-input">
            </div>
            <div class="form-group">
                <label class="form-label">نوع القرابة <span style="color:#DC2626;">*</span></label>
                <select name="relationship" class="form-select" required>
                    <option value="">-- اختر --</option>
                    <option value="son" <?= old('relationship') === 'son' ? 'selected' : '' ?>>ابن</option>
                    <option value="daughter" <?= old('relationship') === 'daughter' ? 'selected' : '' ?>>ابنة</option>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">الرقم القومي <small style="color:#0284C7;">(مطلوب فوق 16 سنة — يستخرج تاريخ الميلاد والنوع تلقائياً)</small></label>
                <input type="text" name="national_id" id="child_nid" value="<?= e(old('national_id')) ?>" class="form-input" maxlength="14" style="direction:ltr;text-align:left;font-size:16px;letter-spacing:2px;" placeholder="14 رقم">
                <div id="child-nid-feedback" style="margin-top:5px;font-size:12px;"></div>
            </div>
            <div class="form-group">
                <label class="form-label">رقم شهادة الميلاد <small style="color:#6B7280;">(للأطفال تحت 16 سنة)</small></label>
                <input type="text" name="birth_certificate_number" value="<?= e(old('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> <small id="child_dob_source" style="color:#059669;display:none;">(من الرقم القومي)</small></label>
                <input type="date" name="date_of_birth" id="child_dob" value="<?= e(old('date_of_birth')) ?>" class="form-input" required>
            </div>
            <div class="form-group">
                <label class="form-label">السن <small id="child_age_source" style="color:#059669;display:none;">(محسوب تلقائياً)</small></label>
                <input type="text" id="child_age_display" class="form-input" style="background:#F3F4F6;" readonly>
                <input type="hidden" name="age_years" id="child_age_years">
                <input type="hidden" name="age_months" id="child_age_months">
            </div>
            <div class="form-group">
                <label class="form-label">النوع <span style="color:#DC2626;">*</span> <small id="child_gender_source" style="color:#059669;display:none;">(من الرقم القومي)</small></label>
                <select name="gender" id="child_gender" class="form-select" required>
                    <option value="">-- اختر --</option>
                    <option value="male" <?= old('gender') === 'male' ? 'selected' : '' ?>>ذكر</option>
                    <option value="female" <?= old('gender') === 'female' ? 'selected' : '' ?>>أنثى</option>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">الجنسية <span style="color:#DC2626;">*</span></label>
                <select name="nationality" class="form-select" required>
                    <option value="مصري" <?= (old('nationality', 'مصري') === 'مصري') ? 'selected' : '' ?>>مصري</option>
                    <?php foreach ($countries as $c): ?>
                        <?php if ($c['nationality_ar'] !== 'مصري'): ?>
                        <option value="<?= e($c['nationality_ar']) ?>" <?= old('nationality') === $c['nationality_ar'] ? 'selected' : '' ?>><?= e($c['nationality_ar']) ?></option>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">الكلية / المدرسة</label>
                <input type="text" name="school_faculty" value="<?= e(old('school_faculty')) ?>" class="form-input">
            </div>
            <div class="form-group" style="grid-column:1/-1;">
                <label class="form-label">ملاحظات</label>
                <textarea name="remarks" class="form-textarea" rows="2"><?= e(old('remarks')) ?></textarea>
            </div>
        </div>
    </div>

    <div style="display:flex;gap:10px;">
        <button type="submit" class="btn btn-primary">إضافة الابن/الابنة</button>
        <a href="/members/<?= (int) $member['id'] ?>" class="btn btn-outline">إلغاء</a>
    </div>
</form>

<?php $__template->endSection(); ?>

<?php $__template->section('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var nidInput = document.getElementById('child_nid');
    var dobInput = document.getElementById('child_dob');
    var ageDisplay = document.getElementById('child_age_display');
    var ageYears = document.getElementById('child_age_years');
    var ageMonths = document.getElementById('child_age_months');
    var genderSelect = document.getElementById('child_gender');
    var feedback = document.getElementById('child-nid-feedback');

    var dobSourceEl = document.getElementById('child_dob_source');
    var ageSourceEl = document.getElementById('child_age_source');
    var genderSourceEl = document.getElementById('child_gender_source');
    var nidLocked = false;

    nidInput.addEventListener('input', function() {
        var val = this.value.replace(/\D/g, '');
        this.value = val;
        if (val.length === 14) {
            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(data) {
                    var p = data.parsed;
                    if (p && p.is_valid) {
                        dobInput.value = p.dob;
                        dobInput.readOnly = true;
                        dobInput.style.background = '#F0FDF4';
                        dobSourceEl.style.display = 'inline';
                        ageSourceEl.style.display = 'inline';
                        genderSourceEl.style.display = 'inline';
                        ageDisplay.value = p.age_years + ' سنة و ' + p.age_months + ' شهر';
                        ageYears.value = p.age_years;
                        ageMonths.value = p.age_months;
                        genderSelect.value = p.gender;
                        genderSelect.style.background = '#F0FDF4';
                        genderSelect.setAttribute('data-nid-locked', '1');
                        nidLocked = true;
                        feedback.innerHTML = '<span style="color:#059669;">صالح — تم استخراج تاريخ الميلاد والنوع</span>';
                        if (data.duplicate) {
                            feedback.innerHTML += '<br><span style="color:#DC2626;">مسجل: ' + data.duplicate.full_name_ar + '</span>';
                        }
                    } else {
                        feedback.innerHTML = '<span style="color:#DC2626;">' + (p.errors ? p.errors.join(' | ') : 'غير صالح') + '</span>';
                    }
                })
                .catch(function() { feedback.innerHTML = '<span style="color:#DC2626;">خطأ</span>'; });
        } else {
            feedback.innerHTML = '';
            if (nidLocked) {
                dobInput.readOnly = false;
                dobInput.style.background = '';
                genderSelect.style.background = '';
                genderSelect.removeAttribute('data-nid-locked');
                dobSourceEl.style.display = 'none';
                ageSourceEl.style.display = 'none';
                genderSourceEl.style.display = 'none';
                nidLocked = false;
            }
        }
    });

    // Manual DOB age calculation
    dobInput.addEventListener('change', function() {
        if (this.value && !nidInput.value) {
            var dob = new Date(this.value);
            var now = new Date();
            var years = now.getFullYear() - dob.getFullYear();
            var months = now.getMonth() - dob.getMonth();
            if (months < 0 || (months === 0 && now.getDate() < dob.getDate())) { years--; months += 12; }
            if (now.getDate() < dob.getDate()) months--;
            if (months < 0) months = 0;
            ageDisplay.value = years + ' سنة و ' + months + ' شهر';
            ageYears.value = years;
            ageMonths.value = months;
        }
    });
});
</script>
<?php $__template->endSection(); ?>