<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>إضافة <?= $member['gender'] === 'female' ? 'زوج' : 'زوجة' ?> — <?= e($member['full_name_ar']) ?><?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>

<?php
$isFemale = ($member['gender'] === 'female');
$spouseLabel = $isFemale ? 'الزوج' : 'الزوجة';
$genderLabel = $isFemale ? 'ذكر' : 'أنثى';
$genderValue = $requiredGender;
?>

<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>ترتيب <?= $spouseLabel ?>:</strong> #<?= (int) $spouseOrder ?>
        <?php if ($isFemale): ?>
            &nbsp;|&nbsp; <span style="background:#EFF6FF;color:#0284C7;padding:3px 10px;border-radius:4px;font-size:12px;font-weight:600;">👤 يُسمح بزوج واحد فقط</span>
        <?php else: ?>
            &nbsp;|&nbsp; <span style="color:#6B7280;font-size:13px;">(<?= $currentCount ?>/<?= $maxAllowed ?>)</span>
        <?php endif; ?>
    </div>
    <a href="/members/<?= (int) $member['id'] ?>" class="btn btn-outline">← العودة للعضو</a>
</div>

<form method="POST" action="/members/<?= (int) $member['id'] ?>/spouses">
    <?= 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;">بيانات <?= $spouseLabel ?></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">النوع</label>
                <input type="text" value="<?= e($genderLabel) ?>" class="form-input" style="background:#F3F4F6;font-weight:600;color:#0D7377;" disabled>
                <input type="hidden" name="gender" value="<?= e($genderValue) ?>">
                <small style="color:#6B7280;font-size:11px;">يتم تحديده تلقائياً بناءً على نوع العضو/ة</small>
            </div>

            <div class="form-group">
                <label class="form-label">الرقم القومي</label>
                <input type="text" name="national_id" id="spouse_nid" value="<?= e(old('national_id')) ?>" class="form-input" maxlength="14" style="direction:ltr;text-align:left;">
                <div id="spouse-nid-feedback" style="margin-top:5px;font-size:12px;"></div>
            </div>

            <div class="form-group">
                <label class="form-label">تاريخ الميلاد <span style="color:#DC2626;">*</span></label>
                <input type="date" name="date_of_birth" id="spouse_dob" value="<?= e(old('date_of_birth')) ?>" class="form-input" required>
            </div>

            <div class="form-group">
                <label class="form-label">السن</label>
                <input type="text" id="spouse_age_display" class="form-input" style="background:#F3F4F6;" readonly>
                <input type="hidden" name="age_years" id="spouse_age_years">
                <input type="hidden" name="age_months" id="spouse_age_months">
            </div>

            <div class="form-group">
                <label class="form-label">تاريخ الزواج <span style="color:#DC2626;">*</span></label>
                <input type="date" name="marriage_date" value="<?= e(old('marriage_date')) ?>" class="form-input" required>
            </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>
                <small style="color:#D97706;font-size:11px;">⚠ الجنسية تؤثر على الرسوم — الأجنبي = 15% من قيمة العضوية</small>
            </div>

            <div class="form-group">
                <label class="form-label">المؤهل</label>
                <select name="qualification_id" class="form-select">
                    <option value="">-- اختر --</option>
                    <?php foreach ($qualifications as $q): ?>
                        <option value="<?= (int) $q['id'] ?>" <?= old('qualification_id') == $q['id'] ? 'selected' : '' ?>><?= e($q['name_ar']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label class="form-label">الوظيفة</label>
                <input type="text" name="occupation" value="<?= e(old('occupation')) ?>" class="form-input">
            </div>

            <div class="form-group">
                <label class="form-label">رقم المحمول</label>
                <input type="tel" name="mobile" value="<?= e(old('mobile')) ?>" class="form-input" style="direction:ltr;text-align:left;">
            </div>

            <div class="form-group">
                <label class="form-label">تليفون العمل</label>
                <input type="tel" name="work_phone" value="<?= e(old('work_phone')) ?>" class="form-input" style="direction:ltr;text-align:left;">
            </div>

            <div class="form-group" style="grid-column:1/-1;">
                <label class="form-label">عنوان العمل</label>
                <textarea name="work_address" class="form-textarea" rows="2"><?= e(old('work_address')) ?></textarea>
            </div>
        </div>
    </div>

    <div style="display:flex;gap:10px;">
        <button type="submit" class="btn btn-primary">إضافة <?= $spouseLabel ?></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('spouse_nid');
    var dobInput = document.getElementById('spouse_dob');
    var ageDisplay = document.getElementById('spouse_age_display');
    var ageYears = document.getElementById('spouse_age_years');
    var ageMonths = document.getElementById('spouse_age_months');
    var feedback = document.getElementById('spouse-nid-feedback');
    var requiredGender = '<?= e($genderValue) ?>';

    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;
                        ageDisplay.value = p.age_years + ' سنة و ' + p.age_months + ' شهر';
                        ageYears.value = p.age_years;
                        ageMonths.value = p.age_months;
                        feedback.innerHTML = '<span style="color:#059669;">✓ صالح</span>';

                        // Check gender mismatch
                        if (p.gender !== requiredGender) {
                            var needed = requiredGender === 'male' ? 'ذكر' : 'أنثى';
                            feedback.innerHTML += '<br><span style="color:#DC2626;">✖ الرقم القومي يشير إلى نوع مختلف — المطلوب: ' + needed + '</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 = ''; }
    });

    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(); ?>