<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>مكتب الخدمة<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>
<div style="margin-bottom:16px;">
    <!-- Lookup Bar -->
    <div class="card" style="padding:20px 24px;display:flex;align-items:center;gap:16px;flex-wrap:wrap;">
        <i data-lucide="search" style="width:24px;height:24px;color:#6B7280;"></i>
        <input type="text" id="lookupNid" class="form-input" placeholder="الرقم القومي..." style="width:240px;direction:ltr;text-align:left;font-size:18px;padding:14px 16px;" maxlength="14">
        <button type="button" id="lookupBtn" class="btn btn-primary" style="padding:14px 32px;font-size:16px;">بحث</button>
        <div id="memberInfo" style="flex:1;min-width:200px;font-size:15px;"></div>
    </div>
</div>

<!-- Tabs -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px;">
    <button class="desk-tab active" data-tab="registration"><i data-lucide="user-plus" style="width:28px;height:28px;display:block;margin:0 auto 8px;"></i>تسجيل لاعب</button>
    <button class="desk-tab" data-tab="booking"><i data-lucide="calendar-check" style="width:28px;height:28px;display:block;margin:0 auto 8px;"></i>حجز ملعب</button>
    <button class="desk-tab" data-tab="ticket"><i data-lucide="ticket" style="width:28px;height:28px;display:block;margin:0 auto 8px;"></i>تذكرة نشاط</button>
    <button class="desk-tab" data-tab="locker"><i data-lucide="lock" style="width:28px;height:28px;display:block;margin:0 auto 8px;"></i>إيجار لوكر</button>
</div>

<!-- Tab: Registration -->
<div class="desk-panel active" id="panel-registration">
    <div class="card" style="padding:30px;text-align:center;">
        <p style="color:#6B7280;margin:0 0 15px;">لبدء تسجيل لاعب جديد أو إضافة لاعب لمجموعة:</p>
        <a href="/sa/registration" class="btn btn-primary" style="padding:10px 24px;">تسجيل لاعب جديد</a>
        <span style="margin:0 10px;color:#9CA3AF;">أو</span>
        <a href="/sa/players/create" class="btn btn-outline" style="padding:10px 24px;">إضافة لاعب بدون اشتراك</a>
    </div>
</div>

<!-- Tab: Booking -->
<div class="desk-panel" id="panel-booking" style="display:none;">
    <div class="card" style="padding:30px;text-align:center;">
        <p style="color:#6B7280;margin:0 0 15px;">لحجز ملعب أو مرفق:</p>
        <a href="/sa/booking-wizard" class="btn btn-primary" style="padding:10px 24px;" id="bookingWizardLink">فتح معالج الحجز</a>
    </div>
</div>

<!-- Tab: Ticket -->
<div class="desk-panel" id="panel-ticket" style="display:none;">
    <div class="card" style="padding:20px;">
        <h4 style="margin:0 0 16px;color:#1F2937;font-size:15px;">إصدار تذكرة نشاط</h4>
        <form id="ticketForm">
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">
                <div class="form-group">
                    <label class="form-label">نوع النشاط <span style="color:#DC2626;">*</span></label>
                    <select name="activity_type" class="form-select" required>
                        <option value="">-- اختر النشاط --</option>
                        <?php foreach ($activityTypes as $key => $label): ?>
                        <option value="<?= e($key) ?>"><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">اسم الضيف <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="guest_name" class="form-input" required placeholder="اسم الضيف" id="ticketGuestName">
                </div>
                <div class="form-group">
                    <label class="form-label">عدد الأشخاص</label>
                    <input type="number" name="guest_count" class="form-input" value="1" min="1" max="20" style="direction:ltr;text-align:left;">
                </div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-top:12px;">
                <div class="form-group">
                    <label class="form-label">المبلغ (ج.م)</label>
                    <input type="number" name="amount_paid" class="form-input" value="0" min="0" step="0.5" style="direction:ltr;text-align:left;">
                </div>
                <div class="form-group">
                    <label class="form-label">المرفق</label>
                    <select name="facility_id" class="form-select">
                        <option value="">-- اختياري --</option>
                        <?php foreach ($facilities as $f): ?>
                        <option value="<?= (int) $f['id'] ?>"><?= e($f['name_ar']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">ملاحظات</label>
                    <input type="text" name="notes" class="form-input" placeholder="اختياري">
                </div>
            </div>
            <input type="hidden" name="carnet_id" id="ticketCarnetId" value="">
            <input type="hidden" name="member_id" id="ticketMemberId" value="">
            <div style="margin-top:16px;">
                <button type="submit" class="btn btn-primary" style="padding:10px 30px;">إصدار التذكرة</button>
                <span id="ticketResult" style="margin-right:12px;font-size:13px;"></span>
            </div>
        </form>
    </div>
</div>

<!-- Tab: Locker -->
<div class="desk-panel" id="panel-locker" style="display:none;">
    <div class="card" style="padding:30px;text-align:center;">
        <p style="color:#6B7280;margin:0 0 15px;">لتأجير لوكر:</p>
        <a href="/sa/locker-rentals/create" class="btn btn-primary" style="padding:10px 24px;" id="lockerLink">فتح صفحة الإيجار</a>
    </div>
</div>

<style>
.desk-tab {
    padding:24px 16px;
    border:2px solid #E5E7EB;
    background:#fff;
    border-radius:12px;
    cursor:pointer;
    font-size:18px;
    font-weight:700;
    color:#6B7280;
    text-align:center;
    transition:all .15s;
    min-height:100px;
    display:flex;
    flex-direction:column;
    align-items:center;
    justify-content:center;
    -webkit-tap-highlight-color:transparent;
    user-select:none;
}
.desk-tab:hover { background:#F9FAFB;border-color:#93C5FD; }
.desk-tab:active { transform:scale(.97); }
.desk-tab.active { background:#EFF6FF;border-color:#2563EB;color:#1D4ED8;box-shadow:0 4px 12px rgba(37,99,235,.15); }
</style>

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

    var tabs = document.querySelectorAll('.desk-tab');
    var panels = document.querySelectorAll('.desk-panel');
    tabs.forEach(function(tab) {
        tab.addEventListener('click', function() {
            tabs.forEach(function(t) { t.classList.remove('active'); });
            panels.forEach(function(p) { p.style.display = 'none'; });
            this.classList.add('active');
            document.getElementById('panel-' + this.dataset.tab).style.display = 'block';
            history.replaceState(null, '', '#' + this.dataset.tab);
        });
    });

    // Restore tab from hash
    var hash = window.location.hash.replace('#', '');
    if (hash && document.querySelector('[data-tab="' + hash + '"]')) {
        document.querySelector('[data-tab="' + hash + '"]').click();
    }

    // Lookup
    var lookupState = { member_id: null, carnet_id: null, name: '' };
    document.getElementById('lookupBtn').addEventListener('click', doLookup);
    document.getElementById('lookupNid').addEventListener('keydown', function(e) {
        if (e.key === 'Enter') { e.preventDefault(); doLookup(); }
    });

    function doLookup() {
        var nid = document.getElementById('lookupNid').value.trim();
        if (!nid) return;
        document.getElementById('memberInfo').innerHTML = '<span style="color:#6B7280;font-size:13px;">جاري البحث...</span>';

        fetch('/sa/service-desk/lookup', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
            body: '_csrf_token=' + encodeURIComponent(document.querySelector('meta[name="csrf-token"]')?.content || '') + '&national_id=' + encodeURIComponent(nid)
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (!data.success) {
                document.getElementById('memberInfo').innerHTML = '<span style="color:#DC2626;font-size:13px;">' + escHtml(data.error) + '</span>';
                return;
            }
            var m = data.membership;
            var html = '<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">';
            if (m && m.is_valid) {
                html += '<span style="background:#05966915;color:#059669;padding:3px 10px;border-radius:6px;font-size:12px;font-weight:600;">عضو فعال</span>';
                html += '<span style="font-size:13px;font-weight:600;">' + escHtml(m.member_name || '') + '</span>';
                html += '<span style="font-size:12px;color:#6B7280;">عضوية: ' + escHtml(m.membership_number || '') + '</span>';
                lookupState.member_id = m.member_id || null;
                lookupState.name = m.member_name || '';
            } else {
                html += '<span style="background:#DC262615;color:#DC2626;padding:3px 10px;border-radius:6px;font-size:12px;font-weight:600;">غير عضو</span>';
                lookupState.member_id = null;
                lookupState.name = '';
            }
            if (data.player) {
                html += '<span style="font-size:12px;color:#2563EB;">لاعب: ' + escHtml(data.player.full_name_ar) + ' (' + escHtml(data.player.registration_serial) + ')</span>';
                if (!lookupState.name) lookupState.name = data.player.full_name_ar;
            }
            if (data.carnet) {
                var remaining = (data.carnet.max_invitations || 0) - (data.carnet.used_count || 0);
                html += '<span style="font-size:11px;color:#6B7280;">كارنيه: متبقي ' + remaining + ' دعوة</span>';
                lookupState.carnet_id = data.carnet.id;
            } else {
                lookupState.carnet_id = null;
            }
            html += '</div>';
            document.getElementById('memberInfo').innerHTML = html;

            // Auto-fill ticket form
            document.getElementById('ticketGuestName').value = lookupState.name;
            document.getElementById('ticketCarnetId').value = lookupState.carnet_id || '';
            document.getElementById('ticketMemberId').value = lookupState.member_id || '';

            // Update booking wizard link with member context
            if (lookupState.member_id) {
                document.getElementById('bookingWizardLink').href = '/sa/booking-wizard?member_id=' + lookupState.member_id;
                document.getElementById('lockerLink').href = '/sa/locker-rentals/create?member_id=' + lookupState.member_id;
            }
        });
    }

    // Ticket form submission
    document.getElementById('ticketForm').addEventListener('submit', function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        var params = new URLSearchParams(formData);
        params.append('_csrf_token', document.querySelector('meta[name="csrf-token"]')?.content || '');

        document.getElementById('ticketResult').innerHTML = '<span style="color:#6B7280;">جاري الإصدار...</span>';

        fetch('/sa/service-desk/ticket', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
            body: params.toString()
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.success) {
                document.getElementById('ticketResult').innerHTML = '<span style="color:#059669;">✓ ' + escHtml(data.message) + '</span>';
                document.getElementById('ticketForm').reset();
            } else {
                document.getElementById('ticketResult').innerHTML = '<span style="color:#DC2626;">' + escHtml(data.error) + '</span>';
            }
        });
    });

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