<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/roulette_engine.php';
require_once __DIR__ . '/games_settings_helpers.php';
require_once __DIR__ . '/level_lib.php';

header('Content-Type: application/json; charset=utf-8');

$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

$meta = roulette_public_meta();

if ($method === 'GET') {
    if ($uid <= 0) {
        echo json_encode(
            [
                'ok' => true,
                'authenticated' => false,
                'minBet' => ROULETTE_MIN_BET,
                'maxBet' => ROULETTE_MAX_BET,
                'meta' => $meta,
            ],
            JSON_UNESCAPED_UNICODE
        );
        exit;
    }
    $st = $pdo->prepare('SELECT coins FROM users WHERE id = :id LIMIT 1');
    $st->execute([':id' => $uid]);
    $row = $st->fetch();
    if (!$row) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'user'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $coins = (int) $row['coins'];
    echo json_encode(
        [
            'ok' => true,
            'authenticated' => true,
            'coins' => $coins,
            'minBet' => ROULETTE_MIN_BET,
            'maxBet' => ROULETTE_MAX_BET,
            'meta' => $meta,
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

if ($method !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

mocker_require_csrf_post();

if ($uid <= 0) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth'], JSON_UNESCAPED_UNICODE);
    exit;
}

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

if ($action !== 'spin') {
    echo json_encode(['ok' => false, 'error' => 'action'], JSON_UNESCAPED_UNICODE);
    exit;
}

$bet = (int) ($input['bet'] ?? 0);
if ($bet < ROULETTE_MIN_BET || $bet > ROULETTE_MAX_BET) {
    echo json_encode(['ok' => false, 'error' => 'bet_range', 'min' => ROULETTE_MIN_BET, 'max' => ROULETTE_MAX_BET], JSON_UNESCAPED_UNICODE);
    exit;
}

$betType = strtolower(trim((string) ($input['betType'] ?? '')));
$betValueRaw = $input['betValue'] ?? null;

$needsValue = in_array($betType, ['straight', 'dozen', 'column'], true);
if ($needsValue && ($betValueRaw === null || $betValueRaw === '')) {
    echo json_encode(['ok' => false, 'error' => 'bad_value'], JSON_UNESCAPED_UNICODE);
    exit;
}
if (!$needsValue) {
    $betValueRaw = null;
}

$eval = roulette_evaluate_bet($betType, $betValueRaw, 0);
if (!$eval['ok']) {
    echo json_encode(['ok' => false, 'error' => $eval['error'] ?? 'bad_type'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $pdo->beginTransaction();

    $stUser = $pdo->prepare('SELECT coins FROM users WHERE id = :id LIMIT 1');
    $stUser->execute([':id' => $uid]);
    $urow = $stUser->fetch();
    if (!$urow) {
        $pdo->rollBack();
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'user'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $coins = (int) $urow['coins'];
    if ($coins < $bet) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => 'coins'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $upd = $pdo->prepare('UPDATE users SET coins = coins - :b WHERE id = :id AND coins >= :b');
    $upd->execute([':b' => $bet, ':id' => $uid]);
    if ($upd->rowCount() !== 1) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => 'coins'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $winning = mocker_games_roulette_spin_for_bet($betType, $betValueRaw);
    $eval2 = roulette_evaluate_bet($betType, $betValueRaw, $winning);
    if (!$eval2['ok']) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => $eval2['error'] ?? 'bad_type'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $mult = (int) ($eval2['mult'] ?? 0);
    $payout = $mult > 0 ? (int) ($bet * $mult) : 0;

    if ($payout > 0) {
        $up2 = $pdo->prepare('UPDATE users SET coins = coins + :p WHERE id = :id');
        $up2->execute([':p' => $payout, ':id' => $uid]);
    }

    $betValueDb = null;
    if ($betValueRaw !== null && $betValueRaw !== '') {
        $betValueDb = (int) $betValueRaw;
    }

    try {
        $roundId = 0;
        $ins = $pdo->prepare(
            'INSERT INTO roulette_rounds (user_id, created_at, bet, bet_type, bet_value, winning_number, multiplier, payout)
             VALUES (:uid, :t, :bet, :bt, :bv, :wn, :m, :pay)'
        );
        $ins->execute([
            ':uid' => $uid,
            ':t' => time(),
            ':bet' => $bet,
            ':bt' => $betType,
            ':bv' => $betValueDb,
            ':wn' => $winning,
            ':m' => $mult,
            ':pay' => $payout,
        ]);
        $roundId = (int) $pdo->lastInsertId();
        if ($roundId > 0) {
            mocker_level_award_game_round($pdo, $uid, 'roulette', $roundId);
        }
    } catch (Throwable $e) {
        error_log('roulette_rounds: ' . $e->getMessage());
    }

    $pdo->commit();

    $st2 = $pdo->prepare('SELECT coins FROM users WHERE id = :id LIMIT 1');
    $st2->execute([':id' => $uid]);
    $coinsAfter = (int) ($st2->fetch()['coins'] ?? 0);

    $winAngleDeg = roulette_win_angle_deg($winning);
    $net = $payout - $bet;

    $message = $payout > 0
        ? ($mult >= 36 ? 'Tam isabet — tek sayı!' : 'Kazandın!')
        : ($winning === 0 ? 'Sıfır — bahisler krupiyede.' : 'Bu tur olmadı — tekrar dene.');

    echo json_encode(
        [
            'ok' => true,
            'coins' => $coinsAfter,
            'winning' => $winning,
            'winAngleDeg' => $winAngleDeg,
            'betType' => $betType,
            'betValue' => $betValueDb,
            'multiplier' => $mult,
            'payout' => $payout,
            'net' => $net,
            'message' => $message,
        ],
        JSON_UNESCAPED_UNICODE
    );
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log('game_roulette: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'server'], JSON_UNESCAPED_UNICODE);
}
