<?php
// trap.php - QR Trap udający zagadkę
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
require 'db.php';

// Formatujemy tak samo jak puzzle.php aby nie wzbudzać podejrzeń
$puzzle_id = isset($_GET['id']) ? $_GET['id'] : 'T1';
$token = isset($_GET['t']) ? $_GET['t'] : '';

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IT Party</title>
    <link
        href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&family=Rajdhani:wght@300;500;700&display=swap"
        rel="stylesheet">
    <script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
    <style>
        :root {
            --stark-blue: #00a8ff;
            --stark-cyan: #00f3ff;
            --gold-accent: #ffdb58;
            --alert-red: #ff3333;
            --hud-bg: rgba(0, 10, 20, 0.9);
            --hud-border: #00f3ff;
        }

        body {
            background-color: #000;
            background-image:
                radial-gradient(circle at 50% 50%, #001a33 0%, #000000 100%),
                linear-gradient(0deg, rgba(0, 168, 255, 0.05) 1px, transparent 1px);
            background-size: 100% 100%, 40px 40px;
            color: #fff;
            font-family: 'Rajdhani', sans-serif;
            margin: 0;
            padding: 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #ui-container {
            width: 95%;
            max-width: 600px;
            background: var(--hud-bg);
            border: 2px solid var(--hud-border);
            padding: 30px;
            box-sizing: border-box;
            box-shadow: 0 0 30px rgba(0, 243, 255, 0.2);
            position: relative;
        }

        #user-identity {
            position: absolute;
            top: -20px;
            right: 20px;
            background: #000;
            padding: 5px 15px;
            border: 1px solid var(--stark-blue);
            font-family: 'Orbitron';
            font-size: 0.8rem;
            display: none;
        }

        .step-container {
            display: none;
        }

        .active-step {
            display: block;
        }

        .tech-frame {
            border: 1px solid var(--stark-blue);
            background: rgba(0, 168, 255, 0.05);
            padding: 20px;
            margin: 20px 0;
            position: relative;
        }

        .status-message {
            text-align: center;
            font-weight: bold;
            letter-spacing: 2px;
            margin: 15px 0;
            text-transform: uppercase;
            font-size: 1.1rem;
        }

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

        #reader {
            width: 100%;
            border: 2px solid var(--stark-blue);
            background: #000;
        }

        .trap-message {
            text-align: center;
            font-family: 'Orbitron';
            color: var(--alert-red);
            font-size: 1.2rem;
            line-height: 1.6;
        }
    </style>
</head>

<body>

    <div id="ui-container">
        <div id="user-identity">
            IMPREZOWICZ: <span id="id-display" style="color: var(--gold-accent);">...</span>
        </div>

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

        <!-- STEP 2: Trap Notification -->
        <div id="step-trap" class="step-container">
            <div class="tech-frame" style="border-color: var(--alert-red); background: rgba(255, 51, 51, 0.1);">
                <div class="trap-message">
                    TA ZAGADKA TO PUŁAPKA.<br>
                    WPADŁEŚ I PONOSISZ TEGO KONSEKWENCJE.<br>
                    <span style="font-size: 2.5rem; display: block; margin-top: 20px;">TRACISZ 5 PUNKTÓW</span>
                </div>
            </div>
            <div
                style="text-align: center; border-top: 1px solid var(--stark-blue); padding-top: 20px; color: var(--stark-cyan); letter-spacing: 1px; font-weight: bold; text-transform: uppercase; margin-top: 20px;">
                Rozejrzyj się wokół! <br> <span style="color: var(--gold-accent); font-size: 0.9rem;">W sali ukrytych
                    jest jeszcze wiele innych (prawdziwych) zagadek.</span>
            </div>
        </div>
    </div>

    <script>
        const html5QrCode = new Html5Qrcode("reader");
        let guestId = 0;
        let isProcessing = false;

        window.onload = () => {
            startScanner();
        };

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

        function onScanSuccess(decodedText) {
            if (isProcessing) return;
            html5QrCode.stop().then(() => {
                verifyGuest(decodedText);
            });
        }

        async function verifyGuest(qrCode) {
            isProcessing = true;
            try {
                const response = await fetch('check_guest.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ qr_code: qrCode })
                });
                const data = await response.json();

                if (data.status === 'success') {
                    guestId = data.guest_id;
                    document.getElementById('id-display').innerText = data.guest_name.toUpperCase();
                    document.getElementById('user-identity').style.display = 'block';

                    penalizeUser();
                } else {
                    document.getElementById('id-status').innerText = "NIEZNANY IMPREZOWICZ - ODMOWA DOSTĘPU";
                    document.getElementById('id-status').classList.add('status-error');
                    setTimeout(startScanner, 2000);
                    isProcessing = false;
                }
            } catch (e) {
                alert("Błąd połączenia z bazą S.H.I.E.L.D.");
                location.reload();
            }
        }

        async function penalizeUser() {
            try {
                await fetch('penalize_trap.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ guest_id: guestId })
                });

                // Zawsze wyświetlamy komunikat pułapki
                document.getElementById('step-id').style.display = 'none';
                document.getElementById('step-trap').style.display = 'block';

            } catch (e) {
                console.error("Penalty error:", e);
                // Mimo błędu zapisu kary, pokazujemy komunikat dla efektu psychologicznego
                document.getElementById('step-id').style.display = 'none';
                document.getElementById('step-trap').style.display = 'block';
            }
        }
    </script>

</body>

</html>