<?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: Form Fee Payment (استمارة اشتراك) -->
    <div id="step-form" 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="file-text" 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:36px;font-weight:800;color:#2563EB;margin-bottom:8px;"><?= number_format((float) $registration['registration_fee'], 0) ?> <span style="font-size:16px;">ج.م</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> إرسال للخزينة — <?= number_format((float) $registration['registration_fee'], 0) ?> ج.م
                    </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: Activity/Group Selection -->
    <div id="step-activity" class="wizard-step" style="<?= ($step ?? 1) == 3 ? '' : 'display:none;' ?>">
        <?php if (!in_array($registration['medical_status'] ?? 'pending', ['fit', 'conditional'])): ?>
        <div style="background:#FEF3C7;border:1px solid #F59E0B;border-radius:8px;padding:10px 14px;margin-bottom:12px;display:flex;align-items:center;gap:8px;">
            <i data-lucide="alert-triangle" style="width:16px;height:16px;color:#D97706;flex-shrink:0;"></i>
            <span style="font-size:12px;color:#92400E;font-weight:600;">اللاعب بدون شهادة طبية سارية — يمكنه التسجيل لكن سيظهر بعلامة تحذير</span>
        </div>
        <?php endif; ?>
        <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;">
                <!-- Discipline Filter Chips -->
                <div id="disciplineChips" style="display:flex;flex-wrap:wrap;gap:6px;margin-bottom:12px;">
                    <button type="button" class="disc-chip active" data-disc="" style="padding:6px 14px;border-radius:16px;border:1px solid #E5E7EB;background:#2563EB;color:white;font-size:12px;font-weight:600;cursor:pointer;">الكل</button>
                    <?php
                    $seenDisc = [];
                    foreach ($groups as $g) {
                        $dName = $g['discipline_name'] ?? '';
                        $dId = $g['discipline_id'] ?? '';
                        if ($dName && !isset($seenDisc[$dId])) {
                            $seenDisc[$dId] = $dName;
                            echo '<button type="button" class="disc-chip" data-disc="' . e($dId) . '" style="padding:6px 14px;border-radius:16px;border:1px solid #E5E7EB;background:white;color:#374151;font-size:12px;font-weight:600;cursor:pointer;">' . e($dName) . '</button>';
                        }
                    }
                    ?>
                </div>
                <div style="margin-bottom:12px;">
                    <input type="text" id="groupSearch" class="form-input" placeholder="ابحث عن نشاط أو مجموعة..." style="padding:14px;font-size:15px;border-radius:10px;">
                </div>
                <div id="groupsList" style="display:grid;grid-template-columns:1fr;gap:10px;max-height:50vh;overflow-y:auto;-webkit-overflow-scrolling:touch;">
                    <?php foreach ($groups as $g): ?>
                    <div class="group-option" data-group-id="<?= (int) $g['id'] ?>" data-disc-id="<?= (int) ($g['discipline_id'] ?? 0) ?>" 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:12px;padding:16px;cursor:pointer;transition:all 0.2s;-webkit-tap-highlight-color:transparent;touch-action:manipulation;">
                        <div style="display:flex;justify-content:space-between;align-items:flex-start;">
                            <div style="flex:1;">
                                <div style="font-weight:700;font-size:15px;color:#1A1A2E;"><?= e($g['name_ar']) ?></div>
                                <div style="font-size:13px;color:#6B7280;margin-top:4px;"><?= e($g['discipline_name'] ?? '') ?> — <?= e($g['program_name'] ?? '') ?></div>
                            </div>
                            <div style="text-align:left;flex-shrink:0;padding-right:10px;">
                                <div style="font-size:16px;font-weight:800;color:#059669;">
                                    <?= number_format($registration['player_type'] === 'member' ? (float) $g['monthly_fee_member'] : (float) $g['monthly_fee_nonmember'], 0) ?>
                                </div>
                                <div style="font-size:11px;color:#6B7280;">ج.م / شهر</div>
                            </div>
                        </div>
                        <div style="margin-top:8px;display:flex;align-items:center;gap:8px;">
                            <div style="flex:1;height:6px;background:#E5E7EB;border-radius:3px;overflow:hidden;">
                                <div style="height:100%;background:<?= ((int) $g['current_count'] / max(1, (int) $g['max_capacity'])) > 0.8 ? '#F59E0B' : '#059669' ?>;width:<?= min(100, ((int) $g['current_count'] / max(1, (int) $g['max_capacity'])) * 100) ?>%;border-radius:3px;"></div>
                            </div>
                            <span style="font-size:11px;color:#6B7280;white-space:nowrap;"><?= (int) $g['current_count'] ?>/<?= (int) $g['max_capacity'] ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Subscription Options -->
        <div class="card" style="margin-bottom:16px;" id="subscriptionOptions">
            <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:16px;">
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:14px;">
                    <label style="display:flex;align-items:center;justify-content:center;gap:8px;padding:14px;border:2px solid #2563EB;border-radius:10px;cursor:pointer;background:#EFF6FF;min-height:50px;touch-action:manipulation;-webkit-tap-highlight-color:transparent;">
                        <input type="radio" name="subscription_months" value="1" checked style="accent-color:#2563EB;width:18px;height:18px;">
                        <span style="font-weight:700;font-size:15px;">شهر</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;position:relative;min-height:50px;touch-action:manipulation;-webkit-tap-highlight-color:transparent;">
                        <input type="radio" name="subscription_months" value="3" style="accent-color:#059669;width:18px;height:18px;">
                        <span style="font-weight:700;font-size:15px;">3 أشهر</span>
                        <span style="position:absolute;top:-8px;left:50%;transform:translateX(-50%);background:#059669;color:#fff;font-size:10px;padding:2px 8px;border-radius:4px;font-weight:700;white-space:nowrap;">خصم 15%</span>
                    </label>
                </div>
                <label style="display:flex;align-items:center;gap:10px;padding:14px;border:1px solid #E5E7EB;border-radius:10px;cursor:pointer;touch-action:manipulation;-webkit-tap-highlight-color:transparent;">
                    <input type="checkbox" id="hasSibling" style="accent-color:#7C3AED;width:20px;height:20px;">
                    <span style="font-size:14px;font-weight:500;">يوجد أخ/أخت مسجل بنفس النشاط</span>
                    <span style="font-size:11px;color:#7C3AED;font-weight:700;margin-right:auto;">خصم أشقاء</span>
                </label>
            </div>
        </div>

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

        <div style="display:grid;grid-template-columns:1fr auto;gap:10px;">
            <button type="button" id="btnActivityNext" class="btn btn-primary" style="padding:16px;font-size:16px;font-weight:700;border-radius:12px;min-height:56px;" <?= $selectedGroup ? '' : 'disabled' ?>>
                <i data-lucide="banknote" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> إرسال للخزينة
            </button>
            <button type="button" class="btn btn-outline" style="padding:16px;border-radius:12px;min-height:56px;" onclick="showStep('photo')">
                <i data-lucide="arrow-right" style="width:18px;height:18px;"></i>
            </button>
        </div>
    </div>

    <!-- Step 4: Pending Payment -->
    <div id="step-payment" 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:#FEF3C7;margin:0 auto 16px;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:16px;font-size:24px;font-weight:800;color:#2563EB;"><?= number_format((float) $registration['subscription_amount'] + (float) $registration['card_fee'] + (float) $registration['form_fee'], 0) ?> ج.م</div>
            </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>
            <form method="POST" action="/sa/registration/<?= (int) $registration['id'] ?>/cancel" style="display:contents;">
                <?= csrf_field() ?>
                <button type="submit" class="btn btn-outline" style="padding:14px;font-size:14px;border-radius:10px;min-height:50px;color:#DC2626;border-color:#DC2626;" onclick="return confirm('هل تريد إلغاء التسجيل؟')">
                    <i data-lucide="x" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> إلغاء
                </button>
            </form>
        </div>
    </div>

    <!-- Step 5: Complete -->
    <div id="step-complete" class="wizard-step" style="<?= ($step ?? 1) == 5 ? '' : '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="file-text" 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'] ? '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']): ?>
        <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;">
                <!-- Member Quick Lookup -->
                <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;touch-action:manipulation;-webkit-tap-highlight-color:rgba(37,99,235,0.1);">
            <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'], '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;
        }

        // Membership number lookup
        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 || '') + (data.is_member ? '' : ' <span style="color:#92400E;">(' + (data.reason || 'غير فعال') + ')</span>');
                            fillMemberData(data);
                        } else {
                            memberLookupBox.style.background = '#FEF2F2';
                            memberLookupBox.style.color = '#DC2626';
                            memberLookupBox.textContent = data.reason || 'رقم العضوية غير موجود';
                        }
                    });
                }, 400);
            });
        }

        // NID lookup
        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 if (data.reason) {
                                memberBadge.style.background = '#FEF3C7';
                                memberBadge.style.color = '#92400E';
                                memberBadge.innerHTML = '<strong>غير عضو</strong> — ' + data.reason;
                            } 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 form fee
    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 = 'إرسال للخزينة';
                }
            });
        });
    }

    // 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: 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) {
                var sub = data.subscription_amount || 0;
                var card = <?= isset($registration) ? (int) $registration['card_fee'] : 0 ?>;
                var form = <?= isset($registration) ? (int) $registration['form_fee'] : 0 ?>;
                document.getElementById('feeSub').textContent = Number(sub).toLocaleString() + ' ج.م';
                document.getElementById('feeTotal').textContent = Number(sub + card + form).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';
                g.style.background = '';
            });
            this.style.borderColor = '#2563EB';
            this.style.background = '#F0F7FF';
            selectedGroupId = this.dataset.groupId;
            submitActivitySelection(selectedGroupId);
        });
    });

    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);
        });
    });

    var siblingCheckbox = document.getElementById('hasSibling');
    if (siblingCheckbox) {
        siblingCheckbox.addEventListener('change', function() {
            if (selectedGroupId) submitActivitySelection(selectedGroupId);
        });
    }

    // Discipline chip filtering
    var activeDiscId = '';
    document.querySelectorAll('.disc-chip').forEach(function(chip) {
        chip.addEventListener('click', function() {
            document.querySelectorAll('.disc-chip').forEach(function(c) {
                c.style.background = 'white'; c.style.color = '#374151';
            });
            this.style.background = '#2563EB'; this.style.color = 'white';
            activeDiscId = this.dataset.disc;
            filterGroups();
        });
    });

    // Group search
    var groupSearch = document.getElementById('groupSearch');
    if (groupSearch) {
        groupSearch.addEventListener('input', filterGroups);
    }

    function filterGroups() {
        var q = (groupSearch ? groupSearch.value : '').toLowerCase();
        document.querySelectorAll('.group-option').forEach(function(el) {
            var matchText = !q || el.dataset.name.toLowerCase().indexOf(q) >= 0;
            var matchDisc = !activeDiscId || el.dataset.discId === activeDiscId;
            el.style.display = (matchText && matchDisc) ? '' : 'none';
        });
    }

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