<?php
// game/slot.php
require_once __DIR__ . '/../config/koneksi.php';

$token = $_GET['token'] ?? '';
$tokenEsc = mysqli_real_escape_string($conn, $token);

$sessRes = mysqli_query($conn, "SELECT gs.*, g.name AS game_name, g.slug, g.min_bet, g.max_bet
    FROM game_sessions gs JOIN games g ON gs.game_id = g.id
    WHERE gs.token = '$tokenEsc' AND gs.expires_at > NOW() LIMIT 1");
$session = mysqli_fetch_assoc($sessRes);

if (!$session) {
    die('Sesi game sudah habis atau tidak valid. Silakan buka ulang dari situs.');
}

$playerRes = mysqli_query($conn, "SELECT * FROM players WHERE id = {$session['player_id']}");
$player = mysqli_fetch_assoc($playerRes);

// ==========================================
// TEMA PER GAME
// ==========================================
$themes = [

    // ========== MAHJONG SLOT (pakai gambar) ==========
    'mahjong-slot' => [
        'bg1' => '#1a0a00',
        'bg2' => '#0d0500',
        'accent' => '#ffd700',
        'accent2' => '#c62828',
        'label' => 'MAHJONG WAYS',
        'use_images' => true,          // penting
        'symbols' => [                  // nama file di folder symbols/
            'wild.png',
            'scatter.png',
            'fa.png',
            'zhong.png',
            'white.png',
            '8wan.png',
            '5dot.png',
            '5bam.png',
            '2dot.png',
            '2bam.png'
        ],
        'jackpot_symbol' => 'wild.png',
    ],

    // ========== TEMA LAMA (emoji) tetap ada ==========
    'golden-pharaoh' => [
        'bg1' => '#3d2a0a', 'bg2' => '#0d0801',
        'accent' => '#ffd700', 'accent2' => '#c9962c',
        'symbols' => ['🔺', '👁️', '🏺', '🐍', '👑', '💎', '☀️', '🦅'],
        'jackpot_symbol' => '👑',
        'label' => 'EGYPT GOLD',
        'use_images' => false,
    ],
    'lucky-dragon' => [
        'bg1' => '#4a0d0d', 'bg2' => '#1a0202',
        'accent' => '#ffcc00', 'accent2' => '#d4302f',
        'symbols' => ['🐉', '🧧', '🏮', '🥟', '🎋', '💰', '🀄', '🎆'],
        'jackpot_symbol' => '🐉',
        'label' => 'ORIENTAL FORTUNE',
        'use_images' => false,
    ],
    'wild-safari' => [
        'bg1' => '#2a3d1a', 'bg2' => '#0d1408',
        'accent' => '#ffa726', 'accent2' => '#66bb6a',
        'symbols' => ['🦁', '🐘', '🦒', '🦓', '🌴', '🥁', '🏹', '🦏'],
        'jackpot_symbol' => '🦁',
        'label' => 'AFRICAN SAFARI',
        'use_images' => false,
    ],
    'candy-burst' => [
        'bg1' => '#4a0d3d', 'bg2' => '#1a0215',
        'accent' => '#ff6ec7', 'accent2' => '#b388ff',
        'symbols' => ['🍬', '🍭', '🧁', '🍫', '🍩', '🍪', '🎂', '🍡'],
        'jackpot_symbol' => '🍭',
        'label' => 'SWEET MANIA',
        'use_images' => false,
    ],
    'pirate-treasure' => [
        'bg1' => '#0d1f3d', 'bg2' => '#020610',
        'accent' => '#ffd700', 'accent2' => '#8b5a2b',
        'symbols' => ['☠️', '⚓', '🏴‍☠️', '💰', '🗺️', '⚔️', '🦜', '🔱'],
        'jackpot_symbol' => '☠️',
        'label' => 'HIGH SEAS QUEST',
        'use_images' => false,
    ],
];

$theme = $themes[$session['slug']] ?? [
    'bg1' => '#2a1a4a', 'bg2' => '#0d0518',
    'accent' => '#ffd700', 'accent2' => '#a239ea',
    'symbols' => ['🍒', '🍋', '🍊', '🍇', '⭐', '💎', '7️⃣', '👑'],
    'jackpot_symbol' => '👑',
    'label' => 'CLASSIC SLOT',
    'use_images' => false,
];

$useImages = !empty($theme['use_images']);
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title><?php echo htmlspecialchars($session['game_name']); ?></title>
<style>
    * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', sans-serif; }
    html, body { height: 100%; overflow: hidden; }
    body {
        background: radial-gradient(circle at top, <?php echo $theme['bg1']; ?>, <?php echo $theme['bg2']; ?>);
        position: fixed; inset: 0; display: flex; flex-direction: column; color: #fff;
    }
    #topbar {
        display: flex; justify-content: space-between; align-items: center;
        padding: 14px 18px; background: rgba(0,0,0,0.45);
        border-bottom: 2px solid <?php echo $theme['accent']; ?>;
    }
    #topbar .title-wrap { display: flex; flex-direction: column; }
    #topbar .title { font-weight: 800; font-size: 15px; color: <?php echo $theme['accent']; ?>; }
    #topbar .subtitle { font-size: 9px; letter-spacing: 2px; color: <?php echo $theme['accent2']; ?>; font-weight: 700; }
    #balance-pill {
        background: linear-gradient(to right, <?php echo $theme['accent2']; ?>, <?php echo $theme['accent']; ?>);
        border-radius: 20px; padding: 8px 16px; font-weight: 700; font-size: 13px; color: #000;
    }
    #reels-wrap {
        flex: 1; display: flex; align-items: center; justify-content: center; padding: 15px;
    }
    #reels {
        display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px;
        background: rgba(0,0,0,0.55); border: 3px solid <?php echo $theme['accent']; ?>; border-radius: 16px;
        padding: 14px; box-shadow: 0 0 40px <?php echo $theme['accent']; ?>55;
    }
    .reel {
        width: 64px; height: 64px; background: rgba(255,255,255,0.07); border-radius: 10px;
        display: flex; align-items: center; justify-content: center;
        overflow: hidden; border: 1px solid rgba(255,255,255,0.1);
    }
    .reel img {
        width: 56px; height: 56px; object-fit: contain;
    }
    .reel.spinning img {
        animation: spin-blur 0.12s linear infinite;
    }
    @keyframes spin-blur {
        0%   { opacity: 1; transform: translateY(0); }
        50%  { opacity: 0.4; transform: translateY(6px); }
        100% { opacity: 1; transform: translateY(0); }
    }

    #result-banner {
        position: absolute; top: 38%; left: 50%; transform: translate(-50%, -50%);
        font-size: 26px; font-weight: 900; color: <?php echo $theme['accent']; ?>;
        text-shadow: 0 0 20px <?php echo $theme['accent']; ?>;
        opacity: 0; transition: opacity 0.3s; pointer-events: none; white-space: nowrap;
    }
    #result-banner.show { opacity: 1; }

    #controls {
        background: rgba(0,0,0,0.5); padding: 16px; display: flex; align-items: center;
        justify-content: center; gap: 16px;
    }
    .bet-btn {
        background: rgba(255,255,255,0.1); border: 1px solid <?php echo $theme['accent']; ?>; color: <?php echo $theme['accent']; ?>;
        width: 38px; height: 38px; border-radius: 50%; font-size: 20px; cursor: pointer;
    }
    #bet-display { font-weight: 800; font-size: 16px; min-width: 100px; text-align: center; }
    #spin-btn {
        background: linear-gradient(to bottom, <?php echo $theme['accent']; ?>, <?php echo $theme['accent2']; ?>); color: #1a0a00;
        border: none; border-radius: 50%; width: 72px; height: 72px; font-weight: 900;
        font-size: 14px; cursor: pointer; box-shadow: 0 4px 15px rgba(0,0,0,0.45);
    }
    #spin-btn:disabled { opacity: 0.5; }
    #msg { text-align: center; padding: 6px; font-size: 13px; color: #ff6b6b; min-height: 20px; }
</style>
</head>
<body>

<div id="topbar">
    <div class="title-wrap">
        <span class="title">🀄 <?php echo htmlspecialchars($session['game_name']); ?></span>
        <span class="subtitle"><?php echo htmlspecialchars($theme['label']); ?></span>
    </div>
    <span id="balance-pill">Rp <span id="balance-val"><?php echo number_format($player['balance'], 0, ',', '.'); ?></span></span>
</div>

<div id="reels-wrap" style="position:relative;">
    <div id="reels">
        <?php
        $initSymbols = $theme['symbols'];
        for ($i = 0; $i < 15; $i++):   // 5 kolom x 3 baris
            $sym = $initSymbols[$i % count($initSymbols)];
        ?>
        <div class="reel" id="reel-<?php echo $i; ?>">
            <?php if ($useImages): ?>
                <img src="../symbols/<?php echo htmlspecialchars($sym); ?>" alt="">
            <?php else: ?>
                <?php echo $sym; ?>
            <?php endif; ?>
        </div>
        <?php endfor; ?>
    </div>
    <div id="result-banner"></div>
</div>

<div id="msg"></div>

<div id="controls">
    <button class="bet-btn" onclick="changeBet(-1)">−</button>
    <div id="bet-display">Rp <?php echo number_format($session['min_bet'], 0, ',', '.'); ?></div>
    <button class="bet-btn" onclick="changeBet(1)">+</button>
    <button id="spin-btn" onclick="doSpin()">SPIN</button>
</div>

<script>
const TOKEN = <?php echo json_encode($token); ?>;
const MIN_BET = <?php echo (int)$session['min_bet']; ?>;
const MAX_BET = <?php echo (int)$session['max_bet']; ?>;
const BET_STEP = MIN_BET;
let currentBet = MIN_BET;
let isSpinning = false;

const USE_IMAGES = <?php echo $useImages ? 'true' : 'false'; ?>;
const SYMBOLS = <?php echo json_encode($theme['symbols']); ?>;
const JACKPOT_SYMBOL = <?php echo json_encode($theme['jackpot_symbol']); ?>;

function changeBet(dir) {
    if (isSpinning) return;
    currentBet = Math.max(MIN_BET, Math.min(MAX_BET, currentBet + dir * BET_STEP));
    document.getElementById('bet-display').textContent = 'Rp ' + currentBet.toLocaleString('id-ID');
}

function randomSymbol() {
    return SYMBOLS[Math.floor(Math.random() * SYMBOLS.length)];
}

function setReelContent(el, symbol) {
    if (USE_IMAGES) {
        el.innerHTML = '<img src="../symbols/' + symbol + '" alt="">';
    } else {
        el.textContent = symbol;
    }
}

async function doSpin() {
    if (isSpinning) return;
    isSpinning = true;
    document.getElementById('spin-btn').disabled = true;
    document.getElementById('msg').textContent = '';
    document.getElementById('result-banner').classList.remove('show');

    const reels = document.querySelectorAll('.reel');
    reels.forEach(r => r.classList.add('spinning'));

    const spinAnim = setInterval(() => {
        reels.forEach(r => setReelContent(r, randomSymbol()));
    }, 70);

    try {
        const res = await fetch('spin_api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ token: TOKEN, bet: currentBet })
        });
        const data = await res.json();

        setTimeout(() => {
            clearInterval(spinAnim);
            reels.forEach(r => r.classList.remove('spinning'));

            if (!data.status) {
                document.getElementById('msg').textContent = data.message || 'Gagal spin.';
                isSpinning = false;
                document.getElementById('spin-btn').disabled = false;
                return;
            }

            // Tampilkan hasil visual
            reels.forEach(r => {
                const finalSym = data.win ? JACKPOT_SYMBOL : randomSymbol();
                setReelContent(r, finalSym);
            });

            document.getElementById('balance-val').textContent = Number(data.balance).toLocaleString('id-ID');

            const banner = document.getElementById('result-banner');
            if (data.win) {
                banner.textContent = 'MENANG! +Rp ' + Number(data.payout).toLocaleString('id-ID');
                banner.style.color = '#4caf50';
            } else {
                banner.textContent = '';
            }
            banner.classList.add('show');
            setTimeout(() => banner.classList.remove('show'), 1800);

            isSpinning = false;
            document.getElementById('spin-btn').disabled = false;
        }, 800);
    } catch (e) {
        clearInterval(spinAnim);
        document.getElementById('msg').textContent = 'Koneksi gagal, coba lagi.';
        isSpinning = false;
        document.getElementById('spin-btn').disabled = false;
    }
}
</script>

</body>
</html>
