<?php
// puzzle.php
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';

$puzzle_id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$token = isset($_GET['t']) ? $_GET['t'] : '';
$salt = "S.H.I.E.L.D._SALT_2026";

// Prosta weryfikacja tokena
$expected_token = md5($puzzle_id . $salt);
$access_granted = ($puzzle_id > 0 && $token === $expected_token);

$puzzle = null;
if ($access_granted) {
    $data_file = 'data.json';
    if (file_exists($data_file)) {
        $puzzles = json_decode(file_get_contents($data_file), true);
        foreach ($puzzles as $p) {
            if ($p['id'] === $puzzle_id) {
                $puzzle = $p;
                break;
            }
        }
    }
}

if (!$puzzle) {
    $access_granted = false;
}
?>
<!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>
    <!-- Prism.js for code highlighting -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet" />
    <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;
            --success-green: #00ff88;
        }

        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;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            overflow-x: hidden;
        }

        #ui-container {
            width: 95%;
            max-width: 600px;
            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: 30px;
            box-sizing: border-box;
            backdrop-filter: blur(10px);
            box-shadow: 0 0 50px rgba(0, 243, 255, 0.2);
            position: relative;
            z-index: 10;
        }

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

        .step-container {
            display: none;
            flex-direction: column;
            align-items: center;
            width: 100%;
        }

        .active-step {
            display: flex;
        }

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

        #reader {
            width: 100%;
        }

        .status-message {
            margin-top: 15px;
            text-transform: uppercase;
            font-weight: bold;
            text-align: center;
            min-height: 1.5em;
        }

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

        .status-success {
            color: var(--success-green);
            text-shadow: 0 0 10px var(--success-green);
        }

        /* Puzzle Styling */
        .puzzle-card {
            width: 100%;
        }

        .code-block {
            margin-bottom: 20px;
            border: 1px solid var(--stark-blue);
            background: rgba(0, 0, 0, 0.8) !important;
            font-size: 0.9rem;
        }

        .question-text {
            font-size: 1.2rem;
            color: var(--reactor-core);
            margin-bottom: 25px;
            text-align: center;
            font-weight: 500;
        }

        .options-grid {
            display: grid;
            gap: 15px;
            width: 100%;
        }

        .option-btn {
            background: rgba(0, 168, 255, 0.1);
            border: 1px solid var(--stark-blue);
            color: var(--stark-cyan);
            padding: 15px;
            font-family: 'Rajdhani';
            font-size: 1.1rem;
            cursor: pointer;
            transition: 0.3s;
            text-align: left;
            position: relative;
            overflow: hidden;
        }

        .option-btn:hover {
            background: rgba(0, 168, 255, 0.3);
            border-color: var(--stark-cyan);
            box-shadow: 0 0 15px var(--stark-cyan);
        }

        .option-btn.correct {
            background: rgba(0, 255, 136, 0.2);
            border-color: var(--success-green);
            color: var(--success-green);
        }

        .option-btn.wrong {
            background: rgba(255, 51, 51, 0.2);
            border-color: var(--alert-red);
            color: var(--alert-red);
        }

        #user-identity {
            display: none;
            background: rgba(0, 243, 255, 0.1);
            border-left: 3px solid var(--stark-cyan);
            padding: 10px;
            margin-bottom: 20px;
            text-align: center;
            font-family: 'Orbitron';
            color: #fff;
        }

        .btn-large {
            background: transparent;
            border: 2px solid var(--stark-cyan);
            color: var(--stark-cyan);
            padding: 15px 30px;
            font-family: 'Orbitron';
            text-transform: uppercase;
            cursor: pointer;
            transition: 0.3s;
            margin-top: 20px;
        }

        .btn-large:hover {
            background: var(--stark-cyan);
            color: #000;
            box-shadow: 0 0 20px var(--stark-cyan);
        }
    </style>
</head>

<body>

    <div id="ui-container">
        <h1>IT PARTY CHALLENGE</h1>

        <?php if (!$access_granted): ?>
            <div style="text-align: center; color: var(--alert-red);">
                <h2 style="font-family: 'Orbitron';">BRAK DOSTĘPU</h2>
                <p>Ten kod QR jest nieprawidłowy lub wygasł.</p>
            </div>
        <?php else: ?>
            <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: Puzzle -->
            <div id="step-puzzle" class="step-container">
                <div class="puzzle-card">
                    <div class="code-block">
                        <pre><code class="language-javascript"><?php echo htmlspecialchars($puzzle['code']); ?></code></pre>
                    </div>
                    <div class="question-text">
                        <?php echo htmlspecialchars($puzzle['question']); ?>
                    </div>
                    <div class="options-grid" id="options-container">
                        <?php foreach ($puzzle['options'] as $idx => $opt): ?>
                            <button class="option-btn" onclick="checkAnswer(<?php echo $idx; ?>, this)">
                                <?php echo htmlspecialchars($opt); ?>
                            </button>
                        <?php endforeach; ?>
                    </div>
                    <div id="puzzle-status" class="status-message">WYBIERZ ODPOWIEDŹ</div>
                </div>
            </div>

            <!-- STEP 3: Success -->
            <div id="step-success" class="step-container">
                <h2 style="color: var(--success-green); font-family: 'Orbitron'; text-align: center;">ZADANIE WYKONANE</h2>
                <p style="text-align: center;">Punkty zostały dodane do Twojego konta.</p>
                <div id="new-points-display"
                    style="font-size: 2rem; color: var(--gold-accent); font-family: 'Orbitron'; text-align: center; margin: 20px 0;">
                    +5 PKT</div>
                Dobra robota, Imprezowiczu! <br> <span style="color: var(--gold-accent); font-size: 0.9rem;">Znajdź kolejne
                    kody QR ukryte na sali, aby zdobyć więcej punktów.</span>
            </div>

            <div id="step-error" class="step-container">
                <h2 id="error-title" style="color: var(--alert-red); font-family: 'Orbitron'; text-align: center;">STATUS
                </h2>
                <p id="error-message" style="text-align: center; font-weight: bold; color: var(--gold-accent);"></p>
                <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 zagadek do odnalezienia.</span>
                </div>
            </div>

        <?php endif; ?>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-css.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-sql.min.js"></script>

    <script>
        let guestId = null;
        let puzzleId = <?php echo $puzzle_id; ?>;
        const html5QrCode = new Html5Qrcode("reader");

        function switchStep(stepId) {
            document.querySelectorAll('.step-container').forEach(el => el.classList.remove('active-step'));
            document.getElementById('step-' + stepId).classList.add('active-step');
        }

        // Initialize QR Scanner on load (if in step-id)
        window.onload = () => {
            if (document.getElementById('reader')) {
                startScanner();
            }
        };

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

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

        function onScanFailure(error) { /* Ignore scan noise */ }

        async function verifyGuest(qrCode) {
            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';

                    checkIfAlreadySolved();
                } else {
                    document.getElementById('id-status').innerText = "NIEZNANY IMPREZOWICZ - ODMOWA DOSTĘPU";
                    document.getElementById('id-status').classList.add('status-error');
                    setTimeout(startScanner, 2000);
                }
            } catch (e) {
                document.getElementById('id-status').innerText = "Błąd systemu";
                document.getElementById('id-status').classList.add('status-error');
            }
        }

        async function checkIfAlreadySolved() {
            // We'll create check_puzzle_status.php soon
            try {
                const response = await fetch('check_puzzle_status.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ guest_id: guestId, puzzle_id: puzzleId })
                });
                const data = await response.json();

                if (data.status === 'solved') {
                    document.getElementById('error-title').innerText = "ZADANIE JUŻ WYKONANE";
                    document.getElementById('error-message').innerText = "To zadanie zostało już wcześniej rozwiązane przez Ciebie.";
                    switchStep('error');
                } else {
                    switchStep('puzzle');
                }
            } catch (e) {
                switchStep('puzzle'); // Fallback to puzzle and let add_points handle it
            }
        }

        let isSubmitting = false;
        async function checkAnswer(selectedIdx, btn) {
            if (isSubmitting) return;

            const correctIdx = <?php echo isset($puzzle['answer_index']) ? $puzzle['answer_index'] : -1; ?>;

            if (selectedIdx === correctIdx) {
                isSubmitting = true;
                btn.classList.add('correct');
                document.getElementById('puzzle-status').innerText = "POPRAWNA ODPOWIEDŹ! ZAPISYWANIE...";
                document.getElementById('puzzle-status').classList.add('status-success');

                submitScore(5);
            } else {
                isSubmitting = true;
                btn.classList.add('wrong');
                document.getElementById('puzzle-status').innerText = "BŁĘDNA ODPOWIEDŹ - ZAPISYWANIE...";
                document.getElementById('puzzle-status').classList.add('status-error');

                submitScore(0);
            }
        }

        async function submitScore(points) {
            try {
                const response = await fetch('add_puzzle_points.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        guest_id: guestId,
                        puzzle_id: puzzleId,
                        points: points
                    })
                });
                const data = await response.json();

                if (data.status === 'success') {
                    if (points > 0) {
                        switchStep('success');
                    } else {
                        setTimeout(() => {
                            document.getElementById('error-title').innerText = "STATUS ZADANIA";
                            document.getElementById('error-message').innerText = "Niestety, odpowiedź była błędna. To zadanie zostało już zakończone (brak punktów).";
                            switchStep('error');
                        }, 1500);
                    }
                } else {
                    document.getElementById('error-title').innerText = "BŁĄD ZAPISU";
                    document.getElementById('error-message').innerText = data.message || "Nie udało się zapisać Twojego wyniku.";
                    switchStep('error');
                }
            } catch (e) {
                document.getElementById('error-title').innerText = "BŁĄD POŁĄCZENIA";
                document.getElementById('error-message').innerText = "Wystąpił problem z połączeniem. Twój wynik mógł nie zostać zapisany.";
                switchStep('error');
            }
        }
    </script>

</body>

</html>