<?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">
    <?= 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:#0D7377;"></i>
            <h3 style="margin:0;color:#0D7377;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" required 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" required 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" style="direction:ltr;text-align:left;">
                    <small id="nidStatus" style="display:none;margin-top:4px;font-size:11px;"></small>
                </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" style="direction:ltr;text-align:left;">
                </div>
                <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 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" readonly style="direction:ltr;text-align:left;background:#F9FAFB;">
                </div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 3fr;gap:20px;margin-top:15px;">
                <div class="form-group">
                    <label class="form-label">النوع</label>
                    <select id="genderSelect" class="form-select" disabled>
                        <option value="">-- اختر --</option>
                        <option value="male" <?= old('gender') === 'male' ? 'selected' : '' ?>>ذكر</option>
                        <option value="female" <?= old('gender') === 'female' ? 'selected' : '' ?>>أنثى</option>
                    </select>
                    <input type="hidden" name="gender" id="genderHidden" value="<?= e(old('gender')) ?>">
                </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" required>
                        <?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" class="form-select" required>
                        <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" required>
                        <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 (shown when coach_type = academy) -->
            <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>
            <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')) ?>" class="form-input" min="0" step="1" placeholder="مثال: 5" 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"><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();
    }

    // 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');
    function toggleAcademyFields() {
        var isAcademy = coachTypeSelect.value === 'academy';
        academyFields.style.display = isAcademy ? 'block' : 'none';
        financialFields.style.display = isAcademy ? 'none' : 'grid';
        paymentModelField.style.display = isAcademy ? 'none' : '';
        var acadSelect = document.getElementById('academySelect');
        if (isAcademy) {
            acadSelect.setAttribute('required', 'required');
            paymentModelSelect.removeAttribute('required');
        } else {
            acadSelect.removeAttribute('required');
            paymentModelSelect.setAttribute('required', 'required');
        }
    }
    coachTypeSelect.addEventListener('change', toggleAcademyFields);
    toggleAcademyFields();

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

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

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

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

    updateVisibility();

    // NID auto-parse
    var nid = document.getElementById('nidInput');
    var dob = document.getElementById('dobInput');
    var genderSelect = document.getElementById('genderSelect');
    var genderHidden = document.getElementById('genderHidden');
    var nidStatus = document.getElementById('nidStatus');

    function parseNid(val) {
        if (val.length !== 14) { nidStatus.style.display = 'none'; dob.readOnly = false; dob.style.background = ''; genderSelect.disabled = false; return; }
        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(d){
            var p = d.parsed;
            if (p && p.is_valid) {
                dob.value = p.dob || '';
                dob.readOnly = true;
                dob.style.background = '#F9FAFB';
                var g = p.gender || '';
                genderSelect.value = g;
                genderSelect.disabled = true;
                genderHidden.value = g;
                nidStatus.style.display = 'block';
                nidStatus.style.color = '#059669';
                nidStatus.textContent = (p.governorate_name_ar || '') + ' — ' + (p.age_years || '') + ' سنة';
            } else {
                nidStatus.style.display = 'block';
                nidStatus.style.color = '#DC2626';
                nidStatus.textContent = (p && p.errors) ? p.errors[0] : 'رقم قومي غير صحيح';
            }
        }).catch(function(){});
    }

    nid.addEventListener('input', function(){ parseNid(this.value.trim()); });
    genderSelect.addEventListener('change', function(){ genderHidden.value = this.value; });
    if (nid.value.trim().length === 14) parseNid(nid.value.trim());
});
</script>
<?php $__template->endSection(); ?>
