<!DOCTYPE html>
<html lang="pl">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>S.H.I.E.L.D. DISPENSER CONTROL</title>
    <!-- Fonts -->
    <link
        href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&family=Rajdhani:wght@300;500;700&display=swap"
        rel="stylesheet">
    <!-- HTML5-QRCode Library -->
    <script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
    <style>
        :root {
            --stark-blue: #00a8ff;
            --stark-cyan: #00f3ff;
            --reactor-core: #ffffff;
            --hud-bg: rgba(0, 10, 20, 0.85);
            --hud-border: rgba(0, 243, 255, 0.6);
            --alert-red: #ff3333;
            --gold-accent: #ffd700;
        }

        body {
            background-color: #000;
            background-image:
                radial-gradient(circle at 50% 50%, #051a2e 0%, #000000 100%),
                linear-gradient(0deg, rgba(0, 243, 255, 0.03) 1px, transparent 1px),
                linear-gradient(90deg, rgba(0, 243, 255, 0.03) 1px, transparent 1px);
            background-size: 100% 100%, 40px 40px, 40px 40px;
            color: var(--stark-cyan);
            font-family: 'Rajdhani', sans-serif;
            margin: 0;
            padding: 0;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            perspective: 1000px;
        }

        #ui-container {
            width: 90%;
            max-width: 550px;
            height: auto;
            max-height: 90%;
            position: relative;
            z-index: 10;
            background: var(--hud-bg);
            border: 2px solid var(--hud-border);
            clip-path: polygon(30px 0, 100% 0, 100% calc(100% - 30px), calc(100% - 30px) 100%, 0 100%, 0 30px);
            padding: 20px;
            box-sizing: border-box;
            backdrop-filter: blur(10px);
            box-shadow: 0 0 50px rgba(0, 243, 255, 0.2);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            overflow-y: auto;
        }

        h1 {
            font-family: 'Orbitron', sans-serif;
            text-align: center;
            color: var(--stark-blue);
            text-transform: uppercase;
            letter-spacing: 4px;
            margin-bottom: 5px;
            text-shadow: 0 0 10px var(--stark-blue);
            font-weight: 900;
        }

        .sub-header {
            text-align: center;
            font-size: 0.8rem;
            color: var(--stark-cyan);
            letter-spacing: 2px;
            margin-bottom: 30px;
            opacity: 0.8;
        }

        .step-container {
            display: none;
            flex-direction: column;
            align-items: center;
            transition: opacity 0.5s ease;
            width: 100%;
        }

        .active-step {
            display: flex;
        }

        .tech-frame {
            width: 100%;
            height: 300px;
            border: 2px solid var(--stark-cyan);
            box-shadow: 0 0 20px var(--stark-cyan);
            position: relative;
            overflow: hidden;
            margin-bottom: 20px;
        }

        video {
            width: 100% !important;
            height: 100% !important;
            object-fit: cover;
        }

        .drink-buttons {
            display: grid;
            grid-template-columns: 1fr;
            gap: 15px;
            width: 100%;
            margin-top: 20px;
        }

        button {
            background: transparent;
            border: 2px solid var(--stark-cyan);
            color: var(--stark-cyan);
            padding: 20px;
            font-family: 'Orbitron';
            cursor: pointer;
            text-transform: uppercase;
            transition: 0.3s;
            font-size: 1.2rem;
            width: 100%;
            letter-spacing: 2px;
        }

        button:hover {
            background: var(--stark-cyan);
            color: #000;
            box-shadow: 0 0 20px var(--stark-cyan);
        }

        #pouring-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
            z-index: 1000;
            display: none;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
            backdrop-filter: blur(15px);
        }

        .pouring-text {
            font-family: 'Orbitron';
            font-size: 2.5rem;
            color: var(--gold-accent);
            text-shadow: 0 0 20px var(--gold-accent);
            animation: blink 1s infinite;
        }

        @keyframes blink {
            50% {
                opacity: 0.3;
            }
        }

        .status-message {
            margin-top: 10px;
            font-size: 1.1rem;
            text-transform: uppercase;
            font-weight: bold;
            letter-spacing: 1px;
            text-align: center;
        }

        .status-error {
            color: var(--alert-red);
            text-shadow: 0 0 10px var(--alert-red);
        }

        #guest-info {
            background: rgba(0, 243, 255, 0.1);
            border-left: 3px solid var(--stark-cyan);
            padding: 15px;
            margin-bottom: 20px;
            text-align: center;
            width: 100%;
            box-sizing: border-box;
        }
    </style>
</head>

<body>

    <div id="ui-container">
        <h1>STACJA NALEWANIA</h1>
        <div class="sub-header">AUTORYZACJA BIOMETRYCZNA WYMAGANA</div>

        <!-- STEP 1: SCAN QR -->
        <div id="step-scan" class="step-container active-step">
            <div id="reader" class="tech-frame"></div>
            <div id="status" class="status-message">ZESKANUJ SWÓJ KOD</div>
        </div>

        <!-- STEP 2: CHOOSE DRINK -->
        <div id="step-drink" class="step-container">
            <div id="guest-info">
                WITAJ: <span id="guest-name" style="color: var(--gold-accent); font-weight: bold;">---</span>
            </div>
            <div class="drink-buttons">
                <button onclick="pour('wodka')">Wódka</button>
                <button onclick="pour('whisky')">Whisky</button>
                <button onclick="pour('nalewka')">Nalewka</button>
                <button onclick="reset()"
                    style="border-color: var(--alert-red); color: var(--alert-red); margin-top: 10px; font-size: 0.8rem; padding: 10px;">ANULUJ</button>
            </div>
        </div>
    </div>

    <!-- POURING OVERLAY -->
    <div id="pouring-overlay">
        <div class="pouring-text">NALEWANIE TRUNKU...</div>
        <div style="color: var(--stark-cyan); margin-top: 20px; font-family: 'Rajdhani'; letter-spacing: 2px;">PROSZĘ
            PODSTAWIĆ SZKLANKĘ</div>
    </div>

    <script>
        const html5QrCode = new Html5Qrcode("reader");
        let currentGuestId = null;

        function startScanner() {
            const config = { fps: 15, qrbox: { width: 250, height: 250 } };
            html5QrCode.start(
                { facingMode: "user" },
                config,
                onScanSuccess,
                (err) => { }
            ).catch(err => {
                document.getElementById('status').innerText = "BŁĄD KAMERY";
                document.getElementById('status').classList.add('status-error');
            });
        }

        async function onScanSuccess(decodedText) {
            html5QrCode.stop().then(async () => {
                document.getElementById('status').innerText = "WERYFIKACJA...";
                try {
                    const response = await fetch('check_guest.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ qr_code: decodedText })
                    });
                    const data = await response.json();

                    if (data.status === 'success') {
                        currentGuestId = data.guest_id;
                        document.getElementById('guest-name').innerText = data.guest_name.toUpperCase();
                        showStep('drink');
                    } else {
                        document.getElementById('status').innerText = "NIEZNANY KOD";
                        document.getElementById('status').classList.add('status-error');
                        setTimeout(startScanner, 2000);
                    }
                } catch (e) {
                    document.getElementById('status').innerText = "BŁĄD POŁĄCZENIA";
                    setTimeout(startScanner, 2000);
                }
            });
        }

        function showStep(step) {
            document.getElementById('step-scan').style.display = 'none';
            document.getElementById('step-drink').style.display = 'none';
            document.getElementById('step-' + step).style.display = 'flex';
        }

        async function pour(drink) {
            if (!currentGuestId) {
                alert("Błąd: Proszę najpierw zeskanować kod!");
                return;
            }

            document.getElementById('pouring-overlay').style.display = 'flex';
            console.log(`Próba nalania: ${drink}, ID: ${currentGuestId}`);

            try {
                // Using a relative path with a cache buster and explicit method
                const response = await fetch('trigger_pour.php?t=' + Date.now(), {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        guest_id: currentGuestId,
                        drink: drink
                    })
                });

                const data = await response.json();
                console.log("Server response:", data);

                if (data.status !== 'success') {
                    console.error("Błąd serwera:", data.message);
                }
            } catch (err) {
                console.error("Błąd połączenia:", err);
            }

            // Always wait 5s as per requirement
            setTimeout(() => {
                document.getElementById('pouring-overlay').style.display = 'none';
                reset();
            }, 5000);
        }

        function reset() {
            currentGuestId = null;
            showStep('scan');
            document.getElementById('status').innerText = "ZESKANUJ SWÓJ KOD";
            document.getElementById('status').classList.remove('status-error');
            startScanner();
        }

        // Initialize
        window.onload = startScanner;
    </script>
</body>

</html>