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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Login required', 'rewardIndex' => null]);
    exit;
}

$userId = (int)$_SESSION['user_id'];
global $pdo;

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS spin_credits (user_id INT PRIMARY KEY, credits INT NOT NULL DEFAULT 0)");
    $pdo->exec("CREATE TABLE IF NOT EXISTS spin_history (id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, reward_id INT, reward_name VARCHAR(100), reward_type VARCHAR(20), amount DECIMAL(15,2) DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)");

    $cred = $pdo->prepare("SELECT credits FROM spin_credits WHERE user_id = ?");
    $cred->execute([$userId]);
    $credits = (int)($cred->fetchColumn() ?: 0);
    if ($credits < 1) {
        echo json_encode(['success' => false, 'message' => 'No spins left. Recharge or refer friends to get spins!', 'rewardIndex' => null]);
        exit;
    }

    $rewards = $pdo->query("SELECT id, name, type, amount, probability FROM spin_rewards WHERE is_active = 1 ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
    if (empty($rewards)) {
        echo json_encode(['success' => false, 'message' => 'Wheel not configured.', 'rewardIndex' => null]);
        exit;
    }

    $totalProb = array_sum(array_column($rewards, 'probability'));
    $rand = $totalProb > 0 ? (mt_rand(1, (int)($totalProb * 100)) / 100) : 0;
    $cum = 0;
    $winnerIndex = 0;
    foreach ($rewards as $i => $r) {
        $cum += (float)$r['probability'];
        if ($rand <= $cum) {
            $winnerIndex = $i;
            break;
        }
    }
    $winner = $rewards[$winnerIndex];

    $pdo->beginTransaction();
    $pdo->prepare("UPDATE spin_credits SET credits = credits - 1 WHERE user_id = ? AND credits >= 1")->execute([$userId]);
    if ($pdo->rowCount() === 0) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'No spins left.', 'rewardIndex' => null]);
        exit;
    }

    $amount = (float)($winner['amount'] ?? 0);
    $type = $winner['type'] ?? 'empty';
    if ($type === 'cash' && $amount > 0) {
        $pdo->prepare("UPDATE wallets SET main_balance = main_balance + ? WHERE user_id = ?")->execute([$amount, $userId]);
    } elseif ($type === 'bonus' && $amount > 0) {
        $pdo->prepare("UPDATE wallets SET bonus_balance = bonus_balance + ? WHERE user_id = ?")->execute([$amount, $userId]);
    }

    $pdo->prepare("INSERT INTO spin_history (user_id, reward_id, reward_name, reward_type, amount) VALUES (?, ?, ?, ?, ?)")
        ->execute([$userId, $winner['id'], $winner['name'], $type, $amount]);
    $pdo->commit();

    echo json_encode([
        'success' => true,
        'message' => $type === 'empty' ? 'Try again!' : ('Won: ' . $winner['name'] . ' ₹' . number_format($amount, 2)),
        'rewardIndex' => $winnerIndex,
        'reward' => ['name' => $winner['name'], 'type' => $type, 'amount' => $amount]
    ]);
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => 'Error', 'rewardIndex' => null]);
}
