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

<?php $__template->section('page_actions'); ?>
<a href="/sa/bookings" 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="bookingWizard">
    <!-- 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:#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: Identity -->
    <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;">
                <!-- Member Quick Lookup -->
                <div>
                    <label class="form-label">رقم العضوية <span style="font-weight:400;color:#6B7280;font-size:12px;">(للأعضاء — يملأ كل البيانات تلقائياً)</span></label>
                    <input type="text" id="bkMembershipNo" class="form-input" style="padding:14px;font-size:18px;border-radius:10px;direction:ltr;text-align:right;letter-spacing:1px;" inputmode="numeric" placeholder="أدخل رقم العضوية">
                    <div id="memberLookupResult" style="display:none;margin-top:10px;padding: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">الرقم القومي</label>
                    <input type="text" id="bkNid" 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 رقم (اختياري للزوار)">
                    <div id="nidResult" style="display:none;margin-top:10px;padding:12px;border-radius:8px;font-size:13px;"></div>
                </div>
                <div>
                    <label class="form-label">الاسم <span style="color:#DC2626;">*</span></label>
                    <input type="text" id="bkName" class="form-input" style="padding:14px;font-size:15px;border-radius:10px;" placeholder="اسم الحاجز">
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                    <div>
                        <label class="form-label">النوع</label>
                        <div id="bkGender" style="padding:14px;font-size:14px;color:#6B7280;">—</div>
                    </div>
                    <div>
                        <label class="form-label">السن</label>
                        <div id="bkAge" style="padding:14px;font-size:14px;color:#6B7280;">—</div>
                    </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 id="step1Error" style="display:none;margin-top:12px;padding:12px;background:#FEF2F2;border-radius:8px;color:#DC2626;font-size:13px;"></div>
        </div>
    </div>

    <!-- Step 2: Facility -->
    <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="map-pin" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> اختيار المرفق</h3>
        </div>
        <div style="padding:20px;">
            <div style="margin-bottom:12px;">
                <input type="text" id="unitSearchInput" class="form-input" placeholder="ابحث عن مرفق أو ملعب..." style="padding:12px;font-size:14px;border-radius:10px;">
            </div>
            <div id="facilitiesList" style="display:grid;grid-template-columns:1fr;gap:12px;">
                <div style="text-align:center;padding:40px;color:#9CA3AF;">جاري التحميل...</div>
            </div>
            <button type="button" id="btnStep2Back" class="btn btn-outline" style="width:100%;margin-top:16px;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: Date & Time -->
    <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="clock" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> اختيار الموعد</h3>
            <div id="selectedUnitLabel" style="font-size:12px;color:#6B7280;margin-top:4px;"></div>
        </div>
        <div style="padding:20px;">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:16px;">
                <div>
                    <label class="form-label">التاريخ</label>
                    <input type="date" id="bkDate" class="form-input" style="padding:12px;font-size:14px;border-radius:10px;direction:ltr;text-align:left;" value="<?= date('Y-m-d') ?>">
                </div>
                <div>
                    <label class="form-label">عدد المشاركين</label>
                    <input type="number" id="bkParticipants" class="form-input" style="padding:12px;font-size:14px;border-radius:10px;direction:ltr;text-align:left;" value="1" min="1">
                </div>
            </div>

            <div id="slotsGrid" style="display:grid;grid-template-columns:repeat(auto-fill, minmax(100px, 1fr));gap:8px;margin-bottom:16px;">
                <div style="text-align:center;padding:20px;color:#9CA3AF;grid-column:1/-1;">اختر التاريخ لعرض المواعيد</div>
            </div>

            <div id="selectedSlotInfo" style="display:none;padding:12px;background:#EFF6FF;border-radius:8px;margin-bottom:16px;">
                <div style="font-size:13px;font-weight:600;color:#1D4ED8;">الموعد المختار:</div>
                <div id="slotSummary" style="font-size:14px;margin-top:4px;"></div>
                <div id="pricePreview" style="font-size:18px;font-weight:800;color:#059669;margin-top:8px;"></div>
            </div>

            <button type="button" id="btnStep3Next" 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="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>
    </div>

    <!-- Step 4: Confirmation -->
    <div id="step4" 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="confirmSummary" style="margin-bottom:20px;"></div>

            <button type="button" id="btnConfirmBook" 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> تأكيد وإرسال للخزينة
            </button>
            <button type="button" id="btnStep4Back" 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="step4Error" 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="successBookingNumber" style="font-size:14px;color:#6B7280;margin-bottom:8px;"></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>
            <button type="button" id="btnNewBooking" class="btn btn-primary" style="padding:14px 32px;font-size:14px;border-radius:10px;min-height:50px;">
                <i data-lucide="plus" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> حجز جديد
            </button>
        </div>
    </div>
</div>

<!-- Recent Bookings -->
<?php if (!empty($recentBookings)): ?>
<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 ($recentBookings as $bk): ?>
        <a href="/sa/bookings/<?= (int) $bk['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;touch-action:manipulation;">
            <div>
                <div style="font-weight:600;font-size:14px;color:#1A1A2E;"><?= e($bk['booker_name']) ?></div>
                <div style="font-size:12px;color:#6B7280;margin-top:2px;">
                    <?= e($bk['facility_name'] ?? '') ?> — <?= e($bk['unit_name'] ?? '') ?>
                    · <?= e($bk['booking_date']) ?> (<?= e(substr($bk['start_time'], 0, 5)) ?>–<?= e(substr($bk['end_time'], 0, 5)) ?>)
                </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) $bk['total_amount'], 0) ?> ج.م</div>
                <?php
                    $statusColors = ['confirmed' => '#2563EB', 'checked_in' => '#059669', 'completed' => '#6B7280', 'cancelled' => '#DC2626', 'pending' => '#D97706'];
                    $statusLabels = ['confirmed' => 'مؤكد', 'checked_in' => 'حاضر', 'completed' => 'مكتمل', 'cancelled' => 'ملغي', 'pending' => 'معلق'];
                    $sc = $statusColors[$bk['status']] ?? '#6B7280';
                    $sl = $statusLabels[$bk['status']] ?? $bk['status'];
                    $pc = $bk['payment_status'] === 'paid' ? '#059669' : ($bk['payment_status'] === 'pending' ? '#D97706' : '#DC2626');
                    $pl = $bk['payment_status'] === 'paid' ? 'مدفوع' : ($bk['payment_status'] === 'pending' ? 'بانتظار الدفع' : 'غير مدفوع');
                ?>
                <span style="font-size:10px;padding:2px 6px;border-radius:4px;background:<?= $sc ?>20;color:<?= $sc ?>;"><?= $sl ?></span>
                <span style="font-size:10px;padding:2px 6px;border-radius:4px;background:<?= $pc ?>20;color:<?= $pc ?>;"><?= $pl ?></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 = {
        nationalId: '',
        name: '',
        isMember: false,
        memberId: null,
        effectiveType: 'non_member',
        unitId: null,
        unitName: '',
        facilityName: '',
        date: document.getElementById('bkDate').value,
        startTime: '',
        endTime: '',
        participants: 1,
        totalAmount: 0,
        pricing: null
    };

    function setStep(n) {
        for (var i = 1; i <= 4; 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 <= 4; 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'; }
        }
    }

    function showSuccess() {
        for (var i = 1; i <= 4; i++) { document.getElementById('step' + i).style.display = 'none'; }
        document.getElementById('stepSuccess').style.display = '';
        for (var j = 1; j <= 4; j++) {
            var c = document.getElementById('stepCircle' + j);
            c.style.background = '#059669'; c.style.color = '#fff';
        }
    }

    // Step 1: Identity inputs
    var membershipInput = document.getElementById('bkMembershipNo');
    var nidInput = document.getElementById('bkNid');
    var nameInput = document.getElementById('bkName');
    var btnStep1 = document.getElementById('btnStep1Next');

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

    function applyLookupResult(data) {
        if (!data.success) return;
        state.nationalId = data.national_id || '';
        state.effectiveType = data.effective_type;
        state.isMember = data.is_member;
        state.memberId = data.member_id;
        state.membershipNumber = data.membership_number || '';

        if (data.name) nameInput.value = data.name;
        if (data.national_id && !nidInput.value) nidInput.value = data.national_id;
        if (data.membership_number && !membershipInput.value) membershipInput.value = data.membership_number;
        document.getElementById('bkGender').textContent = data.gender === 'male' ? 'ذكر' : (data.gender === 'female' ? 'أنثى' : '—');
        document.getElementById('bkAge').textContent = data.age ? data.age + ' سنة' : '—';
        checkStep1Valid();
    }

    function showLookupBadge(box, data) {
        if (data.is_member) {
            box.style.background = '#ECFDF5';
            box.style.color = '#059669';
            box.innerHTML = '<strong>عضو فعال</strong>' + (data.membership_number ? ' — رقم ' + data.membership_number : '') + (data.name ? ' — ' + data.name : '');
        } else if (data.reason) {
            box.style.background = '#FEF3C7';
            box.style.color = '#92400E';
            box.innerHTML = '<strong>غير عضو</strong> — ' + data.reason;
        } else {
            box.style.background = '#F3F4F6';
            box.style.color = '#374151';
            box.innerHTML = 'غير عضو';
        }
        box.style.display = '';
    }

    // Membership number lookup
    var memberLookupTimer = null;
    membershipInput.addEventListener('input', function() {
        var val = this.value.replace(/\D/g, '');
        this.value = val;
        var box = document.getElementById('memberLookupResult');
        if (val.length < 1) { box.style.display = 'none'; return; }
        clearTimeout(memberLookupTimer);
        memberLookupTimer = setTimeout(function() {
            box.style.display = '';
            box.style.background = '#F3F4F6';
            box.style.color = '#6B7280';
            box.textContent = 'جاري البحث...';
            fetch('/sa/booking-wizard/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) {
                    applyLookupResult(data);
                    showLookupBadge(box, data);
                } else {
                    box.style.background = '#FEF2F2';
                    box.style.color = '#DC2626';
                    box.textContent = data.reason || 'رقم العضوية غير موجود';
                }
            });
        }, 400);
    });

    // NID lookup
    nidInput.addEventListener('input', function() {
        var val = this.value.replace(/\D/g, '');
        this.value = val;
        if (val.length === 14) {
            fetch('/sa/booking-wizard/lookup', {
                method: 'POST',
                headers: {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': csrfToken},
                body: JSON.stringify({national_id: val, _csrf_token: csrfToken})
            }).then(function(r) { return r.json(); }).then(function(data) {
                var box = document.getElementById('nidResult');
                if (data.success) {
                    applyLookupResult(data);
                    showLookupBadge(box, data);
                } else {
                    box.style.background = '#FEF2F2';
                    box.style.color = '#DC2626';
                    box.textContent = data.error || 'خطأ';
                    box.style.display = '';
                }
            });
        } else {
            document.getElementById('nidResult').style.display = 'none';
        }
    });

    btnStep1.addEventListener('click', function() {
        state.name = nameInput.value.trim();
        if (!state.name) return;
        setStep(2);
        loadFacilities();
    });

    // Step 2: Facilities
    function loadFacilities() {
        fetch('/sa/booking-wizard/units', {headers: {'X-Requested-With': 'XMLHttpRequest'}})
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (!data.success) return;
            var container = document.getElementById('facilitiesList');
            var html = '';
            data.facilities.forEach(function(fac) {
                html += '<div style="margin-bottom:8px;"><div style="font-size:13px;font-weight:600;color:#374151;margin-bottom:6px;padding:4px 0;border-bottom:1px solid #E5E7EB;">' + fac.name + '</div>';
                fac.units.forEach(function(u) {
                    var icon = u.booking_mode === 'exclusive' ? 'lock' : 'users';
                    html += '<div class="unit-card" data-unit-id="' + u.id + '" data-unit-name="' + u.name + '" data-facility-name="' + fac.name + '" style="padding:14px;border:2px solid #E5E7EB;border-radius:10px;margin-bottom:8px;cursor:pointer;touch-action:manipulation;min-height:56px;display:flex;align-items:center;justify-content:space-between;transition:border-color 0.15s;">';
                    html += '<div><div style="font-weight:600;font-size:14px;">' + u.name + '</div>';
                    html += '<div style="font-size:11px;color:#6B7280;">' + (u.booking_mode === 'exclusive' ? 'حجز كامل' : 'مشترك — سعة ' + u.max_capacity) + '</div></div>';
                    html += '<i data-lucide="' + icon + '" style="width:20px;height:20px;color:#9CA3AF;"></i>';
                    html += '</div>';
                });
                html += '</div>';
            });
            container.innerHTML = html;
            if (window.lucide) lucide.createIcons();

            container.querySelectorAll('.unit-card').forEach(function(card) {
                card.addEventListener('click', function() {
                    container.querySelectorAll('.unit-card').forEach(function(c) { c.style.borderColor = '#E5E7EB'; c.style.background = ''; });
                    this.style.borderColor = '#2563EB';
                    this.style.background = '#EFF6FF';
                    state.unitId = parseInt(this.dataset.unitId);
                    state.unitName = this.dataset.unitName;
                    state.facilityName = this.dataset.facilityName;
                    setTimeout(function() {
                        setStep(3);
                        document.getElementById('selectedUnitLabel').textContent = state.facilityName + ' — ' + state.unitName;
                        loadSlots();
                    }, 200);
                });
            });
        });
    }

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

    document.getElementById('unitSearchInput').addEventListener('input', function() {
        var q = this.value.toLowerCase();
        document.querySelectorAll('#facilitiesList > div').forEach(function(group) {
            var cards = group.querySelectorAll('.unit-card');
            var anyVisible = false;
            cards.forEach(function(card) {
                var match = (card.dataset.unitName + ' ' + card.dataset.facilityName).toLowerCase().indexOf(q) >= 0;
                card.style.display = match ? '' : 'none';
                if (match) anyVisible = true;
            });
            group.style.display = (!q || anyVisible) ? '' : 'none';
        });
    });

    // Step 3: Time slots
    var dateInput = document.getElementById('bkDate');
    var participantsInput = document.getElementById('bkParticipants');

    dateInput.addEventListener('change', function() {
        state.date = this.value;
        loadSlots();
    });

    participantsInput.addEventListener('change', function() {
        state.participants = parseInt(this.value) || 1;
        if (state.startTime) updatePricePreview();
    });

    function loadSlots() {
        if (!state.unitId || !state.date) return;
        var grid = document.getElementById('slotsGrid');
        grid.innerHTML = '<div style="text-align:center;padding:20px;color:#9CA3AF;grid-column:1/-1;">جاري التحميل...</div>';

        fetch('/sa/booking-wizard/slots?unit_id=' + state.unitId + '&date=' + state.date, {headers: {'X-Requested-With': 'XMLHttpRequest'}})
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (!data.success) { grid.innerHTML = '<div style="color:#DC2626;padding:20px;grid-column:1/-1;">' + (data.error || 'خطأ') + '</div>'; return; }
            var html = '';
            data.slots.forEach(function(s) {
                var bg, color, cursor, clickable;
                if (s.status === 'free') { bg = '#ECFDF5'; color = '#059669'; cursor = 'pointer'; clickable = true; }
                else if (s.status === 'partial') { bg = '#FEF3C7'; color = '#D97706'; cursor = 'pointer'; clickable = true; }
                else if (s.status === 'occupied') { bg = '#FEF2F2'; color = '#DC2626'; cursor = 'not-allowed'; clickable = false; }
                else { bg = '#F3F4F6'; color = '#9CA3AF'; cursor = 'not-allowed'; clickable = false; }

                html += '<div class="slot-btn" data-start="' + s.start_time + '" data-end="' + s.end_time + '" data-status="' + s.status + '" data-remaining="' + s.remaining_capacity + '" style="padding:10px 6px;border-radius:8px;text-align:center;background:' + bg + ';color:' + color + ';cursor:' + cursor + ';border:2px solid transparent;touch-action:manipulation;font-size:13px;font-weight:600;' + (!clickable ? 'opacity:0.7;' : '') + '">';
                html += s.start_time;
                if (s.status === 'partial') html += '<div style="font-size:10px;font-weight:400;">متبقي ' + s.remaining_capacity + '</div>';
                if (s.status === 'occupied' && s.booker) html += '<div style="font-size:9px;font-weight:400;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' + s.booker + '</div>';
                html += '</div>';
            });
            grid.innerHTML = html;

            grid.querySelectorAll('.slot-btn').forEach(function(btn) {
                if (btn.dataset.status === 'occupied' || btn.dataset.status === 'blackout') return;
                btn.addEventListener('click', function() {
                    grid.querySelectorAll('.slot-btn').forEach(function(b) { b.style.borderColor = 'transparent'; });
                    this.style.borderColor = '#2563EB';
                    state.startTime = this.dataset.start;
                    state.endTime = this.dataset.end;
                    document.getElementById('selectedSlotInfo').style.display = '';
                    document.getElementById('slotSummary').textContent = state.date + ' — ' + state.startTime + ' إلى ' + state.endTime;
                    document.getElementById('btnStep3Next').disabled = false;
                    updatePricePreview();
                });
            });
        });

        document.getElementById('selectedSlotInfo').style.display = 'none';
        document.getElementById('btnStep3Next').disabled = true;
    }

    function updatePricePreview() {
        var url = '/api/sa/bookings/price-preview?unit_id=' + state.unitId + '&date=' + state.date + '&start_time=' + state.startTime + '&end_time=' + state.endTime + '&participants=' + state.participants + '&is_member=' + (state.isMember ? '1' : '0');
        fetch(url, {headers: {'X-Requested-With': 'XMLHttpRequest'}})
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.pricing && data.pricing.total_amount !== undefined) {
                state.totalAmount = data.pricing.total_amount;
                state.pricing = data.pricing;
                document.getElementById('pricePreview').textContent = Number(data.pricing.total_amount).toLocaleString() + ' ج.م';
            } else {
                document.getElementById('pricePreview').textContent = '—';
            }
        }).catch(function() {
            document.getElementById('pricePreview').textContent = '—';
        });
    }

    document.getElementById('btnStep3Next').addEventListener('click', function() {
        state.participants = parseInt(participantsInput.value) || 1;
        setStep(4);
        renderConfirmation();
    });
    document.getElementById('btnStep3Back').addEventListener('click', function() { setStep(2); });

    // Step 4: Confirmation
    function renderConfirmation() {
        var memberBadge = state.isMember
            ? '<span style="padding:2px 8px;border-radius:4px;background:#ECFDF5;color:#059669;font-size:11px;font-weight:600;">عضو</span>'
            : '<span style="padding:2px 8px;border-radius:4px;background:#FEF3C7;color:#D97706;font-size:11px;font-weight:600;">غير عضو</span>';

        var html = '<div style="border:1px solid #E5E7EB;border-radius:10px;overflow:hidden;">';
        html += '<div style="padding:12px 16px;background:#F9FAFB;border-bottom:1px solid #E5E7EB;font-weight:600;font-size:14px;">ملخص الحجز</div>';
        html += '<table style="width:100%;font-size:13px;">';
        html += '<tr><td style="padding:10px 16px;font-weight:600;color:#6B7280;width:35%;">الحاجز</td><td style="padding:10px 16px;">' + state.name + ' ' + memberBadge + '</td></tr>';
        html += '<tr style="background:#F9FAFB;"><td style="padding:10px 16px;font-weight:600;color:#6B7280;">المرفق</td><td style="padding:10px 16px;">' + state.facilityName + ' — ' + state.unitName + '</td></tr>';
        html += '<tr><td style="padding:10px 16px;font-weight:600;color:#6B7280;">التاريخ</td><td style="padding:10px 16px;">' + state.date + '</td></tr>';
        html += '<tr style="background:#F9FAFB;"><td style="padding:10px 16px;font-weight:600;color:#6B7280;">الوقت</td><td style="padding:10px 16px;">' + state.startTime + ' — ' + state.endTime + '</td></tr>';
        html += '<tr><td style="padding:10px 16px;font-weight:600;color:#6B7280;">المشاركين</td><td style="padding:10px 16px;">' + state.participants + '</td></tr>';
        if (state.pricing) {
            html += '<tr style="background:#F9FAFB;"><td style="padding:10px 16px;font-weight:600;color:#6B7280;">السعر للفرد/ساعة</td><td style="padding:10px 16px;">' + Number(state.pricing.price_per_person).toLocaleString() + ' ج.م</td></tr>';
            html += '<tr><td style="padding:10px 16px;font-weight:600;color:#6B7280;">الفترة</td><td style="padding:10px 16px;">' + (state.pricing.bracket_name || '—') + '</td></tr>';
        }
        html += '<tr style="border-top:2px solid #E5E7EB;"><td style="padding:14px 16px;font-weight:800;font-size:16px;">الإجمالي</td><td style="padding:14px 16px;font-weight:800;font-size:18px;color:#2563EB;">' + Number(state.totalAmount).toLocaleString() + ' ج.م</td></tr>';
        html += '</table></div>';
        document.getElementById('confirmSummary').innerHTML = html;
    }

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

    document.getElementById('btnConfirmBook').addEventListener('click', function() {
        var btn = this;
        btn.disabled = true;
        btn.innerHTML = '<span>جاري الحجز...</span>';
        document.getElementById('step4Error').style.display = 'none';

        fetch('/sa/booking-wizard/book', {
            method: 'POST',
            headers: {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': csrfToken},
            body: JSON.stringify({
                unit_id: state.unitId,
                date: state.date,
                start_time: state.startTime,
                end_time: state.endTime,
                participants: state.participants,
                booker_name: state.name,
                national_id: state.nationalId,
                is_member: state.isMember,
                member_id: state.memberId || 0,
                _csrf_token: csrfToken
            })
        }).then(function(r) {
            if (!r.ok && r.status === 419) throw new Error('انتهت صلاحية الجلسة — يرجى تحديث الصفحة');
            return r.json();
        }).then(function(data) {
            if (data.success) {
                document.getElementById('successBookingNumber').textContent = 'رقم الحجز: ' + data.booking_number;
                showSuccess();
            } else {
                document.getElementById('step4Error').textContent = data.error || 'حدث خطأ';
                document.getElementById('step4Error').style.display = '';
                btn.disabled = false;
                btn.innerHTML = '<i data-lucide="banknote" style="width:20px;height:20px;vertical-align:middle;margin-left:6px;"></i> تأكيد وإرسال للخزينة';
                if (window.lucide) lucide.createIcons();
            }
        }).catch(function(err) {
            document.getElementById('step4Error').textContent = err.message || 'خطأ في الاتصال — يرجى تحديث الصفحة والمحاولة مرة أخرى';
            document.getElementById('step4Error').style.display = '';
            btn.disabled = false;
            btn.innerHTML = '<i data-lucide="banknote" style="width:20px;height:20px;vertical-align:middle;margin-left:6px;"></i> تأكيد وإرسال للخزينة';
            if (window.lucide) lucide.createIcons();
        });
    });

    document.getElementById('btnNewBooking').addEventListener('click', function() {
        state = {nationalId:'', name:'', isMember:false, memberId:null, effectiveType:'non_member', unitId:null, unitName:'', facilityName:'', date:document.getElementById('bkDate').value, startTime:'', endTime:'', participants:1, totalAmount:0, pricing:null};
        nidInput.value = '';
        nameInput.value = '';
        document.getElementById('nidResult').style.display = 'none';
        document.getElementById('bkGender').textContent = '—';
        document.getElementById('bkAge').textContent = '—';
        btnStep1.disabled = true;
        setStep(1);
    });

    setStep(1);
})();
</script>
<?php $__template->endSection(); ?>
