<?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: ?>
<!-- Lookup Form -->
<div class="card">
    <div style="padding:14px 16px;border-bottom:1px solid #E5E7EB;">
        <span style="font-weight:700;font-size:15px;">تسجيل لاعب سباحة جديد</span>
    </div>
    <form id="lookupForm" style="padding:16px;">
        <?= csrf_field() ?>
        <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;">رقم العضوية</label>
                <input type="text" name="membership_number" class="form-control" placeholder="اختياري" 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="text" name="national_id" class="form-control" maxlength="14" placeholder="14 رقم" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;direction:ltr;">
            </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="text" name="full_name_ar" class="form-control" required 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;">الاسم بالإنجليزي</label>
                <input type="text" name="full_name_en" class="form-control" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;direction:ltr;">
            </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;">الهاتف</label>
                <input type="text" name="phone" class="form-control" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;direction:ltr;">
            </div>
            <div></div>
        </div>

        <!-- Guardian Section -->
        <div style="border-top:1px solid #E5E7EB;padding-top:16px;margin-top:8px;margin-bottom:16px;">
            <span style="font-size:13px;font-weight:700;color:#374151;">بيانات ولي الأمر (إذا كان اللاعب أقل من 18 سنة)</span>
        </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;">اسم ولي الأمر</label>
                <input type="text" name="guardian_name" 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;">هاتف ولي الأمر</label>
                <input type="text" name="guardian_phone" class="form-control" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;direction:ltr;">
            </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;">الرقم القومي لولي الأمر</label>
                <input type="text" name="guardian_national_id" class="form-control" maxlength="14" style="width:100%;padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;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:8px 12px;border:1px solid #D1D5DB;border-radius:6px;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>

        <button type="submit" class="btn btn-primary" style="width:100%;padding:10px;font-size:14px;">
            <i data-lucide="search" style="width:15px;height:15px;vertical-align:middle;margin-left:6px;"></i>بحث وتسجيل
        </button>
        <div id="lookupError" 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('lookupForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const form = this;
    const btn = form.querySelector('button[type=submit]');
    const errDiv = document.getElementById('lookupError');
    errDiv.style.display = 'none';
    btn.disabled = true;
    btn.innerHTML = 'جاري البحث...';

    const fd = new FormData(form);
    fetch('/sa/swimming/register/lookup', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(data => {
            if (data.success && data.redirect) {
                window.location.href = data.redirect;
            } else {
                errDiv.textContent = data.error || 'حدث خطأ';
                errDiv.style.display = 'block';
                btn.disabled = false;
                btn.innerHTML = '<i data-lucide="search" style="width:15px;height:15px;vertical-align:middle;margin-left:6px;"></i>بحث وتسجيل';
            }
        })
        .catch(() => {
            errDiv.textContent = 'فشل الاتصال بالسيرفر';
            errDiv.style.display = 'block';
            btn.disabled = false;
            btn.innerHTML = '<i data-lucide="search" style="width:15px;height:15px;vertical-align:middle;margin-left:6px;"></i>بحث وتسجيل';
        });
});
</script>
<?php endif; ?>

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