<?php
session_start();
require_once 'config.php';
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}
$pageTitle = 'Lucky Spin';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Lucky Spin - <?= defined('APP_NAME') ? APP_NAME : 'GameHub' ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #ff4a4a; --bg: #F7F8FA; }
        * { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        body { font-family: -apple-system, sans-serif; background: var(--bg); color: #333; max-width: 480px; margin: 0 auto; min-height: 100vh; padding: 15px; }

        .header { display: flex; align-items: center; justify-content: space-between; padding: 12px 0; }
        .back { font-size: 20px; color: #333; text-decoration: none; }
        .title { font-size: 18px; font-weight: 800; }
        .spins-badge { background: linear-gradient(135deg, #ff6c6b, var(--primary)); color: #fff; padding: 8px 16px; border-radius: 20px; font-weight: 800; font-size: 14px; }

        .wheel-wrap { position: relative; width: 280px; height: 280px; margin: 20px auto 25px; }
        .wheel-canvas { width: 100%; height: 100%; border-radius: 50%; box-shadow: 0 0 0 8px #fff, 0 0 0 10px var(--primary), 0 8px 30px rgba(0,0,0,0.2); }
        .wheel-pointer { position: absolute; top: -15px; left: 50%; transform: translateX(-50%); width: 0; height: 0; border-left: 20px solid transparent; border-right: 20px solid transparent; border-top: 28px solid var(--primary); filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3)); z-index: 10; }

        .spin-btn { display: block; width: 100%; max-width: 200px; margin: 0 auto 20px; padding: 16px; background: linear-gradient(135deg, #ff6c6b, var(--primary)); color: #fff; border: none; border-radius: 30px; font-size: 18px; font-weight: 800; cursor: pointer; box-shadow: 0 6px 20px rgba(255,74,74,0.4); transition: transform 0.2s; }
        .spin-btn:active { transform: scale(0.96); }
        .spin-btn:disabled { opacity: 0.6; cursor: not-allowed; }

        .info-box { background: #fff; border-radius: 12px; padding: 15px; margin-bottom: 15px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); font-size: 13px; color: #666; }
        .info-box strong { color: #333; }
        .toast { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%) translateY(80px); background: rgba(0,0,0,0.85); color: #fff; padding: 14px 24px; border-radius: 12px; font-weight: 600; z-index: 9999; opacity: 0; transition: all 0.3s; }
        .toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }
    </style>
</head>
<body>
    <div class="header">
        <a href="index.php" class="back"><i class="fas fa-chevron-left"></i></a>
        <span class="title">Lucky Spin</span>
        <span class="spins-badge"><i class="fas fa-ticket-alt"></i> <span id="spinCount">0</span> Spins</span>
    </div>

    <div class="wheel-wrap">
        <div class="wheel-pointer"></div>
        <canvas class="wheel-canvas" id="wheelCanvas" width="280" height="280"></canvas>
    </div>
    <button type="button" class="spin-btn" id="spinBtn">SPIN</button>

    <div class="info-box">
        <strong>How to get spins?</strong><br>
        • 1 Spin on every recharge<br>
        • 1 Spin when your referred friend completes first recharge
    </div>

    <div id="toast" class="toast"></div>

    <script>
        let rewards = [];
        let spinCount = 0;
        let isSpinning = false;
        let rotation = 0;

        function drawWheel() {
            const canvas = document.getElementById('wheelCanvas');
            const ctx = canvas.getContext('2d');
            const size = canvas.width;
            const r = size / 2;
            const n = rewards.length || 8;
            const slice = (2 * Math.PI) / n;

            for (let i = 0; i < n; i++) {
                ctx.beginPath();
                ctx.moveTo(r, r);
                ctx.arc(r, r, r - 2, i * slice, (i + 1) * slice);
                ctx.closePath();
                const color = rewards[i] && rewards[i].color ? rewards[i].color : (i % 2 ? '#fff' : '#f0f0f0');
                ctx.fillStyle = color;
                ctx.fill();
                ctx.strokeStyle = '#ddd';
                ctx.lineWidth = 1;
                ctx.stroke();
                ctx.save();
                ctx.translate(r, r);
                ctx.rotate(i * slice + slice / 2);
                ctx.textAlign = 'right';
                ctx.fillStyle = '#333';
                ctx.font = '11px sans-serif';
                const label = rewards[i] ? (rewards[i].name || '') : '?';
                ctx.fillText(label.length > 8 ? label.substring(0, 6) + '..' : label, r - 12, 4);
                ctx.restore();
            }
        }

        function loadWheel() {
            fetch('getspinwell.php')
                .then(r => r.json())
                .then(res => {
                    if (res.code === 0 && res.data) {
                        rewards = res.data.rewards || [];
                        spinCount = res.data.spinCount || 0;
                        document.getElementById('spinCount').textContent = spinCount;
                        document.getElementById('spinBtn').disabled = spinCount < 1;
                        if (rewards.length < 2) rewards = rewards.concat([{ name: 'Try Again', color: '#eee' }, { name: '₹5', color: '#ffe0e0' }].slice(0, 2 - rewards.length));
                        drawWheel();
                    }
                })
                .catch(() => { document.getElementById('spinCount').textContent = '0'; });
        }

        function showToast(msg) {
            const t = document.getElementById('toast');
            t.textContent = msg;
            t.classList.add('show');
            setTimeout(() => t.classList.remove('show'), 2500);
        }

        document.getElementById('spinBtn').addEventListener('click', function() {
            if (isSpinning || spinCount < 1) return;
            isSpinning = true;
            this.disabled = true;

            fetch('do_spin.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' })
                .then(r => r.json())
                .then(data => {
                    const idx = data.rewardIndex != null ? data.rewardIndex : 0;
                    const n = rewards.length || 8;
                    const sliceAngle = (360 / n) * (Math.PI / 180);
                    const targetAngle = 5 * 2 * Math.PI + (n - 1 - idx) * sliceAngle - sliceAngle / 2;
                    rotation += targetAngle;
                    const wheel = document.getElementById('wheelCanvas');
                    wheel.style.transform = 'rotate(' + rotation + 'rad)';
                    wheel.style.transition = 'transform 4s cubic-bezier(0.2, 0.8, 0.3, 1)';

                    setTimeout(() => {
                        isSpinning = false;
                        spinCount--;
                        document.getElementById('spinCount').textContent = spinCount;
                        document.getElementById('spinBtn').disabled = spinCount < 1;
                        showToast(data.message || (data.reward ? data.reward.name : 'Done!'));
                    }, 4200);
                })
                .catch(() => {
                    isSpinning = false;
                    this.disabled = spinCount >= 1;
                    showToast('Error. Try again.');
                });
        });

        loadWheel();
    </script>
</body>
</html>
