<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $user_id = Auth::check();

    // 1. Verificar "Anti-Cheat": ¿Ya giró hoy?
    $stmt = $pdo->prepare("
        SELECT id FROM user_spins 
        WHERE user_id = ? 
        AND DATE(spun_at) = CURDATE()
    ");
    $stmt->execute([$user_id]);
    
    if ($stmt->fetch()) {
        throw new Exception("Ya has girado la ruleta hoy. Vuelve mañana.");
    }

    // 2. Traer configuración global
    $config_stmt = $pdo->query("SELECT daily_spin_max_prize, daily_spin_max_prob, daily_spin_active FROM gamification_settings LIMIT 1");
    $config = $config_stmt->fetch();

    if (!$config || !$config['daily_spin_active']) {
        throw new Exception("La ruleta está temporalmente desactivada.");
    }

    $max_prize = (int)$config['daily_spin_max_prize'];
    $max_prob = (float)$config['daily_spin_max_prob']; // ej. 1.00%

    // 3. MATEMÁTICA PURA SERVER-SIDE: Determinar ganador
    // Valores reales disponibles en la rueda (según diseño frontend): 10, 20, 50, 100, 200, 500, MAX
    $prizes = [
        ['value' => 10,  'prob' => 45.0], // 45%
        ['value' => 20,  'prob' => 25.0], // 25%
        ['value' => 50,  'prob' => 15.0], // 15%
        ['value' => 100, 'prob' => 10.0], // 10%
        ['value' => 200, 'prob' => 3.0],  // 3%
        ['value' => 500, 'prob' => 1.0 + (1.0 - $max_prob)],  // Absorbe lo que resta del max prob para cuadrar a 100%
        ['value' => $max_prize, 'prob' => $max_prob] // Configurable desde el admin (Ej. 1%)
    ];

    $random = mt_rand(1, 10000) / 100; // Número random entre 0.01 y 100.00
    $cumulative = 0;
    $winning_prize = 10; // Fallback

    foreach ($prizes as $prize) {
        $cumulative += $prize['prob'];
        if ($random <= $cumulative) {
            $winning_prize = $prize['value'];
            break;
        }
    }

    // 4. TRANSACCIÓN ATÓMICA DE SEGURIDAD (ACID)
    $pdo->beginTransaction();

    // Sumar diamantes al usuario
    $update_wallet = $pdo->prepare("UPDATE users SET diamonds = diamonds + ? WHERE id = ?");
    $update_wallet->execute([$winning_prize, $user_id]);

    // Registrar el giro del usuario
    $insert_spin = $pdo->prepare("INSERT INTO user_spins (user_id, prize_value) VALUES (?, ?)");
    $insert_spin->execute([$user_id, $winning_prize]);

    // Registrar transacción de wallet
    $insert_trans = $pdo->prepare("INSERT INTO wallet_transactions (user_id, amount, type, description) VALUES (?, ?, 'in', 'Premio de Ruleta Diaria')");
    $insert_trans->execute([$user_id, $winning_prize]);

    $pdo->commit();

    echo json_encode([
        'success' => true,
        'prize' => $winning_prize,
        'message' => "¡Has ganado " . $winning_prize . " diamantes!"
    ]);

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
