<?php
$__template->layout('Layout.main');
?>
<?php $__template->section('title'); ?>إضافة لاعب جديد<?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/sa/players" class="btn btn-outline"><i data-lucide="arrow-right" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> رجوع</a>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<form method="POST" action="/sa/players">
    <?= csrf_field() ?>

    <!-- Basic Information -->
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
            <h3 style="margin:0;font-size:16px;font-weight:600;">البيانات الأساسية</h3>
        </div>
        <div style="padding:20px;display:grid;grid-template-columns:repeat(auto-fit, minmax(250px, 1fr));gap:15px;">
            <div>
                <label class="form-label">نوع اللاعب <span style="color:#DC2626;">*</span></label>
                <select name="player_type" class="form-select" id="player_type" required>
                    <option value="">اختر...</option>
                    <option value="member" <?= old('player_type') === 'member' ? 'selected' : '' ?>>عضو</option>
                    <option value="non_member" <?= old('player_type') === 'non_member' ? 'selected' : '' ?>>غير عضو</option>
                </select>
            </div>
            <div id="member_id_field" style="display:none;">
                <label class="form-label">رقم العضوية <span style="color:#DC2626;">*</span> <span style="font-weight:400;color:#6B7280;font-size:12px;">(يملأ البيانات تلقائياً)</span></label>
                <input type="text" id="membershipNoInput" value="<?= e(old('membership_number') ?? '') ?>" class="form-input" placeholder="أدخل رقم العضوية" inputmode="numeric" dir="ltr" style="text-align:right;letter-spacing:1px;">
                <input type="hidden" name="member_id" id="memberIdHidden" value="<?= e(old('member_id') ?? '') ?>">
                <div id="memberLookupStatus" style="display:none;margin-top:6px;padding:8px 12px;border-radius:6px;font-size:12px;"></div>
            </div>
            <div>
                <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 maxlength="300">
            </div>
            <div>
                <label class="form-label">الاسم بالإنجليزي</label>
                <input type="text" name="full_name_en" value="<?= e(old('full_name_en') ?? '') ?>" class="form-input" dir="ltr" maxlength="300">
            </div>
            <div>
                <label class="form-label">الرقم القومي</label>
                <input type="text" name="national_id" value="<?= e(old('national_id') ?? '') ?>" class="form-input" maxlength="14" dir="ltr" id="nidInput">
                <small id="nidStatus" style="display:none;margin-top:4px;font-size:11px;"></small>
            </div>
            <div>
                <label class="form-label">تاريخ الميلاد</label>
                <input type="date" name="date_of_birth" value="<?= e(old('date_of_birth') ?? '') ?>" class="form-input" id="dobInput" readonly style="background:#F9FAFB;">
                <input type="hidden" name="age_years" id="ageYears">
            </div>
            <div>
                <label class="form-label">النوع</label>
                <select class="form-select" id="genderInput" disabled style="background:#F9FAFB;">
                    <option value="male" <?= old('gender') === 'male' || old('gender') === '' ? 'selected' : '' ?>>ذكر</option>
                    <option value="female" <?= old('gender') === 'female' ? 'selected' : '' ?>>أنثى</option>
                </select>
                <input type="hidden" name="gender" id="genderHidden" value="<?= e(old('gender') ?? 'male') ?>">
            </div>
            <div>
                <label class="form-label">الهاتف</label>
                <input type="text" name="phone" value="<?= e(old('phone') ?? '') ?>" class="form-input" dir="ltr" maxlength="30">
            </div>
            <div>
                <label class="form-label">البريد الإلكتروني</label>
                <input type="email" name="email" value="<?= e(old('email') ?? '') ?>" class="form-input" dir="ltr" maxlength="200">
            </div>
        </div>
    </div>

    <!-- Guardian Information -->
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
            <h3 style="margin:0;font-size:16px;font-weight:600;">بيانات ولي الأمر</h3>
        </div>
        <div style="padding:20px;display:grid;grid-template-columns:repeat(auto-fit, minmax(250px, 1fr));gap:15px;">
            <div>
                <label class="form-label">اسم ولي الأمر</label>
                <input type="text" name="guardian_name" value="<?= e(old('guardian_name') ?? '') ?>" class="form-input" maxlength="300">
            </div>
            <div>
                <label class="form-label">هاتف ولي الأمر</label>
                <input type="text" name="guardian_phone" value="<?= e(old('guardian_phone') ?? '') ?>" class="form-input" dir="ltr" maxlength="30">
            </div>
            <div>
                <label class="form-label">الرقم القومي لولي الأمر</label>
                <input type="text" name="guardian_national_id" value="<?= e(old('guardian_national_id') ?? '') ?>" class="form-input" maxlength="14" dir="ltr">
            </div>
            <div>
                <label class="form-label">صلة القرابة</label>
                <select name="guardian_relationship" class="form-select">
                    <option value="">اختر...</option>
                    <option value="father" <?= old('guardian_relationship') === 'father' ? 'selected' : '' ?>>أب</option>
                    <option value="mother" <?= old('guardian_relationship') === 'mother' ? 'selected' : '' ?>>أم</option>
                    <option value="brother" <?= old('guardian_relationship') === 'brother' ? 'selected' : '' ?>>أخ</option>
                    <option value="sister" <?= old('guardian_relationship') === 'sister' ? 'selected' : '' ?>>أخت</option>
                    <option value="uncle" <?= old('guardian_relationship') === 'uncle' ? 'selected' : '' ?>>عم / خال</option>
                    <option value="other" <?= old('guardian_relationship') === 'other' ? 'selected' : '' ?>>أخرى</option>
                </select>
            </div>
        </div>
    </div>

    <!-- Notes -->
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
            <h3 style="margin:0;font-size:16px;font-weight:600;">ملاحظات</h3>
        </div>
        <div style="padding:20px;">
            <textarea name="notes" class="form-input" rows="4" placeholder="ملاحظات إضافية..."><?= e(old('notes') ?? '') ?></textarea>
        </div>
    </div>

    <div style="display:flex;gap:10px;justify-content:flex-start;">
        <button type="submit" class="btn btn-primary"><i data-lucide="save" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> حفظ</button>
        <a href="/sa/players" class="btn btn-outline">إلغاء</a>
    </div>
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') lucide.createIcons();

    var playerType = document.getElementById('player_type');
    var memberField = document.getElementById('member_id_field');
    var membershipNoInput = document.getElementById('membershipNoInput');
    var memberIdHidden = document.getElementById('memberIdHidden');
    var memberLookupStatus = document.getElementById('memberLookupStatus');
    var csrfToken = document.querySelector('meta[name="csrf-token"]') ? document.querySelector('meta[name="csrf-token"]').content : '';
    var csrfInput = document.querySelector('input[name="_csrf_token"]');
    if (csrfInput) csrfToken = csrfInput.value;

    function toggleMemberId() {
        memberField.style.display = playerType.value === 'member' ? '' : 'none';
    }
    playerType.addEventListener('change', toggleMemberId);
    toggleMemberId();

    // Membership number auto-fill
    var memberLookupTimer = null;
    if (membershipNoInput) {
        membershipNoInput.addEventListener('input', function() {
            var val = this.value.replace(/\D/g, '');
            this.value = val;
            if (val.length < 1) { memberLookupStatus.style.display = 'none'; memberIdHidden.value = ''; return; }
            clearTimeout(memberLookupTimer);
            memberLookupTimer = setTimeout(function() {
                memberLookupStatus.style.display = '';
                memberLookupStatus.style.background = '#F3F4F6';
                memberLookupStatus.style.color = '#6B7280';
                memberLookupStatus.textContent = 'جاري البحث...';
                fetch('/api/sa/member-lookup', {
                    method: 'POST',
                    headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest','X-CSRF-TOKEN': csrfToken},
                    body: JSON.stringify({membership_number: val, _csrf_token: csrfToken})
                }).then(function(r){return r.json();}).then(function(data) {
                    if (data.success && data.member_id) {
                        memberIdHidden.value = data.member_id;
                        memberLookupStatus.style.background = '#ECFDF5';
                        memberLookupStatus.style.color = '#059669';
                        memberLookupStatus.innerHTML = '<strong>' + (data.name || '') + '</strong>' + (data.is_member ? ' — عضو فعال' : ' — <span style="color:#92400E;">' + (data.reason || 'غير فعال') + '</span>');
                        // Auto-fill form fields
                        var nameInput = document.querySelector('[name="full_name_ar"]');
                        var phoneInput = document.querySelector('[name="phone"]');
                        var nidField = document.getElementById('nidInput');
                        if (data.name && nameInput && !nameInput.value.trim()) nameInput.value = data.name;
                        if (data.phone && phoneInput && !phoneInput.value.trim()) phoneInput.value = data.phone;
                        if (data.national_id && nidField) {
                            nidField.value = data.national_id;
                            nidField.readOnly = true;
                            nidField.style.background = '#F9FAFB';
                            nidField.dispatchEvent(new Event('input'));
                        }
                    } else {
                        memberIdHidden.value = '';
                        memberLookupStatus.style.background = '#FEF2F2';
                        memberLookupStatus.style.color = '#DC2626';
                        memberLookupStatus.textContent = data.reason || 'رقم العضوية غير موجود';
                        var nf = document.getElementById('nidInput');
                        if (nf) { nf.readOnly = false; nf.style.background = ''; }
                    }
                });
            }, 400);
        });
    }

    var nidInput = document.getElementById('nidInput');
    var nidStatus = document.getElementById('nidStatus');
    var dobInput = document.getElementById('dobInput');
    var ageYears = document.getElementById('ageYears');
    var genderInput = document.getElementById('genderInput');
    var genderHidden = document.getElementById('genderHidden');

    if (nidInput) {
        nidInput.addEventListener('input', function() {
            var v = this.value.replace(/\D/g, '');
            this.value = v;
            if (v.length === 14) {
                if (playerType.value === 'member') {
                    nidStatus.style.display = 'none';
                    return;
                }
                fetch('/api/members/parse-nid', {
                    method: 'POST',
                    headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest'},
                    body: JSON.stringify({national_id: v})
                })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (data.parsed && data.parsed.is_valid) {
                        dobInput.value = data.parsed.dob;
                        dobInput.style.background = '#ECFDF5';
                        ageYears.value = data.parsed.age_years;
                        genderInput.value = data.parsed.gender;
                        genderHidden.value = data.parsed.gender;
                        genderInput.style.background = '#ECFDF5';
                        nidStatus.style.display = 'block';
                        nidStatus.style.color = '#059669';
                        nidStatus.textContent = '✓ ' + data.parsed.governorate_name_ar + ' — ' + data.parsed.age_years + ' سنة';
                    } else {
                        nidStatus.style.display = 'block';
                        nidStatus.style.color = '#DC2626';
                        nidStatus.textContent = (data.parsed && data.parsed.errors) ? data.parsed.errors[0] : 'رقم قومي غير صالح';
                    }
                });
            } else {
                nidStatus.style.display = 'none';
                if (v.length === 0) {
                    dobInput.value = '';
                    dobInput.style.background = '#F9FAFB';
                    dobInput.removeAttribute('readonly');
                    genderInput.disabled = false;
                    genderInput.style.background = '';
                }
            }
        });
    }
});
</script>
<?php $__template->endSection(); ?>
