<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>مكتب التسجيل الرياضي<?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/sa/registration/report" class="btn btn-outline"><i data-lucide="bar-chart-3" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> التقارير</a>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<?php if (isset($registration)): ?>
<!-- Wizard Steps View -->
<div id="wizardApp" data-registration-id="<?= (int) $registration['id'] ?>" data-step="<?= $step ?? 1 ?>">

    <!-- Progress Bar -->
    <div class="card" style="margin-bottom:16px;padding:16px;">
        <div style="display:flex;justify-content:space-between;align-items:center;position:relative;">
            <div style="position:absolute;top:50%;left:40px;right:40px;height:3px;background:#E5E7EB;z-index:0;transform:translateY(-50%);"></div>
            <?php
            $steps = ['الدفع', 'الصورة', 'الأنشطة', 'الاستلام'];
            foreach ($steps as $i => $label):
                $stepNum = $i + 1;
                $isActive = $stepNum == ($step ?? 1);
                $isComplete = $stepNum < ($step ?? 1);
                $bgColor = $isComplete ? '#059669' : ($isActive ? '#2563EB' : '#E5E7EB');
                $textColor = ($isComplete || $isActive) ? '#fff' : '#9CA3AF';
            ?>
            <div style="text-align:center;position:relative;z-index:1;">
                <div style="width:40px;height:40px;border-radius:50%;background:<?= $bgColor ?>;color:<?= $textColor ?>;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:15px;margin:0 auto;">
                    <?= $isComplete ? '✓' : $stepNum ?>
                </div>
                <div style="font-size:11px;margin-top:6px;color:<?= $isActive ? '#2563EB' : '#6B7280' ?>;font-weight:<?= $isActive ? '700' : '400' ?>;"><?= $label ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Player Info Summary -->
    <div class="card" style="margin-bottom:16px;">
        <div style="padding:14px 16px;display:flex;align-items:center;gap:12px;border-bottom:1px solid #E5E7EB;">
            <div style="width:56px;height:56px;border-radius:8px;overflow:hidden;background:#F3F4F6;flex-shrink:0;">
                <?php if ($registration['photo_path']): ?>
                <img src="/<?= e($registration['photo_path']) ?>" style="width:100%;height:100%;object-fit:cover;" alt="">
                <?php else: ?>
                <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;color:#9CA3AF;"><i data-lucide="user" style="width:24px;height:24px;"></i></div>
                <?php endif; ?>
            </div>
            <div style="flex:1;min-width:0;">
                <div style="font-size:16px;font-weight:700;color:#1A1A2E;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?= e($registration['full_name_ar']) ?></div>
                <div style="font-size:12px;color:#6B7280;margin-top:2px;">
                    <span style="padding:2px 6px;border-radius:4px;font-size:11px;font-weight:600;background:<?= $registration['player_type'] === 'member' ? '#ECFDF5' : '#FEF3C7' ?>;color:<?= $registration['player_type'] === 'member' ? '#059669' : '#D97706' ?>;">
                        <?= $registration['player_type'] === 'member' ? 'عضو' : 'غير عضو' ?>
                    </span>
                    <?php if ($registration['player_nid']): ?><span style="margin-right:6px;direction:ltr;display:inline-block;"><?= e($registration['player_nid']) ?></span><?php endif; ?>
                </div>
            </div>
            <div style="text-align:left;flex-shrink:0;">
                <div style="font-size:11px;color:#6B7280;">رقم التسجيل</div>
                <div style="font-size:12px;font-weight:600;direction:ltr;"><?= e($registration['registration_number']) ?></div>
            </div>
        </div>
    </div>

    <!-- Step 1: Pay 100 EGP -->
    <div id="step-pay" class="wizard-step" style="<?= ($step ?? 1) == 1 ? '' : 'display:none;' ?>">
        <div class="card" style="margin-bottom:16px;">
            <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
                <h3 style="margin:0;font-size:16px;font-weight:600;"><i data-lucide="banknote" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> رسوم التسجيل</h3>
            </div>
            <div style="padding:24px;text-align:center;">
                <div style="max-width:400px;margin:0 auto;">
                    <div style="width:80px;height:80px;border-radius:50%;background:#EFF6FF;margin:0 auto 16px;display:flex;align-items:center;justify-content:center;">
                        <i data-lucide="receipt" style="width:40px;height:40px;color:#2563EB;"></i>
                    </div>
                    <p style="font-size:15px;color:#374151;margin:0 0 8px;font-weight:600;">رسوم تسجيل النشاط الرياضي</p>
                    <p style="font-size:13px;color:#6B7280;margin:0 0 20px;">مبلغ شامل يغطي الاستمارة والكارت — بدون أي رسوم إضافية</p>
                    <div style="font-size:42px;font-weight:800;color:#2563EB;margin-bottom:8px;"><?= (int) $registration['total_fees'] ?> <span style="font-size:18px;">ج.م</span></div>
                    <div style="font-size:12px;color:#6B7280;margin-bottom:24px;"><?= $registration['player_type'] === 'member' ? 'أعضاء النادي' : 'غير أعضاء' ?></div>

                    <?php if (($registration['form_payment_status'] ?? 'unpaid') === 'pending'): ?>
                    <div style="padding:16px;background:#FEF3C7;border-radius:10px;">
                        <i data-lucide="clock" style="width:20px;height:20px;color:#D97706;vertical-align:middle;margin-left:6px;"></i>
                        <span style="color:#92400E;font-weight:600;">تم إرسال طلب الدفع — بانتظار التحصيل من الخزينة</span>
                    </div>
                    <?php else: ?>
                    <button type="button" id="btnPayForm" class="btn btn-primary" style="width:100%;padding:16px;font-size:16px;font-weight:700;border-radius:12px;min-height:56px;">
                        <i data-lucide="banknote" style="width:20px;height:20px;vertical-align:middle;margin-left:6px;"></i> إرسال للخزينة — <?= (int) $registration['total_fees'] ?> ج.م
                    </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Step 2: Photo Capture -->
    <div id="step-photo" class="wizard-step" style="<?= ($step ?? 1) == 2 ? '' : 'display:none;' ?>">
        <div class="card" style="margin-bottom:16px;">
            <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
                <h3 style="margin:0;font-size:16px;font-weight:600;"><i data-lucide="camera" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> التقاط الصورة</h3>
            </div>
            <div style="padding:24px;text-align:center;">
                <div id="photoPreview" style="width:200px;height:200px;border-radius:12px;background:#F3F4F6;margin:0 auto 16px;overflow:hidden;display:flex;align-items:center;justify-content:center;">
                    <?php if ($registration['photo_path']): ?>
                    <img src="/<?= e($registration['photo_path']) ?>" style="width:100%;height:100%;object-fit:cover;">
                    <?php else: ?>
                    <i data-lucide="camera" style="width:48px;height:48px;color:#D1D5DB;"></i>
                    <?php endif; ?>
                </div>
                <video id="webcamVideo" style="display:none;width:200px;height:200px;border-radius:12px;object-fit:cover;margin:0 auto 16px;"></video>
                <canvas id="webcamCanvas" style="display:none;"></canvas>
                <div style="display:flex;gap:12px;justify-content:center;flex-wrap:wrap;">
                    <button type="button" id="btnStartWebcam" class="btn btn-outline" style="padding:14px 20px;font-size:14px;min-height:50px;border-radius:10px;">
                        <i data-lucide="video" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> كاميرا
                    </button>
                    <button type="button" id="btnCaptureWebcam" class="btn btn-primary" style="display:none;padding:14px 20px;font-size:14px;min-height:50px;border-radius:10px;">
                        <i data-lucide="camera" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> التقاط
                    </button>
                    <label class="btn btn-outline" style="cursor:pointer;padding:14px 20px;font-size:14px;min-height:50px;border-radius:10px;">
                        <i data-lucide="upload" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> رفع ملف
                        <input type="file" id="photoFileInput" accept="image/*" style="display:none;">
                    </label>
                </div>
                <div id="photoStatus" style="margin-top:12px;font-size:13px;display:none;"></div>
            </div>
        </div>
        <button type="button" id="btnPhotoNext" class="btn btn-primary" style="width:100%;padding:16px;font-size:16px;font-weight:700;border-radius:12px;min-height:56px;" <?= (int) $registration['photo_captured'] ? '' : 'disabled' ?>>
            <i data-lucide="arrow-left" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> التالي — اختيار الأنشطة
        </button>
    </div>

    <!-- Step 3: Discipline Selection (checkboxes) -->
    <div id="step-activity" class="wizard-step" style="<?= ($step ?? 1) == 3 ? '' : 'display:none;' ?>">
        <div class="card" style="margin-bottom:16px;">
            <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
                <h3 style="margin:0;font-size:16px;font-weight:600;"><i data-lucide="trophy" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> اختيار الأنشطة المطلوبة</h3>
            </div>
            <div style="padding:16px;">
                <p style="font-size:13px;color:#6B7280;margin:0 0 16px;">اختر الأنشطة التي يرغب اللاعب في ممارستها — سيتم التقييم الفني وتعيين المجموعة لاحقاً بواسطة المدرب.</p>
                <div id="disciplinesList" style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                    <?php
                    $selectedIds = [];
                    if (!empty($registration['selected_disciplines'])) {
                        $decoded = json_decode($registration['selected_disciplines'], true);
                        if (is_array($decoded)) {
                            foreach ($decoded as $d) {
                                $selectedIds[] = is_array($d) ? (int) ($d['id'] ?? 0) : (int) $d;
                            }
                        }
                    }
                    foreach ($disciplines ?? [] as $d):
                        $isChecked = in_array((int) $d['id'], $selectedIds);
                    ?>
                    <label class="disc-option" style="display:flex;align-items:center;gap:10px;padding:14px 16px;border:2px solid <?= $isChecked ? '#2563EB' : '#E5E7EB' ?>;border-radius:10px;cursor:pointer;transition:all 0.2s;background:<?= $isChecked ? '#F0F7FF' : '' ?>;">
                        <input type="checkbox" name="discipline_ids[]" value="<?= (int) $d['id'] ?>" <?= $isChecked ? 'checked' : '' ?> style="accent-color:#2563EB;width:20px;height:20px;flex-shrink:0;">
                        <i data-lucide="<?= e($d['icon'] ?? 'activity') ?>" style="width:20px;height:20px;color:#0D7377;flex-shrink:0;"></i>
                        <span style="font-weight:600;font-size:14px;"><?= e($d['name_ar']) ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <button type="button" id="btnSaveDisciplines" class="btn btn-primary" style="width:100%;padding:16px;font-size:16px;font-weight:700;border-radius:12px;min-height:56px;">
            <i data-lucide="check" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> حفظ الأنشطة المختارة
        </button>
    </div>

    <!-- Step 4: Complete (print + card) -->
    <div id="step-complete" class="wizard-step" style="<?= ($step ?? 1) == 4 ? '' : 'display:none;' ?>">
        <div class="card" style="margin-bottom:16px;">
            <div style="padding:40px 24px;text-align:center;">
                <div style="width:80px;height:80px;border-radius:50%;background:#ECFDF5;margin:0 auto 16px;display:flex;align-items:center;justify-content:center;">
                    <i data-lucide="check-circle" style="width:40px;height:40px;color:#059669;"></i>
                </div>
                <h3 style="margin:0 0 8px;font-size:18px;font-weight:700;color:#059669;">تم التسجيل بنجاح!</h3>
                <p style="color:#6B7280;font-size:14px;margin:0;">تم دفع رسوم التسجيل — اللاعب في انتظار التقييم الفني من المدرب</p>
            </div>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
            <a href="/sa/registration/<?= (int) $registration['id'] ?>/print-form" target="_blank" class="btn btn-outline" style="padding:14px;font-size:14px;border-radius:10px;min-height:50px;text-align:center;">
                <i data-lucide="printer" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> طباعة الاستمارة
            </a>
            <button type="button" id="btnGenerateCard" class="btn btn-primary" style="padding:14px;font-size:14px;border-radius:10px;min-height:50px;" <?= (int) ($registration['card_generated'] ?? 0) ? 'disabled' : '' ?>>
                <i data-lucide="credit-card" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> إنشاء الكارت
            </button>
        </div>
        <?php if ((int) ($registration['card_generated'] ?? 0)): ?>
        <div style="margin-top:10px;display:grid;grid-template-columns:1fr 1fr;gap:10px;">
            <a href="/sa/registration/<?= (int) $registration['id'] ?>/print-card" target="_blank" class="btn btn-outline" style="padding:14px;font-size:14px;border-radius:10px;min-height:50px;text-align:center;">
                <i data-lucide="printer" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> طباعة الكارت
            </a>
            <a href="/sa/registration" class="btn btn-outline" style="padding:14px;font-size:14px;border-radius:10px;min-height:50px;text-align:center;">
                <i data-lucide="plus" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> تسجيل جديد
            </a>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php else: ?>
<!-- Start New Registration -->
<div class="card" style="margin-bottom:16px;">
    <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;font-size:16px;font-weight:600;"><i data-lucide="user-plus" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> تسجيل جديد</h3>
    </div>
    <div style="padding:20px;">
        <form id="startForm">
            <div style="display:grid;grid-template-columns:1fr;gap:14px;">
                <div>
                    <label class="form-label">رقم العضوية <span style="font-weight:400;color:#6B7280;font-size:12px;">(للأعضاء — يملأ كل البيانات تلقائياً)</span></label>
                    <input type="text" name="membership_number" class="form-input" style="padding:14px;font-size:18px;border-radius:10px;direction:ltr;text-align:right;letter-spacing:1px;" inputmode="numeric" placeholder="أدخل رقم العضوية" id="regMembershipNo">
                    <div id="regMemberLookup" style="display:none;margin-top:8px;padding:10px 12px;border-radius:8px;font-size:13px;"></div>
                </div>
                <div style="text-align:center;color:#9CA3AF;font-size:12px;position:relative;">
                    <span style="background:white;padding:0 12px;position:relative;z-index:1;">أو أدخل الرقم القومي</span>
                    <div style="position:absolute;top:50%;left:0;right:0;height:1px;background:#E5E7EB;z-index:0;"></div>
                </div>
                <div>
                    <label class="form-label">الرقم القومي <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="national_id" class="form-input" style="padding:14px;font-size:18px;border-radius:10px;direction:ltr;text-align:right;letter-spacing:1px;" maxlength="14" inputmode="numeric" pattern="[0-9]*" placeholder="أدخل 14 رقم" id="regNid">
                    <div id="regMemberBadge" style="display:none;margin-top:8px;padding:10px 12px;border-radius:8px;font-size:13px;"></div>
                </div>
                <div>
                    <label class="form-label">الاسم بالعربي <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="full_name_ar" class="form-input" style="padding:14px;font-size:15px;border-radius:10px;" id="regNameAr">
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                    <div>
                        <label class="form-label">الهاتف</label>
                        <input type="text" name="phone" class="form-input" style="padding:14px;font-size:15px;border-radius:10px;" dir="ltr" inputmode="tel" id="regPhone">
                    </div>
                    <div>
                        <label class="form-label">هاتف ولي الأمر</label>
                        <input type="text" name="guardian_phone" class="form-input" style="padding:14px;font-size:15px;border-radius:10px;" dir="ltr" inputmode="tel">
                    </div>
                </div>
                <div>
                    <label class="form-label">اسم ولي الأمر</label>
                    <input type="text" name="guardian_name" class="form-input" style="padding:14px;font-size:15px;border-radius:10px;">
                </div>
            </div>
            <button type="submit" class="btn btn-primary" id="btnStartReg" style="width:100%;margin-top:20px;padding:16px;font-size:16px;font-weight:700;border-radius:12px;min-height:56px;">
                <i data-lucide="play" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> بدء التسجيل
            </button>
            <div id="startError" style="display:none;margin-top:12px;padding:12px;background:#FEF2F2;border-radius:8px;color:#DC2626;font-size:13px;"></div>
        </form>
    </div>
</div>

<!-- Recent Registrations -->
<?php if (!empty($recentRegistrations)): ?>
<div class="card">
    <div style="padding:14px 16px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;font-size:15px;font-weight:600;">آخر التسجيلات</h3>
    </div>
    <div style="padding:0;">
        <?php foreach ($recentRegistrations as $reg): ?>
        <a href="/sa/registration/<?= (int) $reg['id'] ?>" style="display:flex;align-items:center;padding:14px 16px;border-bottom:1px solid #F3F4F6;text-decoration:none;color:inherit;">
            <div style="width:40px;height:40px;border-radius:8px;overflow:hidden;background:#F3F4F6;flex-shrink:0;display:flex;align-items:center;justify-content:center;margin-left:12px;">
                <?php if (!empty($reg['photo_path'])): ?>
                <img src="/<?= e($reg['photo_path']) ?>" style="width:100%;height:100%;object-fit:cover;">
                <?php else: ?>
                <i data-lucide="user" style="width:18px;height:18px;color:#9CA3AF;"></i>
                <?php endif; ?>
            </div>
            <div style="flex:1;min-width:0;">
                <div style="font-weight:600;font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?= e($reg['full_name_ar']) ?></div>
                <div style="font-size:12px;color:#6B7280;margin-top:2px;"><?= e($reg['group_name'] ?? '—') ?></div>
            </div>
            <div style="text-align:left;flex-shrink:0;">
                <?php
                $statusMap = ['in_progress' => ['جاري', '#F59E0B'], 'pending_payment' => ['بانتظار', '#D97706'], 'completed' => ['مكتمل', '#059669'], 'assessed' => ['تم التقييم', '#2563EB'], 'cancelled' => ['ملغى', '#DC2626']];
                $s = $statusMap[$reg['status']] ?? [$reg['status'], '#6B7280'];
                ?>
                <span style="padding:3px 8px;border-radius:6px;font-size:11px;font-weight:600;background:<?= $s[1] ?>15;color:<?= $s[1] ?>;"><?= $s[0] ?></span>
                <div style="font-size:10px;color:#9CA3AF;margin-top:3px;direction:ltr;"><?= substr($reg['created_at'], 5, 11) ?></div>
            </div>
        </a>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>
<?php endif; ?>

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

    var regId = document.getElementById('wizardApp') ? document.getElementById('wizardApp').dataset.registrationId : null;
    var csrfToken = document.querySelector('meta[name="csrf-token"]') ? document.querySelector('meta[name="csrf-token"]').content : '';
    var csrfInput = document.querySelector('input[name="_csrf_token"]');
    if (csrfInput) csrfToken = csrfInput.value;

    // Start form
    var startForm = document.getElementById('startForm');
    if (startForm) {
        var regNid = document.getElementById('regNid');
        var regMembershipNo = document.getElementById('regMembershipNo');
        var memberBadge = document.getElementById('regMemberBadge');
        var memberLookupBox = document.getElementById('regMemberLookup');
        var regNameAr = document.getElementById('regNameAr');
        var regPhone = document.getElementById('regPhone');

        function fillMemberData(data) {
            if (data.name) regNameAr.value = data.name;
            if (data.phone && regPhone && !regPhone.value.trim()) regPhone.value = data.phone;
            if (data.national_id && !regNid.value) regNid.value = data.national_id;
            if (data.membership_number && !regMembershipNo.value) regMembershipNo.value = data.membership_number;
        }

        var regMemberTimer = null;
        if (regMembershipNo) {
            regMembershipNo.addEventListener('input', function() {
                var val = this.value.replace(/\D/g, '');
                this.value = val;
                if (val.length < 1) { memberLookupBox.style.display = 'none'; return; }
                clearTimeout(regMemberTimer);
                regMemberTimer = setTimeout(function() {
                    memberLookupBox.style.display = '';
                    memberLookupBox.style.background = '#F3F4F6';
                    memberLookupBox.style.color = '#6B7280';
                    memberLookupBox.textContent = 'جاري البحث...';
                    fetch('/api/sa/member-lookup', {
                        method: 'POST',
                        headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest','X-CSRF-TOKEN': csrfToken},
                        body: JSON.stringify({membership_number: val, _csrf_token: csrfToken})
                    }).then(function(r){return r.json();}).then(function(data) {
                        if (data.success && data.member_id) {
                            memberLookupBox.style.background = '#ECFDF5';
                            memberLookupBox.style.color = '#059669';
                            memberLookupBox.innerHTML = '<strong>عضو فعال</strong> — ' + (data.name || '');
                            fillMemberData(data);
                        } else {
                            memberLookupBox.style.background = '#FEF2F2';
                            memberLookupBox.style.color = '#DC2626';
                            memberLookupBox.textContent = data.reason || 'رقم العضوية غير موجود';
                        }
                    });
                }, 400);
            });
        }

        if (regNid) {
            regNid.addEventListener('input', function() {
                this.value = this.value.replace(/\D/g, '');
                if (this.value.length === 14) {
                    fetch('/api/sa/member-lookup', {
                        method: 'POST',
                        headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest','X-CSRF-TOKEN': csrfToken},
                        body: JSON.stringify({national_id: this.value, _csrf_token: csrfToken})
                    }).then(function(r){return r.json();}).then(function(data) {
                        if (data.success) {
                            if (data.is_member) {
                                memberBadge.style.background = '#ECFDF5';
                                memberBadge.style.color = '#059669';
                                memberBadge.innerHTML = '<strong>عضو فعال</strong>' + (data.membership_number ? ' — رقم ' + data.membership_number : '');
                            } else {
                                memberBadge.style.background = '#F3F4F6';
                                memberBadge.style.color = '#374151';
                                memberBadge.innerHTML = 'غير عضو';
                            }
                            memberBadge.style.display = '';
                            fillMemberData(data);
                        }
                    });
                } else {
                    memberBadge.style.display = 'none';
                }
            });
        }

        startForm.addEventListener('submit', function(e) {
            e.preventDefault();
            var formData = new FormData(startForm);
            var body = {};
            formData.forEach(function(v, k) { body[k] = v; });
            body._csrf_token = csrfToken;

            document.getElementById('btnStartReg').disabled = true;
            fetch('/sa/registration/lookup', {
                method: 'POST',
                headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest','X-CSRF-TOKEN': csrfToken},
                body: JSON.stringify(body)
            }).then(function(r){return r.json();}).then(function(data) {
                if (data.success && data.redirect) {
                    window.location.href = data.redirect;
                } else {
                    document.getElementById('startError').style.display = 'block';
                    document.getElementById('startError').textContent = data.error || 'حدث خطأ';
                    document.getElementById('btnStartReg').disabled = false;
                }
            }).catch(function() {
                document.getElementById('btnStartReg').disabled = false;
            });
        });
    }

    // Wizard logic
    if (!regId) return;

    function showStep(name) {
        document.querySelectorAll('.wizard-step').forEach(function(el) { el.style.display = 'none'; });
        var target = document.getElementById('step-' + name);
        if (target) target.style.display = '';
    }
    window.showStep = showStep;

    // Step 1: Pay 100 EGP
    var btnPayForm = document.getElementById('btnPayForm');
    if (btnPayForm) {
        btnPayForm.addEventListener('click', function() {
            this.disabled = true;
            this.textContent = 'جاري الإرسال...';
            fetch('/sa/registration/' + regId + '/pay-form', {
                method: 'POST',
                headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest','X-CSRF-TOKEN': csrfToken},
                body: JSON.stringify({_csrf_token: csrfToken})
            }).then(function(r){return r.json();}).then(function(data) {
                if (data.success) {
                    window.location.reload();
                } else {
                    alert(data.error || 'حدث خطأ');
                    btnPayForm.disabled = false;
                    btnPayForm.textContent = 'إرسال للخزينة — <?= (int) $registration['total_fees'] ?> ج.م';
                }
            });
        });
    }

    // Step 2: Photo
    var video = document.getElementById('webcamVideo');
    var canvas = document.getElementById('webcamCanvas');
    var btnStart = document.getElementById('btnStartWebcam');
    var btnCapture = document.getElementById('btnCaptureWebcam');
    var photoPreview = document.getElementById('photoPreview');
    var photoStatus = document.getElementById('photoStatus');
    var btnPhotoNext = document.getElementById('btnPhotoNext');
    var stream = null;

    if (btnStart) {
        btnStart.addEventListener('click', function() {
            navigator.mediaDevices.getUserMedia({video: {facingMode: 'user', width: 400, height: 400}}).then(function(s) {
                stream = s;
                video.srcObject = s;
                video.play();
                video.style.display = 'block';
                photoPreview.style.display = 'none';
                btnCapture.style.display = '';
                btnStart.style.display = 'none';
            }).catch(function() {
                alert('لا يمكن الوصول للكاميرا');
            });
        });

        btnCapture.addEventListener('click', function() {
            canvas.width = 400; canvas.height = 400;
            canvas.getContext('2d').drawImage(video, 0, 0, 400, 400);
            var dataUrl = canvas.toDataURL('image/jpeg', 0.85);
            if (stream) { stream.getTracks().forEach(function(t){t.stop();}); stream = null; }
            video.style.display = 'none';
            btnCapture.style.display = 'none';
            btnStart.style.display = '';
            photoPreview.innerHTML = '<img src="' + dataUrl + '" style="width:100%;height:100%;object-fit:cover;">';
            photoPreview.style.display = '';
            uploadPhoto(dataUrl);
        });
    }

    var fileInput = document.getElementById('photoFileInput');
    if (fileInput) {
        fileInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    photoPreview.innerHTML = '<img src="' + e.target.result + '" style="width:100%;height:100%;object-fit:cover;">';
                    uploadPhoto(e.target.result);
                };
                reader.readAsDataURL(this.files[0]);
            }
        });
    }

    function uploadPhoto(base64) {
        photoStatus.style.display = 'block';
        photoStatus.style.color = '#6B7280';
        photoStatus.textContent = 'جاري رفع الصورة...';
        fetch('/sa/registration/' + regId + '/photo', {
            method: 'POST',
            headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest','X-CSRF-TOKEN': csrfToken},
            body: JSON.stringify({photo_base64: base64, _csrf_token: csrfToken})
        }).then(function(r){return r.json();}).then(function(data) {
            if (data.success) {
                photoStatus.style.color = '#059669';
                photoStatus.textContent = '✓ تم رفع الصورة بنجاح';
                btnPhotoNext.disabled = false;
            } else {
                photoStatus.style.color = '#DC2626';
                photoStatus.textContent = data.error || 'فشل الرفع';
            }
        });
    }

    if (btnPhotoNext) {
        btnPhotoNext.addEventListener('click', function() { showStep('activity'); });
    }

    // Step 3: Discipline selection (checkboxes)
    document.querySelectorAll('.disc-option input[type="checkbox"]').forEach(function(cb) {
        cb.addEventListener('change', function() {
            var label = this.closest('.disc-option');
            if (this.checked) {
                label.style.borderColor = '#2563EB';
                label.style.background = '#F0F7FF';
            } else {
                label.style.borderColor = '#E5E7EB';
                label.style.background = '';
            }
        });
    });

    var btnSaveDisciplines = document.getElementById('btnSaveDisciplines');
    if (btnSaveDisciplines) {
        btnSaveDisciplines.addEventListener('click', function() {
            var checked = document.querySelectorAll('.disc-option input[type="checkbox"]:checked');
            var ids = [];
            checked.forEach(function(cb) { ids.push(parseInt(cb.value)); });

            if (ids.length === 0) {
                alert('يجب اختيار نشاط واحد على الأقل');
                return;
            }

            this.disabled = true;
            this.textContent = 'جاري الحفظ...';

            fetch('/sa/registration/' + regId + '/activity', {
                method: 'POST',
                headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest','X-CSRF-TOKEN': csrfToken},
                body: JSON.stringify({discipline_ids: ids, _csrf_token: csrfToken})
            }).then(function(r){return r.json();}).then(function(data) {
                if (data.success) {
                    showStep('complete');
                } else {
                    alert(data.error || 'حدث خطأ');
                    btnSaveDisciplines.disabled = false;
                    btnSaveDisciplines.innerHTML = '<i data-lucide="check" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> حفظ الأنشطة المختارة';
                    if (typeof lucide !== 'undefined') lucide.createIcons();
                }
            });
        });
    }

    // Step 4: Generate card
    var btnGenCard = document.getElementById('btnGenerateCard');
    if (btnGenCard) {
        btnGenCard.addEventListener('click', function() {
            this.disabled = true;
            fetch('/sa/registration/' + regId + '/generate-card', {
                method: 'POST',
                headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest','X-CSRF-TOKEN': csrfToken},
                body: JSON.stringify({_csrf_token: csrfToken})
            }).then(function(r){return r.json();}).then(function(data) {
                if (data.success) {
                    window.location.reload();
                } else {
                    alert(data.error || 'حدث خطأ');
                    btnGenCard.disabled = false;
                }
            });
        });
    }
});
</script>
<?php $__template->endSection(); ?>
