<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>تسجيل عضو جديد<?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>

<?php if ($needsStartNumber): ?>
<!-- First time: Super admin must set starting form number -->
<div class="card" style="margin-bottom:20px;padding:20px;border-right:4px solid #D97706;">
    <h3 style="color:#D97706;margin:0 0 10px;">⚠ تحديد رقم بداية الاستمارات</h3>
    <p style="color:#6B7280;font-size:14px;margin-bottom:15px;">هذه المرة الأولى — يجب تحديد رقم أول استمارة في النظام</p>
    <form method="POST" action="/members" id="member-form">
        <?= csrf_field() ?>
        <div style="display:flex;gap:15px;align-items:end;margin-bottom:20px;">
            <div class="form-group" style="flex:0 0 200px;">
                <label class="form-label">رقم أول استمارة <span style="color:#DC2626;">*</span></label>
                <input type="number" name="form_start_number" class="form-input" required min="1" style="direction:ltr;text-align:left;font-size:18px;font-weight:700;" placeholder="مثال: 15001">
            </div>
        </div>
<?php else: ?>
<form method="POST" action="/members" id="member-form">
    <?= csrf_field() ?>
<?php endif; ?>

    <!-- Form Info Banner -->
    <div class="card" style="margin-bottom:20px;padding:20px;background:#EFF6FF;border:1px solid #BFDBFE;">
        <div style="display:flex;justify-content:space-between;align-items:center;">
            <div>
                <strong style="color:#0284C7;font-size:16px;">📋 استمارة عضوية جديدة</strong>
                <p style="color:#6B7280;font-size:13px;margin:5px 0 0;">أدخل البيانات الأساسية فقط — باقي البيانات تُملأ في الاستمارة بعد دفع الرسوم</p>
            </div>
            <div style="text-align:left;">
                <?php if (!$needsStartNumber && $nextFormNumber): ?>
                    <div style="font-size:12px;color:#6B7280;">رقم الاستمارة التالي</div>
                    <div style="font-size:28px;font-weight:700;color:#0D7377;direction:ltr;"><?= (int) $nextFormNumber ?></div>
                <?php endif; ?>
                <div style="font-size:13px;color:#D97706;font-weight:600;margin-top:5px;">رسوم الاستمارة: <?= money($formFee) ?></div>
            </div>
        </div>
    </div>

    <!-- Basic Info Card -->
    <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:20px;">
            <!-- Full Name Arabic -->
            <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" placeholder="الاسم رباعي بالعربي" style="font-size:16px;">
            </div>

            <!-- National ID -->
            <div class="form-group">
                <label class="form-label">الرقم القومي <span style="color:#DC2626;">*</span></label>
                <input type="text" name="national_id" id="national_id" value="<?= e(old('national_id')) ?>" class="form-input" maxlength="14" style="direction:ltr;text-align:left;font-size:18px;letter-spacing:2px;" placeholder="أدخل 14 رقم">
                <div id="nid-feedback" style="margin-top:5px;font-size:12px;"></div>
            </div>

            <!-- Phone -->
            <div class="form-group">
                <label class="form-label">رقم المحمول <span style="color:#DC2626;">*</span></label>
                <input type="tel" name="phone_mobile" value="<?= e(old('phone_mobile')) ?>" class="form-input" required maxlength="11" style="direction:ltr;text-align:left;font-size:16px;" placeholder="01XXXXXXXXX">
            </div>

            <!-- Branch -->
            <div class="form-group">
                <label class="form-label">الفرع <span style="color:#DC2626;">*</span></label>
                <select name="branch_id" class="form-select" required style="font-size:16px;">
                    <option value="">-- اختر الفرع --</option>
                    <?php foreach ($branches as $b): ?>
                        <option value="<?= (int) $b['id'] ?>" <?= old('branch_id') == $b['id'] ? 'selected' : '' ?>><?= e($b['name_ar']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Auto-parsed fields (read-only) -->
            <div class="form-group">
                <label class="form-label">تاريخ الميلاد</label>
                <input type="date" name="date_of_birth" id="date_of_birth" value="<?= e(old('date_of_birth')) ?>" class="form-input" style="background:#F3F4F6;" readonly>
            </div>

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

            <div class="form-group">
                <label class="form-label">النوع</label>
                <input type="text" id="gender_display" class="form-input" style="background:#F3F4F6;" readonly>
                <input type="hidden" name="gender" id="gender_hidden" value="<?= e(old('gender')) ?>">
            </div>

            <div class="form-group">
                <label class="form-label">محافظة الميلاد</label>
                <input type="text" id="gov_display" class="form-input" style="background:#F3F4F6;" readonly>
                <input type="hidden" name="governorate_code" id="governorate_code">
            </div>
        </div>
    </div>

    <div style="display:flex;gap:10px;">
        <button type="submit" class="btn btn-primary" style="padding:12px 30px;font-size:16px;">📋 تسجيل وإنشاء الاستمارة</button>
        <a href="/members" class="btn btn-outline" style="padding:12px 20px;">إلغاء</a>
    </div>
</form>

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

<?php $__template->section('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var nidInput = document.getElementById('national_id');
    var dobInput = document.getElementById('date_of_birth');
    var ageDisplay = document.getElementById('age_display');
    var ageYears = document.getElementById('age_years');
    var ageMonths = document.getElementById('age_months');
    var genderDisplay = document.getElementById('gender_display');
    var genderHidden = document.getElementById('gender_hidden');
    var govDisplay = document.getElementById('gov_display');
    var govCode = document.getElementById('governorate_code');
    var feedback = document.getElementById('nid-feedback');

    nidInput.addEventListener('input', function() {
        var val = this.value.replace(/\D/g, '');
        this.value = val;
        if (val.length === 14) {
            feedback.innerHTML = '<span style="color:#0284C7;">جاري التحقق...</span>';
            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;
                        genderDisplay.value = p.gender === 'male' ? 'ذكر' : 'أنثى';
                        genderHidden.value = p.gender;
                        govDisplay.value = p.governorate_name_ar || '';
                        govCode.value = p.governorate_code || '';
                        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 = '';
            dobInput.value = '';
            ageDisplay.value = '';
            genderDisplay.value = '';
            govDisplay.value = '';
        }
    });
});
</script>
<?php $__template->endSection(); ?>