<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>تعديل المدرب: <?= e($coach['full_name_ar'] ?? '') ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/sa/coaches/<?= (int) $coach['id'] ?>" class="btn btn-outline"><i data-lucide="eye" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> عرض</a>
<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'); ?>

<?php
// Use old input if available (after validation failure), otherwise use coach data
$val = function(string $field) use ($coach) {
    $old = old($field);
    return $old !== '' && $old !== null ? $old : ($coach[$field] ?? '');
};
?>

<form method="POST" action="/sa/coaches/<?= (int) $coach['id'] ?>" 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($val('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($val('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($val('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($val('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($val('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($val('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($val('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" <?= $val('gender') === 'male' ? 'selected' : '' ?>>ذكر</option>
                        <option value="female" <?= $val('gender') === 'female' ? 'selected' : '' ?>>أنثى</option>
                    </select>
                    <input type="hidden" name="gender" id="genderHidden" value="<?= e($val('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;gap:20px;">
                <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) ?>" <?= $val('employment_type') === $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="payment_model" class="form-select" required>
                        <option value="">-- اختر --</option>
                        <?php foreach ($paymentModels as $key => $label): ?>
                        <option value="<?= e($key) ?>" <?= $val('payment_model') === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </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="number" name="hourly_rate" value="<?= e($val('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($val('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($val('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($val('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;display:none;">
                لم يتم إضافة تخصصات بعد. اضغط "إضافة تخصص" لإضافة تخصص جديد.
            </div>
            <?php foreach ($coachDisciplines as $cd): ?>
            <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'] ?>" <?= (int) $cd['discipline_id'] === (int) $disc['id'] ? 'selected' : '' ?>><?= 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" <?= ($cd['specialization_level'] ?? '') === 'primary' ? 'selected' : '' ?>>أساسي</option>
                        <option value="secondary" <?= ($cd['specialization_level'] ?? '') === 'secondary' ? 'selected' : '' ?>>ثانوي</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>
            <?php endforeach; ?>
        </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($val('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/<?= (int) $coach['id'] ?>" 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();
    }

    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; }
        fetch('/api/members/parse-nid', {
            method: 'POST',
            headers: {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'},
            body: JSON.stringify({national_id: val})
        })
        .then(function(r){ return r.json(); })
        .then(function(d){
            if (d.success && d.data) {
                dob.value = d.data.dob || '';
                dob.readOnly = true;
                dob.style.background = '#F9FAFB';
                var g = d.data.gender || '';
                genderSelect.value = g;
                genderSelect.disabled = true;
                genderHidden.value = g;
                nidStatus.style.display = 'block';
                nidStatus.style.color = '#059669';
                nidStatus.textContent = (d.data.governorate || '') + ' — ' + (d.data.age || '') + ' سنة';
            } else {
                nidStatus.style.display = 'block';
                nidStatus.style.color = '#DC2626';
                nidStatus.textContent = d.message || 'رقم قومي غير صحيح';
            }
        }).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(); ?>
