<?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;">
            <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>

            <div class="form-group">
                <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;">

            <?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; ?>

            <!-- Programs List (vertical, expandable) -->
            <div id="programsList">
                <?php foreach ($programs as $p):
                    $pId = (int) $p['id'];
                    $fee = $playerType === 'member' ? (float) $p['monthly_fee_member'] : (float) $p['monthly_fee_nonmember'];
                ?>
                <div class="program-item" data-disc-id="<?= (int) $p['discipline_id'] ?>" data-program-id="<?= $pId ?>" style="margin-bottom:6px;">
                    <!-- Program Row -->
                    <div class="program-row" onclick="toggleProgram(this, <?= $pId ?>)"
                         style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border:2px solid #E5E7EB;border-radius:10px;cursor:pointer;transition:all 0.2s;background:#fff;">
                        <div style="display:flex;align-items:center;gap:10px;">
                            <i data-lucide="chevron-down" class="program-chevron" style="width:16px;height:16px;color:#9CA3AF;transition:transform 0.2s;transform:rotate(-90deg);"></i>
                            <div>
                                <div style="font-weight:700;font-size:14px;color:#1A1A2E;"><?= e($p['name_ar']) ?></div>
                                <div style="font-size:11px;color:#6B7280;margin-top:2px;">
                                    <?= (int) $p['session_duration_minutes'] ?> دقيقة | <?= (int) $p['sessions_per_week'] ?> مرات/أسبوع | سعة: <?= (int) $p['max_capacity'] ?>
                                </div>
                            </div>
                        </div>
                        <div style="text-align:left;flex-shrink:0;">
                            <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>

                    <!-- Groups Panel (hidden by default, expands under program) -->
                    <div class="program-groups-panel" data-program-id="<?= $pId ?>" style="display:none;margin:4px 0 0 28px;padding:12px;border:1px solid #E8ECF0;border-radius:8px;background:#F9FAFB;">
                        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;">
                            <span style="font-size:13px;font-weight:600;color:#374151;">المجموعات</span>
                            <button type="button" class="btn btn-outline" style="font-size:11px;padding:4px 10px;border-radius:6px;color:#0D7377;border-color:#0D7377;" onclick="event.stopPropagation();openCreateGroupModal(<?= $pId ?>, '<?= e(addslashes($p['name_ar'])) ?>')">
                                <i data-lucide="plus" style="width:12px;height:12px;vertical-align:middle;margin-left:3px;"></i> أضف مجموعة
                            </button>
                        </div>
                        <div class="groups-container" data-program-id="<?= $pId ?>">
                            <!-- Filled by JS -->
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </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>

<!-- Create Group Modal (centered popup) -->
<div id="createGroupModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:9998;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:16px;padding:28px;width:90%;max-width:400px;box-shadow:0 24px 60px rgba(0,0,0,0.25);">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;">
            <h3 style="margin:0;font-size:16px;font-weight:700;color:#1A1A2E;">
                <i data-lucide="plus-circle" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;color:#0D7377;"></i>
                إنشاء مجموعة جديدة
            </h3>
            <button type="button" onclick="closeCreateGroupModal()" style="background:none;border:none;cursor:pointer;padding:4px;">
                <i data-lucide="x" style="width:20px;height:20px;color:#6B7280;"></i>
            </button>
        </div>
        <div style="margin-bottom:16px;padding:10px 14px;background:#F0FDFA;border-radius:8px;border:1px solid #CCFBF1;">
            <div style="font-size:12px;color:#6B7280;">البرنامج:</div>
            <div id="modalProgramName" style="font-size:14px;font-weight:600;color:#0D7377;margin-top:2px;"></div>
        </div>
        <div class="form-group" style="margin-bottom:20px;">
            <label class="form-label" style="font-size:13px;">اسم المجموعة <span style="color:#9CA3AF;">(اختياري)</span></label>
            <input type="text" id="newGroupName" class="form-input" placeholder="سيتم إنشاء اسم تلقائي إن تُرك فارغاً" style="font-size:14px;">
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
            <button type="button" class="btn btn-outline" onclick="closeCreateGroupModal()" style="padding:12px;font-size:14px;border-radius:10px;">إلغاء</button>
            <button type="button" class="btn btn-primary" id="btnCreateGroup" onclick="createGroup()" style="padding:12px;font-size:14px;border-radius:10px;">
                <i data-lucide="plus" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> إنشاء
            </button>
        </div>
    </div>
</div>

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

function toggleProgram(rowEl, programId) {
    var item = rowEl.closest('.program-item');
    var panel = item.querySelector('.program-groups-panel');
    var chevron = rowEl.querySelector('.program-chevron');
    var wasOpen = panel.style.display !== 'none';

    // Close all other panels
    document.querySelectorAll('.program-item').forEach(function(el) {
        var p = el.querySelector('.program-groups-panel');
        var r = el.querySelector('.program-row');
        var c = r.querySelector('.program-chevron');
        p.style.display = 'none';
        r.style.borderColor = '#E5E7EB';
        r.style.background = '#fff';
        c.style.transform = 'rotate(-90deg)';
    });

    if (!wasOpen) {
        panel.style.display = '';
        rowEl.style.borderColor = '#0D7377';
        rowEl.style.background = '#F0FDFA';
        chevron.style.transform = 'rotate(0deg)';
        selectedProgramId = programId;
        renderGroupsInPanel(programId);
    } else {
        selectedProgramId = null;
    }
    if (typeof lucide !== 'undefined') lucide.createIcons();
}

function renderGroupsInPanel(programId) {
    var container = document.querySelector('.groups-container[data-program-id="' + programId + '"]');
    if (!container) return;

    var groups = groupsData[programId] || [];
    if (groups.length === 0) {
        container.innerHTML = '<div style="text-align:center;padding:16px;color:#9CA3AF;font-size:13px;">' +
            '<i data-lucide="inbox" style="width:24px;height:24px;display:block;margin:0 auto 6px;color:#D1D5DB;"></i>' +
            'لا توجد مجموعات — أنشئ واحدة جديدة</div>';
        if (typeof lucide !== 'undefined') lucide.createIcons();
        return;
    }

    var html = '';
    groups.forEach(function(g) {
        var fee = playerType === 'member' ? parseFloat(g.monthly_fee_member || 0) : parseFloat(g.monthly_fee_nonmember || 0);
        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';

        html += '<label class="group-radio-card" style="display:block;border:2px solid #E5E7EB;border-radius:10px;padding:12px 14px;cursor:pointer;transition:all 0.15s;margin-bottom:6px;background:#fff;">';
        html += '<div style="display:flex;align-items:center;gap:10px;">';
        html += '<input type="radio" name="group_id" value="' + g.id + '" required style="accent-color:#0D7377;width:18px;height:18px;flex-shrink:0;" onchange="onGroupSelect(this)">';
        html += '<div style="flex:1;min-width:0;">';
        html += '<div style="font-weight:600;font-size:13px;color:#1A1A2E;">' + esc(g.name_ar) + '</div>';
        html += '<div style="font-size:11px;color:#6B7280;margin-top:2px;">';
        if (g.coach_name) html += 'المدرب: ' + esc(g.coach_name);
        html += '</div>';
        html += '</div>';
        html += '<div style="text-align:left;flex-shrink:0;">';
        html += '<div style="font-size:14px;font-weight:700;color:#059669;">' + fee.toLocaleString() + ' ج.م</div>';
        html += '</div>';
        html += '</div>';
        // Progress bar
        html += '<div style="margin-top:8px;display:flex;align-items:center;gap:8px;">';
        html += '<div style="flex:1;background:#F3F4F6;border-radius:4px;height:5px;overflow:hidden;">';
        html += '<div style="height:100%;width:' + pct + '%;background:' + barColor + ';border-radius:4px;"></div>';
        html += '</div>';
        html += '<span style="font-size:10px;color:#6B7280;flex-shrink:0;">' + g.current_count + '/' + g.max_capacity + '</span>';
        html += '</div>';
        html += '</label>';
    });
    container.innerHTML = html;
    if (typeof lucide !== 'undefined') lucide.createIcons();
}

function onGroupSelect(radio) {
    document.querySelectorAll('.group-radio-card').forEach(function(el) {
        el.style.borderColor = '#E5E7EB';
        el.style.background = '#fff';
    });
    radio.closest('.group-radio-card').style.borderColor = '#0D7377';
    radio.closest('.group-radio-card').style.background = '#F0FDFA';
}

function openCreateGroupModal(programId, programName) {
    modalProgramId = programId;
    document.getElementById('modalProgramName').textContent = programName;
    document.getElementById('newGroupName').value = '';
    document.getElementById('createGroupModal').style.display = 'flex';
    document.getElementById('newGroupName').focus();
    if (typeof lucide !== 'undefined') lucide.createIcons();
}

function closeCreateGroupModal() {
    document.getElementById('createGroupModal').style.display = 'none';
    modalProgramId = null;
}

function createGroup() {
    if (!modalProgramId) return;
    var name = document.getElementById('newGroupName').value.trim();
    var btn = document.getElementById('btnCreateGroup');
    btn.disabled = true;
    btn.innerHTML = '<i data-lucide="loader" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;animation:spin 1s linear infinite;"></i> جاري الإنشاء...';

    fetch('/api/sa/groups/quick-create', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': csrfToken
        },
        body: '_csrf_token=' + encodeURIComponent(csrfToken) + '&program_id=' + modalProgramId + '&name_ar=' + encodeURIComponent(name)
    })
    .then(function(r) {
        if (!r.ok) {
            return r.text().then(function(t) {
                try { return JSON.parse(t); } catch(e) { throw new Error('خطأ ' + r.status); }
            });
        }
        return r.json();
    })
    .then(function(data) {
        btn.disabled = false;
        btn.innerHTML = '<i data-lucide="plus" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> إنشاء';
        if (typeof lucide !== 'undefined') lucide.createIcons();

        if (!data.success) {
            alert(data.error || data.message || 'فشل في إنشاء المجموعة');
            return;
        }

        if (!groupsData[modalProgramId]) groupsData[modalProgramId] = [];
        groupsData[modalProgramId].push(data.group);
        renderGroupsInPanel(modalProgramId);
        closeCreateGroupModal();
    })
    .catch(function(err) {
        btn.disabled = false;
        btn.innerHTML = '<i data-lucide="plus" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> إنشاء';
        if (typeof lucide !== 'undefined') lucide.createIcons();
        alert(err.message || 'خطأ في الاتصال');
    });
}

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-item').forEach(function(c) {
                c.style.display = c.dataset.discId === discId ? '' : 'none';
            });
            // Close expanded panels
            document.querySelectorAll('.program-groups-panel').forEach(function(p) { p.style.display = 'none'; });
            document.querySelectorAll('.program-row').forEach(function(r) {
                r.style.borderColor = '#E5E7EB';
                r.style.background = '#fff';
                r.querySelector('.program-chevron').style.transform = 'rotate(-90deg)';
            });
            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 progItem = document.querySelector('.program-item[data-program-id="' + selectedProgramId + '"]');
        var progRow = progItem ? progItem.querySelector('.program-row') : null;
        var progName = progRow ? progRow.querySelector('div[style*="font-weight:700"]').textContent.trim() : '';

        var groupCard = selectedGroup.closest('.group-radio-card');
        var groupName = groupCard.querySelector('div[style*="font-weight:600"]').textContent.trim();
        var feeEl = groupCard.querySelector('div[style*="color:#059669"]');

        var discName = '';
        <?php foreach ($programsByDisc as $dId => $dData): ?>
        if (progItem && progItem.dataset.discId === '<?= $dId ?>') discName = '<?= e($dData['name']) ?>';
        <?php endforeach; ?>

        document.getElementById('confGroup').textContent = groupName;
        document.getElementById('confDisc').textContent = discName;
        document.getElementById('confProg').textContent = progName;
        document.getElementById('confLevel').textContent = levelLabels[selectedLevel.value] || selectedLevel.value;
        document.getElementById('confAmount').textContent = feeEl ? feeEl.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'; });

    // Close create modal on backdrop click
    var createModal = document.getElementById('createGroupModal');
    createModal.addEventListener('click', function(e) { if (e.target === createModal) closeCreateGroupModal(); });

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

<style>
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
.program-row:hover { border-color: #B2DFDB !important; background: #FAFFFE !important; }
.group-radio-card:hover { border-color: #B2DFDB !important; }
</style>
<?php $__template->endSection(); ?>
