<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/special_odds_engine.php';

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

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

mocker_require_csrf_post();

$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;
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) ?: [];
$matchId = (int) ($input['matchId'] ?? 0);
$stake = (int) ($input['stake'] ?? 0);

if ($matchId <= 0) {
    echo json_encode(['ok' => false, 'error' => 'bad_request'], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($stake < SPECIAL_ODDS_MIN_STAKE || $stake > SPECIAL_ODDS_MAX_STAKE) {
    echo json_encode(
        [
            'ok' => false,
            'error' => 'stake_range',
            'min' => SPECIAL_ODDS_MIN_STAKE,
            'max' => SPECIAL_ODDS_MAX_STAKE,
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

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

$now = time();

try {
    $pdo->beginTransaction();

    $st = $pdo->prepare(
        'SELECT * FROM special_odds_matches WHERE id = :id AND is_active = 1 LIMIT 1'
    );
    $st->execute([':id' => $matchId]);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    if (!$row) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => 'match_not_found'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    if ((string) ($row['status'] ?? '') !== 'open') {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => 'match_closed'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    if ((int) ($row['kickoff_at'] ?? 0) <= $now) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => 'kickoff_passed'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $pick = strtolower(trim((string) ($row['admin_pick'] ?? 'home')));
    if (!in_array($pick, ['home', 'draw', 'away'], true)) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => 'bad_config'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $od = special_odds_decimal_for_pick($row, $pick);
    if ($od < SPECIAL_ODDS_MIN_ODDS || $od > SPECIAL_ODDS_MAX_ODDS) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => 'odds_invalid'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $maxP = isset($row['max_participants']) ? max(0, (int) $row['max_participants']) : 0;
    $cnt = $pdo->prepare(
        'SELECT COUNT(*) FROM special_odds_bets WHERE match_id = :m AND status = \'pending\''
    );
    $cnt->execute([':m' => $matchId]);
    $n = (int) $cnt->fetchColumn();
    if ($maxP > 0 && $n >= $maxP) {
        $pdo->rollBack();
        echo json_encode(
            [
                'ok' => false,
                'error' => 'participants_full',
                'max' => $maxP,
                'current' => $n,
            ],
            JSON_UNESCAPED_UNICODE
        );
        exit;
    }

    $dup = $pdo->prepare(
        "SELECT id FROM special_odds_bets WHERE user_id = :u AND match_id = :m AND status = 'pending' LIMIT 1"
    );
    $dup->execute([':u' => $uid, ':m' => $matchId]);
    if ($dup->fetch()) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => 'already_bet'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $payout = special_odds_payout_amount($stake, $od);

    $stUser = $pdo->prepare('SELECT coins FROM users WHERE id = :id LIMIT 1');
    $stUser->execute([':id' => $uid]);
    $urow = $stUser->fetch(PDO::FETCH_ASSOC);
    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 < $stake) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => 'insufficient_coins', 'coins' => $coins], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $pdo->prepare('UPDATE users SET coins = coins - :s WHERE id = :id')->execute([':s' => $stake, ':id' => $uid]);

    $ins = $pdo->prepare(
        'INSERT INTO special_odds_bets (match_id, user_id, pick, stake, odds_applied, payout_on_win, status, created_at)
         VALUES (:mid, :uid, :pick, :stake, :odds, :pay, \'pending\', :t)'
    );
    $ins->execute([
        ':mid' => $matchId,
        ':uid' => $uid,
        ':pick' => $pick,
        ':stake' => $stake,
        ':odds' => $od,
        ':pay' => $payout,
        ':t' => $now,
    ]);

    $pdo->commit();

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

    echo json_encode(
        [
            'ok' => true,
            'betId' => (int) $pdo->lastInsertId(),
            'coins' => $newCoins,
            'payoutOnWin' => $payout,
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'save'], JSON_UNESCAPED_UNICODE);
    exit;
}
