<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>تصنيف وتعيين: <?= e($registration['full_name_ar']) ?><?php $__template->endSection(); ?>

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

<!-- Player Info Card -->
<div class="card" style="margin-bottom:16px;">
    <div style="padding:16px 20px;display:flex;align-items:center;gap:14px;">
        <div style="width:64px;height:64px;border-radius:10px;overflow:hidden;background:#F3F4F6;flex-shrink:0;">
            <?php if (!empty($registration['photo_path'])): ?>
            <img src="/<?= e($registration['photo_path']) ?>" style="width:100%;height:100%;object-fit:cover;">
            <?php else: ?>
            <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;color:#9CA3AF;"><i data-lucide="user" style="width:28px;height:28px;"></i></div>
            <?php endif; ?>
        </div>
        <div style="flex:1;">
            <div style="font-size:18px;font-weight:700;color:#1A1A2E;"><?= e($registration['full_name_ar']) ?></div>
            <div style="font-size:13px;color:#6B7280;margin-top:4px;">
                <span style="padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600;background:<?= ($registration['p_type'] ?? 'non_member') === 'member' ? '#ECFDF5' : '#FEF3C7' ?>;color:<?= ($registration['p_type'] ?? 'non_member') === 'member' ? '#059669' : '#D97706' ?>;">
                    <?= ($registration['p_type'] ?? 'non_member') === 'member' ? 'عضو' : 'غير عضو' ?>
                </span>
                <?php if (!empty($registration['player_nid'])): ?>
                <span style="margin-right:8px;direction:ltr;display:inline-block;"><?= e($registration['player_nid']) ?></span>
                <?php endif; ?>
                <?php if (!empty($registration['date_of_birth'])): ?>
                <?php
                $age = (int) ((time() - strtotime($registration['date_of_birth'])) / (365.25 * 86400));
                ?>
                <span style="margin-right:8px;"><?= $age ?> سنة</span>
                <?php endif; ?>
            </div>
        </div>
        <div style="text-align:left;">
            <div style="font-size:11px;color:#6B7280;">رقم التسجيل</div>
            <div style="font-size:13px;font-weight:600;direction:ltr;"><?= e($registration['registration_number']) ?></div>
        </div>
    </div>
    <?php
    $selectedDisc = [];
    if (!empty($registration['selected_disciplines'])) {
        $decoded = json_decode($registration['selected_disciplines'], true);
        if (is_array($decoded)) $selectedDisc = $decoded;
    }
    if (!empty($selectedDisc)):
    ?>
    <div style="padding:0 20px 16px;display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
        <span style="font-size:12px;color:#6B7280;font-weight:600;">الأنشطة المطلوبة:</span>
        <?php foreach ($selectedDisc as $disc): ?>
        <span style="padding:4px 10px;border-radius:6px;background:#EFF6FF;color:#2563EB;font-size:12px;font-weight:600;"><?= e($disc['name'] ?? $disc) ?></span>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<!-- Assessment Form -->
<form method="POST" action="/sa/coach-assessment/<?= (int) $registration['id'] ?>/submit">
    <?= csrf_field() ?>

    <div class="card" style="margin-bottom:16px;">
        <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:8px;">
            <i data-lucide="target" style="width:18px;height:18px;color:#0D7377;"></i>
            <h3 style="margin:0;color:#0D7377;font-size:15px;">تصنيف المستوى</h3>
        </div>
        <div style="padding:20px;">
            <!-- Skill Level -->
            <div class="form-group" style="margin-bottom:20px;">
                <label class="form-label">المستوى <span style="color:#DC2626;">*</span></label>
                <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;">
                    <label style="display:flex;align-items:center;justify-content:center;gap:8px;padding:14px;border:2px solid #E5E7EB;border-radius:10px;cursor:pointer;transition:all 0.2s;">
                        <input type="radio" name="skill_level" value="beginner" required style="accent-color:#2563EB;width:18px;height:18px;">
                        <span style="font-weight:600;font-size:14px;">مبتدئ</span>
                    </label>
                    <label style="display:flex;align-items:center;justify-content:center;gap:8px;padding:14px;border:2px solid #E5E7EB;border-radius:10px;cursor:pointer;transition:all 0.2s;">
                        <input type="radio" name="skill_level" value="intermediate" style="accent-color:#059669;width:18px;height:18px;">
                        <span style="font-weight:600;font-size:14px;">متوسط</span>
                    </label>
                    <label style="display:flex;align-items:center;justify-content:center;gap:8px;padding:14px;border:2px solid #E5E7EB;border-radius:10px;cursor:pointer;transition:all 0.2s;">
                        <input type="radio" name="skill_level" value="advanced" style="accent-color:#7C3AED;width:18px;height:18px;">
                        <span style="font-weight:600;font-size:14px;">متقدم</span>
                    </label>
                </div>
            </div>

            <!-- Assessment Notes -->
            <div class="form-group" style="margin-bottom:20px;">
                <label class="form-label">ملاحظات المدرب</label>
                <textarea name="assessment_notes" class="form-input" rows="3" placeholder="ملاحظات عن مستوى اللاعب..."></textarea>
            </div>
        </div>
    </div>

    <!-- Program & Group Selection -->
    <?php
    $programsByDisc = [];
    foreach ($programs as $p) {
        $dId = (int) ($p['discipline_id'] ?? 0);
        if (!isset($programsByDisc[$dId])) {
            $programsByDisc[$dId] = ['name' => $p['discipline_name'] ?? '', 'programs' => []];
        }
        $programsByDisc[$dId]['programs'][] = $p;
    }
    $groupsByProgram = [];
    foreach ($groups as $g) {
        $pId = (int) ($g['program_id'] ?? 0);
        if (!isset($groupsByProgram[$pId])) $groupsByProgram[$pId] = [];
        $groupsByProgram[$pId][] = $g;
    }
    $playerType = $registration['p_type'] ?? 'non_member';
    ?>

    <div class="card" style="margin-bottom:16px;">
        <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:8px;">
            <i data-lucide="layers" style="width:18px;height:18px;color:#0D7377;"></i>
            <h3 style="margin:0;color:#0D7377;font-size:15px;">اختيار البرنامج والمجموعة <span style="color:#DC2626;">*</span></h3>
        </div>
        <div style="padding:16px;">

            <!-- Step 1: Discipline Tabs -->
            <?php if (count($programsByDisc) > 1): ?>
            <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:14px;">
                <?php foreach ($programsByDisc as $dId => $dData): ?>
                <button type="button" class="disc-filter-btn btn btn-outline" data-disc-id="<?= $dId ?>" style="padding:8px 16px;font-size:13px;border-radius:8px;">
                    <?= e($dData['name']) ?>
                </button>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <!-- Step 2: Program Cards -->
            <div id="programsList" style="display:grid;gap:10px;margin-bottom:16px;">
                <?php foreach ($programs as $p):
                    $pId = (int) $p['id'];
                    $pGroups = $groupsByProgram[$pId] ?? [];
                    $fee = $playerType === 'member' ? (float) $p['monthly_fee_member'] : (float) $p['monthly_fee_nonmember'];
                ?>
                <div class="program-card" data-disc-id="<?= (int) $p['discipline_id'] ?>" data-program-id="<?= $pId ?>"
                     style="border:2px solid #E5E7EB;border-radius:12px;padding:14px 16px;cursor:pointer;transition:all 0.2s;"
                     onclick="selectProgram(this, <?= $pId ?>)">
                    <div style="display:flex;align-items:center;justify-content:space-between;">
                        <div>
                            <div style="font-weight:700;font-size:14px;color:#1A1A2E;"><?= e($p['name_ar']) ?></div>
                            <div style="font-size:12px;color:#6B7280;margin-top:3px;">
                                <?= (int) $p['session_duration_minutes'] ?> دقيقة | <?= (int) $p['sessions_per_week'] ?> مرات/أسبوع
                                | سعة: <?= (int) $p['max_capacity'] ?>
                            </div>
                        </div>
                        <div style="text-align:left;">
                            <div style="font-size:15px;font-weight:700;color:#059669;"><?= number_format($fee, 0) ?> ج.م</div>
                            <div style="font-size:10px;color:#6B7280;"><?= $playerType === 'member' ? 'عضو' : 'غير عضو' ?></div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- Step 3: Groups under selected program -->
            <div id="groupsSection" style="display:none;">
                <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;">
                    <h4 style="margin:0;font-size:14px;color:#374151;"><i data-lucide="users" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;color:#0D7377;"></i> المجموعات المتاحة</h4>
                    <button type="button" id="btnAddGroup" class="btn btn-outline" style="font-size:12px;padding:6px 12px;border-radius:8px;color:#0D7377;border-color:#0D7377;" onclick="showAddGroupModal()">
                        <i data-lucide="plus" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> أضف مجموعة
                    </button>
                </div>
                <div id="groupCards" style="display:grid;gap:10px;max-height:350px;overflow-y:auto;">
                    <!-- Populated by JS -->
                </div>
                <div id="noGroupsMsg" style="display:none;text-align:center;padding:24px;color:#6B7280;font-size:13px;">
                    <i data-lucide="inbox" style="width:32px;height:32px;color:#D1D5DB;display:block;margin:0 auto 8px;"></i>
                    لا توجد مجموعات لهذا البرنامج — أضف مجموعة جديدة
                </div>
            </div>
        </div>
    </div>

    <!-- Add Group Modal -->
    <div id="addGroupModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.4);z-index:9998;align-items:center;justify-content:center;">
        <div style="background:#fff;border-radius:14px;padding:24px;width:90%;max-width:380px;box-shadow:0 20px 60px rgba(0,0,0,0.2);">
            <h3 style="margin:0 0 16px;font-size:16px;font-weight:700;color:#1A1A2E;">إضافة مجموعة جديدة</h3>
            <div class="form-group" style="margin-bottom:14px;">
                <label class="form-label" style="font-size:13px;">اسم المجموعة (اختياري)</label>
                <input type="text" id="newGroupName" class="form-input" placeholder="سيتم إنشاء اسم تلقائي إن تُرك فارغاً">
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                <button type="button" class="btn btn-outline" onclick="hideAddGroupModal()">إلغاء</button>
                <button type="button" class="btn btn-primary" id="btnConfirmAddGroup" onclick="createGroup()">إنشاء</button>
            </div>
        </div>
    </div>

    <!-- Hidden data for JS -->
    <script id="groupsData" type="application/json"><?= json_encode($groupsByProgram, JSON_UNESCAPED_UNICODE) ?></script>
    <script id="playerType" type="application/json"><?= json_encode($playerType) ?></script>

    <button type="button" id="btnShowConfirm" class="btn btn-primary" style="width:100%;padding:16px;font-size:16px;font-weight:700;border-radius:12px;">
        <i data-lucide="check-circle" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> تأكيد التصنيف والتعيين
    </button>

    <!-- Confirmation Overlay -->
    <div id="confirmOverlay" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:9999;align-items:center;justify-content:center;">
        <div style="background:#fff;border-radius:16px;padding:24px;width:90%;max-width:420px;box-shadow:0 20px 60px rgba(0,0,0,0.3);">
            <h3 style="margin:0 0 16px;font-size:17px;font-weight:700;color:#1A1A2E;text-align:center;">
                <i data-lucide="send" style="width:20px;height:20px;vertical-align:middle;margin-left:6px;color:#0D7377;"></i> تأكيد الإرسال للخزنة
            </h3>
            <div style="background:#F9FAFB;border-radius:10px;padding:16px;margin-bottom:16px;">
                <div style="display:grid;gap:10px;font-size:14px;">
                    <div style="display:flex;justify-content:space-between;"><span style="color:#6B7280;">اللاعب:</span><strong id="confPlayer"><?= e($registration['full_name_ar']) ?></strong></div>
                    <div style="display:flex;justify-content:space-between;"><span style="color:#6B7280;">المجموعة:</span><strong id="confGroup">—</strong></div>
                    <div style="display:flex;justify-content:space-between;"><span style="color:#6B7280;">النشاط:</span><strong id="confDisc">—</strong></div>
                    <div style="display:flex;justify-content:space-between;"><span style="color:#6B7280;">البرنامج:</span><strong id="confProg">—</strong></div>
                    <div style="display:flex;justify-content:space-between;"><span style="color:#6B7280;">المستوى:</span><strong id="confLevel">—</strong></div>
                    <div style="display:flex;justify-content:space-between;border-top:1px dashed #E5E7EB;padding-top:10px;margin-top:4px;">
                        <span style="color:#6B7280;font-weight:600;">مبلغ الاشتراك الشهري:</span>
                        <strong id="confAmount" style="color:#059669;font-size:16px;">—</strong>
                    </div>
                </div>
            </div>
            <p style="font-size:12px;color:#6B7280;text-align:center;margin:0 0 16px;">سيتم إرسال طلب دفع الاشتراك للخزنة — اللاعب يتوجه للكاشير لإتمام الدفع</p>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                <button type="button" id="btnCancelConfirm" class="btn btn-outline" style="padding:12px;font-size:14px;border-radius:10px;">رجوع</button>
                <button type="submit" class="btn btn-primary" style="padding:12px;font-size:14px;border-radius:10px;">
                    <i data-lucide="check" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> تأكيد وإرسال
                </button>
            </div>
        </div>
    </div>
</form>

<script>
var groupsData = JSON.parse(document.getElementById('groupsData').textContent);
var playerType = JSON.parse(document.getElementById('playerType').textContent);
var selectedProgramId = null;
var csrfToken = document.querySelector('input[name="_csrf_token"]').value;

function selectProgram(el, programId) {
    selectedProgramId = programId;
    document.querySelectorAll('.program-card').forEach(function(c) {
        c.style.borderColor = '#E5E7EB';
        c.style.background = '';
    });
    el.style.borderColor = '#0D7377';
    el.style.background = '#F0FDFA';

    renderGroups(programId);
    document.getElementById('groupsSection').style.display = '';
    if (typeof lucide !== 'undefined') lucide.createIcons();
}

function renderGroups(programId) {
    var groups = groupsData[programId] || [];
    var container = document.getElementById('groupCards');
    var noMsg = document.getElementById('noGroupsMsg');

    if (groups.length === 0) {
        container.innerHTML = '';
        noMsg.style.display = '';
    } else {
        noMsg.style.display = 'none';
        var html = '';
        groups.forEach(function(g) {
            var fee = playerType === 'member' ? parseFloat(g.monthly_fee_member) : parseFloat(g.monthly_fee_nonmember);
            var pct = g.max_capacity > 0 ? Math.round((g.current_count / g.max_capacity) * 100) : 0;
            var barColor = pct >= 90 ? '#DC2626' : pct >= 70 ? '#F59E0B' : '#059669';
            var checked = '';

            html += '<label class="group-radio-option" style="display:block;border:2px solid #E5E7EB;border-radius:12px;padding:14px 16px;cursor:pointer;transition:all 0.2s;">';
            html += '<div style="display:flex;align-items:center;gap:12px;">';
            html += '<input type="radio" name="group_id" value="' + g.id + '" required style="accent-color:#2563EB;width:20px;height:20px;flex-shrink:0;" onchange="highlightGroup(this)">';
            html += '<div style="flex:1;min-width:0;">';
            html += '<div style="font-weight:600;font-size:14px;">' + esc(g.name_ar) + '</div>';
            html += '<div style="font-size:12px;color:#6B7280;margin-top:2px;">';
            if (g.coach_name) html += 'مدرب: ' + esc(g.coach_name) + ' | ';
            html += esc(g.discipline_name || '') + ' — ' + esc(g.program_name || '');
            html += '</div>';
            html += '</div>';
            html += '<div style="text-align:left;flex-shrink:0;">';
            html += '<div style="font-size:15px;font-weight:700;color:#059669;">' + fee.toLocaleString() + ' ج.م</div>';
            html += '<div style="font-size:11px;color:#6B7280;">' + g.current_count + '/' + g.max_capacity + '</div>';
            html += '</div>';
            html += '</div>';
            // Progress bar
            html += '<div style="margin-top:10px;background:#F3F4F6;border-radius:6px;height:6px;overflow:hidden;">';
            html += '<div style="height:100%;width:' + pct + '%;background:' + barColor + ';border-radius:6px;transition:width 0.3s;"></div>';
            html += '</div>';
            html += '<div style="display:flex;justify-content:space-between;margin-top:4px;font-size:10px;color:#9CA3AF;">';
            html += '<span>' + pct + '% ممتلئة</span>';
            html += '<span>متبقي ' + (g.max_capacity - g.current_count) + ' مكان</span>';
            html += '</div>';
            html += '</label>';
        });
        container.innerHTML = html;
    }
    if (typeof lucide !== 'undefined') lucide.createIcons();
}

function highlightGroup(radio) {
    document.querySelectorAll('#groupCards .group-radio-option').forEach(function(el) {
        el.style.borderColor = '#E5E7EB';
        el.style.background = '';
    });
    radio.closest('.group-radio-option').style.borderColor = '#2563EB';
    radio.closest('.group-radio-option').style.background = '#F0F7FF';
}

function showAddGroupModal() {
    document.getElementById('addGroupModal').style.display = 'flex';
    document.getElementById('newGroupName').value = '';
}

function hideAddGroupModal() {
    document.getElementById('addGroupModal').style.display = 'none';
}

function createGroup() {
    if (!selectedProgramId) return;
    var name = document.getElementById('newGroupName').value.trim();
    var btn = document.getElementById('btnConfirmAddGroup');
    btn.disabled = true;
    btn.textContent = 'جاري الإنشاء...';

    fetch('/api/sa/groups/quick-create', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
        body: '_csrf_token=' + encodeURIComponent(csrfToken) + '&program_id=' + selectedProgramId + '&name_ar=' + encodeURIComponent(name)
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        btn.disabled = false;
        btn.textContent = 'إنشاء';
        if (!data.success) { alert(data.error || 'فشل'); return; }
        // Add to local data
        if (!groupsData[selectedProgramId]) groupsData[selectedProgramId] = [];
        groupsData[selectedProgramId].push(data.group);
        renderGroups(selectedProgramId);
        hideAddGroupModal();
    })
    .catch(function() {
        btn.disabled = false;
        btn.textContent = 'إنشاء';
        alert('خطأ في الاتصال');
    });
}

function esc(s) { var d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML; }

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

    // Discipline filter
    document.querySelectorAll('.disc-filter-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.disc-filter-btn').forEach(function(b) { b.style.background = ''; b.style.color = ''; });
            this.style.background = '#0D7377';
            this.style.color = '#fff';
            var discId = this.dataset.discId;
            document.querySelectorAll('.program-card').forEach(function(c) {
                c.style.display = c.dataset.discId === discId ? '' : 'none';
            });
            // Hide groups until new program selected
            document.getElementById('groupsSection').style.display = 'none';
            selectedProgramId = null;
        });
    });

    // Skill level highlight
    document.querySelectorAll('input[name="skill_level"]').forEach(function(radio) {
        radio.addEventListener('change', function() {
            document.querySelectorAll('input[name="skill_level"]').forEach(function(r) {
                r.closest('label').style.borderColor = '#E5E7EB';
                r.closest('label').style.background = '';
            });
            this.closest('label').style.borderColor = '#2563EB';
            this.closest('label').style.background = '#EFF6FF';
        });
    });

    // Confirmation overlay
    var overlay = document.getElementById('confirmOverlay');
    var btnShow = document.getElementById('btnShowConfirm');
    var btnCancel = document.getElementById('btnCancelConfirm');
    var levelLabels = {beginner: 'مبتدئ', intermediate: 'متوسط', advanced: 'متقدم'};

    btnShow.addEventListener('click', function() {
        var selectedGroup = document.querySelector('input[name="group_id"]:checked');
        var selectedLevel = document.querySelector('input[name="skill_level"]:checked');

        if (!selectedProgramId) { alert('اختر البرنامج أولاً'); return; }
        if (!selectedGroup) { alert('اختر مجموعة أولاً'); return; }
        if (!selectedLevel) { alert('اختر المستوى أولاً'); return; }

        var progCard = document.querySelector('.program-card[data-program-id="' + selectedProgramId + '"]');
        var progName = progCard ? progCard.querySelector('div[style*="font-weight:700"]').textContent.trim() : '';
        var groupLabel = selectedGroup.closest('.group-radio-option');
        var groupName = groupLabel.querySelector('div[style*="font-weight:600"]').textContent.trim();
        var discEl = groupLabel.querySelector('div[style*="color:#6B7280"]');
        var discText = discEl ? discEl.textContent.trim().split('—') : [''];
        var amountEl = groupLabel.querySelector('div[style*="color:#059669"]');

        document.getElementById('confGroup').textContent = groupName;
        document.getElementById('confDisc').textContent = (discText[1] || discText[0] || '').trim().split('|')[0].trim();
        document.getElementById('confProg').textContent = progName;
        document.getElementById('confLevel').textContent = levelLabels[selectedLevel.value] || selectedLevel.value;
        document.getElementById('confAmount').textContent = amountEl ? amountEl.textContent.trim() : '—';

        overlay.style.display = 'flex';
        if (typeof lucide !== 'undefined') lucide.createIcons();
    });

    btnCancel.addEventListener('click', function() { overlay.style.display = 'none'; });
    overlay.addEventListener('click', function(e) { if (e.target === overlay) overlay.style.display = 'none'; });

    // Auto-select first discipline if only one
    var discBtns = document.querySelectorAll('.disc-filter-btn');
    if (discBtns.length === 1) discBtns[0].click();
});
</script>
<?php $__template->endSection(); ?>
