@php
    use Illuminate\Support\Str;
@endphp
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Gate Ticket</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css" rel="stylesheet"/>
    <style>
        :root { --accent:#ff7f45; --text:#212529; }
        body { background:#f8f9fa; color:var(--text); font-family: Inter, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Apple Color Emoji","Segoe UI Emoji"; }
        .banner { width:100%; height:160px; object-fit: cover; border-radius:1rem; }
        .page { max-width: 480px; margin: 0 auto; padding: 0 1rem; }
        .card { border-radius: 1rem; box-shadow: 0 0.75rem 1.25rem rgba(0,0,0,.08); }
        .cta-btn { background: var(--accent); border:none; border-radius:999px; font-weight:600; letter-spacing:.03em; color:#fff; padding-top:.6rem; }
        .qr { width:180px; height:180px; }
        .copy-btn { cursor:pointer; }
        .mpesa-logo { width:40%; height:auto; }
        .phone-input { font-size:1.1rem; padding-top:.6rem; padding-bottom:.6rem; }
        .phone-input::placeholder { color:#9aa0a6; opacity:1; }
    </style>
</head>
<body>
    @php
        $imgPath = $event?->event_image;
        if ($imgPath) {
            $bannerSrc = Str::startsWith($imgPath, ['http://','https://']) ? $imgPath : asset($imgPath);
        } else {
            $bannerSrc = 'https://placehold.co/1200x380?text=Festival+Banner';
        }
    @endphp

    <div class="page">
        <img src="{{ $bannerSrc }}" alt="Festival" class="banner mt-3">
        <div class="card mt-3">
            <div class="card-body">
                <h5 class="fw-semibold mb-2">{{ $event?->name ?? 'PACE Teenz Festival' }}</h5>
                <div class="text-center mb-3">
                    <img src="https://upload.wikimedia.org/wikipedia/commons/1/15/M-PESA_LOGO-01.svg" alt="M-Pesa" class="mpesa-logo" loading="lazy">
                </div>
                <p class="text-muted mb-3">Use M-Pesa Registered Number:</p>
                <form id="gate-form" action="{{ route('buy-ticket') }}" method="POST">
                    @csrf
                    <div class="mb-4">
                        <label class="form-label">Phone Number</label>
                        <input type="tel" class="form-control form-control-lg phone-input" name="phone" placeholder="Enter phone number" required pattern="^(?:\+254|0)?[17]\d{8}$" title="Enter a valid Kenyan number starting 07 or 01">
                    </div>
                    <input type="hidden" name="firstName" value="Gate">
                    <input type="hidden" name="lastName" value="Guest">
                    <input type="hidden" name="email" value="guest@pacesetter.co.ke">
                    <input type="hidden" name="school" value="Gate">
                    <input type="hidden" name="ticket_type" value="gate">
                    <input type="hidden" name="ticket_quantity" value="1">
                    <input type="hidden" name="event_id" value="{{ $event?->id ?? 1 }}">
                    <button type="submit" class="btn btn-lg cta-btn w-100 mt-2">Gate Ticket – Ksh 1,000</button>
                </form>
                <div id="status" class="mt-3" style="display:none"></div>
            </div>
        </div>

        <div id="success-card" class="card mt-3" style="display:none">
            <div class="card-body text-center">
                <div class="mb-2">Payment request sent. Complete it on your phone.</div>
                <div class="mb-2"><span class="badge bg-success">Reference</span> <span id="ref" class="fw-semibold"></span> <i class="bi bi-clipboard copy-btn" id="copy"></i></div>
                <div class="d-flex flex-column align-items-center gap-2">
                    <img id="qr" class="qr rounded" alt="QR">
                    <a id="open-ticket" class="btn btn-outline-primary btn-sm" target="_blank">Open Ticket</a>
                </div>
                <div class="mt-3">
                    <button id="validate" class="btn btn-success btn-sm">Validate Payment</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        const form = document.getElementById('gate-form');
        const statusBox = document.getElementById('status');
        const successCard = document.getElementById('success-card');
        const refEl = document.getElementById('ref');
        const qrEl = document.getElementById('qr');
        const openEl = document.getElementById('open-ticket');
        const copyEl = document.getElementById('copy');
        const validateBtn = document.getElementById('validate');
        let checkoutId = null;
        let reference = null;

        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            statusBox.style.display = 'block';
            statusBox.className = 'alert alert-info';
            statusBox.textContent = 'Sending payment request...';
            const fd = new FormData(form);
            try {
                const res = await fetch(form.action, { method:'POST', body:fd, headers:{ 'X-Requested-With':'XMLHttpRequest', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content } });
                const data = await res.json();
                if (!res.ok || data.status !== 'success') throw new Error(data.message || 'Payment request failed');
                reference = data.data.ticket.reference;
                checkoutId = data.data.payment?.CheckoutRequestID || null;
                statusBox.className = 'alert alert-success';
                statusBox.textContent = 'Payment request sent. Check your phone to approve.';
                refEl.textContent = reference;
                copyEl.onclick = () => { navigator.clipboard.writeText(reference); };
                const verifyUrl = `${window.location.origin}/ticket/verify/${reference}`;
                qrEl.src = `https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=${encodeURIComponent(verifyUrl)}`;
                openEl.href = `${window.location.origin}/get/ticket/${reference}`;
                successCard.style.display = 'block';
                startPolling(reference);
            } catch(err) {
                statusBox.className = 'alert alert-danger';
                statusBox.textContent = err.message;
            }
        });

        validateBtn.addEventListener('click', async () => {
            if (!checkoutId) return;
            validateBtn.disabled = true;
            validateBtn.textContent = 'Validating...';
            try {
                const res = await fetch(`${window.location.origin}/api/v1/c2b-stk-validation`, { method:'POST', headers:{ 'Content-Type':'application/json' }, body: JSON.stringify({ checkoutRequestID: checkoutId }) });
                const data = await res.json();
                validateBtn.disabled = false;
                validateBtn.textContent = 'Validate Payment';
                if (data && data.response && data.response.payment_status === 'completed') {
                    window.location.href = `${window.location.origin}/get/ticket/${reference}`;
                }
            } catch(e) {
                validateBtn.disabled = false;
                validateBtn.textContent = 'Validate Payment';
            }
        });

        function startPolling(ref) {
            let attempts = 0;
            const maxAttempts = 40;
            const intervalMs = 3000;
            const timer = setInterval(async () => {
                attempts++;
                try {
                    const res = await fetch(`${window.location.origin}/api/v1/ticket-status/${encodeURIComponent(ref)}`);
                    const data = await res.json();
                    if (res.ok && data.payment_status === 'completed') {
                        clearInterval(timer);
                        window.location.href = `${window.location.origin}/get/ticket/${ref}`;
                    }
                } catch(e) {}
                if (attempts >= maxAttempts) {
                    clearInterval(timer);
                }
            }, intervalMs);
        }
    </script>
</body>
</html>
