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

<?php $__template->section('page_actions'); ?>
<a href="/sa/coaches" 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="/sa/coaches" id="coachForm" novalidate>
    <?= csrf_field() ?>

    <!-- Basic Information -->
    <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 1fr;gap:20px;">
                <div class="form-group">
                    <label class="form-label">كود المدرب <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="code" value="<?= e(old('code')) ?>" class="form-input" maxlength="30" placeholder="مثال: COACH-001" style="direction:ltr;text-align:left;text-transform:uppercase;">
                </div>
                <div class="form-group">
                    <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" maxlength="300" placeholder="الاسم الكامل بالعربي">
                </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" maxlength="300" placeholder="Full name in English" style="direction:ltr;text-align:left;">
                </div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:20px;margin-top:15px;">
                <div class="form-group">
                    <label class="form-label">الرقم القومي</label>
                    <input type="text" name="national_id" id="nidInput" value="<?= e(old('national_id')) ?>" class="form-input" placeholder="14 رقم" maxlength="14" inputmode="numeric" style="direction:ltr;text-align:left;letter-spacing:1px;">
                    <div id="nidStatus" style="display:none;margin-top:6px;padding:8px 12px;border-radius:6px;font-size:12px;font-weight:600;"></div>
                </div>
                <div class="form-group">
                    <label class="form-label">تاريخ الميلاد</label>
                    <input type="date" name="date_of_birth" id="dobInput" value="<?= e(old('date_of_birth')) ?>" class="form-input" style="direction:ltr;text-align:left;">
                    <div id="ageDisplay" style="font-size:11px;color:#6B7280;margin-top:4px;"></div>
                </div>
                <div class="form-group">
                    <label class="form-label">النوع</label>
                    <select name="gender" id="genderSelect" class="form-select">
                        <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">الهاتف</label>
                    <input type="text" name="phone" value="<?= e(old('phone')) ?>" class="form-input" maxlength="30" placeholder="01xxxxxxxxx" inputmode="tel" style="direction:ltr;text-align:left;">
                </div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 2fr;gap:20px;margin-top:15px;">
                <div class="form-group">
                    <label class="form-label">البريد الإلكتروني</label>
                    <input type="email" name="email" value="<?= e(old('email')) ?>" class="form-input" maxlength="200" placeholder="email@example.com" style="direction:ltr;text-align:left;">
                </div>
                <div></div>
            </div>
        </div>
    </div>

    <!-- Employment Information -->
    <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="briefcase" style="width:18px;height:18px;color:#059669;"></i>
            <h3 style="margin:0;color:#059669;font-size:15px;">بيانات التوظيف</h3>
        </div>
        <div style="padding:20px;">
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:20px;">
                <div class="form-group">
                    <label class="form-label">نوع المدرب <span style="color:#DC2626;">*</span></label>
                    <select name="coach_type" id="coachTypeSelect" class="form-select">
                        <?php foreach ($coachTypes as $key => $label): ?>
                        <option value="<?= e($key) ?>" <?= (old('coach_type') ?? 'independent') === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">نوع التوظيف <span style="color:#DC2626;">*</span></label>
                    <select name="employment_type" id="employmentTypeSelect" class="form-select">
                        <option value="">-- اختر --</option>
                        <?php foreach ($employmentTypes as $key => $label): ?>
                        <option value="<?= e($key) ?>" <?= old('employment_type') === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group" id="paymentModelField">
                    <label class="form-label">نموذج الدفع <span style="color:#DC2626;">*</span></label>
                    <select name="payment_model" id="paymentModelSelect" class="form-select">
                        <option value="">-- اختر --</option>
                        <?php foreach ($paymentModels as $key => $label): ?>
                        <option value="<?= e($key) ?>" <?= old('payment_model') === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <!-- Academy selector -->
            <div id="academyFields" style="display:none;margin-top:15px;padding:15px;background:#F5F3FF;border:1px solid #8B5CF630;border-radius:10px;">
                <div style="font-size:13px;font-weight:700;color:#7C3AED;margin-bottom:10px;"><i data-lucide="building-2" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> الأكاديمية</div>
                <div class="form-group" style="margin:0;">
                    <select name="academy_id" id="academySelect" class="form-select">
                        <option value="">-- اختر الأكاديمية --</option>
                        <?php foreach ($academies as $acad): ?>
                        <option value="<?= (int) $acad['id'] ?>" <?= old('academy_id') == $acad['id'] ? 'selected' : '' ?>><?= e($acad['name_ar']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div style="margin-top:8px;font-size:11px;color:#7C3AED;">مدرب أكاديمية لا يحتاج نموذج دفع — يتبع نظام رواتب الأكاديمية</div>
            </div>
            <div id="financialFields" style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:20px;margin-top:15px;">
                <div class="form-group">
                    <label class="form-label">سعر الساعة (ج.م)</label>
                    <input type="number" name="hourly_rate" value="<?= e(old('hourly_rate')) ?>" class="form-input" min="0" step="0.01" placeholder="0.00" style="direction:ltr;text-align:left;">
                </div>
                <div class="form-group">
                    <label class="form-label">سعر الحصة (ج.م)</label>
                    <input type="number" name="session_rate" value="<?= e(old('session_rate')) ?>" class="form-input" min="0" step="0.01" placeholder="0.00" style="direction:ltr;text-align:left;">
                </div>
                <div class="form-group">
                    <label class="form-label">الراتب الشهري (ج.م)</label>
                    <input type="number" name="monthly_rate" value="<?= e(old('monthly_rate')) ?>" class="form-input" min="0" step="0.01" placeholder="0.00" style="direction:ltr;text-align:left;">
                </div>
                <div class="form-group">
                    <label class="form-label">أقصى عدد مجموعات</label>
                    <input type="number" name="max_groups" value="<?= e(old('max_groups') ?? '10') ?>" class="form-input" min="1" step="1" style="direction:ltr;text-align:left;">
                </div>
            </div>
        </div>
    </div>

    <!-- Disciplines -->
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;justify-content:space-between;">
            <div style="display:flex;align-items:center;gap:8px;">
                <i data-lucide="activity" style="width:18px;height:18px;color:#7C3AED;"></i>
                <h3 style="margin:0;color:#7C3AED;font-size:15px;">التخصصات</h3>
            </div>
            <button type="button" id="addDisciplineBtn" class="btn btn-sm btn-outline" style="color:#7C3AED;border-color:#7C3AED;">
                <i data-lucide="plus" style="width:14px;height:14px;vertical-align:middle;margin-left:3px;"></i> إضافة تخصص
            </button>
        </div>
        <div style="padding:20px;" id="disciplinesContainer">
            <div id="noDisciplinesMsg" style="text-align:center;padding:20px;color:#9CA3AF;font-size:14px;">
                لم يتم إضافة تخصصات بعد. اضغط "إضافة تخصص" لإضافة تخصص جديد.
            </div>
        </div>
    </div>

    <!-- Bio -->
    <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="file-text" style="width:18px;height:18px;color:#6B7280;"></i>
            <h3 style="margin:0;color:#6B7280;font-size:15px;">نبذة</h3>
        </div>
        <div style="padding:20px;">
            <div class="form-group">
                <label class="form-label">نبذة عن المدرب</label>
                <textarea name="bio_ar" class="form-input" rows="4" placeholder="نبذة مختصرة عن خبرات المدرب ومؤهلاته..."><?= e(old('bio_ar')) ?></textarea>
            </div>
        </div>
    </div>

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

<template id="disciplineRowTemplate">
    <div class="discipline-row" style="display:grid;grid-template-columns:2fr 1fr auto;gap:10px;align-items:end;margin-bottom:10px;padding:10px;background:#F9FAFB;border-radius:8px;">
        <div class="form-group" style="margin:0;">
            <label class="form-label" style="font-size:12px;">التخصص</label>
            <select name="discipline_ids[]" class="form-select" required>
                <option value="">-- اختر التخصص --</option>
                <?php foreach ($disciplines as $disc): ?>
                <option value="<?= (int) $disc['id'] ?>"><?= e($disc['name_ar'] ?? '') ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group" style="margin:0;">
            <label class="form-label" style="font-size:12px;">المستوى</label>
            <select name="levels[]" class="form-select">
                <option value="primary">أساسي</option>
                <option value="secondary">ثانوي</option>
            </select>
        </div>
        <button type="button" class="btn btn-sm btn-outline removeDisciplineBtn" style="color:#DC2626;border-color:#DC2626;margin-bottom:2px;" title="حذف">
            <i data-lucide="trash-2" style="width:14px;height:14px;"></i>
        </button>
    </div>
</template>

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

    // === NID Parser (client-side, no API needed) ===
    var nid = document.getElementById('nidInput');
    var dobInput = document.getElementById('dobInput');
    var genderSelect = document.getElementById('genderSelect');
    var nidStatus = document.getElementById('nidStatus');
    var ageDisplay = document.getElementById('ageDisplay');

    var governorates = {'01':'القاهرة','02':'الإسكندرية','03':'بورسعيد','04':'السويس','11':'دمياط','12':'الدقهلية','13':'الشرقية','14':'القليوبية','15':'كفر الشيخ','16':'الغربية','17':'المنوفية','18':'البحيرة','19':'الإسماعيلية','21':'الجيزة','22':'بني سويف','23':'الفيوم','24':'المنيا','25':'أسيوط','26':'سوهاج','27':'قنا','28':'أسوان','29':'الأقصر','31':'البحر الأحمر','32':'الوادي الجديد','33':'مطروح','34':'شمال سيناء','35':'جنوب سيناء','88':'خارج مصر'};

    function parseNidLocal(val) {
        val = val.replace(/\D/g, '');
        nid.value = val;
        if (val.length < 14) {
            nidStatus.style.display = 'none';
            dobInput.readOnly = false;
            dobInput.style.background = '';
            genderSelect.disabled = false;
            return;
        }
        if (val.length > 14) { val = val.substring(0, 14); nid.value = val; }

        var century = val[0] === '2' ? '19' : (val[0] === '3' ? '20' : null);
        if (!century) {
            showNidError('الرقم القومي غير صحيح — يجب أن يبدأ بـ 2 أو 3');
            return;
        }

        var year = century + val.substring(1, 3);
        var month = val.substring(3, 5);
        var day = val.substring(5, 7);
        var govCode = val.substring(7, 9);
        var genderDigit = parseInt(val[12]);

        var y = parseInt(year), m = parseInt(month), d = parseInt(day);
        if (m < 1 || m > 12 || d < 1 || d > 31) {
            showNidError('تاريخ الميلاد في الرقم القومي غير صحيح');
            return;
        }

        var dob = year + '-' + month + '-' + day;
        var gender = (genderDigit % 2 === 0) ? 'female' : 'male';
        var govName = governorates[govCode] || 'غير معروف';

        // Calculate age
        var birthDate = new Date(y, m - 1, d);
        var today = new Date();
        var age = today.getFullYear() - birthDate.getFullYear();
        var mDiff = today.getMonth() - birthDate.getMonth();
        if (mDiff < 0 || (mDiff === 0 && today.getDate() < birthDate.getDate())) age--;

        // Set fields
        dobInput.value = dob;
        dobInput.readOnly = true;
        dobInput.style.background = '#F0FDF4';
        genderSelect.value = gender;
        genderSelect.disabled = true;
        ageDisplay.textContent = age + ' سنة';

        // Show success
        nidStatus.style.display = 'block';
        nidStatus.style.background = '#ECFDF5';
        nidStatus.style.color = '#059669';
        nidStatus.innerHTML = '<strong>✓</strong> ' + govName + ' — ' + (gender === 'male' ? 'ذكر' : 'أنثى') + ' — ' + age + ' سنة';
    }

    function showNidError(msg) {
        nidStatus.style.display = 'block';
        nidStatus.style.background = '#FEF2F2';
        nidStatus.style.color = '#DC2626';
        nidStatus.textContent = msg;
        dobInput.readOnly = false;
        dobInput.style.background = '';
        genderSelect.disabled = false;
    }

    nid.addEventListener('input', function() { parseNidLocal(this.value); });
    if (nid.value.length === 14) parseNidLocal(nid.value);

    // DOB manual change -> show age
    dobInput.addEventListener('change', function() {
        if (!this.value) { ageDisplay.textContent = ''; return; }
        var parts = this.value.split('-');
        var birth = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]));
        var today = new Date();
        var age = today.getFullYear() - birth.getFullYear();
        var m = today.getMonth() - birth.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) age--;
        ageDisplay.textContent = age + ' سنة';
    });

    // === Coach Type Toggle ===
    var coachTypeSelect = document.getElementById('coachTypeSelect');
    var academyFields = document.getElementById('academyFields');
    var financialFields = document.getElementById('financialFields');
    var paymentModelField = document.getElementById('paymentModelField');
    var paymentModelSelect = document.getElementById('paymentModelSelect');
    var academySelect = document.getElementById('academySelect');

    function toggleCoachType() {
        var isAcademy = coachTypeSelect.value === 'academy';
        academyFields.style.display = isAcademy ? 'block' : 'none';
        financialFields.style.display = isAcademy ? 'none' : 'grid';
        paymentModelField.style.display = isAcademy ? 'none' : '';
        if (isAcademy) {
            paymentModelSelect.value = '';
        }
    }
    coachTypeSelect.addEventListener('change', toggleCoachType);
    toggleCoachType();

    // === Disciplines ===
    var container = document.getElementById('disciplinesContainer');
    var template = document.getElementById('disciplineRowTemplate');
    var addBtn = document.getElementById('addDisciplineBtn');
    var noMsg = document.getElementById('noDisciplinesMsg');

    function updateDisciplineVisibility() {
        noMsg.style.display = container.querySelectorAll('.discipline-row').length === 0 ? 'block' : 'none';
    }

    addBtn.addEventListener('click', function() {
        var clone = template.content.cloneNode(true);
        container.appendChild(clone);
        updateDisciplineVisibility();
        if (typeof lucide !== 'undefined') lucide.createIcons();
    });

    container.addEventListener('click', function(e) {
        var btn = e.target.closest('.removeDisciplineBtn');
        if (btn) { btn.closest('.discipline-row').remove(); updateDisciplineVisibility(); }
    });
    updateDisciplineVisibility();

    // === FORM VALIDATION ===
    function markInvalid(el, msg) {
        el.style.border = '2px solid #EF4444';
        el.style.background = '#FEF2F2';
        var hint = el.parentNode.querySelector('.val-hint');
        if (!hint) {
            hint = document.createElement('div');
            hint.className = 'val-hint';
            hint.style.cssText = 'font-size:11px;color:#DC2626;margin-top:3px;font-weight:600;';
            el.parentNode.appendChild(hint);
        }
        hint.textContent = msg;
    }

    function clearAllValidation() {
        document.querySelectorAll('.val-hint').forEach(function(h) { h.remove(); });
        document.querySelectorAll('[style*="2px solid"]').forEach(function(el) { el.style.border = ''; el.style.background = ''; });
    }

    document.getElementById('coachForm').addEventListener('submit', function(e) {
        clearAllValidation();
        var valid = true;

        function check(name, msg) {
            var el = document.querySelector('[name="' + name + '"]');
            if (!el) return;
            if (!el.value || !el.value.trim()) { markInvalid(el, msg); valid = false; }
        }

        // Required fields
        check('code', 'كود المدرب مطلوب');
        check('full_name_ar', 'الاسم بالعربي مطلوب');
        check('employment_type', 'نوع التوظيف مطلوب');

        var isAcademy = coachTypeSelect.value === 'academy';

        if (!isAcademy) {
            check('payment_model', 'نموذج الدفع مطلوب للمدربين غير الأكاديميين');
        } else {
            if (!academySelect.value) { markInvalid(academySelect, 'اختر الأكاديمية'); valid = false; }
        }

        // NID validation (if entered must be 14 digits)
        var nidVal = nid.value.trim();
        if (nidVal && nidVal.length !== 14) {
            markInvalid(nid, 'الرقم القومي يجب أن يكون 14 رقم');
            valid = false;
        }

        // Email format
        var emailEl = document.querySelector('[name="email"]');
        if (emailEl.value.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailEl.value.trim())) {
            markInvalid(emailEl, 'صيغة البريد الإلكتروني غير صحيحة');
            valid = false;
        }

        // Phone format
        var phoneEl = document.querySelector('[name="phone"]');
        if (phoneEl.value.trim() && !/^[0-9+\-\s()]{7,30}$/.test(phoneEl.value.trim())) {
            markInvalid(phoneEl, 'رقم الهاتف غير صحيح');
            valid = false;
        }

        if (!valid) {
            e.preventDefault();
            var firstBad = document.querySelector('[style*="2px solid"]');
            if (firstBad) firstBad.scrollIntoView({behavior: 'smooth', block: 'center'});
        }
    });

    // Clear validation on input
    document.getElementById('coachForm').addEventListener('input', function(ev) {
        var el = ev.target;
        if (el.style.border && el.style.border.includes('solid')) {
            el.style.border = '';
            el.style.background = '';
            var hint = el.parentNode.querySelector('.val-hint');
            if (hint) hint.remove();
        }
    });
    document.getElementById('coachForm').addEventListener('change', function(ev) {
        var el = ev.target;
        if (el.style.border && el.style.border.includes('solid')) {
            el.style.border = '';
            el.style.background = '';
            var hint = el.parentNode.querySelector('.val-hint');
            if (hint) hint.remove();
        }
    });
});
</script>

<style>
.val-hint { animation: valShake 0.3s ease; }
@keyframes valShake { 0%,100%{transform:translateX(0)} 25%{transform:translateX(-4px)} 75%{transform:translateX(4px)} }
</style>

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