<?php
session_start();
require_once 'config.php';
header('Content-Type: application/json');

try {
    global $pdo;
    $pdo->exec("CREATE TABLE IF NOT EXISTS spin_credits (user_id INT PRIMARY KEY, credits INT NOT NULL DEFAULT 0)");

    $stmt = $pdo->query("SELECT id, name, type, amount, color, probability FROM spin_rewards WHERE is_active = 1 ORDER BY id ASC");
    $rewards = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $spinCount = 0;
    if (isset($_SESSION['user_id'])) {
        $sc = $pdo->prepare("SELECT credits FROM spin_credits WHERE user_id = ?");
        $sc->execute([$_SESSION['user_id']]);
        $spinCount = (int)($sc->fetchColumn() ?: 0);
    }

    $costPerSpin = 0;
    $s = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key = 'spin_cost' LIMIT 1");
    if ($s && $row = $s->fetch()) $costPerSpin = (float)$row['setting_value'];

    echo json_encode([
        "code" => 0,
        "msg" => "Succeed",
        "data" => [
            "spinCount" => $spinCount,
            "costPerSpin" => $costPerSpin,
            "rewards" => $rewards
        ]
    ]);
} catch (Throwable $e) {
    echo json_encode(["code" => 1, "msg" => "Error", "data" => null]);
}
