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

<?php $__template->section('page_actions'); ?>
<a href="/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="/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 $certs = $coach->getCertifications(); ?>

<form method="POST" action="/coaches/<?= (int) $coach->id ?>" enctype="multipart/form-data" 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;">
            <!-- Photo Upload -->
            <div style="display:flex;align-items:center;gap:20px;margin-bottom:20px;">
                <label style="cursor:pointer;">
                    <div id="photoPreview" style="width:80px;height:80px;border-radius:50%;background:#F3F4F6;display:flex;align-items:center;justify-content:center;overflow:hidden;border:3px dashed #D1D5DB;">
                        <?php if (!empty($coach->photo_path)): ?>
                        <img src="<?= e($coach->photo_path) ?>" style="width:80px;height:80px;object-fit:cover;border-radius:50%;">
                        <?php else: ?>
                        <i data-lucide="camera" style="width:24px;height:24px;color:#9CA3AF;"></i>
                        <?php endif; ?>
                    </div>
                    <input type="file" name="photo" accept="image/jpeg,image/png,image/webp" style="display:none;" id="photoInput">
                </label>
                <div>
                    <div style="font-size:13px;font-weight:600;color:#1A1A2E;">صورة المدرب</div>
                    <div style="font-size:11px;color:#9CA3AF;">JPG, PNG أو WebP — حد أقصى 5MB</div>
                </div>
            </div>

            <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>
                    <input type="text" name="full_name_ar" value="<?= e(old('full_name_ar') ?: $coach->full_name_ar) ?>" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">الاسم بالإنجليزي</label>
                    <input type="text" name="full_name_en" value="<?= e(old('full_name_en') ?: ($coach->full_name_en ?? '')) ?>" class="form-input" style="direction:ltr;text-align:left;">
                </div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:20px;margin-top:15px;">
                <div class="form-group">
                    <label class="form-label">كود المدرب <span style="color:#9CA3AF;font-size:11px;">(اختياري)</span></label>
                    <input type="text" name="code" value="<?= e(old('code') ?: $coach->code) ?>" class="form-input" style="direction:ltr;text-align:left;text-transform:uppercase;">
                </div>
                <div class="form-group">
                    <label class="form-label">الرقم القومي</label>
                    <input type="text" name="national_id" id="nidInput" value="<?= e(old('national_id') ?: ($coach->national_id ?? '')) ?>" class="form-input" 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') ?: ($coach->phone ?? '')) ?>" class="form-input" style="direction:ltr;text-align:left;">
                </div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:20px;margin-top:15px;">
                <div class="form-group">
                    <label class="form-label">البريد الإلكتروني</label>
                    <input type="email" name="email" value="<?= e(old('email') ?: ($coach->email ?? '')) ?>" class="form-input" 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') ?: ($coach->date_of_birth ?? '')) ?>" class="form-input" readonly style="background:#F9FAFB;direction:ltr;text-align:left;">
                </div>
                <div class="form-group">
                    <label class="form-label">النوع</label>
                    <select id="genderSelect" class="form-select" disabled>
                        <option value="">-- اختر --</option>
                        <option value="male" <?= (old('gender') ?: ($coach->gender ?? '')) === 'male' ? 'selected' : '' ?>>ذكر</option>
                        <option value="female" <?= (old('gender') ?: ($coach->gender ?? '')) === 'female' ? 'selected' : '' ?>>أنثى</option>
                    </select>
                    <input type="hidden" name="gender" id="genderHidden" value="<?= e(old('gender') ?: ($coach->gender ?? '')) ?>">
                </div>
            </div>
        </div>
    </div>

    <!-- Employment & Payment -->
    <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:#D97706;"></i>
            <h3 style="margin:0;color:#D97706;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') ?: ($coach->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>
                        <?php foreach ($employmentTypes as $key => $label): ?>
                        <option value="<?= e($key) ?>" <?= (old('employment_type') ?: $coach->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>
                        <?php foreach ($paymentModels as $key => $label): ?>
                        <option value="<?= e($key) ?>" <?= (old('payment_model') ?: $coach->payment_model) === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <!-- Academy Assignment (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:12px;"><i data-lucide="building-2" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> تعيين الأكاديمية</div>
                <div style="display:grid;grid-template-columns:2fr 1fr 1fr;gap:15px;">
                    <div class="form-group" style="margin:0;">
                        <label class="form-label">الأكاديمية <span style="color:#DC2626;">*</span></label>
                        <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') ?: ($currentAcademyId ?? '')) == $acad['id'] ? 'selected' : '' ?>><?= e($acad['name_ar']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label class="form-label">المستوى</label>
                        <select name="academy_level_id" class="form-select">
                            <option value="">-- كل المستويات --</option>
                            <?php foreach ($academyLevels as $lvl): ?>
                            <option value="<?= (int) $lvl['id'] ?>" data-academy="<?= (int) $lvl['academy_id'] ?>" <?= (old('academy_level_id') ?: ($currentLevelId ?? '')) == $lvl['id'] ? 'selected' : '' ?>><?= e($lvl['name_ar']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label class="form-label">الدور</label>
                        <select name="academy_role" class="form-select">
                            <?php foreach ($roles as $key => $label): ?>
                            <option value="<?= e($key) ?>" <?= (old('academy_role') ?: ($currentRole ?? 'coach')) === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </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="max_players_default" value="<?= e(old('max_players_default') ?: (string)($coach->max_players_default ?? 20)) ?>" class="form-input" min="1" max="100" style="direction:ltr;text-align:left;">
                </div>
            <div style="display:grid;grid-template-columns: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') ?: (string)($coach->hourly_rate ?? '')) ?>" class="form-input" min="0" step="0.01" 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') ?: (string)($coach->session_rate ?? '')) ?>" class="form-input" min="0" step="0.01" 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') ?: (string)($coach->monthly_rate ?? '')) ?>" class="form-input" min="0" step="0.01" 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;gap:8px;">
            <i data-lucide="activity" style="width:18px;height:18px;color:#2563EB;"></i>
            <h3 style="margin:0;color:#2563EB;font-size:15px;">التخصصات الرياضية</h3>
        </div>
        <div style="padding:20px;">
            <div style="display:flex;flex-wrap:wrap;gap:10px;">
                <?php foreach ($disciplines as $disc): ?>
                <label style="display:flex;align-items:center;gap:6px;padding:8px 14px;border:1px solid #E5E7EB;border-radius:8px;cursor:pointer;transition:all 0.2s;">
                    <input type="checkbox" name="discipline_ids[]" value="<?= (int) $disc['id'] ?>" <?= in_array((int) $disc['id'], $coachDisciplineIds) ? 'checked' : '' ?> style="width:16px;height:16px;accent-color:#0D7377;">
                    <span style="font-size:13px;"><?= e($disc['name_ar']) ?></span>
                </label>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Bio & Certifications -->
    <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:#059669;"></i>
            <h3 style="margin:0;color:#059669;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="3"><?= e(old('bio_ar') ?: ($coach->bio_ar ?? '')) ?></textarea>
            </div>
            <div class="form-group" style="margin-top:15px;">
                <label class="form-label">الشهادات والتراخيص</label>
                <div id="certsContainer">
                    <?php if (!empty($certs)): ?>
                        <?php foreach ($certs as $i => $cert): ?>
                        <div style="display:flex;gap:8px;margin-bottom:8px;">
                            <input type="text" name="certifications[]" value="<?= e($cert) ?>" class="form-input" style="flex:1;">
                            <?php if ($i === 0): ?>
                            <button type="button" onclick="addCertRow()" class="btn btn-outline" style="padding:8px 12px;"><i data-lucide="plus" style="width:14px;height:14px;"></i></button>
                            <?php else: ?>
                            <button type="button" onclick="this.parentElement.remove()" class="btn btn-outline" style="padding:8px 12px;color:#DC2626;"><i data-lucide="x" style="width:14px;height:14px;"></i></button>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                    <div style="display:flex;gap:8px;margin-bottom:8px;">
                        <input type="text" name="certifications[]" class="form-input" placeholder="مثال: رخصة تدريب AFC-B" style="flex:1;">
                        <button type="button" onclick="addCertRow()" class="btn btn-outline" style="padding:8px 12px;"><i data-lucide="plus" style="width:14px;height:14px;"></i></button>
                    </div>
                    <?php endif; ?>
                </div>
            </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="/coaches/<?= (int) $coach->id ?>" 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();

    // Coach type toggle
    var coachTypeSelect = document.getElementById('coachTypeSelect');
    var academyFields = document.getElementById('academyFields');
    function toggleAcademyFields() {
        academyFields.style.display = coachTypeSelect.value === 'academy' ? 'block' : 'none';
        var acadSelect = document.getElementById('academySelect');
        if (coachTypeSelect.value === 'academy') {
            acadSelect.setAttribute('required', 'required');
        } else {
            acadSelect.removeAttribute('required');
        }
    }
    coachTypeSelect.addEventListener('change', toggleAcademyFields);
    toggleAcademyFields();

    var photoInput = document.getElementById('photoInput');
    if (photoInput) {
        photoInput.addEventListener('change', function() {
            var file = this.files[0];
            if (!file) return;
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('photoPreview').innerHTML = '<img src="' + e.target.result + '" style="width:80px;height:80px;object-fit:cover;border-radius:50%;">';
            };
            reader.readAsDataURL(file);
        });
    }
});

function addCertRow() {
    var container = document.getElementById('certsContainer');
    var div = document.createElement('div');
    div.style.cssText = 'display:flex;gap:8px;margin-bottom:8px;';
    div.innerHTML = '<input type="text" name="certifications[]" class="form-input" placeholder="شهادة إضافية..." style="flex:1;"><button type="button" onclick="this.parentElement.remove()" class="btn btn-outline" style="padding:8px 12px;color:#DC2626;"><i data-lucide="x" style="width:14px;height:14px;"></i></button>';
    container.appendChild(div);
    if (typeof lucide !== 'undefined') lucide.createIcons();
}
</script>

<script>
(function(){
    var nid = document.getElementById('nidInput');
    var dob = document.getElementById('dobInput');
    var genderSelect = document.getElementById('genderSelect');
    var genderHidden = document.getElementById('genderHidden');
    var status = document.getElementById('nidStatus');
    if (!nid) return;

    function parseNid(val) {
        if (val.length !== 14) { status.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;
                status.style.display = 'block';
                status.style.color = '#059669';
                status.textContent = (p.governorate_name_ar || '') + ' — ' + (p.age_years || '') + ' سنة';
            } else {
                status.style.display = 'block';
                status.style.color = '#DC2626';
                status.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(); ?>
