<?php
declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
require_once __DIR__ . '/../config.php';

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

if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    echo json_encode(['ok' => false, 'error' => 'Unauthorized']);
    exit;
}
$is_demo = isset($_SESSION['is_demo']) && $_SESSION['is_demo'] == 1;
if (!$is_demo && isset($_SESSION['user_id'])) {
    $uid_chk = (int)$_SESSION['user_id'];
    $is_demo = (int)$pdo->query("SELECT is_demo FROM users WHERE id = $uid_chk")->fetchColumn();
    if ($is_demo) $_SESSION['is_demo'] = 1;
}
if ($is_demo) {
    echo json_encode(['ok' => false, 'error' => 'This account can only play WinGo.']);
    exit;
}
$user_id = (int)$_SESSION['user_id'];
$pdo = $GLOBALS['pdo'];

// Ensure pool exists safely
$pdo->exec("
    CREATE TABLE IF NOT EXISTS `chicken_pool` (
        `id` tinyint(1) UNSIGNED NOT NULL PRIMARY KEY DEFAULT 1,
        `balance` decimal(18,2) DEFAULT 0.00
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    INSERT IGNORE INTO `chicken_pool` (`id`, `balance`) VALUES (1, 0.00);
");

$action = $_GET['action'] ?? '';
$input  = json_decode(file_get_contents('php://input'), true) ?: [];

if ($action === 'get_state') {
    $stmt = $pdo->prepare('SELECT balance FROM users WHERE id = ?');
    $stmt->execute([$user_id]);
    $u = $stmt->fetch();
    echo json_encode([
        'ok' => true,
        'balance_usd' => (float)($u['balance'] ?? 0),
        'fx_rate' => 1
    ]);
    exit;
}

if ($action === 'place_bet') {
    $amount = isset($input['amount']) ? round((float)$input['amount'], 2) : 0.0;
    
    // Aligned to 10 PKR min bet
    if ($amount < 10) {
        echo json_encode(['ok' => false, 'error' => 'Minimum bet is 10']);
        exit;
    }
    
    $round_token = 'chk_' . bin2hex(random_bytes(8)) . '_' . time();

    try {
        $pdo->beginTransaction();
        
        $stmt = $pdo->prepare('SELECT balance, wager FROM users WHERE id = ? FOR UPDATE');
        $stmt->execute([$user_id]);
        $u = $stmt->fetch();
        if (!$u || (float)$u['balance'] < $amount) {
            throw new Exception("Insufficient balance");
        }
        
        // 70% RTP goes to the shared prize pool
        $pool_add = round($amount * 0.70, 2);
        
        $stmt = $pdo->prepare('UPDATE chicken_pool SET balance = balance + ? WHERE id = 1');
        $stmt->execute([$pool_add]);
        
        // Deduct balance and wager requirements
        $stmt = $pdo->prepare('UPDATE users SET balance = balance - ?, wager = GREATEST(0, wager - ?) WHERE id = ?');
        $stmt->execute([$amount, $amount, $user_id]);
        
        $stmt = $pdo->prepare("
            INSERT INTO chicken_bets (user_id, round_token, amount, multiplier, winnings, is_won, is_settled, created_at)
            VALUES (?, ?, ?, 0.00, 0.00, 0, 0, NOW())
        ");
        $stmt->execute([$user_id, $round_token, $amount]);
        
        $pdo->commit();
        
        echo json_encode([
            'ok' => true,
            'round_token' => $round_token,
            'balance_usd' => round((float)$u['balance'] - $amount, 2)
        ]);
        exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
        exit;
    }
}

if ($action === 'step') {
    $round_token = trim((string)($input['round_token'] ?? ''));
    $req_multiplier = isset($input['next_multiplier']) ? (float)$input['next_multiplier'] : 1.05;
    
    if (!$round_token) {
        echo json_encode(['ok' => false, 'error' => 'Missing round token']);
        exit;
    }

    try {
        $pdo->beginTransaction();
        
        $stmt = $pdo->prepare('SELECT * FROM chicken_bets WHERE round_token = ? FOR UPDATE');
        $stmt->execute([$round_token]);
        $bet = $stmt->fetch();
        
        if (!$bet) throw new Exception("Bet not found");
        if ((int)$bet['user_id'] !== $user_id) throw new Exception("Unauthorized");
        if ((int)$bet['is_settled'] === 1) {
            echo json_encode(['ok' => false, 'error' => 'Bet already settled', 'trap' => true]);
            $pdo->rollBack();
            exit;
        }

        $current_mult = (float)$bet['multiplier'];
        if ($current_mult == 0.00) {
            $next_multiplier = 1.05;
        } else if ($req_multiplier > $current_mult + 0.06) {
            $next_multiplier = $current_mult + 0.05;
        } else {
            $next_multiplier = $req_multiplier;
        }

        $amount = (float)$bet['amount'];
        $payout = round($amount * $next_multiplier, 2);
        
        $stmt = $pdo->prepare('SELECT balance FROM chicken_pool WHERE id = 1 FOR UPDATE');
        $stmt->execute();
        $pool = $stmt->fetch();
        $pool_bal = (float)($pool['balance'] ?? 0);
        
        $force_random_loss = (random_int(1, 100) <= 15);
        
        if ($pool_bal < $payout || $force_random_loss) {
            // TRAP!
            $stmt = $pdo->prepare("UPDATE chicken_bets SET is_won = 0, multiplier = ?, winnings = 0, is_settled = 1, settled_at = NOW() WHERE id = ?");
            $stmt->execute([$next_multiplier, $bet['id']]);
            $pdo->commit();
            echo json_encode(['ok' => true, 'trap' => true, 'multiplier' => $next_multiplier]);
            exit;
        } else {
            // SAFE!
            $stmt = $pdo->prepare("UPDATE chicken_bets SET multiplier = ? WHERE id = ?");
            $stmt->execute([$next_multiplier, $bet['id']]);
            $pdo->commit();
            echo json_encode(['ok' => true, 'trap' => false, 'multiplier' => $next_multiplier]);
            exit;
        }
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
        exit;
    }
}

if ($action === 'settle') {
    $round_token = trim((string)($input['round_token'] ?? ''));
    $multiplier = isset($input['multiplier']) ? max(1.0, (float)$input['multiplier']) : 1.0;
    $is_won_client = (isset($input['is_won']) && (int)$input['is_won'] === 1) ? 1 : 0;
    
    if (!$round_token) {
        echo json_encode(['ok' => false, 'error' => 'Missing round token']);
        exit;
    }

    try {
        $pdo->beginTransaction();
        
        $stmt = $pdo->prepare('SELECT balance FROM users WHERE id = ? FOR UPDATE');
        $stmt->execute([$user_id]);
        $u = $stmt->fetch();
        if (!$u) throw new Exception("User not found");
        
        $stmt = $pdo->prepare('SELECT * FROM chicken_bets WHERE round_token = ? FOR UPDATE');
        $stmt->execute([$round_token]);
        $bet = $stmt->fetch();
        
        if (!$bet) {
            throw new Exception("Bet not found");
        }
        if ((int)$bet['user_id'] !== $user_id) {
            throw new Exception("Unauthorized");
        }
        if ((int)$bet['is_settled'] === 1) {
            echo json_encode(['ok' => true, 'already' => true, 'balance_usd' => (float)$u['balance']]);
            $pdo->commit();
            exit;
        }

        $amount = (float)$bet['amount'];
        $multiplier = (float)$bet['multiplier'];
        
        // Calculate payout from the safe server multiplier
        $payout = round($amount * $multiplier, 2);
        
        if ($multiplier > 0) {
            $stmt = $pdo->prepare('SELECT balance FROM chicken_pool WHERE id = 1 FOR UPDATE');
            $stmt->execute();
            
            $stmt = $pdo->prepare('UPDATE chicken_pool SET balance = GREATEST(0, balance - ?) WHERE id = 1');
            $stmt->execute([$payout]);
            
            $stmt = $pdo->prepare('UPDATE users SET balance = balance + ? WHERE id = ?');
            $stmt->execute([$payout, $user_id]);
        }
        
        $stmt = $pdo->prepare("
            UPDATE chicken_bets 
            SET is_won = 1, winnings = ?, is_settled = 1, settled_at = NOW() 
            WHERE id = ?
        ");
        $stmt->execute([$payout, $bet['id']]);
        
        $pdo->commit();
        
        $stmt = $pdo->prepare('SELECT balance FROM users WHERE id = ?');
        $stmt->execute([$user_id]);
        $u_fresh = $stmt->fetch();
        
        echo json_encode([
            'ok' => true,
            'is_won' => 1,
            'payout' => $payout,
            'multiplier' => $multiplier,
            'balance_usd' => (float)($u_fresh['balance'] ?? 0)
        ]);
        exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
        exit;
    }
}

echo json_encode(['ok' => false, 'error' => 'Invalid action']);