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

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

<!-- Filters -->
<div class="card" style="margin-bottom:20px;padding:15px;">
    <form method="GET" action="/sa/pool-tickets" style="display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap;">
        <div>
            <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;">حمام السباحة</label>
            <select name="facility_id" class="form-input" style="min-width:200px;">
                <option value="">-- اختر --</option>
                <?php foreach ($facilities as $f): ?>
                <option value="<?= (int) $f['id'] ?>" <?= $facilityId === (int) $f['id'] ? 'selected' : '' ?>><?= e($f['name_ar']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;">التاريخ</label>
            <input type="date" name="date" value="<?= e($date) ?>" class="form-input">
        </div>
        <button type="submit" class="btn btn-primary">عرض</button>
    </form>
</div>

<?php if ($facilityId > 0): ?>
<!-- Issue Ticket Form -->
<div class="card" style="margin-bottom:20px;padding:15px;">
    <h3 style="font-size:14px;font-weight:700;margin-bottom:12px;">إصدار تذكرة جديدة</h3>
    <form id="issueTicketForm" style="display:grid;grid-template-columns:repeat(auto-fit, minmax(180px, 1fr));gap:10px;align-items:end;">
        <input type="hidden" name="facility_id" value="<?= $facilityId ?>">
        <input type="hidden" name="booking_date" value="<?= e($date) ?>">
        <div>
            <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;">وقت البداية</label>
            <input type="time" name="start_time" class="form-input" required>
        </div>
        <div>
            <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;">وقت النهاية</label>
            <input type="time" name="end_time" class="form-input" required>
        </div>
        <div>
            <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;">النوع</label>
            <select name="is_member" class="form-input">
                <option value="0">زائر</option>
                <option value="1">عضو</option>
            </select>
        </div>
        <div>
            <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;">الاسم</label>
            <input type="text" name="guest_name" class="form-input" placeholder="اسم الزائر">
        </div>
        <div>
            <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px;">الرقم القومي</label>
            <input type="text" name="guest_national_id" class="form-input" placeholder="اختياري" maxlength="14">
        </div>
        <div>
            <button type="submit" class="btn btn-primary" style="width:100%;">إصدار تذكرة</button>
        </div>
    </form>
    <div id="ticketResult" style="margin-top:10px;display:none;"></div>
</div>

<!-- Active Tickets -->
<div class="card">
    <div style="padding:12px 15px;border-bottom:1px solid #E5E7EB;">
        <span style="font-weight:700;">التذاكر النشطة (<?= count($tickets) ?>)</span>
    </div>
    <?php if (empty($tickets)): ?>
    <div style="padding:30px;text-align:center;color:#9CA3AF;">لا توجد تذاكر نشطة</div>
    <?php else: ?>
    <table style="width:100%;border-collapse:collapse;font-size:13px;">
        <thead>
            <tr style="background:#F9FAFB;">
                <th style="padding:10px;border-bottom:1px solid #E5E7EB;text-align:right;">#</th>
                <th style="padding:10px;border-bottom:1px solid #E5E7EB;text-align:right;">الاسم</th>
                <th style="padding:10px;border-bottom:1px solid #E5E7EB;text-align:center;">نوع</th>
                <th style="padding:10px;border-bottom:1px solid #E5E7EB;text-align:right;">الوقت</th>
                <th style="padding:10px;border-bottom:1px solid #E5E7EB;text-align:right;">المبلغ</th>
                <th style="padding:10px;border-bottom:1px solid #E5E7EB;text-align:center;">الحالة</th>
                <th style="padding:10px;border-bottom:1px solid #E5E7EB;text-align:center;">إجراء</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($tickets as $t): ?>
            <?php
                $statusLabels = ['issued' => 'صادرة', 'active' => 'داخل', 'completed' => 'خرج', 'cancelled' => 'ملغاة'];
                $statusColors = ['issued' => '#DBEAFE', 'active' => '#ECFDF5', 'completed' => '#F3F4F6', 'cancelled' => '#FEE2E2'];
            ?>
            <tr style="border-bottom:1px solid #F3F4F6;">
                <td style="padding:10px;"><?= (int) $t['id'] ?></td>
                <td style="padding:10px;"><?= e($t['guest_name'] ?? 'عضو') ?></td>
                <td style="padding:10px;text-align:center;">
                    <span style="background:<?= $t['is_member'] ? '#ECFDF5' : '#FEF3C7' ?>;padding:2px 8px;border-radius:8px;font-size:11px;"><?= $t['is_member'] ? 'عضو' : 'زائر' ?></span>
                </td>
                <td style="padding:10px;font-size:12px;"><?= e($t['start_time'] ?? '') ?> - <?= e($t['end_time'] ?? '') ?></td>
                <td style="padding:10px;"><?= number_format((float) ($t['amount_paid'] ?? 0), 2) ?> ج.م</td>
                <td style="padding:10px;text-align:center;">
                    <span style="background:<?= $statusColors[$t['status']] ?? '#F3F4F6' ?>;padding:2px 8px;border-radius:8px;font-size:11px;font-weight:600;"><?= e($statusLabels[$t['status']] ?? $t['status']) ?></span>
                </td>
                <td style="padding:10px;text-align:center;">
                    <?php if ($t['status'] === 'issued'): ?>
                    <button onclick="ticketAction(<?= (int) $t['id'] ?>, 'entry')" class="btn btn-sm" style="font-size:11px;padding:3px 8px;background:#059669;color:white;border:none;border-radius:4px;cursor:pointer;">دخول</button>
                    <button onclick="ticketAction(<?= (int) $t['id'] ?>, 'cancel')" class="btn btn-sm" style="font-size:11px;padding:3px 8px;background:#DC2626;color:white;border:none;border-radius:4px;cursor:pointer;">إلغاء</button>
                    <?php elseif ($t['status'] === 'active'): ?>
                    <button onclick="ticketAction(<?= (int) $t['id'] ?>, 'exit')" class="btn btn-sm" style="font-size:11px;padding:3px 8px;background:#D97706;color:white;border:none;border-radius:4px;cursor:pointer;">خروج</button>
                    <?php else: ?>
                    -
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</div>
<?php endif; ?>

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

    const form = document.getElementById('issueTicketForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            const fd = new FormData(form);
            const data = {};
            fd.forEach((v,k) => data[k] = v);

            fetch('/sa/pool-tickets/issue', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-Token': document.querySelector('meta[name=csrf-token]')?.content || ''},
                body: new URLSearchParams(data)
            })
            .then(r => r.json())
            .then(res => {
                const el = document.getElementById('ticketResult');
                if (res.success) {
                    el.innerHTML = '<div style="background:#ECFDF5;padding:8px 12px;border-radius:6px;color:#059669;font-size:13px;">تم إصدار التذكرة بنجاح — المبلغ: ' + (res.price || 0) + ' ج.م</div>';
                    el.style.display = 'block';
                    setTimeout(() => location.reload(), 1500);
                } else {
                    el.innerHTML = '<div style="background:#FEE2E2;padding:8px 12px;border-radius:6px;color:#DC2626;font-size:13px;">' + (res.error || 'خطأ') + '</div>';
                    el.style.display = 'block';
                }
            });
        });
    }
});

function ticketAction(id, action) {
    fetch('/sa/pool-tickets/' + id + '/' + action, {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-Token': document.querySelector('meta[name=csrf-token]')?.content || ''},
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) { location.reload(); }
        else { alert(res.error || 'خطأ'); }
    });
}
</script>
<?php $__template->endSection(); ?>
