<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>تسجيل لاعب سباحة<?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/sa/swimming" class="btn btn-outline"><i data-lucide="arrow-right" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> العودة</a>
<?php $__template->endSection(); ?>

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

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

    <!-- 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 = ['البيانات', 'الشهادة الطبية', 'الصورة'];
            $stepMap = ['personal' => 1, 'medical' => 2, 'photo' => 3, 'complete' => 4];
            $currentNum = $stepMap[$step] ?? 1;
            foreach ($steps as $i => $label):
                $stepNum = $i + 1;
                $isActive = $stepNum == $currentNum;
                $isComplete = $stepNum < $currentNum;
                $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 Summary -->
    <div class="card" style="margin-bottom:16px;">
        <div style="padding:14px 16px;display:flex;align-items:center;gap:12px;">
            <div style="width:48px;height:48px;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:20px;height:20px;"></i></div>
                <?php endif; ?>
            </div>
            <div style="flex:1;">
                <div style="font-size:15px;font-weight:700;color:#1A1A2E;"><?= e($registration['full_name_ar']) ?></div>
                <div style="font-size:12px;color:#6B7280;margin-top:2px;">
                    <?php if ($registration['player_nid']): ?><span style="direction:ltr;display:inline-block;"><?= e($registration['player_nid']) ?></span><?php endif; ?>
                    <?php if ($registration['date_of_birth']): ?> • <?= (int) date_diff(date_create($registration['date_of_birth']), date_create())->y ?> سنة<?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <?php if ($step === 'medical'): ?>
    <!-- Medical Certificate Upload -->
    <div class="card">
        <div style="padding:14px 16px;border-bottom:1px solid #E5E7EB;">
            <span style="font-weight:700;font-size:14px;color:#1A1A2E;"><i data-lucide="heart-pulse" style="width:16px;height:16px;vertical-align:middle;margin-left:6px;color:#DC2626;"></i>الشهادة الطبية</span>
            <span style="font-size:11px;color:#DC2626;margin-right:8px;">(مطلوبة - لن يمكن المتابعة بدونها)</span>
        </div>
        <form id="medicalForm" style="padding:16px;" enctype="multipart/form-data">
            <?= csrf_field() ?>
            <div style="margin-bottom:16px;">
                <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">ملف الشهادة الطبية <span style="color:#DC2626;">*</span></label>
                <input type="file" name="medical_file" id="medicalFile" accept=".pdf,.png,.jpg,.jpeg" required
                       style="width:100%;padding:10px;border:2px dashed #D1D5DB;border-radius:8px;font-size:13px;cursor:pointer;">
                <div style="font-size:11px;color:#6B7280;margin-top:4px;">PDF أو صورة (PNG, JPG) — حجم أقصى 10 ميجابايت</div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:16px;">
                <div>
                    <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">تاريخ الفحص <span style="color:#DC2626;">*</span></label>
                    <input type="date" name="exam_date" required class="form-control" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                </div>
                <div>
                    <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">تاريخ الانتهاء <span style="color:#DC2626;">*</span></label>
                    <input type="date" name="expiry_date" required class="form-control" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;">
                </div>
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;padding:10px;">
                <i data-lucide="upload" style="width:15px;height:15px;vertical-align:middle;margin-left:6px;"></i>رفع الشهادة الطبية
            </button>
            <div id="medicalError" style="display:none;margin-top:10px;padding:8px 12px;background:#FEF2F2;color:#DC2626;border-radius:6px;font-size:12px;"></div>
        </form>
    </div>

    <script>
    document.getElementById('medicalForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const form = this;
        const btn = form.querySelector('button[type=submit]');
        const errDiv = document.getElementById('medicalError');
        errDiv.style.display = 'none';
        btn.disabled = true;
        btn.textContent = 'جاري الرفع...';

        const fd = new FormData(form);
        fetch('/sa/swimming/register/<?= (int) $registration['id'] ?>/medical', {
            method: 'POST',
            body: fd
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                window.location.href = data.redirect || window.location.href;
            } else {
                errDiv.textContent = data.error || 'حدث خطأ';
                errDiv.style.display = 'block';
                btn.disabled = false;
                btn.textContent = 'رفع الشهادة الطبية';
            }
        })
        .catch(() => {
            errDiv.textContent = 'فشل الاتصال بالسيرفر';
            errDiv.style.display = 'block';
            btn.disabled = false;
            btn.textContent = 'رفع الشهادة الطبية';
        });
    });
    </script>

    <?php elseif ($step === 'photo'): ?>
    <!-- Photo Capture -->
    <div class="card">
        <div style="padding:14px 16px;border-bottom:1px solid #E5E7EB;">
            <span style="font-weight:700;font-size:14px;"><i data-lucide="camera" style="width:16px;height:16px;vertical-align:middle;margin-left:6px;"></i>التقاط صورة اللاعب</span>
        </div>
        <div style="padding:16px;text-align:center;">
            <div id="cameraContainer" style="margin-bottom:16px;">
                <video id="cameraFeed" style="width:100%;max-width:320px;border-radius:8px;background:#000;" autoplay playsinline></video>
                <canvas id="cameraCanvas" style="display:none;"></canvas>
            </div>
            <div id="photoPreview" style="display:none;margin-bottom:16px;">
                <img id="capturedImage" style="width:100%;max-width:320px;border-radius:8px;" alt="">
            </div>
            <div style="display:flex;gap:8px;justify-content:center;margin-bottom:12px;">
                <button type="button" id="captureBtn" class="btn btn-primary" onclick="capturePhoto()">
                    <i data-lucide="camera" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i>التقاط
                </button>
                <button type="button" id="retakeBtn" class="btn btn-outline" style="display:none;" onclick="retakePhoto()">إعادة</button>
                <button type="button" id="savePhotoBtn" class="btn btn-primary" style="display:none;" onclick="savePhoto()">حفظ الصورة</button>
            </div>
            <div style="margin-top:12px;padding-top:12px;border-top:1px solid #E5E7EB;">
                <label style="font-size:12px;color:#6B7280;display:block;margin-bottom:6px;">أو ارفع صورة من الجهاز:</label>
                <input type="file" id="photoFileInput" accept="image/*" onchange="handleFileUpload(this)" style="font-size:12px;">
            </div>
            <div id="photoError" style="display:none;margin-top:10px;padding:8px 12px;background:#FEF2F2;color:#DC2626;border-radius:6px;font-size:12px;"></div>
        </div>
    </div>

    <script>
    let stream = null;
    const video = document.getElementById('cameraFeed');
    const canvas = document.getElementById('cameraCanvas');

    navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: 640, height: 480 } })
        .then(s => { stream = s; video.srcObject = s; })
        .catch(() => {});

    function capturePhoto() {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0);
        document.getElementById('capturedImage').src = canvas.toDataURL('image/jpeg', 0.85);
        document.getElementById('cameraContainer').style.display = 'none';
        document.getElementById('photoPreview').style.display = 'block';
        document.getElementById('captureBtn').style.display = 'none';
        document.getElementById('retakeBtn').style.display = '';
        document.getElementById('savePhotoBtn').style.display = '';
    }

    function retakePhoto() {
        document.getElementById('cameraContainer').style.display = '';
        document.getElementById('photoPreview').style.display = 'none';
        document.getElementById('captureBtn').style.display = '';
        document.getElementById('retakeBtn').style.display = 'none';
        document.getElementById('savePhotoBtn').style.display = 'none';
    }

    function handleFileUpload(input) {
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('capturedImage').src = e.target.result;
                document.getElementById('cameraContainer').style.display = 'none';
                document.getElementById('photoPreview').style.display = 'block';
                document.getElementById('captureBtn').style.display = 'none';
                document.getElementById('retakeBtn').style.display = '';
                document.getElementById('savePhotoBtn').style.display = '';
            };
            reader.readAsDataURL(input.files[0]);
        }
    }

    function savePhoto() {
        const btn = document.getElementById('savePhotoBtn');
        const errDiv = document.getElementById('photoError');
        errDiv.style.display = 'none';
        btn.disabled = true;
        btn.textContent = 'جاري الحفظ...';

        const base64 = document.getElementById('capturedImage').src;
        const csrfToken = document.querySelector('meta[name="csrf-token"]') ? document.querySelector('meta[name="csrf-token"]').content : '';

        fetch('/sa/swimming/register/<?= (int) $registration['id'] ?>/photo', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ photo_base64: base64, _csrf_token: csrfToken })
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                if (stream) stream.getTracks().forEach(t => t.stop());
                window.location.href = data.redirect || '/sa/swimming/assign/<?= (int) $registration['id'] ?>';
            } else {
                errDiv.textContent = data.error || 'حدث خطأ';
                errDiv.style.display = 'block';
                btn.disabled = false;
                btn.textContent = 'حفظ الصورة';
            }
        })
        .catch(() => {
            errDiv.textContent = 'فشل الاتصال';
            errDiv.style.display = 'block';
            btn.disabled = false;
            btn.textContent = 'حفظ الصورة';
        });
    }
    </script>

    <?php elseif ($step === 'complete'): ?>
    <!-- Registration Complete -->
    <div class="card" style="text-align:center;padding:40px;">
        <div style="width:64px;height:64px;border-radius:50%;background:#ECFDF5;display:flex;align-items:center;justify-content:center;margin:0 auto 16px;">
            <i data-lucide="check" style="width:32px;height:32px;color:#059669;"></i>
        </div>
        <h3 style="font-size:18px;font-weight:700;color:#1A1A2E;margin-bottom:8px;">تم تسجيل اللاعب بنجاح</h3>
        <p style="font-size:13px;color:#6B7280;margin-bottom:20px;">يمكنك الآن تعيين اللاعب في مجموعة سباحة</p>
        <div style="display:flex;gap:10px;justify-content:center;">
            <a href="/sa/swimming/assign/<?= (int) $registration['id'] ?>" class="btn btn-primary">تعيين في مجموعة</a>
            <a href="/sa/swimming/register" class="btn btn-outline">تسجيل لاعب آخر</a>
        </div>
    </div>
    <?php endif; ?>

</div>

<?php else: ?>
<!-- Registration Form -->
<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="lookupForm">
            <?= csrf_field() ?>
            <div style="display:grid;grid-template-columns:1fr;gap:14px;">

                <!-- Member Quick Lookup -->
                <div>
                    <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">رقم العضوية <span style="font-weight:400;color:#6B7280;font-size:12px;">(للأعضاء — يملأ كل البيانات تلقائياً)</span></label>
                    <input type="text" name="membership_number" id="regMembershipNo" class="form-control" inputmode="numeric" placeholder="أدخل رقم العضوية"
                           style="width:100%;padding:14px;font-size:18px;border:1px solid #D1D5DB;border-radius:10px;direction:ltr;text-align:right;letter-spacing:1px;">
                    <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>

                <!-- National ID -->
                <div>
                    <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">الرقم القومي <span style="color:#DC2626;">*</span> <span style="font-weight:400;color:#6B7280;font-size:11px;">(يستخرج تاريخ الميلاد والنوع تلقائياً)</span></label>
                    <input type="text" name="national_id" id="regNid" class="form-control" maxlength="14" inputmode="numeric" pattern="[0-9]*" placeholder="أدخل 14 رقم"
                           style="width:100%;padding:14px;font-size:18px;border:1px solid #D1D5DB;border-radius:10px;direction:ltr;text-align:right;letter-spacing:1px;">
                    <div id="regNidInfo" style="display:none;margin-top:8px;padding:10px 12px;border-radius:8px;font-size:13px;"></div>
                </div>

                <!-- Name -->
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">الاسم بالعربي <span style="color:#DC2626;">*</span></label>
                        <input type="text" name="full_name_ar" id="regNameAr" class="form-control" required style="width:100%;padding:10px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">الاسم بالإنجليزي</label>
                        <input type="text" name="full_name_en" id="regNameEn" class="form-control" style="width:100%;padding:10px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;direction:ltr;">
                    </div>
                </div>

                <!-- Auto-filled from NID -->
                <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;">
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">تاريخ الميلاد</label>
                        <input type="date" name="date_of_birth" id="regDob" class="form-control" style="width:100%;padding:10px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:13px;">
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">النوع</label>
                        <select name="gender" id="regGender" class="form-control" style="width:100%;padding:10px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:13px;">
                            <option value="">—</option>
                            <option value="male">ذكر</option>
                            <option value="female">أنثى</option>
                        </select>
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">العمر</label>
                        <input type="text" id="regAge" class="form-control" disabled style="width:100%;padding:10px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:13px;background:#F9FAFB;" placeholder="—">
                    </div>
                </div>

                <!-- Phone -->
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">الهاتف</label>
                        <input type="text" name="phone" id="regPhone" class="form-control" inputmode="tel" style="width:100%;padding:10px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;direction:ltr;">
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">العنوان</label>
                        <input type="text" name="address" id="regAddress" class="form-control" style="width:100%;padding:10px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                    </div>
                </div>

                <!-- Guardian Section -->
                <div style="border-top:1px solid #E5E7EB;padding-top:16px;margin-top:4px;">
                    <span style="font-size:13px;font-weight:700;color:#374151;">بيانات ولي الأمر <span style="font-weight:400;color:#6B7280;font-size:11px;">(مطلوب إذا كان اللاعب أقل من 18 سنة)</span></span>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">اسم ولي الأمر</label>
                        <input type="text" name="guardian_name" id="regGuardianName" class="form-control" style="width:100%;padding:10px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;">
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">هاتف ولي الأمر</label>
                        <input type="text" name="guardian_phone" id="regGuardianPhone" class="form-control" inputmode="tel" style="width:100%;padding:10px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;direction:ltr;">
                    </div>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">الرقم القومي لولي الأمر</label>
                        <input type="text" name="guardian_national_id" class="form-control" maxlength="14" style="width:100%;padding:10px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:14px;direction:ltr;">
                    </div>
                    <div>
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:6px;">صلة القرابة</label>
                        <select name="guardian_relationship" class="form-control" style="width:100%;padding:10px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:13px;">
                            <option value="">—</option>
                            <option value="father">أب</option>
                            <option value="mother">أم</option>
                            <option value="brother">أخ</option>
                            <option value="sister">أخت</option>
                            <option value="uncle">عم / خال</option>
                            <option value="other">أخرى</option>
                        </select>
                    </div>
                </div>
            </div>

            <button type="submit" id="btnStartReg" class="btn btn-primary" style="width:100%;margin-top:20px;padding:14px;font-size:15px;font-weight:700;border-radius:10px;">
                <i data-lucide="play" style="width:16px;height:16px;vertical-align:middle;margin-left:6px;"></i> بدء التسجيل
            </button>
            <div id="lookupError" style="display:none;margin-top:12px;padding:10px 12px;background:#FEF2F2;border-radius:8px;color:#DC2626;font-size:13px;"></div>
        </form>
    </div>
</div>

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

    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;

    var regMembershipNo = document.getElementById('regMembershipNo');
    var memberLookupBox = document.getElementById('regMemberLookup');
    var regNid = document.getElementById('regNid');
    var nidInfoBox = document.getElementById('regNidInfo');
    var regNameAr = document.getElementById('regNameAr');
    var regNameEn = document.getElementById('regNameEn');
    var regPhone = document.getElementById('regPhone');
    var regDob = document.getElementById('regDob');
    var regGender = document.getElementById('regGender');
    var regAge = document.getElementById('regAge');

    function fillMemberData(data) {
        if (data.name && !regNameAr.value.trim()) regNameAr.value = data.name;
        if (data.name_en && !regNameEn.value.trim()) regNameEn.value = data.name_en;
        if (data.phone && !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;
        if (data.date_of_birth && !regDob.value) {
            regDob.value = data.date_of_birth;
            calculateAge(data.date_of_birth);
        }
        if (data.gender && !regGender.value) regGender.value = data.gender;
    }

    function parseNid(nid) {
        if (nid.length !== 14) return null;
        var century = nid[0] === '2' ? '19' : (nid[0] === '3' ? '20' : null);
        if (!century) return null;
        var year = century + nid.substring(1, 3);
        var month = nid.substring(3, 5);
        var day = nid.substring(5, 7);
        var dob = year + '-' + month + '-' + day;
        var genderDigit = parseInt(nid[12]);
        var gender = (genderDigit % 2 === 1) ? 'male' : 'female';
        return { dob: dob, gender: gender };
    }

    function calculateAge(dob) {
        if (!dob) { regAge.value = ''; return; }
        var birth = new Date(dob);
        var today = new Date();
        var age = today.getFullYear() - birth.getFullYear();
        var m = today.getMonth() - birth.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) age--;
        regAge.value = age + ' سنة';
    }

    // Membership number live lookup
    var memberTimer = null;
    regMembershipNo.addEventListener('input', function() {
        var val = this.value.replace(/\D/g, '');
        this.value = val;
        if (val.length < 1) { memberLookupBox.style.display = 'none'; return; }
        clearTimeout(memberTimer);
        memberTimer = 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="background:#ECFDF5;padding:1px 6px;border-radius:4px;font-size:11px;">فعال</span>' :
                        ' <span style="color:#92400E;">(' + (data.reason || 'غير فعال') + ')</span>');
                    fillMemberData(data);
                } else {
                    memberLookupBox.style.background = '#FEF2F2';
                    memberLookupBox.style.color = '#DC2626';
                    memberLookupBox.textContent = data.reason || 'رقم العضوية غير موجود';
                }
            }).catch(function() {
                memberLookupBox.style.display = 'none';
            });
        }, 400);
    });

    // NID auto-parse + membership lookup
    regNid.addEventListener('input', function() {
        this.value = this.value.replace(/\D/g, '');
        if (this.value.length === 14) {
            var parsed = parseNid(this.value);
            if (parsed) {
                regDob.value = parsed.dob;
                regGender.value = parsed.gender;
                calculateAge(parsed.dob);
                nidInfoBox.style.display = '';
                nidInfoBox.style.background = '#EFF6FF';
                nidInfoBox.style.color = '#1D4ED8';
                nidInfoBox.innerHTML = '<i data-lucide="info" style="width:13px;height:13px;vertical-align:middle;margin-left:4px;"></i>' +
                    'تاريخ الميلاد: <strong>' + parsed.dob + '</strong> — النوع: <strong>' + (parsed.gender === 'male' ? 'ذكر' : 'أنثى') + '</strong>';
                if (typeof lucide !== 'undefined') lucide.createIcons();
            }
            // Also check membership via NID
            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 && data.is_member) {
                    nidInfoBox.style.background = '#ECFDF5';
                    nidInfoBox.style.color = '#059669';
                    nidInfoBox.innerHTML = '<strong>عضو فعال</strong>' +
                        (data.membership_number ? ' — رقم العضوية: ' + data.membership_number : '') +
                        (data.name ? ' — ' + data.name : '');
                    fillMemberData(data);
                } else if (data.success && data.reason) {
                    nidInfoBox.style.background = '#FEF3C7';
                    nidInfoBox.style.color = '#92400E';
                    nidInfoBox.innerHTML += '<br><strong>غير عضو</strong> — ' + data.reason;
                    if (data.name) fillMemberData(data);
                }
            });
        } else {
            nidInfoBox.style.display = 'none';
        }
    });

    // DOB change -> recalculate age
    regDob.addEventListener('change', function() { calculateAge(this.value); });

    // Submit form
    document.getElementById('lookupForm').addEventListener('submit', function(e) {
        e.preventDefault();
        var btn = document.getElementById('btnStartReg');
        var errDiv = document.getElementById('lookupError');
        errDiv.style.display = 'none';
        btn.disabled = true;
        btn.textContent = 'جاري التسجيل...';

        var formData = new FormData(this);
        var body = {};
        formData.forEach(function(v, k) { body[k] = v; });
        body._csrf_token = csrfToken;

        fetch('/sa/swimming/register/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 {
                errDiv.textContent = data.error || 'حدث خطأ';
                errDiv.style.display = 'block';
                btn.disabled = false;
                btn.textContent = 'بدء التسجيل';
            }
        }).catch(function() {
            errDiv.textContent = 'فشل الاتصال بالسيرفر';
            errDiv.style.display = 'block';
            btn.disabled = false;
            btn.textContent = 'بدء التسجيل';
        });
    });
});
</script>
<?php endif; ?>

<?php $__template->endSection(); ?>
