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

<?php $__template->section('page_actions'); ?>
<a href="/sa/swimming/pool-reservations" class="btn btn-outline"><i data-lucide="list" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> قائمة الحجوزات</a>
<?php $__template->endSection(); ?>

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

<div id="reservationWizard">
    <!-- Progress Bar -->
    <div class="card" style="margin-bottom:16px;padding:16px;">
        <div style="display:flex;align-items:center;justify-content:space-between;gap:4px;">
            <?php
            $steps = ['بيانات الحاجز', 'نوع الحجز', 'التأكيد'];
            foreach ($steps as $i => $label):
                $num = $i + 1;
            ?>
            <div style="display:flex;align-items:center;flex:1;<?= $i < count($steps) - 1 ? '' : 'flex:0;' ?>">
                <div id="stepCircle<?= $num ?>" style="width:36px;height:36px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:14px;background:<?= $num === 1 ? '#2563EB;color:#fff' : '#E5E7EB;color:#6B7280' ?>;flex-shrink:0;"><?= $num ?></div>
                <div style="font-size:11px;margin-right:4px;margin-left:4px;color:#6B7280;white-space:nowrap;"><?= $label ?></div>
                <?php if ($i < count($steps) - 1): ?>
                <div style="flex:1;height:2px;background:#E5E7EB;margin:0 4px;"></div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Step 1: Booker Info -->
    <div id="step1" 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" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> بيانات الحاجز</h3>
        </div>
        <div style="padding:20px;">
            <div style="display:grid;grid-template-columns:1fr;gap:14px;">
                <div>
                    <label class="form-label">اسم المدرب / الحاجز <span style="color:#DC2626;">*</span></label>
                    <input type="text" id="prBookerName" class="form-input" style="padding:14px;font-size:15px;border-radius:10px;" placeholder="اسم المدرب الحر أو الشخص">
                </div>
                <div>
                    <label class="form-label">رقم التليفون</label>
                    <input type="text" id="prBookerPhone" class="form-input" style="padding:14px;font-size:15px;border-radius:10px;direction:ltr;text-align:right;" placeholder="اختياري">
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                    <div>
                        <label class="form-label">نوع الحاجز</label>
                        <select id="prBookerType" class="form-input" style="padding:14px;font-size:14px;border-radius:10px;">
                            <option value="freelance_coach">مدرب حر</option>
                            <option value="entity">مؤسسة</option>
                            <option value="individual">فرد</option>
                        </select>
                    </div>
                    <div>
                        <label class="form-label">عدد المشاركين <span style="color:#DC2626;">*</span></label>
                        <input type="number" id="prParticipants" class="form-input" style="padding:14px;font-size:18px;border-radius:10px;direction:ltr;text-align:center;font-weight:700;" value="1" min="1" max="100">
                    </div>
                </div>
            </div>
            <button type="button" id="btnStep1Next" class="btn btn-primary" style="width:100%;margin-top:20px;padding:16px;font-size:16px;font-weight:700;border-radius:12px;min-height:56px;" disabled>
                <i data-lucide="arrow-left" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> التالي — اختيار نوع الحجز
            </button>
        </div>
    </div>

    <!-- Step 2: Package Selection -->
    <div id="step2" class="card" style="margin-bottom:16px;display:none;">
        <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
            <h3 style="margin:0;font-size:16px;font-weight:600;"><i data-lucide="layers" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> اختيار نوع الحجز</h3>
        </div>
        <div style="padding:20px;">
            <!-- Overflow Alert (hidden by default) -->
            <div id="overflowAlert" style="display:none;padding:14px;background:#FEF3C7;border:1px solid #F59E0B;border-radius:10px;margin-bottom:16px;">
                <div style="font-weight:700;color:#92400E;margin-bottom:8px;"><i data-lucide="alert-triangle" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> <span id="overflowText"></span></div>
                <div style="display:flex;gap:10px;flex-wrap:wrap;">
                    <label style="display:flex;align-items:center;gap:6px;padding:10px 14px;background:#fff;border:2px solid #E5E7EB;border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;">
                        <input type="radio" name="overflowOption" value="additional_lane"> حجز حارة إضافية
                    </label>
                    <label id="overflowCardsLabel" style="display:flex;align-items:center;gap:6px;padding:10px 14px;background:#fff;border:2px solid #E5E7EB;border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;">
                        <input type="radio" name="overflowOption" value="overflow_cards"> <span id="overflowCardsText">إضافة كروت</span>
                    </label>
                </div>
                <div id="overflowCardsPicker" style="display:none;margin-top:12px;padding:12px;background:#fff;border-radius:8px;">
                    <label class="form-label" style="font-size:12px;">اختر باقة الكروت للزائدين:</label>
                    <div id="overflowCardsOptions" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:8px;margin-top:8px;"></div>
                </div>
            </div>

            <!-- Lane Rentals Section -->
            <div style="margin-bottom:20px;">
                <h4 style="margin:0 0 12px;font-size:15px;font-weight:700;color:#1A1A2E;padding-bottom:8px;border-bottom:2px solid #2563EB;">
                    <i data-lucide="waves" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;color:#2563EB;"></i> إيجار الحارات
                </h4>
                <div id="laneRentalGrid" style="display:grid;grid-template-columns:1fr;gap:12px;">
                    <div style="text-align:center;padding:20px;color:#9CA3AF;">جاري التحميل...</div>
                </div>
            </div>

            <!-- Session Cards Section -->
            <div style="margin-bottom:20px;">
                <h4 style="margin:0 0 12px;font-size:15px;font-weight:700;color:#1A1A2E;padding-bottom:8px;border-bottom:2px solid #059669;">
                    <i data-lucide="credit-card" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;color:#059669;"></i> الحصص والكروت
                </h4>
                <div id="sessionCardsGrid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:10px;">
                    <div style="text-align:center;padding:20px;color:#9CA3AF;">جاري التحميل...</div>
                </div>
            </div>

            <!-- Selection Summary -->
            <div id="selectionSummary" style="display:none;padding:14px;background:#EFF6FF;border:1px solid #BFDBFE;border-radius:10px;margin-bottom:16px;">
                <div style="font-size:13px;color:#1D4ED8;font-weight:600;">الاختيار:</div>
                <div id="summaryText" style="font-size:15px;font-weight:700;margin-top:4px;"></div>
                <div id="summaryPrice" style="font-size:22px;font-weight:800;color:#059669;margin-top:6px;"></div>
            </div>

            <button type="button" id="btnStep2Next" class="btn btn-primary" style="width:100%;padding:16px;font-size:16px;font-weight:700;border-radius:12px;min-height:56px;" disabled>
                <i data-lucide="arrow-left" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> التالي — تأكيد الحجز
            </button>
            <button type="button" id="btnStep2Back" class="btn btn-outline" style="width:100%;margin-top:10px;padding:14px;font-size:14px;border-radius:10px;min-height:50px;">
                <i data-lucide="arrow-right" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> رجوع
            </button>
        </div>
    </div>

    <!-- Step 3: Confirmation -->
    <div id="step3" class="card" style="margin-bottom:16px;display:none;">
        <div style="padding:16px 20px;border-bottom:1px solid #E5E7EB;">
            <h3 style="margin:0;font-size:16px;font-weight:600;"><i data-lucide="check-circle" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> تأكيد الحجز</h3>
        </div>
        <div style="padding:20px;">
            <div id="confirmDetails" style="margin-bottom:20px;"></div>
            <div>
                <label class="form-label">ملاحظات (اختياري)</label>
                <textarea id="prNotes" class="form-input" rows="2" style="padding:12px;font-size:14px;border-radius:10px;" placeholder="أي ملاحظات إضافية..."></textarea>
            </div>
            <button type="button" id="btnConfirm" class="btn btn-primary" style="width:100%;margin-top:16px;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> تأكيد وإرسال للخزينة
            </button>
            <button type="button" id="btnStep3Back" class="btn btn-outline" style="width:100%;margin-top:10px;padding:14px;font-size:14px;border-radius:10px;min-height:50px;">
                <i data-lucide="arrow-right" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> رجوع
            </button>
            <div id="step3Error" style="display:none;margin-top:12px;padding:12px;background:#FEF2F2;border-radius:8px;color:#DC2626;font-size:13px;"></div>
        </div>
    </div>

    <!-- Success State -->
    <div id="stepSuccess" class="card" style="margin-bottom:16px;display:none;">
        <div style="padding:40px 20px;text-align:center;">
            <div style="width:64px;height:64px;border-radius:50%;background:#ECFDF5;display:inline-flex;align-items:center;justify-content:center;margin-bottom:16px;">
                <i data-lucide="check" style="width:32px;height:32px;color:#059669;"></i>
            </div>
            <h3 style="margin:0 0 8px;font-size:18px;font-weight:700;color:#059669;">تم إنشاء الحجز بنجاح</h3>
            <div id="successNumber" style="font-size:14px;color:#6B7280;margin-bottom:8px;"></div>
            <div id="successAmount" style="font-size:20px;font-weight:800;color:#2563EB;margin-bottom:16px;"></div>
            <div style="padding:12px;background:#FEF3C7;border-radius:8px;margin:16px auto;max-width:400px;">
                <i data-lucide="clock" style="width:16px;height:16px;vertical-align:middle;color:#D97706;margin-left:4px;"></i>
                <span style="color:#92400E;font-size:13px;">بانتظار التحصيل من الخزينة</span>
            </div>
            <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap;">
                <button type="button" id="btnNewReservation" class="btn btn-primary" style="padding:14px 24px;font-size:14px;border-radius:10px;">
                    <i data-lucide="plus" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> حجز جديد
                </button>
                <a id="btnViewReservation" href="#" class="btn btn-outline" style="padding:14px 24px;font-size:14px;border-radius:10px;">
                    <i data-lucide="eye" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> عرض الحجز
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Recent Reservations -->
<?php if (!empty($recentReservations)): ?>
<div class="card" style="margin-top:16px;">
    <div style="padding:12px 20px;border-bottom:1px solid #E5E7EB;">
        <h4 style="margin:0;font-size:14px;font-weight:600;color:#374151;">آخر الحجوزات</h4>
    </div>
    <div style="padding:0;">
        <?php foreach ($recentReservations as $r): ?>
        <a href="/sa/swimming/pool-reservations/<?= (int) $r['id'] ?>" style="display:flex;align-items:center;justify-content:space-between;padding:12px 20px;border-bottom:1px solid #F3F4F6;text-decoration:none;color:inherit;min-height:56px;">
            <div>
                <div style="font-weight:600;font-size:14px;color:#1A1A2E;"><?= e($r['booker_name']) ?></div>
                <div style="font-size:12px;color:#6B7280;margin-top:2px;">
                    <?= e($r['reservation_number']) ?> · <?php
                        $typeLabels = ['lane_50m' => 'حارة 50م', 'lane_25m' => 'حارة 25م', 'lane_mix' => 'حارة ميكس', 'cards' => 'كروت'];
                        echo $typeLabels[$r['reservation_type']] ?? $r['reservation_type'];
                    ?> · <?= (int) $r['sessions_used'] ?>/<?= (int) $r['sessions_total'] ?> حصة
                </div>
            </div>
            <div style="text-align:left;flex-shrink:0;margin-right:12px;">
                <div style="font-size:13px;font-weight:700;color:#2563EB;"><?= number_format((float) $r['total_amount'], 0) ?> ج.م</div>
                <?php
                    $sc = ['active' => '#059669', 'completed' => '#6B7280', 'cancelled' => '#DC2626', 'expired' => '#D97706'];
                    $sl = ['active' => 'نشط', 'completed' => 'مكتمل', 'cancelled' => 'ملغي', 'expired' => 'منتهي'];
                    $c = $sc[$r['status']] ?? '#6B7280';
                    $l = $sl[$r['status']] ?? $r['status'];
                ?>
                <span style="font-size:10px;padding:2px 6px;border-radius:4px;background:<?= $c ?>20;color:<?= $c ?>;"><?= $l ?></span>
            </div>
        </a>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<script>
(function() {
    var csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || '<?= e($_SESSION['_csrf_token'] ?? '') ?>';

    var state = {
        bookerName: '',
        bookerPhone: '',
        bookerType: 'freelance_coach',
        participantCount: 1,
        reservationType: '',
        pricingId: 0,
        sessionsTotal: 0,
        unitPrice: 0,
        overflowType: null,
        overflowCardsCount: 0,
        overflowAmount: 0,
        totalAmount: 0
    };

    var pricingData = null;
    var laneCapacities = { '50m': 12, '25m': 8, 'mix': 24 };
    var typeLabels = { lane_50m: 'إيجار حارة 50م', lane_25m: 'إيجار حارة 25م', lane_mix: 'إيجار حارة ميكس', cards: 'كروت حصص' };

    function setStep(n) {
        for (var i = 1; i <= 3; i++) {
            var el = document.getElementById('step' + i);
            if (el) el.style.display = (i === n) ? '' : 'none';
        }
        document.getElementById('stepSuccess').style.display = 'none';
        for (var j = 1; j <= 3; j++) {
            var c = document.getElementById('stepCircle' + j);
            if (j < n) { c.style.background = '#059669'; c.style.color = '#fff'; }
            else if (j === n) { c.style.background = '#2563EB'; c.style.color = '#fff'; }
            else { c.style.background = '#E5E7EB'; c.style.color = '#6B7280'; }
        }
    }

    // Step 1 logic
    var nameInput = document.getElementById('prBookerName');
    var phoneInput = document.getElementById('prBookerPhone');
    var typeSelect = document.getElementById('prBookerType');
    var participantsInput = document.getElementById('prParticipants');
    var btnStep1 = document.getElementById('btnStep1Next');

    function checkStep1() {
        btnStep1.disabled = nameInput.value.trim() === '';
    }
    nameInput.addEventListener('input', checkStep1);

    btnStep1.addEventListener('click', function() {
        state.bookerName = nameInput.value.trim();
        state.bookerPhone = phoneInput.value.trim();
        state.bookerType = typeSelect.value;
        state.participantCount = Math.max(1, parseInt(participantsInput.value) || 1);
        setStep(2);
        loadPricing();
    });

    // Step 2 logic
    function loadPricing() {
        if (pricingData) { renderPricing(); return; }
        fetch('/api/sa/swimming/pool-reservations/pricing', {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        }).then(function(r) { return r.json(); }).then(function(data) {
            if (data.success) {
                pricingData = data.data;
                renderPricing();
            }
        });
    }

    function renderPricing() {
        renderLaneRentals();
        renderSessionCards();
    }

    function renderLaneRentals() {
        var container = document.getElementById('laneRentalGrid');
        var lanes = pricingData.lane_rentals;
        if (!lanes || !lanes.length) {
            container.innerHTML = '<div style="color:#9CA3AF;text-align:center;padding:20px;">لا توجد أسعار حارات</div>';
            return;
        }

        var grouped = {};
        lanes.forEach(function(l) {
            var key = l.lane_type;
            if (!grouped[key]) grouped[key] = [];
            grouped[key].push(l);
        });

        var laneNames = { '50m': 'حارة 50 متر', '25m': 'حارة 25 متر', 'mix': 'حارة ميكس (25م/50م)' };
        var html = '';

        Object.keys(grouped).forEach(function(laneType) {
            var items = grouped[laneType];
            html += '<div style="border:2px solid #E5E7EB;border-radius:12px;padding:14px;transition:border-color .2s;" class="lane-group" data-lane-type="' + laneType + '">';
            html += '<div style="font-weight:700;font-size:14px;margin-bottom:10px;color:#1A1A2E;"><i data-lucide="waves" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;color:#2563EB;"></i> ' + (laneNames[laneType] || laneType) + '</div>';
            html += '<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(110px,1fr));gap:8px;">';
            items.forEach(function(item) {
                var resType = 'lane_' + laneType;
                html += '<label style="display:block;cursor:pointer;text-align:center;padding:10px 8px;border:2px solid #E5E7EB;border-radius:8px;transition:all .2s;" class="pricing-option" data-type="' + resType + '" data-pricing-id="' + item.id + '" data-sessions="' + item.sessions_per_month + '" data-price="' + item.price + '">';
                html += '<input type="radio" name="packageChoice" style="display:none;">';
                html += '<div style="font-size:20px;font-weight:800;color:#2563EB;">' + item.sessions_per_month + '</div>';
                html += '<div style="font-size:10px;color:#6B7280;">حصة/شهر</div>';
                html += '<div style="font-size:13px;font-weight:700;color:#059669;margin-top:4px;">' + Number(item.price).toLocaleString() + ' ج.م</div>';
                html += '</label>';
            });
            html += '</div></div>';
        });

        container.innerHTML = html;
        if (typeof lucide !== 'undefined') lucide.createIcons();
        bindPricingClicks();
    }

    function renderSessionCards() {
        var container = document.getElementById('sessionCardsGrid');
        var cards = pricingData.session_cards;
        if (!cards || !cards.length) {
            container.innerHTML = '<div style="color:#9CA3AF;text-align:center;padding:20px;">لا توجد أسعار كروت</div>';
            return;
        }

        var html = '';
        cards.forEach(function(card) {
            html += '<label style="display:block;cursor:pointer;text-align:center;padding:12px 8px;border:2px solid #E5E7EB;border-radius:10px;transition:all .2s;" class="pricing-option" data-type="cards" data-pricing-id="' + card.id + '" data-sessions="' + card.total_sessions + '" data-price="' + card.price + '">';
            html += '<input type="radio" name="packageChoice" style="display:none;">';
            html += '<div style="font-size:22px;font-weight:800;color:#059669;">' + card.total_sessions + '</div>';
            html += '<div style="font-size:10px;color:#6B7280;">حصة</div>';
            html += '<div style="font-size:13px;font-weight:700;color:#1A1A2E;margin-top:4px;">' + Number(card.price).toLocaleString() + ' ج.م</div>';
            html += '<div style="font-size:10px;color:#9CA3AF;">' + Math.round(card.price_per_session) + ' ج.م/حصة</div>';
            html += '</label>';
        });

        container.innerHTML = html;
        bindPricingClicks();
    }

    function bindPricingClicks() {
        document.querySelectorAll('.pricing-option').forEach(function(el) {
            el.addEventListener('click', function() {
                document.querySelectorAll('.pricing-option').forEach(function(o) {
                    o.style.borderColor = '#E5E7EB';
                    o.style.background = '';
                });
                this.style.borderColor = '#2563EB';
                this.style.background = '#EFF6FF';

                state.reservationType = this.dataset.type;
                state.pricingId = parseInt(this.dataset.pricingId);
                state.sessionsTotal = parseInt(this.dataset.sessions);
                state.unitPrice = parseFloat(this.dataset.price);
                state.overflowType = null;
                state.overflowCardsCount = 0;
                state.overflowAmount = 0;

                checkOverflow();
                updateSummary();
                document.getElementById('btnStep2Next').disabled = false;
            });
        });
    }

    function checkOverflow() {
        var alertEl = document.getElementById('overflowAlert');
        if (state.reservationType === 'cards') {
            alertEl.style.display = 'none';
            return;
        }

        var laneType = state.reservationType.replace('lane_', '');
        var capacity = laneCapacities[laneType] || 12;
        var overflow = state.participantCount - capacity;

        if (overflow <= 0) {
            alertEl.style.display = 'none';
            return;
        }

        document.getElementById('overflowText').textContent =
            'عدد المشاركين (' + state.participantCount + ') يتجاوز سعة الحارة (' + capacity + ') بـ ' + overflow + ' شخص';
        document.getElementById('overflowCardsText').textContent = 'إضافة ' + overflow + ' كروت للزائدين';
        alertEl.style.display = '';

        document.querySelectorAll('input[name="overflowOption"]').forEach(function(radio) {
            radio.checked = false;
            radio.addEventListener('change', function() {
                state.overflowType = this.value;
                if (this.value === 'overflow_cards') {
                    state.overflowCardsCount = overflow;
                    showOverflowCardsPicker(overflow);
                } else {
                    state.overflowCardsCount = 0;
                    state.overflowAmount = state.unitPrice;
                    document.getElementById('overflowCardsPicker').style.display = 'none';
                }
                updateSummary();
            });
        });
    }

    function showOverflowCardsPicker(count) {
        var picker = document.getElementById('overflowCardsPicker');
        var container = document.getElementById('overflowCardsOptions');
        picker.style.display = '';

        var cards = pricingData.session_cards || [];
        var html = '';
        cards.forEach(function(card) {
            var totalForOverflow = card.price * count;
            html += '<label style="display:block;cursor:pointer;text-align:center;padding:8px;border:2px solid #E5E7EB;border-radius:8px;font-size:12px;" class="overflow-card-option" data-price="' + totalForOverflow + '" data-sessions="' + card.total_sessions + '">';
            html += '<input type="radio" name="overflowCardChoice" style="display:none;">';
            html += '<div style="font-weight:700;">' + card.total_sessions + ' حصة</div>';
            html += '<div style="color:#059669;font-weight:600;">' + Number(totalForOverflow).toLocaleString() + ' ج.م</div>';
            html += '<div style="color:#9CA3AF;">(' + count + ' × ' + Number(card.price).toLocaleString() + ')</div>';
            html += '</label>';
        });
        container.innerHTML = html;

        container.querySelectorAll('.overflow-card-option').forEach(function(el) {
            el.addEventListener('click', function() {
                container.querySelectorAll('.overflow-card-option').forEach(function(o) {
                    o.style.borderColor = '#E5E7EB'; o.style.background = '';
                });
                this.style.borderColor = '#059669'; this.style.background = '#ECFDF5';
                state.overflowAmount = parseFloat(this.dataset.price);
                updateSummary();
            });
        });
    }

    function updateSummary() {
        var summaryEl = document.getElementById('selectionSummary');
        if (!state.reservationType) { summaryEl.style.display = 'none'; return; }

        state.totalAmount = state.unitPrice + (state.overflowAmount || 0);

        var label = (typeLabels[state.reservationType] || state.reservationType) + ' — ' + state.sessionsTotal + ' حصة';
        if (state.overflowType === 'additional_lane') {
            label += ' + حارة إضافية';
        } else if (state.overflowType === 'overflow_cards' && state.overflowAmount > 0) {
            label += ' + ' + state.overflowCardsCount + ' كروت';
        }

        document.getElementById('summaryText').textContent = label;
        document.getElementById('summaryPrice').textContent = Number(state.totalAmount).toLocaleString() + ' ج.م';
        summaryEl.style.display = '';
    }

    document.getElementById('btnStep2Next').addEventListener('click', function() {
        setStep(3);
        renderConfirmation();
    });

    document.getElementById('btnStep2Back').addEventListener('click', function() { setStep(1); });

    // Step 3: Confirmation
    function renderConfirmation() {
        var html = '<table style="width:100%;font-size:14px;border-collapse:collapse;">';
        html += '<tr style="border-bottom:1px solid #F3F4F6;"><td style="padding:10px 0;color:#6B7280;">الاسم</td><td style="padding:10px 0;font-weight:600;">' + escHtml(state.bookerName) + '</td></tr>';
        if (state.bookerPhone) {
            html += '<tr style="border-bottom:1px solid #F3F4F6;"><td style="padding:10px 0;color:#6B7280;">التليفون</td><td style="padding:10px 0;">' + escHtml(state.bookerPhone) + '</td></tr>';
        }
        html += '<tr style="border-bottom:1px solid #F3F4F6;"><td style="padding:10px 0;color:#6B7280;">عدد المشاركين</td><td style="padding:10px 0;font-weight:600;">' + state.participantCount + '</td></tr>';
        html += '<tr style="border-bottom:1px solid #F3F4F6;"><td style="padding:10px 0;color:#6B7280;">نوع الحجز</td><td style="padding:10px 0;font-weight:600;">' + (typeLabels[state.reservationType] || '') + '</td></tr>';
        html += '<tr style="border-bottom:1px solid #F3F4F6;"><td style="padding:10px 0;color:#6B7280;">عدد الحصص</td><td style="padding:10px 0;font-weight:600;">' + state.sessionsTotal + ' حصة</td></tr>';
        html += '<tr style="border-bottom:1px solid #F3F4F6;"><td style="padding:10px 0;color:#6B7280;">سعر الباقة</td><td style="padding:10px 0;font-weight:600;">' + Number(state.unitPrice).toLocaleString() + ' ج.م</td></tr>';
        if (state.overflowAmount > 0) {
            var ovLabel = state.overflowType === 'additional_lane' ? 'حارة إضافية' : 'كروت إضافية (' + state.overflowCardsCount + ')';
            html += '<tr style="border-bottom:1px solid #F3F4F6;"><td style="padding:10px 0;color:#6B7280;">' + ovLabel + '</td><td style="padding:10px 0;font-weight:600;">' + Number(state.overflowAmount).toLocaleString() + ' ج.م</td></tr>';
        }
        html += '<tr><td style="padding:12px 0;font-weight:700;font-size:16px;color:#1A1A2E;">الإجمالي</td><td style="padding:12px 0;font-weight:800;font-size:20px;color:#059669;">' + Number(state.totalAmount).toLocaleString() + ' ج.م</td></tr>';
        html += '</table>';
        document.getElementById('confirmDetails').innerHTML = html;
    }

    document.getElementById('btnStep3Back').addEventListener('click', function() { setStep(2); });

    document.getElementById('btnConfirm').addEventListener('click', function() {
        var btn = this;
        btn.disabled = true;
        btn.textContent = 'جاري الإنشاء...';
        document.getElementById('step3Error').style.display = 'none';

        fetch('/api/sa/swimming/pool-reservations/store', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': csrfToken
            },
            body: JSON.stringify({
                _csrf_token: csrfToken,
                booker_name: state.bookerName,
                booker_phone: state.bookerPhone,
                booker_type: state.bookerType,
                participant_count: state.participantCount,
                reservation_type: state.reservationType,
                pricing_id: state.pricingId,
                sessions_total: state.sessionsTotal,
                unit_price: state.unitPrice,
                notes: document.getElementById('prNotes').value.trim(),
                overflow_type: state.overflowType,
                overflow_cards_count: state.overflowCardsCount,
                overflow_amount: state.overflowAmount
            })
        }).then(function(r) { return r.json(); }).then(function(data) {
            if (data.success) {
                showSuccess(data);
            } else {
                var errEl = document.getElementById('step3Error');
                errEl.textContent = data.error || 'حدث خطأ';
                errEl.style.display = '';
                btn.disabled = false;
                btn.innerHTML = '<i data-lucide="banknote" style="width:20px;height:20px;vertical-align:middle;margin-left:6px;"></i> تأكيد وإرسال للخزينة';
                if (typeof lucide !== 'undefined') lucide.createIcons();
            }
        }).catch(function() {
            var errEl = document.getElementById('step3Error');
            errEl.textContent = 'خطأ في الاتصال';
            errEl.style.display = '';
            btn.disabled = false;
            btn.innerHTML = '<i data-lucide="banknote" style="width:20px;height:20px;vertical-align:middle;margin-left:6px;"></i> تأكيد وإرسال للخزينة';
            if (typeof lucide !== 'undefined') lucide.createIcons();
        });
    });

    function showSuccess(data) {
        for (var i = 1; i <= 3; i++) { document.getElementById('step' + i).style.display = 'none'; }
        document.getElementById('stepSuccess').style.display = '';
        for (var j = 1; j <= 3; j++) {
            var c = document.getElementById('stepCircle' + j);
            c.style.background = '#059669'; c.style.color = '#fff';
        }
        document.getElementById('successNumber').textContent = 'رقم الحجز: ' + data.reservation_number;
        document.getElementById('successAmount').textContent = Number(data.total_amount).toLocaleString() + ' ج.م';
        document.getElementById('btnViewReservation').href = '/sa/swimming/pool-reservations/' + data.reservation_id;
    }

    document.getElementById('btnNewReservation').addEventListener('click', function() {
        state = { bookerName:'', bookerPhone:'', bookerType:'freelance_coach', participantCount:1, reservationType:'', pricingId:0, sessionsTotal:0, unitPrice:0, overflowType:null, overflowCardsCount:0, overflowAmount:0, totalAmount:0 };
        nameInput.value = ''; phoneInput.value = ''; participantsInput.value = '1';
        typeSelect.value = 'freelance_coach';
        document.getElementById('prNotes').value = '';
        document.getElementById('btnStep1Next').disabled = true;
        document.getElementById('btnStep2Next').disabled = true;
        document.getElementById('selectionSummary').style.display = 'none';
        document.getElementById('overflowAlert').style.display = 'none';
        document.querySelectorAll('.pricing-option').forEach(function(o) { o.style.borderColor='#E5E7EB'; o.style.background=''; });
        var btn = document.getElementById('btnConfirm');
        btn.disabled = false;
        btn.innerHTML = '<i data-lucide="banknote" style="width:20px;height:20px;vertical-align:middle;margin-left:6px;"></i> تأكيد وإرسال للخزينة';
        setStep(1);
        if (typeof lucide !== 'undefined') lucide.createIcons();
    });

    function escHtml(str) {
        var d = document.createElement('div'); d.textContent = str; return d.innerHTML;
    }
})();
</script>
<?php $__template->endSection(); ?>
