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

<?php $__template->section('page_actions'); ?>
<a href="/players" class="btn btn-outline"><i data-lucide="arrow-right" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> العودة للقائمة</a>
<?php $__template->endSection(); ?>

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

<form method="POST" action="/players" id="playerForm" enctype="multipart/form-data">
    <?= csrf_field() ?>

    <!-- Section 1: Basic Data -->
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:8px;">
            <i data-lucide="user" style="width:18px;height:18px;color:#1e3a5f;"></i>
            <h3 style="margin:0;color:#1e3a5f;font-size:15px;">البيانات الأساسية</h3>
        </div>
        <div style="padding:20px;">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
                <div class="form-group">
                    <label class="form-label">نوع اللاعب <span style="color:#DC2626;">*</span></label>
                    <select name="player_type" id="playerType" class="form-input" required>
                        <option value="">-- اختر النوع --</option>
                        <?php foreach ($playerTypes as $key => $label): ?>
                        <option value="<?= e($key) ?>" <?= old('player_type') === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group" id="memberIdGroup" style="display:none;">
                    <label class="form-label">رقم العضوية</label>
                    <input type="number" name="member_id" value="<?= e(old('member_id')) ?>" class="form-input" min="1" style="direction:ltr;text-align:left;" placeholder="رقم العضوية في النادي">
                </div>
                <div class="form-group" style="text-align:center;">
                    <label class="form-label">الصورة الشخصية</label>
                    <div style="width:100px;height:100px;border-radius:50%;background:#F3F4F6;margin:0 auto 8px;display:flex;align-items:center;justify-content:center;overflow:hidden;border:2px dashed #D1D5DB;cursor:pointer;" onclick="document.getElementById('photoInput').click();" id="photoPreview">
                        <i data-lucide="camera" style="width:28px;height:28px;color:#9CA3AF;"></i>
                    </div>
                    <input type="file" name="photo" id="photoInput" accept="image/jpeg,image/png,image/webp" style="display:none;">
                    <small style="color:#9CA3AF;font-size:11px;">JPG, PNG أو WebP (حد أقصى 5MB)</small>
                </div>
                <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 placeholder="الاسم رباعي بالعربي" style="font-size:16px;">
                </div>
                <div class="form-group" style="grid-column:1/-1;">
                    <label class="form-label">الاسم بالكامل (إنجليزي)</label>
                    <input type="text" name="full_name_en" value="<?= e(old('full_name_en')) ?>" class="form-input" placeholder="Full name in English" style="direction:ltr;text-align:left;">
                </div>
                <div class="form-group">
                    <label class="form-label">الرقم القومي <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="national_id" id="nidInput" value="<?= e(old('national_id')) ?>" class="form-input" maxlength="14" style="direction:ltr;text-align:left;font-size:16px;letter-spacing:1px;" placeholder="أدخل 14 رقم">
                    <div id="nidFeedback" style="margin-top:4px;font-size:12px;display:none;"></div>
                </div>
                <div class="form-group">
                    <label class="form-label">رقم جواز السفر</label>
                    <input type="text" name="passport_number" value="<?= e(old('passport_number')) ?>" class="form-input" style="direction:ltr;text-align:left;" placeholder="رقم جواز السفر (اختياري)">
                </div>
                <div class="form-group">
                    <label class="form-label">تاريخ الميلاد <span style="color:#DC2626;">*</span></label>
                    <input type="date" name="date_of_birth" id="dobInput" value="<?= e(old('date_of_birth')) ?>" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">النوع <span style="color:#DC2626;">*</span></label>
                    <select name="gender" id="genderInput" class="form-input" required>
                        <option value="">-- اختر --</option>
                        <?php foreach ($genders as $key => $label): ?>
                        <option value="<?= e($key) ?>" <?= old('gender') === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">العمر</label>
                    <input type="text" id="ageDisplay" class="form-input" readonly style="background:#F3F4F6;cursor:not-allowed;" placeholder="يتم حسابه تلقائياً">
                </div>
                <div class="form-group">
                    <label class="form-label">المحافظة</label>
                    <input type="text" id="govDisplay" class="form-input" readonly style="background:#F3F4F6;cursor:not-allowed;" placeholder="تُستنتج من الرقم القومي">
                </div>
            </div>
        </div>
    </div>

    <!-- Section 2: Contact & Guardian -->
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:8px;">
            <i data-lucide="phone" style="width:18px;height:18px;color:#1e3a5f;"></i>
            <h3 style="margin:0;color:#1e3a5f;font-size:15px;">بيانات التواصل والولي</h3>
        </div>
        <div style="padding:20px;">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
                <div class="form-group">
                    <label class="form-label">رقم الهاتف</label>
                    <input type="tel" name="phone" value="<?= e(old('phone')) ?>" class="form-input" maxlength="15" style="direction:ltr;text-align:left;" placeholder="01XXXXXXXXX">
                </div>
                <div class="form-group">
                    <label class="form-label">البريد الإلكتروني</label>
                    <input type="email" name="email" value="<?= e(old('email')) ?>" class="form-input" style="direction:ltr;text-align:left;" placeholder="email@example.com">
                </div>
                <div class="form-group" style="grid-column:1/-1;">
                    <label class="form-label">العنوان</label>
                    <textarea name="address" class="form-input" rows="2" placeholder="عنوان السكن..."><?= e(old('address')) ?></textarea>
                </div>
            </div>

            <div style="border-top:1px solid #E5E7EB;margin:20px 0;padding-top:20px;">
                <h4 style="margin:0 0 15px;color:#374151;font-size:14px;"><i data-lucide="shield" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> بيانات ولي الأمر</h4>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
                    <div class="form-group">
                        <label class="form-label">اسم ولي الأمر</label>
                        <input type="text" name="guardian_name" value="<?= e(old('guardian_name')) ?>" class="form-input" placeholder="الاسم الكامل لولي الأمر">
                    </div>
                    <div class="form-group">
                        <label class="form-label">هاتف ولي الأمر</label>
                        <input type="tel" name="guardian_phone" value="<?= e(old('guardian_phone')) ?>" class="form-input" maxlength="15" style="direction:ltr;text-align:left;" placeholder="01XXXXXXXXX">
                    </div>
                    <div class="form-group">
                        <label class="form-label">الرقم القومي لولي الأمر</label>
                        <input type="text" name="guardian_national_id" value="<?= e(old('guardian_national_id')) ?>" class="form-input" maxlength="14" style="direction:ltr;text-align:left;" placeholder="14 رقم">
                    </div>
                    <div class="form-group">
                        <label class="form-label">صلة القرابة</label>
                        <select name="guardian_relationship" class="form-input">
                            <option value="">-- اختر --</option>
                            <?php foreach ($relationships as $key => $label): ?>
                            <option value="<?= e($key) ?>" <?= old('guardian_relationship') === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>

            <div style="border-top:1px solid #E5E7EB;margin:20px 0;padding-top:20px;">
                <h4 style="margin:0 0 15px;color:#374151;font-size:14px;"><i data-lucide="graduation-cap" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> البيانات التعليمية</h4>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
                    <div class="form-group">
                        <label class="form-label">اسم المدرسة</label>
                        <input type="text" name="school_name" value="<?= e(old('school_name')) ?>" class="form-input" placeholder="اسم المدرسة">
                    </div>
                    <div class="form-group">
                        <label class="form-label">الصف الدراسي</label>
                        <input type="text" name="school_grade" value="<?= e(old('school_grade')) ?>" class="form-input" placeholder="مثال: الصف الخامس الابتدائي">
                    </div>
                </div>
            </div>

            <div class="form-group" style="margin-top:10px;">
                <label class="form-label">ملاحظات</label>
                <textarea name="notes" class="form-input" rows="3" placeholder="أي ملاحظات إضافية..."><?= e(old('notes')) ?></textarea>
            </div>
        </div>
    </div>

    <!-- Submit -->
    <div style="display:flex;gap:10px;justify-content:flex-start;">
        <button type="submit" class="btn btn-primary" style="padding:12px 30px;font-size:15px;">
            <i data-lucide="check" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> تسجيل اللاعب
        </button>
        <a href="/players" class="btn btn-outline" style="padding:12px 30px;font-size:15px;">إلغاء</a>
    </div>
</form>

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

    var playerTypeSelect = document.getElementById('playerType');
    var memberIdGroup = document.getElementById('memberIdGroup');

    function toggleMemberId() {
        if (playerTypeSelect.value === 'member') {
            memberIdGroup.style.display = '';
        } else {
            memberIdGroup.style.display = 'none';
        }
    }

    playerTypeSelect.addEventListener('change', toggleMemberId);
    toggleMemberId();

    // Photo preview
    var photoInput = document.getElementById('photoInput');
    var photoPreview = document.getElementById('photoPreview');
    photoInput.addEventListener('change', function() {
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                photoPreview.innerHTML = '<img src="' + e.target.result + '" style="width:100%;height:100%;object-fit:cover;">';
            };
            reader.readAsDataURL(this.files[0]);
        }
    });

    // NID Auto-Parse
    var nidInput = document.getElementById('nidInput');
    var nidFeedback = document.getElementById('nidFeedback');
    var dobInput = document.getElementById('dobInput');
    var genderInput = document.getElementById('genderInput');
    var ageDisplay = document.getElementById('ageDisplay');
    var govDisplay = document.getElementById('govDisplay');
    var nidTimer = null;

    nidInput.addEventListener('input', function() {
        clearTimeout(nidTimer);
        var val = this.value.replace(/\D/g, '');
        this.value = val;
        nidFeedback.style.display = 'none';

        if (val.length === 14) {
            nidTimer = setTimeout(function() { parseNid(val); }, 200);
        } else {
            nidInput.style.borderColor = '';
        }
    });

    function parseNid(nid) {
        var formData = new FormData();
        formData.append('national_id', nid);
        formData.append('_csrf_token', document.querySelector('input[name="_csrf_token"]').value);

        fetch('/api/players/parse-nid', {method: 'POST', body: formData})
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.is_valid) {
                    nidInput.style.borderColor = '#059669';
                    nidFeedback.style.display = 'block';
                    nidFeedback.style.color = '#059669';
                    nidFeedback.textContent = 'رقم قومي صالح';

                    if (data.dob) dobInput.value = data.dob;
                    if (data.gender) genderInput.value = data.gender;
                    if (data.age_years !== null) ageDisplay.value = data.age_years + ' سنة' + (data.age_months ? ' و ' + data.age_months + ' شهر' : '');
                    if (data.governorate_name_ar) govDisplay.value = data.governorate_name_ar;

                    if (data.duplicate) {
                        nidFeedback.style.color = '#D97706';
                        nidFeedback.innerHTML = '<strong>تحذير:</strong> هذا الرقم القومي مسجل بالفعل للاعب: ' +
                            data.duplicate.name + ' (مسلسل: ' + data.duplicate.serial + ')';
                    }
                } else {
                    nidInput.style.borderColor = '#DC2626';
                    nidFeedback.style.display = 'block';
                    nidFeedback.style.color = '#DC2626';
                    nidFeedback.textContent = (data.errors && data.errors[0]) || 'رقم قومي غير صالح';
                }
            })
            .catch(function() {
                nidInput.style.borderColor = '';
            });
    }
});
</script>
<?php $__template->endSection(); ?>
