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

    <!-- Progress Bar -->
    <div class="card" style="margin-bottom:20px;padding:20px;">
        <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 ?? 2);
                $isComplete = $stepNum < ($step ?? 2);
                $bgColor = $isComplete ? '#059669' : ($isActive ? '#2563EB' : '#E5E7EB');
                $textColor = ($isComplete || $isActive) ? '#fff' : '#9CA3AF';
            ?>
            <div style="text-align:center;position:relative;z-index:1;">
                <div style="width:36px;height:36px;border-radius:50%;background:<?= $bgColor ?>;color:<?= $textColor ?>;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:14px;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:20px;">
        <div style="padding:15px 20px;display:flex;align-items:center;gap:15px;border-bottom:1px solid #E5E7EB;">
            <div style="width:60px;height:60px;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:28px;height:28px;"></i></div>
                <?php endif; ?>
            </div>
            <div style="flex:1;">
                <div style="font-size:16px;font-weight:700;color:#1A1A2E;"><?= e($registration['full_name_ar']) ?></div>
                <div style="font-size:12px;color:#6B7280;margin-top:2px;">
                    <?= $registration['player_type'] === 'member' ? 'عضو' : 'غير عضو' ?>
                    <?php if ($registration['player_nid']): ?> — <?= e($registration['player_nid']) ?><?php endif; ?>
                </div>
            </div>
            <div style="text-align:left;">
                <span style="font-size:11px;color:#6B7280;">رقم التسجيل</span>
                <div style="font-size:13px;font-weight:600;direction:ltr;"><?= e($registration['registration_number']) ?></div>
            </div>
        </div>
    </div>

    <!-- Step 2: Photo Capture -->
    <div id="step-photo" class="wizard-step" style="<?= ($step ?? 2) == 2 ? '' : 'display:none;' ?>">
        <div class="card" style="margin-bottom:20px;">
            <div style="padding:15px 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:20px;text-align:center;">
                <div id="photoPreview" style="width:200px;height:200px;border-radius:12px;background:#F3F4F6;margin:0 auto 15px;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 15px;"></video>
                <canvas id="webcamCanvas" style="display:none;"></canvas>
                <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap;">
                    <button type="button" id="btnStartWebcam" class="btn btn-outline"><i data-lucide="video" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> كاميرا</button>
                    <button type="button" id="btnCaptureWebcam" class="btn btn-primary" style="display:none;"><i data-lucide="camera" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> التقاط</button>
                    <label class="btn btn-outline" style="cursor:pointer;"><i data-lucide="upload" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> رفع ملف<input type="file" id="photoFileInput" accept="image/*" style="display:none;"></label>
                </div>
                <div id="photoStatus" style="margin-top:10px;font-size:12px;display:none;"></div>
            </div>
        </div>
        <div style="display:flex;gap:10px;">
            <button type="button" id="btnPhotoNext" class="btn btn-primary" <?= (int) $registration['photo_captured'] ? '' : 'disabled' ?>><i data-lucide="arrow-left" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> التالي — اختيار النشاط</button>
        </div>
    </div>

    <!-- Step 3: Activity/Group Selection -->
    <div id="step-activity" class="wizard-step" style="<?= ($step ?? 2) == 3 ? '' : 'display:none;' ?>">
        <div class="card" style="margin-bottom:20px;">
            <div style="padding:15px 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:20px;">
                <div style="margin-bottom:15px;">
                    <input type="text" id="groupSearch" class="form-input" placeholder="ابحث عن نشاط أو مجموعة..." style="max-width:400px;">
                </div>
                <div id="groupsList" style="display:grid;grid-template-columns:repeat(auto-fill, minmax(280px, 1fr));gap:12px;">
                    <?php foreach ($groups as $g): ?>
                    <div class="group-option" data-group-id="<?= (int) $g['id'] ?>" data-name="<?= e($g['name_ar'] . ' ' . ($g['discipline_name'] ?? '')) ?>"
                         style="border:2px solid <?= (isset($selectedGroup) && (int)$selectedGroup['id'] === (int)$g['id']) ? '#2563EB' : '#E5E7EB' ?>;border-radius:10px;padding:14px;cursor:pointer;transition:border-color 0.2s;">
                        <div style="font-weight:600;font-size:14px;color:#1A1A2E;"><?= e($g['name_ar']) ?></div>
                        <div style="font-size:12px;color:#6B7280;margin-top:3px;"><?= e($g['discipline_name'] ?? '') ?> — <?= e($g['program_name'] ?? '') ?></div>
                        <div style="display:flex;justify-content:space-between;margin-top:8px;font-size:12px;">
                            <span style="color:#6B7280;">السعة: <?= (int) $g['current_count'] ?>/<?= (int) $g['max_capacity'] ?></span>
                            <span style="color:#059669;font-weight:600;">
                                <?= $registration['player_type'] === 'member' ? money((float) $g['monthly_fee_member']) : money((float) $g['monthly_fee_nonmember']) ?> / شهر
                            </span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Subscription Options -->
        <div class="card" style="margin-bottom:20px;" id="subscriptionOptions">
            <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
                <h3 style="margin:0;font-size:16px;font-weight:600;"><i data-lucide="settings-2" style="width:16px;height:16px;vertical-align:middle;margin-left:6px;"></i> خيارات الاشتراك</h3>
            </div>
            <div style="padding:20px;">
                <div style="display:flex;gap:15px;flex-wrap:wrap;margin-bottom:15px;">
                    <label style="display:flex;align-items:center;gap:8px;padding:12px 18px;border:2px solid #2563EB;border-radius:8px;cursor:pointer;background:#EFF6FF;">
                        <input type="radio" name="subscription_months" value="1" checked style="accent-color:#2563EB;">
                        <span style="font-weight:600;">شهر واحد</span>
                    </label>
                    <label style="display:flex;align-items:center;gap:8px;padding:12px 18px;border:2px solid #E5E7EB;border-radius:8px;cursor:pointer;position:relative;">
                        <input type="radio" name="subscription_months" value="3" style="accent-color:#059669;">
                        <span style="font-weight:600;">3 أشهر</span>
                        <span style="position:absolute;top:-8px;left:10px;background:#059669;color:#fff;font-size:10px;padding:2px 6px;border-radius:4px;font-weight:700;">خصم 15%</span>
                    </label>
                </div>
                <div style="margin-bottom:0;">
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                        <input type="checkbox" id="hasSibling" style="accent-color:#7C3AED;width:18px;height:18px;">
                        <span style="font-size:14px;">يوجد أخ/أخت مسجل بنفس النشاط <span style="font-size:11px;color:#7C3AED;font-weight:600;">(خصم أشقاء)</span></span>
                    </label>
                </div>
            </div>
        </div>

        <!-- Fee Breakdown -->
        <div class="card" style="margin-bottom:20px;" id="feeBreakdown" style="<?= $selectedGroup ? '' : 'display:none;' ?>">
            <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
                <h3 style="margin:0;font-size:16px;font-weight:600;">تفاصيل الرسوم</h3>
            </div>
            <div style="padding:20px;">
                <table style="width:100%;font-size:14px;">
                    <tr><td style="padding:6px 0;">رسوم التسجيل</td><td style="text-align:left;font-weight:600;" id="feeReg"><?= money((float) $registration['registration_fee']) ?></td></tr>
                    <tr><td style="padding:6px 0;">رسوم الكارت</td><td style="text-align:left;font-weight:600;" id="feeCard"><?= money((float) $registration['card_fee']) ?></td></tr>
                    <tr><td style="padding:6px 0;">رسوم الاستمارة</td><td style="text-align:left;font-weight:600;" id="feeForm"><?= money((float) $registration['form_fee']) ?></td></tr>
                    <tr><td style="padding:6px 0;">اشتراك النشاط</td><td style="text-align:left;font-weight:600;" id="feeSub"><?= money((float) ($registration['subscription_amount'] ?? 0)) ?></td></tr>
                    <tr id="feeDiscountRow" style="display:none;color:#059669;"><td style="padding:6px 0;">خصم</td><td style="text-align:left;font-weight:600;" id="feeDiscount"></td></tr>
                    <tr style="border-top:2px solid #E5E7EB;"><td style="padding:10px 0;font-weight:700;font-size:15px;">الإجمالي</td><td style="text-align:left;font-weight:800;font-size:15px;color:#2563EB;" id="feeTotal"><?= money((float) $registration['total_fees']) ?></td></tr>
                </table>
                <div id="discountNotes" style="display:none;margin-top:10px;padding:8px 12px;background:#ECFDF5;border-radius:6px;font-size:12px;color:#059669;"></div>
            </div>
        </div>

        <div style="display:flex;gap:10px;">
            <button type="button" id="btnActivityNext" class="btn btn-primary" <?= $selectedGroup ? '' : 'disabled' ?>><i data-lucide="banknote" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> إرسال للخزينة</button>
            <button type="button" class="btn btn-outline" onclick="showStep('photo')"><i data-lucide="arrow-right" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> رجوع</button>
        </div>
    </div>

    <!-- Step 4: Pending Payment -->
    <div id="step-payment" class="wizard-step" style="<?= ($step ?? 2) == 4 ? '' : 'display:none;' ?>">
        <div class="card" style="margin-bottom:20px;">
            <div style="padding:40px;text-align:center;">
                <div style="width:80px;height:80px;border-radius:50%;background:#FEF3C7;margin:0 auto 15px;display:flex;align-items:center;justify-content:center;">
                    <i data-lucide="clock" style="width:40px;height:40px;color:#D97706;"></i>
                </div>
                <h3 style="margin:0 0 8px;font-size:18px;font-weight:700;color:#1A1A2E;">بانتظار الدفع في الخزينة</h3>
                <p style="color:#6B7280;font-size:14px;margin:0;">تم إرسال طلب الدفع — ينتظر التحصيل من الخزينة</p>
                <div style="margin-top:15px;font-size:20px;font-weight:800;color:#2563EB;"><?= money((float) $registration['total_fees']) ?></div>
            </div>
        </div>
        <div style="display:flex;gap:10px;">
            <a href="/sa/registration/<?= (int) $registration['id'] ?>/print-form" target="_blank" class="btn btn-outline"><i data-lucide="printer" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> طباعة الاستمارة</a>
            <form method="POST" action="/sa/registration/<?= (int) $registration['id'] ?>/cancel" style="display:inline;">
                <?= csrf_field() ?>
                <button type="submit" class="btn btn-outline" style="color:#DC2626;border-color:#DC2626;" onclick="return confirm('هل تريد إلغاء التسجيل؟')">إلغاء التسجيل</button>
            </form>
        </div>
    </div>

    <!-- Step 5: Complete -->
    <div id="step-complete" class="wizard-step" style="<?= ($step ?? 2) == 5 ? '' : 'display:none;' ?>">
        <div class="card" style="margin-bottom:20px;">
            <div style="padding:40px;text-align:center;">
                <div style="width:80px;height:80px;border-radius:50%;background:#ECFDF5;margin:0 auto 15px;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:flex;gap:10px;flex-wrap:wrap;">
            <a href="/sa/registration/<?= (int) $registration['id'] ?>/print-form" target="_blank" class="btn btn-outline"><i data-lucide="file-text" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> طباعة الاستمارة</a>
            <button type="button" id="btnGenerateCard" class="btn btn-primary" <?= (int) $registration['card_generated'] ? 'disabled' : '' ?>><i data-lucide="credit-card" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> إنشاء الكارت</button>
            <?php if ((int) $registration['card_generated']): ?>
            <a href="/sa/registration/<?= (int) $registration['id'] ?>/print-card" target="_blank" class="btn btn-outline"><i data-lucide="printer" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> طباعة الكارت</a>
            <?php endif; ?>
            <a href="/sa/registration" class="btn btn-outline"><i data-lucide="plus" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> تسجيل جديد</a>
        </div>
    </div>
</div>

<?php else: ?>
<!-- Start New Registration -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 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:repeat(auto-fit, minmax(220px, 1fr));gap:15px;">
                <div>
                    <label class="form-label">نوع اللاعب <span style="color:#DC2626;">*</span></label>
                    <select name="player_type" id="regPlayerType" class="form-select" required>
                        <option value="non_member">غير عضو</option>
                        <option value="member">عضو</option>
                    </select>
                </div>
                <div id="memberIdWrap" style="display:none;">
                    <label class="form-label">رقم العضوية <span style="color:#DC2626;">*</span></label>
                    <input type="number" name="member_id" class="form-input" placeholder="رقم العضوية">
                </div>
                <div>
                    <label class="form-label">الرقم القومي <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="national_id" class="form-input" maxlength="14" dir="ltr" placeholder="14 رقم" id="regNid">
                    <small id="regNidInfo" style="display:none;margin-top:4px;font-size:11px;color:#059669;"></small>
                </div>
                <div>
                    <label class="form-label">الاسم بالعربي <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="full_name_ar" class="form-input" id="regNameAr">
                </div>
                <div>
                    <label class="form-label">الهاتف</label>
                    <input type="text" name="phone" class="form-input" dir="ltr">
                </div>
                <div>
                    <label class="form-label">اسم ولي الأمر</label>
                    <input type="text" name="guardian_name" class="form-input">
                </div>
                <div>
                    <label class="form-label">هاتف ولي الأمر</label>
                    <input type="text" name="guardian_phone" class="form-input" dir="ltr">
                </div>
            </div>
            <div style="margin-top:20px;">
                <button type="submit" class="btn btn-primary" id="btnStartReg"><i data-lucide="play" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> بدء التسجيل</button>
            </div>
            <div id="startError" style="display:none;margin-top:10px;padding:10px;background:#FEF2F2;border-radius:6px;color:#DC2626;font-size:13px;"></div>
        </form>
    </div>
</div>

<!-- Recent Registrations -->
<?php if (!empty($recentRegistrations)): ?>
<div class="card">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;font-size:16px;font-weight:600;">آخر التسجيلات</h3>
    </div>
    <table style="width:100%;border-collapse:collapse;font-size:13px;">
        <thead>
            <tr style="background:#F9FAFB;">
                <th style="padding:10px 15px;text-align:right;font-weight:600;color:#6B7280;">الرقم</th>
                <th style="padding:10px 15px;text-align:right;font-weight:600;color:#6B7280;">اللاعب</th>
                <th style="padding:10px 15px;text-align:right;font-weight:600;color:#6B7280;">النشاط</th>
                <th style="padding:10px 15px;text-align:right;font-weight:600;color:#6B7280;">الحالة</th>
                <th style="padding:10px 15px;text-align:right;font-weight:600;color:#6B7280;">التاريخ</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($recentRegistrations as $reg): ?>
            <tr style="border-top:1px solid #F3F4F6;">
                <td style="padding:10px 15px;"><a href="/sa/registration/<?= (int) $reg['id'] ?>" style="color:#2563EB;font-weight:600;"><?= e($reg['registration_number']) ?></a></td>
                <td style="padding:10px 15px;"><?= e($reg['full_name_ar']) ?></td>
                <td style="padding:10px 15px;"><?= e($reg['group_name'] ?? '—') ?></td>
                <td style="padding:10px 15px;">
                    <?php
                    $statusMap = ['in_progress' => ['جاري', '#F59E0B'], 'pending_payment' => ['بانتظار الدفع', '#D97706'], 'completed' => ['مكتمل', '#059669'], 'cancelled' => ['ملغى', '#DC2626']];
                    $s = $statusMap[$reg['status']] ?? [$reg['status'], '#6B7280'];
                    ?>
                    <span style="padding:3px 8px;border-radius:4px;font-size:11px;font-weight:600;background:<?= $s[1] ?>15;color:<?= $s[1] ?>;"><?= $s[0] ?></span>
                </td>
                <td style="padding:10px 15px;direction:ltr;text-align:right;"><?= substr($reg['created_at'], 0, 16) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</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 playerTypeSelect = document.getElementById('regPlayerType');
        var memberIdWrap = document.getElementById('memberIdWrap');
        playerTypeSelect.addEventListener('change', function() {
            memberIdWrap.style.display = this.value === 'member' ? '' : 'none';
        });

        var regNid = document.getElementById('regNid');
        var regNidInfo = document.getElementById('regNidInfo');
        if (regNid) {
            regNid.addEventListener('input', function() {
                this.value = this.value.replace(/\D/g, '');
                if (this.value.length === 14) {
                    fetch('/api/members/parse-nid', {
                        method: 'POST',
                        headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest'},
                        body: JSON.stringify({national_id: this.value})
                    }).then(function(r){return r.json();}).then(function(data) {
                        if (data.parsed && data.parsed.is_valid) {
                            regNidInfo.style.display = 'block';
                            regNidInfo.textContent = '✓ ' + data.parsed.governorate_name_ar + ' — ' + data.parsed.age_years + ' سنة — ' + (data.parsed.gender === 'male' ? 'ذكر' : 'أنثى');
                        } else {
                            regNidInfo.style.display = 'block';
                            regNidInfo.style.color = '#DC2626';
                            regNidInfo.textContent = 'رقم قومي غير صالح';
                        }
                    });
                } else {
                    regNidInfo.style.display = 'none';
                    regNidInfo.style.color = '#059669';
                }
            });
        }

        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;

    // Photo: webcam
    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);
        });
    }

    // Photo: file upload
    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'); });
    }

    // Activity selection
    var selectedGroupId = null;

    function getSubscriptionMonths() {
        var checked = document.querySelector('input[name="subscription_months"]:checked');
        return checked ? parseInt(checked.value) : 1;
    }

    function submitActivitySelection(gid) {
        var months = getSubscriptionMonths();
        var hasSibling = document.getElementById('hasSibling').checked ? 1 : 0;

        fetch('/sa/registration/' + regId + '/activity', {
            method: 'POST',
            headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest','X-CSRF-TOKEN': csrfToken},
            body: JSON.stringify({group_id: gid, months: months, has_sibling: hasSibling, _csrf_token: csrfToken})
        }).then(function(r){return r.json();}).then(function(data) {
            if (data.success) {
                document.getElementById('feeSub').textContent = data.subscription_amount.toLocaleString() + ' ج.م';
                document.getElementById('feeTotal').textContent = data.total_fees.toLocaleString() + ' ج.م';
                document.getElementById('feeBreakdown').style.display = '';
                document.getElementById('btnActivityNext').disabled = false;

                var discountRow = document.getElementById('feeDiscountRow');
                var discountNotes = document.getElementById('discountNotes');
                if (data.total_discount && data.total_discount > 0) {
                    discountRow.style.display = '';
                    document.getElementById('feeDiscount').textContent = '- ' + data.total_discount.toLocaleString() + ' ج.م';
                    var notes = '';
                    if (data.discounts && data.discounts.length > 0) {
                        data.discounts.forEach(function(d) { notes += '✓ ' + (d.name_ar || d.code) + ' (' + d.amount.toLocaleString() + ' ج.م)<br>'; });
                    }
                    if (notes) { discountNotes.innerHTML = notes; discountNotes.style.display = ''; }
                } else {
                    discountRow.style.display = 'none';
                    discountNotes.style.display = 'none';
                }
            }
        });
    }

    document.querySelectorAll('.group-option').forEach(function(el) {
        el.addEventListener('click', function() {
            document.querySelectorAll('.group-option').forEach(function(g) { g.style.borderColor = '#E5E7EB'; });
            this.style.borderColor = '#2563EB';
            selectedGroupId = this.dataset.groupId;
            submitActivitySelection(selectedGroupId);
        });
    });

    // Re-calculate on months/sibling change
    document.querySelectorAll('input[name="subscription_months"]').forEach(function(radio) {
        radio.addEventListener('change', function() {
            document.querySelectorAll('input[name="subscription_months"]').forEach(function(r) {
                r.closest('label').style.borderColor = '#E5E7EB';
                r.closest('label').style.background = '';
            });
            this.closest('label').style.borderColor = this.value === '3' ? '#059669' : '#2563EB';
            this.closest('label').style.background = this.value === '3' ? '#F0FDF4' : '#EFF6FF';
            if (selectedGroupId) submitActivitySelection(selectedGroupId);
        });
    });
    document.getElementById('hasSibling').addEventListener('change', function() {
        if (selectedGroupId) submitActivitySelection(selectedGroupId);
    });

    // Group search
    var groupSearch = document.getElementById('groupSearch');
    if (groupSearch) {
        groupSearch.addEventListener('input', function() {
            var q = this.value.toLowerCase();
            document.querySelectorAll('.group-option').forEach(function(el) {
                el.style.display = el.dataset.name.toLowerCase().indexOf(q) >= 0 ? '' : 'none';
            });
        });
    }

    // Submit to payment
    var btnActivityNext = document.getElementById('btnActivityNext');
    if (btnActivityNext) {
        btnActivityNext.addEventListener('click', function() {
            this.disabled = true;
            fetch('/sa/registration/' + regId + '/pay', {
                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) {
                    showStep('payment');
                } else {
                    alert(data.error || 'حدث خطأ');
                    btnActivityNext.disabled = false;
                }
            });
        });
    }

    // 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(); ?>
