<?php
require_once __DIR__ . '/config.php';

try {
    $data = json_decode(file_get_contents('php://input'), true);
    
    $sessionToken = $data['session_token'] ?? '';
    $betAmount = floatval($data['bet_amount'] ?? 0);
    $multiplier = floatval($data['multiplier'] ?? 0);
    $winAmount = floatval($data['win_amount'] ?? 0);
    $result = $data['result'] ?? 'loss'; // 'cashout', 'loss', 'win'
    
    if (empty($sessionToken)) {
        echo json_encode(['success' => false, 'message' => 'Token inválido']);
        exit;
    }
    
    // Buscar user_id pela sessão
    $stmt = $pdo->prepare("SELECT user_id FROM sessions WHERE session_token = ? AND expires_at > NOW()");
    $stmt->execute([$sessionToken]);
    $session = $stmt->fetch();
    
    if (!$session) {
        echo json_encode(['success' => false, 'message' => 'Sessão inválida']);
        exit;
    }
    
    $userId = $session['user_id'];
    
    // Salvar no histórico
    $stmt = $pdo->prepare("
        INSERT INTO game_history (user_id, bet_amount, multiplier, win_amount, result, created_at)
        VALUES (?, ?, ?, ?, ?, NOW())
    ");
    $stmt->execute([$userId, $betAmount, $multiplier, $winAmount, $result]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Histórico salvo'
    ]);
    
} catch (Exception $e) {
    error_log("Erro save_game_history: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Erro ao salvar: ' . $e->getMessage()
    ]);
}
