<?php
session_start();
include 'cfg.php';

if (!isset($_SESSION['voucher_code'])) {;
    exit();
}

$stmt = $pdo->prepare("SELECT * FROM vouchers WHERE code = ?");
$stmt->execute([$_SESSION['voucher_code']]);
$voucher = $stmt->fetch();

if (!$voucher) {
    die("Voucher tidak valid");
}

// Jika user sudah pernah mulai gosok, paksa kembali ke game saat menekan back.
$resumeStmt = $pdo->prepare("SELECT circle_count, game_over, opened_circles FROM game_state WHERE voucher_code = ?");
$resumeStmt->execute([$_SESSION['voucher_code']]);
$resumeState = $resumeStmt->fetch();

if ($resumeState) {
    $_SESSION['selected_circles'] = (int) $resumeState['circle_count'];
    header("Location: game.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['circle_count'])) {
    $circle_count = (int) $_POST['circle_count'];
    $_SESSION['selected_circles'] = $circle_count;

    $bomb_position = (int) $voucher['bomb_position'];
    if ($bomb_position >= $circle_count || $bomb_position < 0) {
        $bomb_position = rand(0, $circle_count - 1);
    }

    $_SESSION['bombPosition'] = $bomb_position;
    $_SESSION['opened'] = [];

    header("Location: game.php");
    exit();
}

$target_circle_count = (int) $voucher['circle_count'];

$options = [
    ['value' => 3, 'label' => '3 Lingkaran',  'game_label' => '3 Lingkaran',  'fill' => '#c83d35', 'text' => '#fff1de'],
    ['value' => 6, 'label' => '6 Lingkaran',  'game_label' => '6 Lingkaran',  'fill' => '#f8ecd3', 'text' => '#c43b34'],
    ['value' => 9, 'label' => '9 Lingkaran',  'game_label' => '9 Lingkaran',  'fill' => '#c83d35', 'text' => '#fff1de'],
    ['value' => 12, 'label' => '12 Lingkaran', 'game_label' => '12 Lingkaran', 'fill' => '#f8ecd3', 'text' => '#c43b34']
];

$targetIndex = 0;
foreach ($options as $index => $option) {
    if ($option['value'] === $target_circle_count) {
        $targetIndex = $index;
        break;
    }
}

$segmentCount = count($options);
$segmentAngle = 360 / $segmentCount;
$targetCenterAngle = ($targetIndex * $segmentAngle) + ($segmentAngle / 2);
$stop_rotation = 360 - $targetCenterAngle;

$targetLabel = null;
foreach ($options as $option) {
    if ($option['value'] === $target_circle_count) {
        $targetLabel = $option;
        break;
    }
}

if (!$targetLabel) {
    $targetLabel = $options[0];
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Putar Roda Keberuntungan</title>
    <style>
        :root {
            --bg-1: #10273d;
            --bg-2: #08111d;
            --gold-1: #f7d47b;
            --gold-2: #ad6e1f;
            --gold-3: #7a4311;
            --red-1: #cf4036;
            --red-2: #8a211c;
            --cream: #f8ecd3;
            --text: #fff8eb;
            --muted: #efd6b3;
            --shadow: rgba(0, 0, 0, 0.35);
        }

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            min-height: 100vh;
            display: flex;
            align-items: flex-start;
            justify-content: center;
            padding: 24px 16px;
            overflow-x: hidden;
            font-family: "Trebuchet MS", "Segoe UI", sans-serif;
            color: var(--text);
            background:
                radial-gradient(circle at top, rgba(223, 159, 54, 0.12), transparent 22%),
                radial-gradient(circle at bottom right, rgba(45, 121, 199, 0.12), transparent 26%),
                linear-gradient(180deg, var(--bg-1), var(--bg-2));
        }

        .layout {
            width: 100%;
            max-width: 980px;
            display: grid;
            grid-template-columns: minmax(280px, 380px) minmax(300px, 1fr);
            gap: 36px;
            align-items: center;
        }

        .page-shell {
            width: 100%;
            max-width: 1080px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 18px;
        }

        .navbar {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 16px;
            padding: 12px 18px;
            border: 1px solid rgba(255, 230, 186, 0.14);
            border-radius: 18px;
            background: linear-gradient(180deg, rgba(56, 20, 16, 0.82), rgba(20, 7, 7, 0.86));
            box-shadow: 0 16px 32px rgba(0, 0, 0, 0.18);
        }

        .navbar-brand img {
            width: clamp(108px, 18vw, 150px);
            height: auto;
            display: block;
            filter: drop-shadow(0 12px 22px rgba(0, 0, 0, 0.3));
        }

        .navbar-title {
            font-size: 13px;
            font-weight: 800;
            letter-spacing: 0.1em;
            text-transform: uppercase;
            color: var(--muted);
        }

        .panel {
            padding: 30px 28px;
            border: 1px solid rgba(255, 230, 186, 0.14);
            border-radius: 28px;
            background: linear-gradient(180deg, rgba(56, 20, 16, 0.92), rgba(20, 7, 7, 0.95));
            box-shadow: 0 24px 50px var(--shadow);
        }

        .eyebrow {
            margin: 0 0 10px;
            color: var(--gold-1);
            font-size: 12px;
            font-weight: 700;
            letter-spacing: 0.18em;
            text-transform: uppercase;
        }

        h1 {
            margin: 0;
            font-size: 38px;
            line-height: 1.05;
            color: #fff7e9;
        }

        .lead {
            margin: 16px 0 0;
            font-size: 15px;
            line-height: 1.7;
            color: var(--muted);
        }

        .meta-card {
            margin-top: 24px;
            padding: 18px 18px 16px;
            border-radius: 20px;
            background: rgba(255, 244, 222, 0.08);
            border: 1px solid rgba(255, 232, 185, 0.12);
        }

        .meta-label {
            margin: 0;
            font-size: 12px;
            letter-spacing: 0.12em;
            text-transform: uppercase;
            color: #f8c969;
        }

        .meta-value {
            margin: 8px 0 0;
            font-size: 28px;
            font-weight: 800;
            color: #fff6df;
        }

        .meta-note {
            margin: 8px 0 0;
            font-size: 13px;
            color: #ecd3af;
        }

        .spin-btn {
            width: 100%;
            margin-top: 24px;
            padding: 15px 18px;
            border: none;
            border-radius: 999px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 900;
            letter-spacing: 0.08em;
            color: #4c1609;
            background: linear-gradient(180deg, #ffe4a0 0%, #f5bd54 48%, #c9811f 100%);
            box-shadow: inset 0 2px 0 rgba(255, 255, 255, 0.35), 0 16px 30px rgba(0, 0, 0, 0.28);
            transition: transform 0.2s ease, box-shadow 0.2s ease, filter 0.2s ease;
        }

        .spin-btn:hover {
            transform: translateY(-2px);
            filter: brightness(1.04);
            box-shadow: inset 0 2px 0 rgba(255, 255, 255, 0.35), 0 20px 34px rgba(0, 0, 0, 0.32);
        }

        .spin-btn:disabled {
            cursor: not-allowed;
            opacity: 0.75;
            transform: none;
        }

        .result-card {
            margin-top: 18px;
            padding: 16px 18px;
            border-radius: 18px;
            border: 1px solid rgba(255, 229, 175, 0.18);
            background: rgba(255, 243, 213, 0.08);
            display: none;
        }

        .result-card.show {
            display: block;
            animation: fadeInUp 0.45s ease;
        }

        .result-title {
            margin: 0 0 6px;
            font-size: 12px;
            letter-spacing: 0.12em;
            text-transform: uppercase;
            color: #f0c76d;
        }

        .result-text {
            margin: 0;
            font-size: 24px;
            font-weight: 900;
            color: #fff6e4;
        }

        .wheel-stage {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 24px 12px 8px;
        }

        .pointer-top {
            position: absolute;
            top: 0;
            left: 50%;
            z-index: 8;
            transform: translateX(-50%);
            width: 72px;
            height: 118px;
            transform-origin: 50% 12px;
            pointer-events: none;
        }

        .pointer-top.is-ticking {
            animation: pointerTick 0.12s ease-in-out infinite alternate;
        }

        .pointer-top::before {
            content: "";
            position: absolute;
            top: 0;
            left: 50%;
            width: 26px;
            height: 26px;
            transform: translateX(-50%);
            border-radius: 50%;
            background: radial-gradient(circle at 35% 35%, #fff8d6 0%, #f0bf5a 55%, #925216 100%);
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.28);
        }

        .pointer-head {
            position: absolute;
            top: 12px;
            left: 50%;
            width: 44px;
            height: 58px;
            transform: translateX(-50%);
            border-radius: 55% 55% 48% 48%;
            background: linear-gradient(180deg, #fff1bb 0%, #e2a942 55%, #8d4d14 100%);
            box-shadow: inset 0 2px 3px rgba(255, 255, 255, 0.34), 0 10px 16px rgba(0, 0, 0, 0.24);
        }

        .pointer-head::after {
            content: "";
            position: absolute;
            top: 14px;
            left: 50%;
            width: 16px;
            height: 42px;
            transform: translateX(-50%);
            background: linear-gradient(180deg, #fff6dc 0%, #f2c65b 36%, #a55d17 100%);
            clip-path: polygon(50% 100%, 0 0, 100% 0);
        }

        .pointer-stem {
            position: absolute;
            top: 58px;
            left: 50%;
            width: 12px;
            height: 54px;
            transform: translateX(-50%);
            border-radius: 999px;
            background: linear-gradient(180deg, #6d270f 0%, #341108 100%);
            box-shadow: inset 0 2px 3px rgba(255,255,255,0.12);
        }

        .pointer-shadow {
            position: absolute;
            top: 92px;
            left: 50%;
            width: 56px;
            height: 18px;
            transform: translateX(-50%);
            border-radius: 50%;
            background: radial-gradient(circle, rgba(0, 0, 0, 0.28) 0%, rgba(0, 0, 0, 0) 72%);
        }

        .wheel-wrap {
            position: relative;
            width: min(74vw, 430px);
            aspect-ratio: 1;
            margin-top: 44px;
            filter: drop-shadow(0 20px 24px rgba(0, 0, 0, 0.34));
        }

        .wheel-lights {
            position: absolute;
            inset: 0;
            z-index: 4;
            pointer-events: none;
        }

        .bulb {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 14px;
            height: 14px;
            margin: -7px;
            border-radius: 50%;
            background: radial-gradient(circle at 35% 35%, #fff9d8 0%, #ffd35c 45%, #cf7c19 100%);
            box-shadow: 0 0 8px rgba(255, 218, 102, 0.8), 0 0 18px rgba(255, 181, 74, 0.45);
        }

        .wheel-frame {
            position: absolute;
            inset: 0;
            z-index: 2;
            border-radius: 50%;
            background: linear-gradient(145deg, #6e260f 0%, #a3491c 18%, #f5d285 32%, #773012 48%, #3f1209 100%);
            box-shadow: inset 0 0 0 6px rgba(255, 232, 185, 0.3), inset 0 0 20px rgba(0, 0, 0, 0.38);
        }

        .wheel {
            position: absolute;
            inset: 19px;
            z-index: 3;
            border-radius: 50%;
            overflow: hidden;
            background: #42130d;
            transition: transform 4.8s cubic-bezier(0.15, 0.9, 0.12, 1);
        }

        .wheel::after {
            content: "";
            position: absolute;
            inset: 0;
            border-radius: 50%;
            background: radial-gradient(circle at 30% 30%, rgba(255,255,255,0.3), transparent 32%), radial-gradient(circle at 50% 50%, transparent 58%, rgba(81, 20, 12, 0.28) 100%);
            pointer-events: none;
        }

        .wheel-center {
            position: absolute;
            top: 50%;
            left: 50%;
            z-index: 5;
            width: 58px;
            height: 58px;
            transform: translate(-50%, -50%);
            border-radius: 50%;
            background: radial-gradient(circle at 30% 30%, #fff3b8 0%, #dca648 42%, #9a5c16 76%, #62300d 100%);
            box-shadow: inset 0 2px 8px rgba(255, 255, 255, 0.3), 0 6px 14px rgba(0, 0, 0, 0.28);
        }

        .wheel-center::before,
        .wheel-center::after {
            content: "";
            position: absolute;
            top: 50%;
            left: 50%;
            width: 34px;
            height: 3px;
            border-radius: 999px;
            background: rgba(140, 76, 16, 0.45);
            transform: translate(-50%, -50%);
        }

        .wheel-center::after {
            transform: translate(-50%, -50%) rotate(90deg);
        }

        .stand {
            position: relative;
            width: 150px;
            margin-top: -6px;
            z-index: 1;
        }

        .stand-neck {
            width: 88px;
            height: 28px;
            margin: 0 auto;
            border-radius: 10px 10px 4px 4px;
            background: linear-gradient(180deg, #5e5e5e, #181818 80%);
            box-shadow: inset 0 3px 4px rgba(255,255,255,0.12);
        }

        .stand-base {
            width: 150px;
            height: 30px;
            margin: -4px auto 0;
            border-radius: 8px 8px 14px 14px;
            background: linear-gradient(180deg, #505050 0%, #1a1a1a 46%, #080808 100%);
            box-shadow: inset 0 2px 3px rgba(255,255,255,0.16), 0 10px 18px rgba(0,0,0,0.3);
        }

        .stand-shadow {
            width: 180px;
            height: 18px;
            margin: 8px auto 0;
            border-radius: 50%;
            background: radial-gradient(circle, rgba(0, 0, 0, 0.35) 0%, rgba(0,0,0,0.18) 45%, rgba(0,0,0,0) 80%);
        }

        .wheel-svg {
            width: 100%;
            height: 100%;
            display: block;
        }

        .slice-divider {
            stroke: rgba(123, 35, 19, 0.42);
            stroke-width: 2;
        }

        .status-row {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 18px;
        }

        .badge {
            padding: 10px 14px;
            border-radius: 999px;
            font-size: 13px;
            font-weight: 700;
            color: #fff4df;
            border: 1px solid rgba(255, 230, 189, 0.18);
            background: rgba(255, 247, 228, 0.08);
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes pointerTick {
            from {
                transform: translateX(-50%) rotate(-7deg);
            }
            to {
                transform: translateX(-50%) rotate(7deg);
            }
        }

        @media (max-width: 860px) {
            .layout {
                grid-template-columns: 1fr;
                gap: 18px;
                max-width: 560px;
            }

            .panel {
                order: 2;
                padding: 24px 22px;
            }

            .wheel-stage {
                order: 1;
                padding-top: 0;
            }
        }

        @media (max-width: 640px) {
            body {
                padding: 16px 12px 24px;
            }

            .page-shell {
                gap: 14px;
            }

            .panel {
                padding: 22px 18px;
                border-radius: 22px;
            }

            .meta-card {
                margin-top: 18px;
                padding: 16px;
            }

            .meta-value {
                font-size: 24px;
            }

            .status-row {
                gap: 8px;
            }

            .badge {
                width: 100%;
                text-align: center;
            }

            .spin-btn {
                margin-top: 18px;
                padding: 14px 16px;
                font-size: 15px;
            }

            .result-card {
                margin-top: 14px;
                padding: 14px 15px;
            }

            .result-text {
                font-size: 21px;
            }

            .wheel-wrap {
                width: min(90vw, 360px);
                margin-top: 36px;
            }

            .bulb {
                width: 12px;
                height: 12px;
                margin: -6px;
            }

            .stand {
                transform: scale(0.92);
            }
        }

        @media (max-width: 480px) {
            h1 {
                font-size: 28px;
            }

            .lead {
                font-size: 14px;
            }

            .wheel-wrap {
                width: min(92vw, 330px);
                margin-top: 34px;
            }

            .pointer-top {
                width: 60px;
                height: 100px;
            }

            .pointer-head {
                width: 38px;
                height: 50px;
            }

            .pointer-head::after {
                top: 12px;
                width: 14px;
                height: 36px;
            }

            .pointer-stem {
                top: 52px;
                height: 46px;
            }

            .wheel-center {
                width: 48px;
                height: 48px;
            }

            .meta-value {
                font-size: 22px;
            }
        }
    </style>
</head>
<body>
    <div class="page-shell">
        <header class="navbar">
            <div class="navbar-brand">
                <img src="logo.png" alt="Logo">
            </div>
            <div class="navbar-title">Acak Lingkaran</div>
        </header>
        <div class="layout">
        <div class="panel">
            <p class="eyebrow">Acak Lingkaran</p>
            <h1>Putar roda Untuk Menentukan Jumlah Lingkaranmu</h1>
            <p class="lead">Setelah roda sudah berhenti berputar, kamu akan langsung diarahkan ke papan game berikutnya.</p>

            <div class="meta-card">
                <p class="meta-note">Hasil roda ini akan menentukan jumlah lingkaran yang dipakai pada permainan berikutnya.</p>
            </div>

            <div class="status-row">
                <div class="badge">Voucher: <?= htmlspecialchars($_SESSION['voucher_code']) ?></div>
            </div>


            <div class="result-card" id="resultCard">
                <p class="result-title">Hasil Spin</p>
                <p class="result-text" id="resultText"></p>
            </div>

            <form id="resultForm" method="post">
                <input type="hidden" name="circle_count" id="circleCountInput">
            </form>
        </div>

        <div class="wheel-stage">
            <div class="pointer-top" id="pointerTop" aria-hidden="true">
                <div class="pointer-head"></div>
                <div class="pointer-stem"></div>
                <div class="pointer-shadow"></div>
            </div>
            <div class="wheel-wrap">
                <div class="wheel-lights" id="wheelLights"></div>
                <div class="wheel-frame"></div>
                <div class="wheel" id="wheel">
                    <svg class="wheel-svg" viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg" aria-label="Roda hadiah">
                        <defs>
                            <filter id="innerGlow" x="-20%" y="-20%" width="140%" height="140%">
                                <feDropShadow dx="0" dy="0" stdDeviation="5" flood-color="#fff1bf" flood-opacity="0.35"/>
                            </filter>
                        </defs>
                        <g id="wheelSlices"></g>
                        <circle cx="200" cy="200" r="192" fill="none" stroke="rgba(255,241,212,0.46)" stroke-width="5" filter="url(#innerGlow)" />
                    </svg>
                </div>
                <div class="wheel-center"></div>
            </div>
            <div class="stand">
                <div class="stand-neck"></div>
                <div class="stand-base"></div>
                <div class="stand-shadow"></div>
                <button class="spin-btn" id="spinBtn" type="button">PUTAR RODA</button>
            </div>
        </div>
        </div>
    </div>

    <script>
        const wheel = document.getElementById('wheel');
        const wheelLights = document.getElementById('wheelLights');
        const wheelSlices = document.getElementById('wheelSlices');
        const spinBtn = document.getElementById('spinBtn');
        const pointerTop = document.getElementById('pointerTop');
        const resultCard = document.getElementById('resultCard');
        const resultText = document.getElementById('resultText');
        const resultForm = document.getElementById('resultForm');
        const circleCountInput = document.getElementById('circleCountInput');

        const targetCircles = <?= json_encode($target_circle_count) ?>;
        const stopRotation = <?= json_encode($stop_rotation) ?>;
        const targetName = <?= json_encode($targetLabel['game_label']) ?>;
        const slices = <?= json_encode($options, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

        const center = 200;
        const radius = 188;
        const innerRadius = 22;
        const segmentAngle = 360 / slices.length;

        function polarToCartesian(cx, cy, r, angle) {
            const radians = (angle - 90) * Math.PI / 180;
            return {
                x: cx + (r * Math.cos(radians)),
                y: cy + (r * Math.sin(radians))
            };
        }

        function createSlicePath(startAngle, endAngle) {
            const outerStart = polarToCartesian(center, center, radius, endAngle);
            const outerEnd = polarToCartesian(center, center, radius, startAngle);
            const innerStart = polarToCartesian(center, center, innerRadius, startAngle);
            const innerEnd = polarToCartesian(center, center, innerRadius, endAngle);
            const largeArc = endAngle - startAngle <= 180 ? 0 : 1;

            return [
                `M ${innerStart.x} ${innerStart.y}`,
                `L ${outerEnd.x} ${outerEnd.y}`,
                `A ${radius} ${radius} 0 ${largeArc} 1 ${outerStart.x} ${outerStart.y}`,
                `L ${innerEnd.x} ${innerEnd.y}`,
                `A ${innerRadius} ${innerRadius} 0 ${largeArc} 0 ${innerStart.x} ${innerStart.y}`,
                'Z'
            ].join(' ');
        }

        function renderWheel() {
            slices.forEach((slice, index) => {
                const startAngle = index * segmentAngle;
                const endAngle = startAngle + segmentAngle;
                const midAngle = startAngle + (segmentAngle / 2);
                const textPos = polarToCartesian(center, center, 116, midAngle);

                const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
                path.setAttribute('d', createSlicePath(startAngle, endAngle));
                path.setAttribute('fill', slice.fill);
                path.setAttribute('class', 'slice-divider');
                wheelSlices.appendChild(path);

                const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
                text.setAttribute('x', textPos.x);
                text.setAttribute('y', textPos.y);
                text.setAttribute('fill', slice.text);
                text.setAttribute('font-size', '23');
                text.setAttribute('font-weight', '900');
                text.setAttribute('text-anchor', 'middle');
                text.setAttribute('dominant-baseline', 'middle');
                text.setAttribute('transform', `rotate(${midAngle - 90} ${textPos.x} ${textPos.y})`);
                text.textContent = slice.label;
                wheelSlices.appendChild(text);
            });
        }

        function renderLights() {
            const totalLights = 24;
            const lightRadius = 198;

            for (let i = 0; i < totalLights; i += 1) {
                const angle = (i / totalLights) * 360;
                const bulb = document.createElement('span');
                bulb.className = 'bulb';
                bulb.style.transform = `rotate(${angle}deg) translate(${lightRadius}px) rotate(${-angle}deg)`;
                bulb.style.animationDelay = `${i * 0.08}s`;
                wheelLights.appendChild(bulb);
            }
        }

        renderWheel();
        renderLights();

        let isSpinning = false;

        spinBtn.addEventListener('click', () => {
            if (isSpinning) {
                return;
            }

            isSpinning = true;
            spinBtn.disabled = true;
            spinBtn.textContent = 'MEMUTAR...';
            resultCard.classList.remove('show');
            pointerTop.classList.add('is-ticking');

            const rounds = Math.floor(Math.random() * 3) + 5;
            const totalRotation = (rounds * 360) + stopRotation;
            wheel.style.transform = `rotate(${totalRotation}deg)`;

            window.setTimeout(() => {
                pointerTop.classList.remove('is-ticking');
                resultText.textContent = targetName;
                resultCard.classList.add('show');

                window.setTimeout(() => {
                    circleCountInput.value = targetCircles;
                    resultForm.submit();
                }, 1400);
            }, 4900);
        });
    </script>
</body>
</html>
