<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once("backend/functions.php");

global $CURUSER, $site_config, $phpself;

dbconn(false);

$site_config["LEFTNAV"] = false;
$site_config["MIDDLENAV"] = false;
$site_config["RIGHTNAV"] = false;

if (empty($CURUSER) || (int)$CURUSER["class"] < 1) {
    show_error_msg("Blackjack", "You do not have permission to play blackjack.", 1);
}

$phpself = "blackjack.php";
$userId = (int)$CURUSER["id"];

$MB = 1024 * 1024;
$GB = 1024 * 1024 * 1024;

$minBet = isset($site_config["blackjack_min_bet"])
    ? (int)$site_config["blackjack_min_bet"]
    : 100 * $MB;

$maxBet = isset($site_config["blackjack_max_bet"])
    ? (int)$site_config["blackjack_max_bet"]
    : 200 * $GB;

$GLOBALS["blackjack_max_bet_runtime"] = $maxBet;


/*
 * --------------------------------------------------------------------------
 * Helpers
 * --------------------------------------------------------------------------
 */

function bj_h(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, "UTF-8");
}

function bj_db(): mysqli
{
    if (
        empty($GLOBALS["DBconnector"])
        || !($GLOBALS["DBconnector"] instanceof mysqli)
    ) {
        throw new RuntimeException("Database connection is not available.");
    }

    return $GLOBALS["DBconnector"];
}

function bj_query_one(mysqli $db, string $sql): ?array
{
    $result = $db->query($sql);

    if (!($result instanceof mysqli_result)) {
        throw new RuntimeException("Blackjack database query failed.");
    }

    $row = $result->fetch_assoc();
    $result->free();

    return $row ?: null;
}

function bj_balance(int $userId): int
{
    $db = bj_db();

    $row = bj_query_one(
        $db,
        "SELECT uploaded
         FROM users
         WHERE id = " . $userId . "
         LIMIT 1"
    );

    return $row ? (int)$row["uploaded"] : 0;
}

function bj_query_all(mysqli $db, string $sql): array
{
    $result = $db->query($sql);

    if (!($result instanceof mysqli_result)) {
        throw new RuntimeException("Blackjack database query failed.");
    }

    $rows = [];

    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }

    $result->free();

    return $rows;
}

function bj_signed_size(int $bytes): string
{
    if ($bytes > 0) {
        return "+" . mksize($bytes);
    }

    if ($bytes < 0) {
        return "-" . mksize(abs($bytes));
    }

    return mksize(0);
}

function bj_player_stats(int $userId): array
{
    $db = bj_db();

    $row = bj_query_one(
        $db,
        "SELECT
            COUNT(*) AS hands,
            SUM(CASE WHEN r.result IN ('win','blackjack') THEN 1 ELSE 0 END) AS wins,
            SUM(CASE WHEN r.result = 'loss' THEN 1 ELSE 0 END) AS losses,
            SUM(CASE WHEN r.result = 'push' THEN 1 ELSE 0 END) AS pushes,
            SUM(CASE WHEN r.result = 'blackjack' THEN 1 ELSE 0 END) AS blackjacks,
            COALESCE(SUM(r.wager), 0) AS wagered,
            COALESCE(SUM(r.payout), 0) AS payouts,
            COALESCE(SUM(r.profit), 0) AS net_profit,
            COALESCE(MAX(CASE WHEN r.profit > 0 THEN r.profit ELSE 0 END), 0) AS biggest_win
         FROM (
             SELECT result, wager, payout, profit 
             FROM blackjack_games 
             WHERE user_id = $userId AND status = 'settled'
             
             UNION ALL
             
             SELECT 
                 CASE 
                    WHEN result = 'loss' THEN 'win'
                    WHEN result = 'win' THEN 'loss'
                    WHEN result = 'blackjack' THEN 'loss'
                    ELSE result 
                 END AS result,
                 wager,
                 CASE 
                    WHEN result = 'loss' THEN wager * 2
                    WHEN result = 'push' THEN wager
                    ELSE 0 
                 END AS payout,
                 CASE 
                    WHEN result = 'loss' THEN CAST(wager AS SIGNED)
                    WHEN result = 'push' THEN 0
                    ELSE CAST(wager AS SIGNED) * -1 
                 END AS profit
             FROM blackjack_games 
             WHERE opponent_id = $userId AND status = 'settled'
         ) AS r"
    );

    $stats = [
        "hands" => $row ? (int)$row["hands"] : 0,
        "wins" => $row ? (int)$row["wins"] : 0,
        "losses" => $row ? (int)$row["losses"] : 0,
        "pushes" => $row ? (int)$row["pushes"] : 0,
        "blackjacks" => $row ? (int)$row["blackjacks"] : 0,
        "wagered" => $row ? (int)$row["wagered"] : 0,
        "payouts" => $row ? (int)$row["payouts"] : 0,
        "net_profit" => $row ? (int)$row["net_profit"] : 0,
        "biggest_win" => $row ? (int)$row["biggest_win"] : 0,
        "current_streak_type" => "none",
        "current_streak" => 0,
        "best_win_streak" => 0,
    ];

    $results = bj_query_all(
        $db,
        "SELECT r.result
         FROM (
             SELECT id, result 
             FROM blackjack_games 
             WHERE user_id = $userId AND status = 'settled'
             
             UNION ALL
             
             SELECT id, 
                 CASE 
                    WHEN result = 'loss' THEN 'win'
                    WHEN result = 'win' THEN 'loss'
                    WHEN result = 'blackjack' THEN 'loss'
                    ELSE result 
                 END AS result
             FROM blackjack_games 
             WHERE opponent_id = $userId AND status = 'settled'
         ) AS r
         ORDER BY r.id ASC"
    );

    $currentType = "none";
    $currentCount = 0;
    $bestWin = 0;
    $runningWins = 0;

    foreach ($results as $resultRow) {
        $result = (string)$resultRow["result"];

        if ($result === "push") {
            continue;
        }

        $type = in_array($result, ["win", "blackjack"], true)
            ? "win"
            : "loss";

        if ($type === $currentType) {
            $currentCount++;
        } else {
            $currentType = $type;
            $currentCount = 1;
        }

        if ($type === "win") {
            $runningWins++;
            if ($runningWins > $bestWin) {
                $bestWin = $runningWins;
            }
        } else {
            $runningWins = 0;
        }
    }

    $stats["current_streak_type"] = $currentType;
    $stats["current_streak"] = $currentCount;
    $stats["best_win_streak"] = $bestWin;

    return $stats;
}

function bj_pvp_start_hand(int $userId, int $wager, array $deck): int {
    $db = bj_db();
    $db->begin_transaction();

    try {
        $activeCount = bj_query_one($db, "SELECT COUNT(*) as cnt FROM blackjack_games WHERE user_id = $userId AND status IN ('pvp_p1', 'waiting') FOR UPDATE");
        if ($activeCount && $activeCount['cnt'] >= 3) {
            throw new RuntimeException("You already have 3 PvP tables active or waiting. Please wait for opponents or cancel one.");
        }

        $user = bj_query_one($db, "SELECT uploaded FROM users WHERE id = $userId LIMIT 1 FOR UPDATE");
        if (!$user || (int)$user["uploaded"] < $wager) {
            throw new RuntimeException("Insufficient upload balance.");
        }

        $shoe = bj_shuffle_codes(array_keys($deck));
        $shoePos = 0;
        
        $playerCards = [bj_draw($shoe, $shoePos), bj_draw($shoe, $shoePos)]; 
        $dealerCards = [bj_draw($shoe, $shoePos), bj_draw($shoe, $shoePos)]; 
        $playerPoints = bj_hand_value($playerCards, $deck);
        $dealerPoints = bj_hand_value($dealerCards, $deck);

        $db->query("UPDATE users SET uploaded = uploaded - $wager WHERE id = $userId");

        $now = date('Y-m-d H:i:s');
        
        $status = ($playerPoints === 21) ? 'waiting' : 'pvp_p1';
        $activeKey = ($status === 'pvp_p1') ? "pvp_p1:$userId" : NULL;
        
        $sql = "INSERT INTO blackjack_games (user_id, active_key, wager, status, shoe, shoe_pos, player_cards, dealer_cards, player_points, dealer_points, created_at, updated_at) 
                VALUES ($userId, " . ($activeKey ? "'$activeKey'" : "NULL") . ", $wager, '$status', '" . $db->real_escape_string(implode(",", $shoe)) . "', $shoePos, '" . $db->real_escape_string(implode(",", $playerCards)) . "', '" . $db->real_escape_string(implode(",", $dealerCards)) . "', $playerPoints, $dealerPoints, '$now', '$now')";
        
        $db->query($sql);
        $gameId = (int)$db->insert_id;

        $db->commit();
        return $gameId;
    } catch (Throwable $e) {
        $db->rollback();
        throw $e;
    }
}

function bj_pvp_join_hand(int $userId, int $gameId, array $deck): void {
    $db = bj_db();
    $db->begin_transaction();

    try {
        $game = bj_query_one($db, "SELECT * FROM blackjack_games WHERE id = $gameId AND status = 'waiting' LIMIT 1 FOR UPDATE");
        if (!$game) {
            throw new RuntimeException("Game not found or already in progress.");
        }

        if ((int)$game["user_id"] === $userId) {
            throw new RuntimeException("You cannot join your own game.");
        }

        $wager = (int)$game["wager"];
        $user = bj_query_one($db, "SELECT uploaded FROM users WHERE id = $userId LIMIT 1 FOR UPDATE");
        if (!$user || (int)$user["uploaded"] < $wager) {
            throw new RuntimeException("Insufficient upload balance.");
        }

        $db->query("UPDATE users SET uploaded = uploaded - $wager WHERE id = $userId");
        $now = date('Y-m-d H:i:s');

        $dealerCards = bj_codes_from_string((string)$game['dealer_cards']);
        $dealerPoints = bj_hand_value($dealerCards, $deck);

        if ($dealerPoints === 21) {
            $db->query("UPDATE blackjack_games SET opponent_id = $userId, status = 'pvp_p2' WHERE id = $gameId");
            $game['opponent_id'] = $userId;
            $game['status'] = 'pvp_p2';
            bj_settle_locked($db, $game, $deck, false);
        } else {
            $activeKey = "pvp_p2:$userId";
            $db->query("UPDATE blackjack_games SET opponent_id = $userId, status = 'pvp_p2', active_key = '$activeKey', updated_at = '$now' WHERE id = $gameId");
        }
        
        $db->commit();

    } catch (Throwable $e) {
        $db->rollback();
        throw $e;
    }
}

function bj_pvp_cancel_hand(int $userId, int $gameId): void {
    $db = bj_db();
    $db->begin_transaction();
    try {
        $game = bj_query_one($db, "SELECT * FROM blackjack_games WHERE id = $gameId AND user_id = $userId AND status = 'waiting' LIMIT 1 FOR UPDATE");
        if ($game) {
            $wager = (int)$game['wager'];
            $db->query("UPDATE users SET uploaded = uploaded + $wager WHERE id = $userId");
            $db->query("UPDATE blackjack_games SET status = 'cancelled', active_key = NULL WHERE id = $gameId");
        }
        $db->commit();
    } catch (Throwable $e) {
        $db->rollback();
        throw $e;
    }
}

function bj_leaderboard(int $limit = 10): array
{
    $db = bj_db();
    $limit = max(1, min(25, $limit));

    return bj_query_all(
        $db,
        "SELECT
            u.id,
            u.username,
            COUNT(*) AS hands,
            SUM(CASE WHEN r.result IN ('win','blackjack') THEN 1 ELSE 0 END) AS wins,
            SUM(CASE WHEN r.result = 'loss' THEN 1 ELSE 0 END) AS losses,
            SUM(CASE WHEN r.result = 'push' THEN 1 ELSE 0 END) AS pushes,
            SUM(CASE WHEN r.result = 'blackjack' THEN 1 ELSE 0 END) AS blackjacks,
            COALESCE(SUM(r.profit), 0) AS net_profit,
            COALESCE(MAX(CASE WHEN r.profit > 0 THEN r.profit ELSE 0 END), 0) AS biggest_win
         FROM (
             SELECT user_id AS p_id, result, profit 
             FROM blackjack_games 
             WHERE status = 'settled' AND user_id > 0
             
             UNION ALL
             
             SELECT opponent_id AS p_id,
                 CASE 
                    WHEN result = 'loss' THEN 'win'
                    WHEN result = 'win' THEN 'loss'
                    WHEN result = 'blackjack' THEN 'loss'
                    ELSE result 
                 END AS result,
                 CASE 
                    WHEN result = 'loss' THEN CAST(wager AS SIGNED)
                    WHEN result = 'push' THEN 0
                    ELSE CAST(wager AS SIGNED) * -1 
                 END AS profit
             FROM blackjack_games 
             WHERE status = 'settled' AND opponent_id IS NOT NULL AND opponent_id > 0
         ) AS r
         INNER JOIN users AS u ON u.id = r.p_id
         GROUP BY u.id, u.username
         ORDER BY net_profit DESC, wins DESC, hands DESC, u.username ASC
         LIMIT " . $limit
    );
}

function bj_admin_stat_players(): array
{
    $db = bj_db();

    return bj_query_all(
        $db,
        "SELECT
            u.id,
            u.username,
            COUNT(*) AS hands
         FROM (
             SELECT user_id AS p_id 
             FROM blackjack_games 
             WHERE status = 'settled' AND user_id > 0
             
             UNION ALL
             
             SELECT opponent_id AS p_id 
             FROM blackjack_games 
             WHERE status = 'settled' AND opponent_id IS NOT NULL AND opponent_id > 0
         ) AS r
         INNER JOIN users AS u ON u.id = r.p_id
         GROUP BY u.id, u.username
         ORDER BY u.username ASC"
    );
}

function bj_admin_reset_stats(int $targetUserId): int
{
    global $CURUSER;

    if (empty($CURUSER) || (int)$CURUSER["class"] < 7) {
        throw new RuntimeException("You do not have permission to reset blackjack stats.");
    }

    if ($targetUserId <= 0) {
        throw new RuntimeException("Select a player to reset.");
    }

    $db = bj_db();

    $player = bj_query_one(
        $db,
        "SELECT id, username
         FROM users
         WHERE id = " . $targetUserId . "
         LIMIT 1"
    );

    if (!$player) {
        throw new RuntimeException("That player could not be found.");
    }

    // Completely delete Solo matches for this user
    $db->query(
        "DELETE FROM blackjack_games
         WHERE user_id = " . $targetUserId . "
           AND status = 'settled'
           AND (opponent_id IS NULL OR opponent_id = 0)"
    );
    $deletedSolo = (int)$db->affected_rows;

    // Anonymize ID in PvP matches where they were P1 (Creator)
    $db->query(
        "UPDATE blackjack_games
         SET user_id = 0
         WHERE user_id = " . $targetUserId . "
           AND status = 'settled'
           AND opponent_id > 0"
    );
    $updatedCreator = (int)$db->affected_rows;

    // Anonymize ID in PvP matches where they were P2 (Joiner)
    $db->query(
        "UPDATE blackjack_games
         SET opponent_id = 0
         WHERE opponent_id = " . $targetUserId . "
           AND status = 'settled'"
    );
    $updatedJoiner = (int)$db->affected_rows;

    // If any PvP match is left with id 0 for both user_id and opponent_id (both players reset), delete it
    $db->query(
        "DELETE FROM blackjack_games
         WHERE (user_id IS NULL OR user_id = 0)
           AND (opponent_id IS NULL OR opponent_id = 0)
           AND status = 'settled'"
    );

    $total = $deletedSolo + $updatedCreator + $updatedJoiner;

    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }

    $_SESSION["blackjack_admin_notice"] =
        "Blackjack stats reset for " . (string)$player["username"]
        . ". Cleared " . number_format($total) . " completed hand"
        . ($total === 1 ? "" : "s") . ".";

    return $total;
}

function bj_streak_text(array $stats): string
{
    $count = (int)$stats["current_streak"];
    $type = (string)$stats["current_streak_type"];

    if ($count <= 0 || $type === "none") {
        return "—";
    }

    return $count . " " . ($type === "win" ? "win" : "loss")
        . ($count === 1 ? "" : "s");
}

function bj_render_stats(int $userId): void
{
    $stats = bj_player_stats($userId);
    $decisions = $stats["wins"] + $stats["losses"];
    $winRate = $decisions > 0
        ? number_format(($stats["wins"] / $decisions) * 100, 1) . "%"
        : "—";

    if ($stats["losses"] > 0) {
        $ratio = number_format($stats["wins"] / $stats["losses"], 2);
    } elseif ($stats["wins"] > 0) {
        $ratio = "∞";
    } else {
        $ratio = "—";
    }

    echo '<section class="blackjack-stats-panel">';
    echo '<div class="blackjack-stats-heading">';
    echo '<h2>Your Blackjack Stats</h2>';
    echo '<p>Pushes do not count against win rate or streaks.</p>';
    echo '</div>';

    echo '<div class="blackjack-stats-grid">';

    $cards = [
        ["Hands Played", number_format($stats["hands"])],
        ["Record", $stats["wins"] . "-" . $stats["losses"] . "-" . $stats["pushes"]],
        ["Win Rate", $winRate],
        ["W/L Ratio", $ratio],
        ["Blackjacks", number_format($stats["blackjacks"])],
        ["Current Streak", bj_streak_text($stats)],
        ["Best Win Streak", number_format($stats["best_win_streak"])],
        ["Net Profit", bj_signed_size($stats["net_profit"])],
        ["Biggest Win", $stats["biggest_win"] > 0 ? mksize($stats["biggest_win"]) : "—"],
        ["Total Wagered", mksize($stats["wagered"])],
    ];

    foreach ($cards as $card) {
        echo '<div class="blackjack-stat-card">';
        echo '<span class="blackjack-stat-label">' . bj_h((string)$card[0]) . '</span>';
        echo '<strong class="blackjack-stat-value">' . bj_h((string)$card[1]) . '</strong>';
        echo '</div>';
    }

    echo '</div>';

    $leaders = bj_leaderboard(10);

    echo '<details class="blackjack-leaderboard">';
    echo '<summary>🏆 Leaderboard</summary>';

    if (!$leaders) {
        echo '<p class="blackjack-empty-stats">No completed hands yet.</p>';
    } else {
        echo '<div class="blackjack-leaderboard-wrap">';
        echo '<table class="blackjack-pvp-table" style="margin-top:0;">';
        echo '<thead><tr>';
        echo '<th>#</th><th>Player</th><th>Hands</th><th>Record</th>';
        echo '<th>Win Rate</th><th>Blackjacks</th><th>Net</th><th>Biggest Win</th>';
        echo '</tr></thead><tbody>';

        foreach ($leaders as $index => $leader) {
            $wins = (int)$leader["wins"];
            $losses = (int)$leader["losses"];
            $pushes = (int)$leader["pushes"];
            $leaderDecisions = $wins + $losses;
            $leaderRate = $leaderDecisions > 0
                ? number_format(($wins / $leaderDecisions) * 100, 1) . "%"
                : "—";

            $isCurrent = (int)$leader["id"] === $userId
                ? ' class="blackjack-leaderboard-you"'
                : '';

            echo '<tr' . $isCurrent . '>';
            echo '<td>' . ($index + 1) . '</td>';
            echo '<td>' . bj_h((string)$leader["username"]);
            if ((int)$leader["id"] === $userId) {
                echo ' <span class="blackjack-you-tag">YOU</span>';
            }
            echo '</td>';
            echo '<td>' . number_format((int)$leader["hands"]) . '</td>';
            echo '<td>' . $wins . '-' . $losses . '-' . $pushes . '</td>';
            echo '<td>' . bj_h($leaderRate) . '</td>';
            echo '<td>' . number_format((int)$leader["blackjacks"]) . '</td>';
            echo '<td><span style="color:' . ((int)$leader["net_profit"] >= 0 ? '#34d399' : '#f87171') . '">' . bj_h(bj_signed_size((int)$leader["net_profit"])) . '</span></td>';
            echo '<td>' . ((int)$leader["biggest_win"] > 0
                ? bj_h(mksize((int)$leader["biggest_win"]))
                : '—') . '</td>';
            echo '</tr>';
        }

        echo '</tbody></table>';
        echo '</div>';
    }

    echo '</details>';
    echo '</section>';

    global $CURUSER;

    if (!empty($CURUSER) && (int)$CURUSER["class"] >= 7) {
        $notice = "";

        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (!empty($_SESSION["blackjack_admin_notice"])) {
            $notice = (string)$_SESSION["blackjack_admin_notice"];
            unset($_SESSION["blackjack_admin_notice"]);
        }

        $players = bj_admin_stat_players();

        echo '<section class="blackjack-admin-zone" aria-label="Blackjack administration">';
        echo '<div class="blackjack-admin-badge">ADMIN ONLY</div>';
        echo '<h3>Reset Player Blackjack Stats</h3>';
        echo '<p>Only do this at the request of the user. This deletes their blackjack history.</p>';

        if ($notice !== "") {
            echo '<div class="blackjack-admin-notice">' . bj_h($notice) . '</div>';
        }

        if ($players) {
            echo '<form class="blackjack-admin-reset-form" method="post" '
                . 'action="blackjack.php" autocomplete="off">';
            echo '<input type="hidden" name="csrf" value="'
                . bj_h(bj_csrf_token()) . '">';
            echo '<input type="hidden" name="action" value="reset_stats">';
            echo '<select name="target_user_id" class="blackjack-input blackjack-admin-player" required>';
            echo '<option value="">Select player...</option>';

            foreach ($players as $player) {
                echo '<option value="' . (int)$player["id"] . '">'
                    . bj_h((string)$player["username"])
                    . ' — ' . number_format((int)$player["hands"])
                    . ' hand' . ((int)$player["hands"] === 1 ? '' : 's')
                    . '</option>';
            }

            echo '</select>';
            echo '<button class="blackjack-button blackjack-btn-primary blackjack-reset-button" '
                . 'type="submit">Reset Stats</button>';
            echo '</form>';
        } else {
            echo '<p class="blackjack-empty-stats">No player has completed blackjack hands.</p>';
        }

        echo '</section>';
    }
}

function bj_csrf_token(): string
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }

    if (empty($_SESSION["blackjack_csrf"])) {
        $_SESSION["blackjack_csrf"] = bin2hex(random_bytes(32));
    }

    return (string)$_SESSION["blackjack_csrf"];
}

function bj_require_csrf(): void
{
    $posted = isset($_POST["csrf"]) ? (string)$_POST["csrf"] : "";
    $stored = bj_csrf_token();

    if ($posted === "" || !hash_equals($stored, $posted)) {
        show_error_msg(
            "Blackjack",
            "Your blackjack session expired. Reload the page and try again.",
            1
        );
    }
}

function bj_redirect_to_hand(int $gameId, string $animation = ""): void
{
    $location = "blackjack.php?hand=" . $gameId;

    if ($animation !== "") {
        $location .= "&anim=" . rawurlencode($animation);
    }

    header("Location: " . $location);
    exit;
}


/*
 * --------------------------------------------------------------------------
 * The database does NOT contain card definitions.
 * --------------------------------------------------------------------------
 */

function bj_deck(): array
{
    $deck = [];
    $suits = ["p", "b", "k", "c"];

    foreach ($suits as $suit) {
        for ($rank = 2; $rank <= 10; $rank++) {
            $code = $rank . $suit;

            $deck[$code] = [
                "value" => $rank,
                "pic"   => $rank . $suit . ".webp",
            ];
        }

        $deck["v" . $suit] = [
            "value" => 10,
            "pic"   => "v" . $suit . ".webp",
        ];

        $deck["d" . $suit] = [
            "value" => 10,
            "pic"   => "d" . $suit . ".webp",
        ];

        $deck["k" . $suit] = [
            "value" => 10,
            "pic"   => "k" . $suit . ".webp",
        ];

        $deck["t" . $suit] = [
            "value" => 1,
            "pic"   => "t" . $suit . ".webp",
        ];
    }

    return $deck;
}

function bj_shuffle_codes(array $codes): array
{
    $codes = array_values($codes);

    for ($i = count($codes) - 1; $i > 0; $i--) {
        $j = random_int(0, $i);

        if ($i !== $j) {
            $tmp = $codes[$i];
            $codes[$i] = $codes[$j];
            $codes[$j] = $tmp;
        }
    }

    return $codes;
}

function bj_codes_to_string(array $codes): string
{
    return implode(",", $codes);
}

function bj_codes_from_string(string $value): array
{
    if (trim($value) === "") {
        return [];
    }

    return array_values(
        array_filter(
            array_map("trim", explode(",", $value)),
            static function ($item) {
                return $item !== "";
            }
        )
    );
}

function bj_draw(array $shoe, int &$shoePos): string
{
    if (!isset($shoe[$shoePos])) {
        throw new RuntimeException("The blackjack shoe is exhausted.");
    }

    $card = (string)$shoe[$shoePos];
    $shoePos++;

    return $card;
}

function bj_hand_value(array $cards, array $deck): int
{
    $total = 0;
    $aces = 0;

    foreach ($cards as $code) {
        if (!isset($deck[$code])) {
            throw new RuntimeException("Invalid card found in blackjack hand.");
        }

        $value = (int)$deck[$code]["value"];

        if ($value === 1) {
            $aces++;
            $total++;
        } else {
            $total += $value;
        }
    }

    while ($aces > 0 && $total + 10 <= 21) {
        $total += 10;
        $aces--;
    }

    return $total;
}

function bj_is_blackjack(array $cards, array $deck): bool
{
    return count($cards) === 2 && bj_hand_value($cards, $deck) === 21;
}


function bj_can_split(array $cards, array $deck): bool
{
    if (count($cards) !== 2) {
        return false;
    }

    if (!isset($deck[$cards[0]], $deck[$cards[1]])) {
        return false;
    }


    $rankOne = substr((string)$cards[0], 0, 1);
    $rankTwo = substr((string)$cards[1], 0, 1);

    return $rankOne === $rankTwo;
}

function bj_encode_split_state(array $state): string
{
    return "S;"
        . (int)$state["active"] . ";"
        . (string)$state["status"][0] . ";"
        . (string)$state["status"][1] . ";"
        . bj_codes_to_string($state["hands"][0]) . ";"
        . bj_codes_to_string($state["hands"][1]) . ";"
        . (int)$state["base_wager"];
}

function bj_decode_split_state(string $value): ?array
{
    if (strncmp($value, "S;", 2) !== 0) {
        return null;
    }

    $parts = explode(";", $value, 7);

    if (count($parts) !== 7) {
        throw new RuntimeException("Invalid split-hand state.");
    }

    return [
        "active" => max(0, min(1, (int)$parts[1])),
        "status" => [
            (string)$parts[2],
            (string)$parts[3],
        ],
        "hands" => [
            bj_codes_from_string((string)$parts[4]),
            bj_codes_from_string((string)$parts[5]),
        ],
        "base_wager" => (int)$parts[6],
    ];
}

function bj_split_hand_result(
    array $cards,
    int $dealerValue,
    bool $dealerBlackjack,
    array $deck
): string {
    $value = bj_hand_value($cards, $deck);

    if ($dealerBlackjack) {
        return "loss";
    }

    if ($value > 21) {
        return "loss";
    }

    if ($dealerValue > 21) {
        return "win";
    }

    if ($value > $dealerValue) {
        return "win";
    }

    if ($value === $dealerValue) {
        return "push";
    }

    return "loss";
}


/*
 * --------------------------------------------------------------------------
 * Game storage
 * --------------------------------------------------------------------------
 */

function bj_get_active_game(
    mysqli $db,
    int $userId,
    bool $forUpdate = false
): ?array {
    $sql =
        "SELECT *
         FROM blackjack_games
         WHERE (status = 'playing' AND user_id = $userId AND active_key = 'house:$userId')
            OR (status = 'pvp_p1' AND user_id = $userId AND active_key = 'pvp_p1:$userId')
            OR (status = 'pvp_p2' AND opponent_id = $userId AND active_key = 'pvp_p2:$userId')
         LIMIT 1";

    if ($forUpdate) {
        $sql .= " FOR UPDATE";
    }

    return bj_query_one($db, $sql);
}

function bj_get_game(
    mysqli $db,
    int $gameId,
    int $userId
): ?array {
    $sql = "SELECT bg.*, u.username as creator_name, o.username as opponent_name 
            FROM blackjack_games bg 
            LEFT JOIN users u ON u.id = bg.user_id 
            LEFT JOIN users o ON o.id = bg.opponent_id 
            WHERE bg.id = $gameId AND (bg.user_id = $userId OR bg.opponent_id = $userId)
            LIMIT 1";
    return bj_query_one($db, $sql);
}

function bj_get_game_for_update(
    mysqli $db,
    int $gameId,
    int $userId
): ?array {
    $sql = "SELECT bg.*, u.username as creator_name, o.username as opponent_name 
            FROM blackjack_games bg 
            LEFT JOIN users u ON u.id = bg.user_id 
            LEFT JOIN users o ON o.id = bg.opponent_id 
            WHERE bg.id = $gameId AND (bg.user_id = $userId OR bg.opponent_id = $userId)
            LIMIT 1 FOR UPDATE";
    return bj_query_one($db, $sql);
}

function bj_parse_wager(
    array $post,
    int $minBet,
    int $maxBet
): int {
    if (
        isset($post["wager_bytes"])
        && ctype_digit((string)$post["wager_bytes"])
        && (int)$post["wager_bytes"] > 0
    ) {
        $wager = (int)$post["wager_bytes"];
    } else {
        $amount = isset($post["wager_amount"])
            ? (float)$post["wager_amount"]
            : 0.0;

        $unit = isset($post["wager_unit"])
            ? strtoupper((string)$post["wager_unit"])
            : "GB";

        if (!is_finite($amount) || $amount <= 0) {
            throw new RuntimeException("Enter a wager greater than zero.");
        }

        if ($unit === "MB") {
            $multiplier = 1024 * 1024;
        } elseif ($unit === "GB") {
            $multiplier = 1024 * 1024 * 1024;
        } else {
            throw new RuntimeException("Invalid wager unit.");
        }

        $wager = (int)round($amount * $multiplier);
    }

    if ($wager < $minBet) {
        throw new RuntimeException(
            "Minimum wager is " . mksize($minBet) . "."
        );
    }

    if ($wager > $maxBet) {
        throw new RuntimeException(
            "Maximum wager is " . mksize($maxBet) . "."
        );
    }

    return $wager;
}

function bj_update_playing_hand(
    mysqli $db,
    array $game,
    array $playerCards,
    array $dealerCards,
    int $shoePos,
    int $playerValue,
    int $dealerValue,
    ?string $playerCardsStored = null
): void {
    $storedCards = $playerCardsStored !== null
        ? $playerCardsStored
        : bj_codes_to_string($playerCards);

    $now = date('Y-m-d H:i:s');

    $db->query(
        "UPDATE blackjack_games
         SET player_cards = '" . $db->real_escape_string($storedCards) . "',
             dealer_cards = '" . $db->real_escape_string(bj_codes_to_string($dealerCards)) . "',
             shoe_pos = " . $shoePos . ",
             player_points = " . $playerValue . ",
             dealer_points = " . $dealerValue . ",
             updated_at = '" . $now . "'
         WHERE id = " . (int)$game["id"]
    );
}

function send_pm(int $sender, int $receiver, string $subject, string $msg): void
{
    $db = bj_db();
    $added = date('Y-m-d H:i:s');
    $subject_sq = $db->real_escape_string($subject);
    $msg_sq = $db->real_escape_string($msg);
    
    $db->query("INSERT INTO messages (sender, receiver, added, subject, msg) VALUES ($sender, $receiver, '$added', '$subject_sq', '$msg_sq')");
}

function bj_settle_locked(
    mysqli $db,
    array $game,
    array $deck,
    bool $playDealer
): array {
    $isPvP = !empty($game['opponent_id']);
    $now = date('Y-m-d H:i:s');

    if ($isPvP) {
        $wager = (int)$game["wager"];
        $creatorId = (int)$game["user_id"];
        $opponentId = (int)$game["opponent_id"];

        $creatorName = !empty($game['creator_name']) ? $game['creator_name'] : 'Player';
        if ($creatorName === 'Player') {
            $cU = bj_query_one($db, "SELECT username, class FROM users WHERE id = $creatorId LIMIT 1");
            if ($cU) $creatorName = $cU['username'];
        }

        $opponentName = !empty($game['opponent_name']) ? $game['opponent_name'] : 'Player';
        if ($opponentName === 'Player') {
            $oU = bj_query_one($db, "SELECT username, class FROM users WHERE id = $opponentId LIMIT 1");
            if ($oU) $opponentName = $oU['username'];
        }

        $playerValue = (int)$game['player_points']; // P1 (Creator)
        $dealerValue = (int)$game['dealer_points']; // P2 (Joiner)
        $playerCards = bj_codes_from_string((string)$game['player_cards']);
        $dealerCards = bj_codes_from_string((string)$game['dealer_cards']);
        $playerBlackjack = bj_is_blackjack($playerCards, $deck);
        $dealerBlackjack = bj_is_blackjack($dealerCards, $deck);
        $shoePos = (int)$game['shoe_pos'];
        
        $resultForCreator = 'loss'; 
        $payoutCreator = 0;
        $profitCreator = -$wager;
        $payoutOpponent = 0;
        
        $creatorMessage = "";
        $opponentMessage = "";
        $wagerStr = mksize($wager);

        if ($playerValue > 21 && $dealerValue > 21) {
            $resultForCreator = 'push';
            $payoutCreator = $wager;
            $payoutOpponent = $wager;
            $profitCreator = 0;
            $creatorMessage = "Your Blackjack PvP match against {$opponentName} resulted in a PUSH. Both players busted. Your $wagerStr wager was returned.";
            $opponentMessage = "Your Blackjack PvP match against {$creatorName} resulted in a PUSH. Both players busted. Your $wagerStr wager was returned.";
        } elseif ($playerValue > 21) {
            $resultForCreator = 'loss';
            $payoutOpponent = $wager * 2;
            $creatorMessage = "You lost your Blackjack PvP match against {$opponentName}. You busted. You lost your $wagerStr wager.";
            $opponentMessage = "You WON your Blackjack PvP match against {$creatorName}! Your opponent busted. You won $wagerStr!";
        } elseif ($dealerValue > 21) {
            $resultForCreator = 'win';
            $payoutCreator = $wager * 2;
            $profitCreator = $wager;
            $creatorMessage = "You WON your Blackjack PvP match against {$opponentName}! Your opponent busted. You won $wagerStr!";
            $opponentMessage = "You lost your Blackjack PvP match against {$creatorName}. You busted. You lost your $wagerStr wager.";
        } elseif ($playerBlackjack && $dealerBlackjack) {
            $resultForCreator = 'push';
            $payoutCreator = $wager;
            $payoutOpponent = $wager;
            $profitCreator = 0;
            $creatorMessage = "Your Blackjack PvP match against {$opponentName} resulted in a PUSH. Both players had Blackjack. Your $wagerStr wager was returned.";
            $opponentMessage = "Your Blackjack PvP match against {$creatorName} resulted in a PUSH. Both players had Blackjack. Your $wagerStr wager was returned.";
        } elseif ($playerBlackjack) {
            $resultForCreator = 'win';
            $payoutCreator = $wager * 2;
            $profitCreator = $wager;
            $creatorMessage = "You WON your Blackjack PvP match against {$opponentName} with a Blackjack! You won $wagerStr!";
            $opponentMessage = "You lost your Blackjack PvP match against {$creatorName}. Your opponent had Blackjack. You lost your $wagerStr wager.";
        } elseif ($dealerBlackjack) {
            $resultForCreator = 'loss';
            $payoutOpponent = $wager * 2;
            $creatorMessage = "You lost your Blackjack PvP match against {$opponentName}. Your opponent had Blackjack. You lost your $wagerStr wager.";
            $opponentMessage = "You WON your Blackjack PvP match against {$creatorName} with a Blackjack! You won $wagerStr!";
        } elseif ($playerValue > $dealerValue) {
            $resultForCreator = 'win';
            $payoutCreator = $wager * 2;
            $profitCreator = $wager;
            $creatorMessage = "You WON your Blackjack PvP match against {$opponentName} ($playerValue points to $dealerValue). You won $wagerStr!";
            $opponentMessage = "You lost your Blackjack PvP match against {$creatorName} ($dealerValue points to $playerValue). You lost your $wagerStr wager.";
        } elseif ($dealerValue > $playerValue) {
            $resultForCreator = 'loss';
            $payoutOpponent = $wager * 2;
            $creatorMessage = "You lost your Blackjack PvP match against {$opponentName} ($playerValue points to $dealerValue). You lost your $wagerStr wager.";
            $opponentMessage = "You WON your Blackjack PvP match against {$creatorName} ($dealerValue points to $playerValue). You won $wagerStr!";
        } else {
            $resultForCreator = 'push';
            $payoutCreator = $wager;
            $payoutOpponent = $wager;
            $profitCreator = 0;
            $creatorMessage = "Your Blackjack PvP match against {$opponentName} resulted in a PUSH (Tie at $playerValue points). Your $wagerStr wager was returned.";
            $opponentMessage = "Your Blackjack PvP match against {$creatorName} resulted in a PUSH (Tie at $dealerValue points). Your $wagerStr wager was returned.";
        }

        if ($payoutCreator > 0) {
            $db->query("UPDATE users SET uploaded = uploaded + $payoutCreator WHERE id = $creatorId");
        }
        if ($payoutOpponent > 0) {
            $db->query("UPDATE users SET uploaded = uploaded + $payoutOpponent WHERE id = $opponentId");
        }

        $db->query(
            "UPDATE blackjack_games 
             SET status = 'settled', 
                 active_key = NULL, 
                 dealer_cards = '" . $db->real_escape_string(bj_codes_to_string($dealerCards)) . "', 
                 shoe_pos = $shoePos, 
                 dealer_points = $dealerValue, 
                 result = '" . $db->real_escape_string($resultForCreator) . "', 
                 payout = $payoutCreator, 
                 profit = $profitCreator, 
                 updated_at = '$now', 
                 settled_at = '$now' 
             WHERE id = " . $game['id']
        );

        send_pm(0, $creatorId, "Blackjack PvP Result", $creatorMessage);
        send_pm(0, $opponentId, "Blackjack PvP Result", $opponentMessage);

        $game['status'] = 'settled';
        $game['active_key'] = null;
        $game['result'] = $resultForCreator;
        $game['payout'] = $payoutCreator;
        $game['profit'] = $profitCreator;
        
        return $game;
    }


    // SOLO MODE
    $wager = (int)$game["wager"];
    $userId = (int)$game["user_id"];
    $dealerCards = bj_codes_from_string((string)$game["dealer_cards"]);
    $shoe = bj_codes_from_string((string)$game["shoe"]);
    $shoePos = (int)$game["shoe_pos"];
    $dealerValue = bj_hand_value($dealerCards, $deck);
    $dealerBlackjack = bj_is_blackjack($dealerCards, $deck);
    $split = bj_decode_split_state((string)$game["player_cards"]);

    if ($split !== null) {
        $anyLiveHand = false;

        foreach ($split["hands"] as $hand) {
            if (bj_hand_value($hand, $deck) <= 21) {
                $anyLiveHand = true;
                break;
            }
        }

        if ($playDealer && !$dealerBlackjack && $anyLiveHand) {
            while ($dealerValue < 17) {
                $dealerCards[] = bj_draw($shoe, $shoePos);
                $dealerValue = bj_hand_value($dealerCards, $deck);
            }
        }

        $baseWager = (int)$split["base_wager"];
        $payout = 0;
        $handResults = [];

        foreach ($split["hands"] as $hand) {
            $handResult = bj_split_hand_result(
                $hand,
                $dealerValue,
                $dealerBlackjack,
                $deck
            );

            $handResults[] = $handResult;

            if ($handResult === "win") {
                $payout += $baseWager * 2;
            } elseif ($handResult === "push") {
                $payout += $baseWager;
            }
        }

        $profit = $payout - ($baseWager * 2);

        if ($profit > 0) {
            $result = "win";
        } elseif ($profit < 0) {
            $result = "loss";
        } else {
            $result = "push";
        }

        if ($payout > 0) {
            $db->query(
                "UPDATE users
                 SET uploaded = uploaded + " . $payout . "
                 WHERE id = " . $userId
            );
        }

        $playerPoints = bj_hand_value($split["hands"][0], $deck);

        $db->query(
            "UPDATE blackjack_games
             SET active_key = NULL,
                 status = 'settled',
                 player_cards = '" . $db->real_escape_string(bj_encode_split_state($split)) . "',
                 dealer_cards = '" . $db->real_escape_string(bj_codes_to_string($dealerCards)) . "',
                 shoe_pos = " . $shoePos . ",
                 player_points = " . $playerPoints . ",
                 dealer_points = " . $dealerValue . ",
                 result = '" . $db->real_escape_string($result) . "',
                 payout = " . $payout . ",
                 profit = " . $profit . ",
                 updated_at = '" . $now . "',
                 settled_at = '" . $now . "'
             WHERE id = " . (int)$game["id"] . "
               AND status = 'playing'"
        );

        $game["active_key"] = null;
        $game["status"] = "settled";
        $game["player_cards"] = bj_encode_split_state($split);
        $game["dealer_cards"] = bj_codes_to_string($dealerCards);
        $game["shoe_pos"] = $shoePos;
        $game["player_points"] = $playerPoints;
        $game["dealer_points"] = $dealerValue;
        $game["result"] = $result;
        $game["payout"] = $payout;
        $game["profit"] = $profit;

        return $game;
    }

    $playerCards = bj_codes_from_string((string)$game["player_cards"]);
    $playerValue = bj_hand_value($playerCards, $deck);
    $playerBlackjack = bj_is_blackjack($playerCards, $deck);

    if (
        $playDealer
        && !$playerBlackjack
        && !$dealerBlackjack
        && $playerValue <= 21
    ) {
        while ($dealerValue < 17) {
            $dealerCards[] = bj_draw($shoe, $shoePos);
            $dealerValue = bj_hand_value($dealerCards, $deck);
        }
    }

    $result = "loss";
    $payout = 0;
    $profit = -$wager;

    if ($playerBlackjack && $dealerBlackjack) {
        $result = "push";
        $payout = $wager;
        $profit = 0;
    } elseif ($playerBlackjack) {
        $result = "blackjack";
        $profit = intdiv($wager * 3, 2);
        $payout = $wager + $profit;
    } elseif ($dealerBlackjack) {
        $result = "loss";
    } elseif ($playerValue > 21) {
        $result = "loss";
    } elseif ($dealerValue > 21) {
        $result = "win";
        $payout = $wager * 2;
        $profit = $wager;
    } elseif ($playerValue > $dealerValue) {
        $result = "win";
        $payout = $wager * 2;
        $profit = $wager;
    } elseif ($playerValue === $dealerValue) {
        $result = "push";
        $payout = $wager;
        $profit = 0;
    }

    if ($payout > 0) {
        $db->query(
            "UPDATE users
             SET uploaded = uploaded + " . $payout . "
             WHERE id = " . $userId
        );
    }

    $db->query(
        "UPDATE blackjack_games
         SET active_key = NULL,
             status = 'settled',
             player_cards = '" . $db->real_escape_string(bj_codes_to_string($playerCards)) . "',
             dealer_cards = '" . $db->real_escape_string(bj_codes_to_string($dealerCards)) . "',
             shoe_pos = " . $shoePos . ",
             player_points = " . $playerValue . ",
             dealer_points = " . $dealerValue . ",
             result = '" . $db->real_escape_string($result) . "',
             payout = " . $payout . ",
             profit = " . $profit . ",
             updated_at = '" . $now . "',
             settled_at = '" . $now . "'
         WHERE id = " . (int)$game["id"] . "
           AND status = 'playing'"
    );

    $game["active_key"] = null;
    $game["status"] = "settled";
    $game["player_cards"] = bj_codes_to_string($playerCards);
    $game["dealer_cards"] = bj_codes_to_string($dealerCards);
    $game["shoe_pos"] = $shoePos;
    $game["player_points"] = $playerValue;
    $game["dealer_points"] = $dealerValue;
    $game["result"] = $result;
    $game["payout"] = $payout;
    $game["profit"] = $profit;

    return $game;
}

function bj_start_hand(
    int $userId,
    int $wager,
    array $deck
): int {
    $db = bj_db();
    $db->begin_transaction();

    try {
        $user = bj_query_one(
            $db,
            "SELECT uploaded
             FROM users
             WHERE id = " . $userId . "
             LIMIT 1
             FOR UPDATE"
        );

        if (!$user) {
            throw new RuntimeException("Your account could not be loaded.");
        }

        $active = bj_get_active_game($db, $userId, true);

        if ($active) {
            $db->commit();
            return (int)$active["id"];
        }

        $balance = (int)$user["uploaded"];

        if ($balance < $wager) {
            throw new RuntimeException(
                "You do not have enough uploaded credit for that wager."
            );
        }

        $shoe = bj_shuffle_codes(array_keys($deck));
        $shoePos = 0;

        $playerCards = [];
        $dealerCards = [];

        $playerCards[] = bj_draw($shoe, $shoePos);
        $dealerCards[] = bj_draw($shoe, $shoePos);
        $playerCards[] = bj_draw($shoe, $shoePos);
        $dealerCards[] = bj_draw($shoe, $shoePos);

        $playerValue = bj_hand_value($playerCards, $deck);
        $dealerValue = bj_hand_value($dealerCards, $deck);

        $db->query(
            "UPDATE users
             SET uploaded = uploaded - " . $wager . "
             WHERE id = " . $userId
        );

        $now = date('Y-m-d H:i:s');

        $db->query(
            "INSERT INTO blackjack_games
                (
                    user_id,
                    active_key,
                    wager,
                    status,
                    shoe,
                    shoe_pos,
                    player_cards,
                    dealer_cards,
                    player_points,
                    dealer_points,
                    created_at,
                    updated_at
                )
             VALUES
                (
                    " . $userId . ",
                    '" . $db->real_escape_string("house:" . $userId) . "',
                    " . $wager . ",
                    'playing',
                    '" . $db->real_escape_string(bj_codes_to_string($shoe)) . "',
                    " . $shoePos . ",
                    '" . $db->real_escape_string(bj_codes_to_string($playerCards)) . "',
                    '" . $db->real_escape_string(bj_codes_to_string($dealerCards)) . "',
                    " . $playerValue . ",
                    " . $dealerValue . ",
                    '" . $now . "',
                    '" . $now . "'
                )"
        );

        $gameId = (int)$db->insert_id;

        $game = bj_get_game($db, $gameId, $userId);

        if (!$game) {
            throw new RuntimeException(
                "The new blackjack hand could not be loaded."
            );
        }

        if (
            bj_is_blackjack($playerCards, $deck)
            || bj_is_blackjack($dealerCards, $deck)
        ) {
            bj_settle_locked($db, $game, $deck, false);
        }

        $db->commit();

        return $gameId;
    } catch (Throwable $e) {
        $db->rollback();
        throw $e;
    }
}

function bj_play_action(
    int $userId,
    string $action,
    array $deck,
    int $maxBet,
    int $gameId = 0
): int {
    $db = bj_db();
    $db->begin_transaction();

    try {
        if ($gameId > 0) {
            $game = bj_get_game_for_update($db, $gameId, $userId);
        } else {
            $game = bj_get_active_game($db, $userId, true);
        }

        if (!$game) {
            throw new RuntimeException("Game not found or no active hand.");
        }

        $isPvpP1 = $game['status'] === 'pvp_p1' && $userId === (int)$game['user_id'];
        $isPvpP2 = $game['status'] === 'pvp_p2' && $userId === (int)$game['opponent_id'];
        $isSolo = $game['status'] === 'playing' && $userId === (int)$game['user_id'];

        if (!$isPvpP1 && !$isPvpP2 && !$isSolo) {
            throw new RuntimeException("It's not your turn or you are not participating.");
        }

        $gameId = (int)$game["id"];
        $isPvP = $isPvpP1 || $isPvpP2;

        if (($action === "double" || $action === "split") && $isPvP) {
            throw new RuntimeException("Double down and split are disabled in PvP mode.");
        }

        $dealerCards = bj_codes_from_string((string)$game["dealer_cards"]);
        $playerCards = bj_codes_from_string((string)$game["player_cards"]);
        $shoe = bj_codes_from_string((string)$game["shoe"]);
        $shoePos = (int)$game["shoe_pos"];
        $dealerValue = bj_hand_value($dealerCards, $deck);
        $playerValue = bj_hand_value($playerCards, $deck);
        $split = bj_decode_split_state((string)$game["player_cards"]);
        $now = date('Y-m-d H:i:s');

        // Hit Logic
        if ($action === "hit") {
            if ($isPvpP2) {
                $dealerCards[] = bj_draw($shoe, $shoePos);
                $dealerValue = bj_hand_value($dealerCards, $deck);
                $game["dealer_cards"] = bj_codes_to_string($dealerCards);
                $game["shoe_pos"] = $shoePos;
                $game["dealer_points"] = $dealerValue;

                if ($dealerValue >= 21) {
                    bj_settle_locked($db, $game, $deck, false);
                } else {
                    $db->query("UPDATE blackjack_games SET dealer_cards = '" . $db->real_escape_string($game["dealer_cards"]) . "', shoe_pos = $shoePos, dealer_points = $dealerValue, updated_at = '$now' WHERE id = $gameId");
                }
            } elseif ($isPvpP1) {
                $playerCards[] = bj_draw($shoe, $shoePos);
                $playerValue = bj_hand_value($playerCards, $deck);
                $game["player_cards"] = bj_codes_to_string($playerCards);
                $game["shoe_pos"] = $shoePos;
                $game["player_points"] = $playerValue;

                if ($playerValue >= 21) {
                    $db->query("UPDATE blackjack_games SET status = 'waiting', active_key = NULL, player_cards = '" . $db->real_escape_string($game["player_cards"]) . "', shoe_pos = $shoePos, player_points = $playerValue, updated_at = '$now' WHERE id = $gameId");
                } else {
                    $db->query("UPDATE blackjack_games SET player_cards = '" . $db->real_escape_string($game["player_cards"]) . "', shoe_pos = $shoePos, player_points = $playerValue, updated_at = '$now' WHERE id = $gameId");
                }
            } else { // Solo
                $playerCards[] = bj_draw($shoe, $shoePos);
                $playerValue = bj_hand_value($playerCards, $deck);
                $game["player_cards"] = bj_codes_to_string($playerCards);
                $game["shoe_pos"] = $shoePos;
                $game["player_points"] = $playerValue;

                if ($playerValue >= 21) {
                    bj_settle_locked($db, $game, $deck, $playerValue === 21);
                } else {
                    bj_update_playing_hand($db, $game, $playerCards, $dealerCards, $shoePos, $playerValue, $dealerValue);
                }
            }

        // Stand Logic
        } elseif ($action === "stand") {
            if ($isPvpP1) {
                $db->query("UPDATE blackjack_games SET status = 'waiting', active_key = NULL, updated_at = '$now' WHERE id = $gameId");
            } elseif ($isPvpP2) {
                bj_settle_locked($db, $game, $deck, false);
            } else { // Solo
                bj_settle_locked($db, $game, $deck, true);
            }

        // Double Logic
        } elseif ($action === "double") {
            if ($split !== null) throw new RuntimeException("Double Down is not available after splitting yet.");
            if (count($playerCards) !== 2) throw new RuntimeException("Double Down is only available on your first two cards.");

            $baseWager = (int)$game["wager"];
            $doubledWager = $baseWager * 2;
            if ($doubledWager > $maxBet) throw new RuntimeException("Doubling would exceed the maximum wager of " . mksize($maxBet) . ".");

            $user = bj_query_one($db, "SELECT uploaded FROM users WHERE id = $userId LIMIT 1 FOR UPDATE");
            if (!$user || (int)$user["uploaded"] < $baseWager) throw new RuntimeException("You need another " . mksize($baseWager) . " of uploaded credit to double down.");
            $db->query("UPDATE users SET uploaded = uploaded - $baseWager WHERE id = $userId");

            $playerCards[] = bj_draw($shoe, $shoePos);
            $playerValue = bj_hand_value($playerCards, $deck);
            $game["wager"] = $doubledWager;
            $game["player_cards"] = bj_codes_to_string($playerCards);
            $game["shoe_pos"] = $shoePos;
            $game["player_points"] = $playerValue;

            $db->query("UPDATE blackjack_games SET wager = $doubledWager, player_cards = '" . $db->real_escape_string(bj_codes_to_string($playerCards)) . "', shoe_pos = $shoePos, player_points = $playerValue, updated_at = '$now' WHERE id = $gameId");
            bj_settle_locked($db, $game, $deck, $playerValue <= 21);
            
        // Split Logic
        } elseif ($action === "split") {
            if ($split !== null) throw new RuntimeException("This hand has already been split.");
            if (!bj_can_split($playerCards, $deck)) throw new RuntimeException("This hand cannot be split.");

            $baseWager = (int)$game["wager"];
            $user = bj_query_one($db, "SELECT uploaded FROM users WHERE id = $userId LIMIT 1 FOR UPDATE");
            if (!$user || (int)$user["uploaded"] < $baseWager) throw new RuntimeException("You need another " . mksize($baseWager) . " of uploaded credit to split this hand.");
            $db->query("UPDATE users SET uploaded = uploaded - $baseWager WHERE id = $userId");

            $handOne = [$playerCards[0], bj_draw($shoe, $shoePos)];
            $handTwo = [$playerCards[1], bj_draw($shoe, $shoePos)];

            $splitAces = (int)$deck[$playerCards[0]]["value"] === 1;
            $handOneDone = $splitAces || bj_hand_value($handOne, $deck) >= 21;
            $handTwoDone = $splitAces || bj_hand_value($handTwo, $deck) >= 21;

            $split = [
                "active" => ($handOneDone && !$handTwoDone ? 1 : 0),
                "status" => [$handOneDone ? "done" : "play", $handTwoDone ? "done" : "play"],
                "hands" => [$handOne, $handTwo],
                "base_wager" => $baseWager,
            ];

            $db->query("UPDATE blackjack_games SET wager = " . ($baseWager * 2) . ", player_cards = '" . $db->real_escape_string(bj_encode_split_state($split)) . "', shoe_pos = $shoePos, player_points = " . bj_hand_value($handOne, $deck) . ", updated_at = '$now' WHERE id = $gameId");

            $game["wager"] = $baseWager * 2;
            $game["player_cards"] = bj_encode_split_state($split);
            $game["shoe_pos"] = $shoePos;

            if ($splitAces || ($split["status"][0] === "done" && $split["status"][1] === "done")) {
                bj_settle_locked($db, $game, $deck, true);
            }
            
        } else {
            throw new RuntimeException("Invalid blackjack action.");
        }

        $db->commit();
        return $gameId;
    } catch (Throwable $e) {
        $db->rollback();
        throw $e;
    }
}


/*
 * --------------------------------------------------------------------------
 * Rendering
 * --------------------------------------------------------------------------
 */

function bj_styles(): void
{
    echo <<<'CSS'
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');

body {
    background: linear-gradient(rgba(4, 8, 11, 0.75), rgba(4, 8, 11, 0.9)), url("images/blackjack/casino-background.webp") center top / cover fixed no-repeat !important;
}

#blackjackApp {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    width: min(900px, calc(100% - 20px));
    margin: 0 auto;
    text-align: center;
    color: #f3f4f6;
}

#blackjackApp * {
    box-sizing: border-box;
}

/* Glassmorphism Panel */
#blackjackApp .blackjack-panel {
    margin: 16px auto;
    padding: 32px 24px;
    border: 1px solid rgba(255, 255, 255, 0.08);
    border-radius: 20px;
    background: linear-gradient(145deg, rgba(17, 24, 39, 0.85), rgba(11, 15, 25, 0.95));
    backdrop-filter: blur(12px);
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.05);
}

/* Green Felt Table */
#blackjackApp .blackjack-table {
    position: relative;
    margin: 16px auto;
    padding: 30px 20px;
    border: 8px solid #1f2937;
    border-radius: 40px;
    background: radial-gradient(circle at center, #065f46, #022c22);
    color: #fff;
    box-shadow: inset 0 0 40px rgba(0, 0, 0, 0.6), 0 15px 30px rgba(0, 0, 0, 0.5);
}

#blackjackApp .blackjack-hands {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-top: 24px;
}

#blackjackApp .blackjack-hand {
    min-height: 175px;
    padding: 20px 12px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 20px;
    background: rgba(0, 0, 0, 0.25);
    box-shadow: inset 0 4px 15px rgba(0, 0, 0, 0.2);
}

#blackjackApp .blackjack-hand h2 {
    margin: 0 0 12px;
    color: #fff;
    font-size: 18px;
    font-weight: 600;
    letter-spacing: 0.5px;
}

#blackjackApp .blackjack-split-active {
    outline: 2px solid rgba(250, 204, 21, 0.8);
    box-shadow: 0 0 20px rgba(250, 204, 21, 0.15);
}

#blackjackApp .blackjack-cards img,
#blackjackApp .blackjack-card-back {
    display: inline-block;
    width: 71px;
    height: 96px;
    margin: 4px;
    vertical-align: middle;
    border-radius: 6px;
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.4);
}

#blackjackApp .blackjack-card-back {
    border: 4px solid #f3f4f6;
    background: repeating-linear-gradient(45deg, #1e3a8a, #1e3a8a 6px, #1e40af 6px, #1e40af 12px);
}

#blackjackApp .blackjack-card-animated {
    opacity: 0;
    transform: translateY(-42px) rotate(-7deg) scale(0.92);
    transition: transform 0.34s cubic-bezier(0.2, 0.9, 0.3, 1.15), opacity 0.22s ease-out;
    will-change: transform, opacity;
}

#blackjackApp .blackjack-card-animated.blackjack-card-show {
    opacity: 1;
    transform: translateY(0) rotate(0deg) scale(1);
}

#blackjackApp .blackjack-card-flip {
    transform-style: preserve-3d;
    backface-visibility: hidden;
}

#blackjackApp .blackjack-card-flip.blackjack-card-show {
    animation: blackjackHoleFlip 0.46s ease-out both;
}

@keyframes blackjackHoleFlip {
    0%   { opacity: 0; transform: perspective(700px) rotateY(90deg) scale(0.96); }
    55%  { opacity: 1; transform: perspective(700px) rotateY(-10deg) scale(1.02); }
    100% { opacity: 1; transform: perspective(700px) rotateY(0deg) scale(1); }
}

#blackjackApp .blackjack-sound-control {
    display: flex;
    justify-content: flex-end;
    flex-wrap: wrap;
    gap: 8px;
    margin: 0 0 12px;
}

#blackjackApp button.blackjack-sound-toggle {
    appearance: none;
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 8px;
    background: rgba(0, 0, 0, 0.3);
    color: #e5e7eb;
    padding: 6px 12px;
    font-family: inherit;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.2s;
}

#blackjackApp button.blackjack-sound-toggle:hover {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.25);
}

#blackjackApp .blackjack-score {
    margin-top: 10px;
    font-weight: 700;
    font-size: 15px;
    background: rgba(0, 0, 0, 0.4);
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
}

#blackjackApp .blackjack-actions {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
    margin-top: 24px;
}

#blackjackApp .blackjack-actions form {
    margin: 0;
}

#blackjackApp .blackjack-chart-corner {
    position: absolute;
    top: 18px;
    right: 20px;
    z-index: 2;
}

#blackjackApp button.blackjack-chart-button {
    min-width: auto !important;
    height: 32px !important;
    padding: 0 12px !important;
    font-size: 12px !important;
    background: rgba(0, 0, 0, 0.5) !important;
    border: 1px solid rgba(255,255,255,0.1) !important;
}

/* Modern Inputs & Selects */
#blackjackApp .blackjack-input {
    background: rgba(0, 0, 0, 0.4);
    border: 1px solid rgba(255, 255, 255, 0.12);
    color: #fff;
    border-radius: 10px;
    height: 44px;
    padding: 0 16px;
    font-family: inherit;
    font-size: 15px;
    transition: all 0.2s ease;
}

#blackjackApp .blackjack-input:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
}

#blackjackApp select.blackjack-input option {
    background: #111827;
    color: #fff;
}

/* Modern Buttons */
#blackjackApp button.blackjack-button {
    appearance: none !important;
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
    min-width: 130px !important;
    height: 44px !important;
    margin: 0 !important;
    padding: 0 20px !important;
    border: 1px solid rgba(255, 255, 255, 0.05) !important;
    border-radius: 10px !important;
    background: #374151 !important; /* Base gray */
    color: #fff !important;
    font-family: inherit !important;
    font-size: 14px !important;
    font-weight: 600 !important;
    line-height: 1 !important;
    text-decoration: none !important;
    cursor: pointer !important;
    transition: all 0.2s ease !important;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.05) !important;
}

#blackjackApp button.blackjack-button:hover:not(:disabled) {
    background: #4b5563 !important;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.05) !important;
}

#blackjackApp button.blackjack-button:disabled {
    opacity: 0.4 !important;
    cursor: not-allowed !important;
    transform: none !important;
    box-shadow: none !important;
}

#blackjackApp button.blackjack-btn-primary {
    background: #2563eb !important; /* Modern Blue */
}

#blackjackApp button.blackjack-btn-primary:hover:not(:disabled) {
    background: #3b82f6 !important;
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
}

#blackjackApp button.blackjack-btn-danger {
    background: #b91c1c !important; /* Modern Red */
}

#blackjackApp button.blackjack-btn-danger:hover:not(:disabled) {
    background: #dc2626 !important;
    box-shadow: 0 4px 12px rgba(220, 38, 38, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
}

#blackjackApp button.blackjack-button.blackjack-ready {
    background: #059669 !important; /* Emerald */
    box-shadow: 0 0 15px rgba(5, 150, 105, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
}

#blackjackApp button.blackjack-button.blackjack-ready:hover:not(:disabled) {
    background: #10b981 !important;
    box-shadow: 0 4px 15px rgba(16, 185, 129, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
}

/* Mode Selector (Solo vs PvP) */
#blackjackApp .blackjack-mode-selector {
    display: flex;
    justify-content: center;
    gap: 8px;
    margin-bottom: 24px;
    background: rgba(0, 0, 0, 0.4);
    padding: 6px;
    border-radius: 12px;
    border: 1px solid rgba(255, 255, 255, 0.05);
    max-width: 480px;
    margin-left: auto;
    margin-right: auto;
}

#blackjackApp .blackjack-mode-btn {
    flex: 1;
    text-align: center;
    text-decoration: none;
    color: #9ca3af;
    padding: 12px 20px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 14px;
    transition: all 0.2s ease;
}

#blackjackApp .blackjack-mode-btn:hover {
    color: #fff;
    background: rgba(255, 255, 255, 0.05);
}

#blackjackApp .blackjack-mode-btn.active-solo {
    color: #fff;
    background: #2563eb;
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);
}

#blackjackApp .blackjack-mode-btn.active-pvp {
    color: #fff;
    background: #059669;
    box-shadow: 0 4px 12px rgba(5, 150, 105, 0.3);
}

#blackjackApp .blackjack-quick-bets {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    gap: 8px;
    margin: 20px 0;
}

#blackjackApp .blackjack-quick-bets button.blackjack-button {
    min-width: 90px !important;
    height: 38px !important;
}

#blackjackApp .blackjack-quick-bets button.blackjack-button.blackjack-bet-selected {
    background: #4b5563 !important;
    border-color: #3b82f6 !important;
    box-shadow: 0 0 10px rgba(59, 130, 246, 0.4) !important;
}

#blackjackApp .blackjack-credit {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
    margin: 10px auto 20px;
    padding: 12px 20px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 12px;
    background: rgba(0, 0, 0, 0.3);
}

#blackjackApp .blackjack-credit-label {
    font-size: 13px;
    font-weight: 600;
    color: #9ca3af;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

#blackjackApp .blackjack-credit-value {
    font-size: 20px;
    font-weight: 700;
    color: #fff;
}

#blackjackApp .blackjack-custom {
    margin: 20px auto 10px;
    display: flex;
    justify-content: center;
    gap: 8px;
}

/* PvP Modern Table */
#blackjackApp .blackjack-pvp-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    margin: 20px 0;
    text-align: left;
}

#blackjackApp .blackjack-pvp-table th {
    background: rgba(0, 0, 0, 0.4);
    padding: 14px 16px;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 1px;
    color: #9ca3af;
    font-weight: 600;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

#blackjackApp .blackjack-pvp-table th:first-child { border-top-left-radius: 10px; border-bottom-left-radius: 10px; }
#blackjackApp .blackjack-pvp-table th:last-child { border-top-right-radius: 10px; border-bottom-right-radius: 10px; }

#blackjackApp .blackjack-pvp-table td {
    padding: 16px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    vertical-align: middle;
    font-size: 14px;
}

#blackjackApp .blackjack-pvp-table tr:last-child td { border-bottom: none; }
#blackjackApp .blackjack-pvp-table tr:hover td { background: rgba(255, 255, 255, 0.03); }

#blackjackApp .blackjack-result {
    max-width: 620px;
    margin: 24px auto 0;
    padding: 20px;
    border-radius: 16px;
    background: rgba(0, 0, 0, 0.4);
    border: 1px solid rgba(255, 255, 255, 0.05);
}

#blackjackApp .blackjack-win { color: #34d399; }
#blackjackApp .blackjack-loss { color: #f87171; }
#blackjackApp .blackjack-push { color: #fbbf24; }

/* Stats Panel */
#blackjackApp .blackjack-stats-panel {
    max-width: 980px;
    margin: 32px auto 0;
    padding: 24px;
    border: 1px solid rgba(255, 255, 255, 0.08);
    border-radius: 20px;
    background: rgba(17, 24, 39, 0.7);
    backdrop-filter: blur(10px);
}

#blackjackApp .blackjack-stats-heading {
    text-align: center;
    margin-bottom: 24px;
}

#blackjackApp .blackjack-stats-heading h2 { margin: 0 0 6px; font-size: 22px; }
#blackjackApp .blackjack-stats-heading p { margin: 0; color: #9ca3af; font-size: 14px; }

#blackjackApp .blackjack-stats-grid {
    display: grid;
    grid-template-columns: repeat(5, minmax(0, 1fr));
    gap: 12px;
}

#blackjackApp .blackjack-stat-card {
    background: rgba(0, 0, 0, 0.3);
    border: 1px solid rgba(255, 255, 255, 0.06);
    border-radius: 12px;
    padding: 16px 12px;
    text-align: center;
    transition: transform 0.2s;
}

#blackjackApp .blackjack-stat-card:hover {
    transform: translateY(-2px);
    background: rgba(255, 255, 255, 0.03);
}

#blackjackApp .blackjack-stat-label {
    display: block;
    margin-bottom: 8px;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: #9ca3af;
}

#blackjackApp .blackjack-stat-value {
    display: block;
    font-size: 18px;
    font-weight: 700;
    line-height: 1.2;
    overflow-wrap: anywhere;
}

#blackjackApp .blackjack-leaderboard {
    margin-top: 24px;
    border-top: 1px solid rgba(255, 255, 255, 0.08);
    padding-top: 16px;
}

#blackjackApp .blackjack-leaderboard summary {
    cursor: pointer;
    font-weight: 600;
    font-size: 16px;
    user-select: none;
    color: #e5e7eb;
}

#blackjackApp .blackjack-leaderboard-wrap {
    margin-top: 16px;
    overflow-x: auto;
}

#blackjackApp .blackjack-leaderboard-you td { background: rgba(59, 130, 246, 0.1); }

#blackjackApp .blackjack-you-tag {
    display: inline-block;
    margin-left: 6px;
    padding: 2px 6px;
    border: 1px solid rgba(59, 130, 246, 0.5);
    border-radius: 6px;
    background: rgba(59, 130, 246, 0.2);
    color: #60a5fa;
    font-size: 10px;
    font-weight: 700;
    vertical-align: middle;
}

#blackjackApp .blackjack-empty-stats {
    margin: 16px 0 0;
    color: #9ca3af;
}

/* Admin Zone Modernized */
#blackjackApp .blackjack-admin-zone {
    max-width: 980px;
    margin: 48px auto 0;
    padding: 24px;
    border: 1px solid rgba(239, 68, 68, 0.3);
    border-radius: 20px;
    background: linear-gradient(145deg, rgba(60, 10, 10, 0.6), rgba(20, 5, 5, 0.8));
    text-align: center;
    box-shadow: 0 10px 30px rgba(239, 68, 68, 0.1);
}

#blackjackApp .blackjack-admin-badge {
    display: inline-block;
    margin-bottom: 12px;
    padding: 4px 10px;
    border: 1px solid rgba(239, 68, 68, 0.6);
    border-radius: 999px;
    background: rgba(239, 68, 68, 0.1);
    color: #f87171;
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 1px;
    text-transform: uppercase;
}

#blackjackApp .blackjack-admin-zone h3 { margin: 0 0 8px; font-size: 20px; }
#blackjackApp .blackjack-admin-zone p { margin: 0 auto 16px; color: #9ca3af; font-size: 14px; }

#blackjackApp .blackjack-admin-reset-form {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
}

#blackjackApp button.blackjack-reset-button {
    background: #b91c1c !important; /* Red 700 */
    border-color: rgba(239, 68, 68, 0.5) !important;
}

#blackjackApp button.blackjack-reset-button:hover:not(:disabled) {
    background: #dc2626 !important; /* Red 600 */
    box-shadow: 0 4px 12px rgba(220, 38, 38, 0.4) !important;
}

#blackjackApp .blackjack-admin-notice {
    max-width: 720px;
    margin: 0 auto 16px;
    padding: 12px;
    border: 1px solid rgba(52, 211, 153, 0.4);
    border-radius: 10px;
    background: rgba(5, 150, 105, 0.15);
    color: #34d399;
    font-weight: 600;
}

@media(max-width: 850px) {
    #blackjackApp .blackjack-stats-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}

@media(max-width: 650px) {
    #blackjackApp .blackjack-hands { grid-template-columns: 1fr; }
    #blackjackApp .blackjack-table { border-width: 6px; border-radius: 26px; padding: 20px 10px; }
    #blackjackApp .blackjack-cards img,
    #blackjackApp .blackjack-card-back { width: 58px; height: 79px; }
}
</style>
CSS;
}

function bj_page_start(): void
{
    stdhead("Blackjack");
    begin_frame("Blackjack");
    bj_styles();

    echo '<div id="blackjackApp">';
    echo '<div class="blackjack-sound-control">';
    echo '<button id="blackjackSoundToggle" class="blackjack-sound-toggle" '
        . 'type="button" aria-pressed="false">🔊 Sound On</button>';
    echo '<button id="blackjackAmbienceToggle" class="blackjack-sound-toggle" '
        . 'type="button" aria-pressed="false">🎰 Ambience On</button>';
    echo '</div>';

    echo <<<'JS'
<script>
(function(){
    "use strict";

    if(window.BlackjackUI){
        return;
    }

    var STORAGE_KEY = "blackjackSoundMuted";
    var AMBIENCE_STORAGE_KEY = "blackjackAmbienceMuted";
    var base = "sounds/blackjack/";
    var files = {
        card: base + "placing-playing-card.mp3",
        flip: base + "flip.wav",
        win: base + "win.wav",
        blackjack: base + "blackjack.wav",
        lose: base + "lose.wav",
        push: base + "push.wav"
    };

    var muted = false;
    var ambienceMuted = false;
    var busy = false;
    var audioContext = null;
    var audioBuffers = {};
    var fallbackAudio = {};

    var ambience = new Audio(base + "blackjack-room-ambience.mp3");
    ambience.preload = "auto";
    ambience.loop = true;
    ambience.volume = 1.00;

    try {
        muted = window.localStorage.getItem(STORAGE_KEY) === "1";
        ambienceMuted = window.localStorage.getItem(AMBIENCE_STORAGE_KEY) === "1";
    } catch (e) {}

    Object.keys(files).forEach(function(name){
        var audio = new Audio(files[name]);
        audio.preload = "auto";
        fallbackAudio[name] = audio;
    });

    function getAudioContext(){
        if(audioContext){
            return audioContext;
        }

        var AudioContextClass = window.AudioContext || window.webkitAudioContext;
        if(!AudioContextClass){
            return null;
        }

        try {
            audioContext = new AudioContextClass();
        } catch (e) {
            audioContext = null;
        }

        return audioContext;
    }

    function preloadSounds(){
        var context = getAudioContext();
        if(!context || typeof window.fetch !== "function"){
            return;
        }

        Object.keys(files).forEach(function(name){
            fetch(files[name], {credentials:"same-origin"})
                .then(function(response){
                    if(!response.ok){
                        throw new Error("Sound load failed");
                    }
                    return response.arrayBuffer();
                })
                .then(function(buffer){
                    return context.decodeAudioData(buffer);
                })
                .then(function(decoded){
                    audioBuffers[name] = decoded;
                })
                .catch(function(){});
        });
    }

    function startAmbience(){
        if(muted || ambienceMuted){
            return;
        }

        ambience.volume = 1.00;

        if(ambience.paused){
            try {
                var ambiencePromise = ambience.play();
                if(ambiencePromise && typeof ambiencePromise.catch === "function"){
                    ambiencePromise.catch(function(){});
                }
            } catch (e) {}
        }
    }

    function pauseAmbience(){
        try {
            ambience.pause();
        } catch (e) {}
    }

    function unlockSound(){
        if(muted){
            return;
        }

        var context = getAudioContext();
        if(context && context.state === "suspended"){
            try {
                var promise = context.resume();
                if(promise && typeof promise.catch === "function"){
                    promise.catch(function(){});
                }
            } catch (e) {}
        }

        startAmbience();
    }

    function playSound(name, volume){
        if(muted){
            return;
        }

        var context = getAudioContext();
        var level = typeof volume === "number" ? volume : 0.72;

        if(context && context.state === "running" && audioBuffers[name]){
            try {
                var source = context.createBufferSource();
                var gain = context.createGain();
                source.buffer = audioBuffers[name];
                gain.gain.value = level;
                source.connect(gain);
                gain.connect(context.destination);
                source.start(0);
                return;
            } catch (e) {}
        }

        if(fallbackAudio[name]){
            try {
                var sound = fallbackAudio[name].cloneNode(true);
                sound.volume = level;
                var promise = sound.play();
                if(promise && typeof promise.catch === "function"){
                    promise.catch(function(){});
                }
            } catch (e) {}
        }
    }

    function updateSoundButton(){
        var button = document.getElementById("blackjackSoundToggle");
        if(!button){
            return;
        }

        button.textContent = muted ? "🔇 Muted" : "🔊 Sound On";
        button.setAttribute("aria-pressed", muted ? "true" : "false");
        button.title = muted
            ? "Turn blackjack sounds on"
            : "Mute blackjack sounds";
    }

    function updateAmbienceButton(){
        var button = document.getElementById("blackjackAmbienceToggle");
        if(!button){
            return;
        }

        button.textContent = ambienceMuted ? "🔇 Ambience Off" : "🎰 Ambience On";
        button.setAttribute("aria-pressed", ambienceMuted ? "true" : "false");
        button.title = ambienceMuted
            ? "Turn room ambience on"
            : "Turn room ambience off";
    }

    function toggleAmbience(){
        ambienceMuted = !ambienceMuted;

        try {
            window.localStorage.setItem(AMBIENCE_STORAGE_KEY, ambienceMuted ? "1" : "0");
        } catch (e) {}

        updateAmbienceButton();

        if(ambienceMuted){
            pauseAmbience();
        } else if(!muted){
            startAmbience();
        }
    }

    function toggleSound(){
        muted = !muted;

        try {
            window.localStorage.setItem(STORAGE_KEY, muted ? "1" : "0");
        } catch (e) {}

        updateSoundButton();

        if(!muted){
            unlockSound();
            window.setTimeout(function(){
                playSound("card", 0.45);
            }, 20);
        } else {
            pauseAmbience();
        }
    }

    function customBytes(form){
        var amount = form.querySelector("#blackjackAmount");
        var unit = form.querySelector("#blackjackUnit");

        if(!amount || !unit){
            return 0;
        }

        var value = parseFloat(amount.value || "0");
        if(!isFinite(value) || value <= 0){
            return 0;
        }

        var multiplier = unit.value === "GB"
            ? 1073741824
            : 1048576;

        return Math.round(value * multiplier);
    }

    function setDealState(form, bytes){
        var deal = form.querySelector("button[type='submit']");
        if(!deal){
            return;
        }

        var balance = parseInt(form.getAttribute("data-balance"), 10) || 0;
        var minBet = parseInt(form.getAttribute("data-min-bet"), 10) || 0;
        var maxBet = parseInt(form.getAttribute("data-max-bet"), 10) || 0;

        var valid = isFinite(bytes)
            && bytes >= minBet
            && bytes <= maxBet
            && bytes <= balance;

        deal.disabled = !valid;
        if(valid){
            deal.classList.add("blackjack-ready");
        } else {
            deal.classList.remove("blackjack-ready");
        }
    }

    function clearQuickSelection(form){
        var buttons = form.querySelectorAll("[data-wager]");
        for(var i = 0; i < buttons.length; i++){
            buttons[i].classList.remove("blackjack-bet-selected");
            buttons[i].setAttribute("aria-pressed", "false");
        }
    }

    function showWagerInCustomFields(form, bytes){
        var amount = form.querySelector("#blackjackAmount");
        var unit = form.querySelector("#blackjackUnit");
        if(!amount || !unit){
            return;
        }

        var GB = 1073741824;
        var MB = 1048576;
        var useGb = bytes >= GB && bytes % GB === 0;

        unit.value = useGb ? "GB" : "MB";
        unit.dataset.previousUnit = unit.value;

        var multiplier = useGb ? GB : MB;
        amount.value = String(bytes / multiplier);

        var minBet = parseInt(form.getAttribute("data-min-bet"), 10) || 0;
        amount.min = String(minBet / multiplier);
    }

    function initWager(){
        var forms = document.querySelectorAll("form[data-min-bet]");
        for(var i=0; i<forms.length; i++) {
            var form = forms[i];
            var hidden = form.querySelector("#blackjackWagerBytes");
            var unit = form.querySelector("#blackjackUnit");

            if(unit){
                unit.dataset.previousUnit = unit.value;
            }

            if(hidden && hidden.value !== ""){
                setDealState(form, parseInt(hidden.value, 10) || 0);
            } else if (form.querySelector("#blackjackAmount")) {
                setDealState(form, customBytes(form));
            }
        }
    }

    function cleanResponseUrl(url){
        try {
            var parsed = new URL(url, window.location.href);
            parsed.searchParams.delete("anim");
            return parsed.toString();
        } catch (e) {
            return url;
        }
    }

    function getAnimationFromUrl(url){
        try {
            return new URL(url, window.location.href).searchParams.get("anim") || "";
        } catch (e) {
            return "";
        }
    }

    function animateCurrent(animation){
        var root = document.getElementById("blackjackApp");
        if(!root){
            return;
        }

        var cards = root.querySelectorAll(
            ".blackjack-card-animated[data-card-sequence]"
        );

        var lastSequence = 1;

        for(var i = 0; i < cards.length; i++){
            (function(card){
                var sequence = parseInt(
                    card.getAttribute("data-card-sequence"),
                    10
                ) || 1;

                if(sequence > lastSequence){
                    lastSequence = sequence;
                }

                window.setTimeout(function(){
                    card.classList.add("blackjack-card-show");
                    var soundName = card.classList.contains("blackjack-card-flip")
                        ? "flip"
                        : "card";
                    playSound(soundName, 0.64);
                }, 110 + ((sequence - 1) * 170));
            })(cards[i]);
        }

        var resultBox = root.querySelector(".blackjack-result[data-result]");
        if(resultBox){
            var result = resultBox.getAttribute("data-result") || "";
            var outcomeDelay = cards.length
                ? 420 + ((lastSequence - 1) * 170)
                : 120;

            window.setTimeout(function(){
                if(result === "blackjack"){
                    playSound("blackjack", 0.82);
                } else if(result === "win"){
                    playSound("win", 0.78);
                } else if(result === "push"){
                    playSound("push", 0.68);
                } else if(result === "loss"){
                    playSound("lose", 0.66);
                }
            }, outcomeDelay);
        }
    }

    function setBusy(state){
        busy = state;
        var app = document.getElementById("blackjackApp");
        if(!app){
            return;
        }

        app.setAttribute("aria-busy", state ? "true" : "false");

        var buttons = app.querySelectorAll("button.blackjack-button");
        for(var i = 0; i < buttons.length; i++){
            if(state){
                buttons[i].setAttribute("data-bj-was-disabled", buttons[i].disabled ? "1" : "0");
                buttons[i].disabled = true;
            } else {
                var previous = buttons[i].getAttribute("data-bj-was-disabled");
                if(previous === "0"){
                    buttons[i].disabled = false;
                } else if(previous === "1"){
                    buttons[i].disabled = true;
                }
                if(previous !== null){
                    buttons[i].removeAttribute("data-bj-was-disabled");
                }
            }
        }
    }

    function swapBlackjack(html, responseUrl){
        var parser = new DOMParser();
        var incomingDocument = parser.parseFromString(html, "text/html");
        var incoming = incomingDocument.getElementById("blackjackApp");
        var current = document.getElementById("blackjackApp");

        if(!incoming || !current){
            throw new Error("Blackjack response could not be loaded.");
        }

        var animation = getAnimationFromUrl(responseUrl);
        current.innerHTML = incoming.innerHTML;

        updateSoundButton();
        updateAmbienceButton();
        initWager();
        animateCurrent(animation);

        if(window.history && window.history.replaceState){
            window.history.replaceState({}, "", cleanResponseUrl(responseUrl));
        }
    }

    function request(url, options){
        if(busy){
            return Promise.resolve();
        }

        setBusy(true);

        options = options || {};
        options.credentials = "same-origin";
        options.redirect = "follow";
        options.headers = options.headers || {};
        options.headers["X-Requested-With"] = "XMLHttpRequest";

        return fetch(url, options)
            .then(function(response){
                if(!response.ok){
                    throw new Error("Blackjack request failed (" + response.status + ").");
                }

                return response.text().then(function(html){
                    swapBlackjack(html, response.url || url);
                });
            })
            .catch(function(error){
                window.alert(error && error.message
                    ? error.message
                    : "Blackjack request failed.");
            })
            .finally(function(){
                setBusy(false);
            });
    }

    function submitForm(form){
        unlockSound();

        var data = new FormData(form);
        return request(window.location.pathname, {
            method: "POST",
            body: data
        });
    }

    function loadWagerScreen(){
        unlockSound();
        return request(window.location.pathname, {
            method: "GET"
        });
    }

    document.addEventListener("pointerdown", function(event){
        if(event.target.closest("#blackjackApp button")){
            unlockSound();
        }
    }, {passive:true});

    document.addEventListener("click", function(event){
        var toggle = event.target.closest("#blackjackSoundToggle");
        if(toggle){
            event.preventDefault();
            toggleSound();
            return;
        }

        var ambienceToggle = event.target.closest("#blackjackAmbienceToggle");
        if(ambienceToggle){
            event.preventDefault();
            toggleAmbience();
            return;
        }

        var quick = event.target.closest("#blackjackApp [data-wager]");
        if(quick && !quick.disabled){
            var form = quick.closest("form");
            if(form){
                var hidden = form.querySelector("#blackjackWagerBytes");
                var bytes = parseInt(quick.getAttribute("data-wager") || "0", 10) || 0;

                clearQuickSelection(form);
                quick.classList.add("blackjack-bet-selected");
                quick.setAttribute("aria-pressed", "true");

                if(hidden){
                    hidden.value = String(bytes);
                }

                showWagerInCustomFields(form, bytes);
                setDealState(form, bytes);
            }
            return;
        }

        var changeBet = event.target.closest("#blackjackChangeBetButton");
        if(changeBet){
            event.preventDefault();
            loadWagerScreen();
        }
    });

    document.addEventListener("input", function(event){
        if(event.target.matches("#blackjackAmount")){
            var form = event.target.closest("form");
            if(form){
                var hidden = form.querySelector("#blackjackWagerBytes");
                if(hidden){
                    hidden.value = "";
                }
                clearQuickSelection(form);
                setDealState(form, customBytes(form));
            }
        }
    });

    document.addEventListener("change", function(event){
        if(event.target.matches("#blackjackUnit")){
            var form = event.target.closest("form");
            if(form){
                var hidden = form.querySelector("#blackjackWagerBytes");
                var amount = form.querySelector("#blackjackAmount");
                var unit = event.target;
                var previousUnit = unit.dataset.previousUnit || "MB";
                var previousMultiplier = previousUnit === "GB"
                    ? 1073741824
                    : 1048576;
                var nextMultiplier = unit.value === "GB"
                    ? 1073741824
                    : 1048576;

                if(amount){
                    var value = parseFloat(amount.value || "0");
                    if(isFinite(value) && value >= 0){
                        var currentBytes = value * previousMultiplier;
                        amount.value = String(currentBytes / nextMultiplier);
                    }

                    var minBet = parseInt(
                        form.getAttribute("data-min-bet"),
                        10
                    ) || 0;
                    if(minBet > 0) {
                        amount.min = String(minBet / nextMultiplier);
                    }
                }

                unit.dataset.previousUnit = unit.value;

                if(hidden){
                    hidden.value = "";
                }
                clearQuickSelection(form);
                setDealState(form, customBytes(form));
            }
        }
    });

    document.addEventListener("submit", function(event){
        var form = event.target;
        if(!(form instanceof HTMLFormElement)){
            return;
        }

        if(!form.closest("#blackjackApp")){
            return;
        }

        if(form.classList.contains("blackjack-admin-reset-form")){
            var player = form.querySelector(".blackjack-admin-player");
            var playerName = player && player.selectedIndex >= 0
                ? player.options[player.selectedIndex].text
                : "this player";

            if(!window.confirm(
                "Reset all blackjack stats for " + playerName + "?\n\n" +
                "This cannot be undone. Their upload balance will not change."
            )){
                event.preventDefault();
                return;
            }
        }

        var actionInput = form.querySelector("input[name='action']");
        if (actionInput && (actionInput.value === "create_table" || actionInput.value === "join_table" || actionInput.value === "cancel_table")) {
            return;
        }

        event.preventDefault();
        submitForm(form);
    });

    window.BlackjackSound = {
        play: playSound,
        unlock: unlockSound,
        ambience: startAmbience,
        isMuted: function(){ return muted; },
        isAmbienceMuted: function(){ return ambienceMuted; }
    };

    window.BlackjackUI = {
        request: request,
        animate: animateCurrent,
        initWager: initWager
    };

    document.addEventListener("DOMContentLoaded", function(){
        preloadSounds();
        updateSoundButton();
        updateAmbienceButton();
        initWager();
        startAmbience();
    });
})();
</script>
JS;
}

function bj_page_end(): void
{
    echo '</div>';

    end_frame();
    stdfoot();
}

function bj_render_cards(
    array $cards,
    array $deck,
    bool $hideHole,
    string $hand,
    string $animation
): void {
    echo '<div class="blackjack-cards" data-hand="' . bj_h($hand) . '">';

    $lastIndex = count($cards) - 1;

    foreach ($cards as $index => $code) {
        $classes = [];
        $animate = false;
        $sequence = 0;

        if ($animation === "deal" && $index < 2) {
            $animate = true;

            if ($hand === "player") {
                $sequence = $index === 0 ? 1 : 3;
            } else {
                $sequence = $index === 0 ? 2 : 4;
            }
        } elseif (
            ($animation === "hit" || $animation === "resolve")
            && $hand === "player"
            && $index === $lastIndex
        ) {
            $animate = true;
            $sequence = 1;
        } elseif (
            ($animation === "dealer" || $animation === "resolve")
            && $hand === "dealer"
            && $index >= 1
        ) {
            $animate = true;
            $sequence = $animation === "resolve"
                ? $index + 1
                : $index;

            if ($index === 1) {
                $classes[] = "blackjack-card-flip";
            }
        }

        if ($animate) {
            $classes[] = "blackjack-card-animated";
        }

        $classAttr = $classes
            ? ' class="' . bj_h(implode(" ", $classes)) . '"'
            : '';

        $sequenceAttr = $animate
            ? ' data-card-sequence="' . $sequence . '"'
            : '';

        if ($hideHole && $index === 1) {
            echo '<span class="blackjack-card-back'
                . ($classes ? ' ' . bj_h(implode(" ", $classes)) : '')
                . '"' . $sequenceAttr
                . ' title="Hidden dealer card"></span>';
            continue;
        }

        if (!isset($deck[$code])) {
            continue;
        }

        echo '<img' . $classAttr . $sequenceAttr
            . ' src="images/blackjack/cards/'
            . bj_h((string)$deck[$code]["pic"])
            . '" alt="Playing card">';
    }

    echo '</div>';
}

function bj_action_form(
    string $label,
    string $action,
    string $buttonId,
    int $gameId = 0
): void {
    echo '<form method="post" action="blackjack.php" autocomplete="off" style="margin:0;">';
    echo '<input type="hidden" name="csrf" value="'
        . bj_h(bj_csrf_token()) . '">';
    echo '<input type="hidden" name="action" value="'
        . bj_h($action) . '">';
    if ($gameId > 0) {
        echo '<input type="hidden" name="game_id" value="' . $gameId . '">';
    }
    echo '<button id="' . bj_h($buttonId)
        . '" class="blackjack-button" type="submit">'
        . bj_h($label) . '</button>';
    echo '</form>';
}

function bj_get_pvp_games(mysqli $db, int $userId): array
{
    return bj_query_all(
        $db,
        "SELECT bg.*, u.username as creator_name, o.username as opponent_name 
         FROM blackjack_games bg 
         INNER JOIN users u ON u.id = bg.user_id 
         LEFT JOIN users o ON o.id = bg.opponent_id 
         WHERE bg.status = 'waiting' 
            OR ((bg.status = 'pvp_p1' OR bg.status = 'pvp_p2') AND (bg.user_id = $userId OR bg.opponent_id = $userId))
         ORDER BY bg.id DESC"
    );
}

function bj_render_wager_screen(
    int $userId,
    int $minBet,
    int $maxBet
): void {
    $balance = bj_balance($userId);
    $MB = 1024 * 1024;
    $GB = 1024 * 1024 * 1024;

    $quickBets = [
        100 * $MB,
        250 * $MB,
        500 * $MB,
        1 * $GB,
        5 * $GB,
        10 * $GB,
        25 * $GB,
        50 * $GB,
        100 * $GB,
        200 * $GB,
    ];

    bj_page_start();

    $mode = $_GET['mode'] ?? 'solo';

    echo '<div class="blackjack-panel">';
    
    // Modern Mode Selector
    echo '<div class="blackjack-mode-selector">';
    echo '<a href="blackjack.php?mode=solo" class="blackjack-mode-btn ' . ($mode === 'solo' ? 'active-solo' : '') . '">🤖 Play vs Computer</a>';
    echo '<a href="blackjack.php?mode=pvp" class="blackjack-mode-btn ' . ($mode === 'pvp' ? 'active-pvp' : '') . '">⚔️ Player vs Player</a>';
    echo '</div>';

    echo '<div class="blackjack-credit">';
    echo '<span class="blackjack-credit-label">Current Balance</span>';
    echo '<span class="blackjack-credit-value">' . mksize($balance) . '</span>';
    echo '</div>';

    if ($mode === 'pvp') {
        echo '<h2 style="margin-top:0;">PvP Tables</h2>';
        echo '<p style="color:#9ca3af;">Join an existing table or create a new one to play against another user.</p>';

        $db = bj_db();
        $pvpGames = bj_get_pvp_games($db, $userId);

        if ($pvpGames) {
            echo '<table class="blackjack-pvp-table">';
            echo '<thead><tr><th>Creator</th><th>Opponent</th><th>Wager</th><th>Status</th><th>Action</th></tr></thead><tbody>';
            foreach ($pvpGames as $g) {
                echo '<tr>';
                echo '<td>' . bj_h($g["creator_name"]) . ((int)$g['user_id'] === $userId ? ' <span style="font-size:11px; color:#60a5fa;">(You)</span>' : '') . '</td>';
                
                $oppName = $g["opponent_name"] ? bj_h($g["opponent_name"]) : '<span style="color:#6b7280; font-style:italic;">Waiting...</span>';
                if ($g["opponent_name"] && (int)$g['opponent_id'] === $userId) $oppName .= ' <span style="font-size:11px; color:#60a5fa;">(You)</span>';
                echo '<td>' . $oppName . '</td>';

                echo '<td><strong>' . mksize((int)$g["wager"]) . '</strong></td>';
                
                $statusText = '<span style="color:#34d399;">Open</span>';
                if ($g['status'] === 'pvp_p1') {
                    $statusText = ((int)$g['user_id'] === $userId) ? '<span style="color:#fbbf24;font-weight:700;">Your Turn</span>' : '<span style="color:#9ca3af;">Creator\'s Turn</span>';
                } elseif ($g['status'] === 'pvp_p2') {
                    $statusText = ((int)$g['opponent_id'] === $userId) ? '<span style="color:#fbbf24;font-weight:700;">Your Turn</span>' : '<span style="color:#9ca3af;">Opponent\'s Turn</span>';
                }
                echo '<td>' . $statusText . '</td>';

                echo '<td>';
                if ((int)$g['user_id'] === $userId || (int)$g['opponent_id'] === $userId) {
                    echo '<button type="button" onclick="location.href=\'blackjack.php?hand=' . $g['id'] . '\'" class="blackjack-button blackjack-btn-primary" style="min-width:100px!important; height:34px!important; font-size:12px!important;">View Table</button>';
                } else {
                    if ($g['status'] === 'waiting') {
                        echo '<form method="post" action="blackjack.php" style="margin:0;">';
                        echo '<input type="hidden" name="action" value="join_table">';
                        echo '<input type="hidden" name="game_id" value="' . $g["id"] . '">';
                        echo '<input type="hidden" name="csrf" value="' . bj_h(bj_csrf_token()) . '">';
                        echo '<button class="blackjack-button blackjack-btn-primary" type="submit" style="min-width:100px!important; height:34px!important; font-size:12px!important;">Join Table</button>';
                        echo '</form>';
                    }
                }
                echo '</td></tr>';
            }
            echo '</tbody></table>';
        } else {
            echo '<div style="margin: 30px 0; padding: 20px; background: rgba(0,0,0,0.2); border-radius: 12px; border: 1px dashed rgba(255,255,255,0.1);"><p style="color:#9ca3af; margin:0;">No active PvP tables found. Create one below!</p></div>';
        }

        echo '<hr style="margin:24px 0; border: none; border-top: 1px solid rgba(255,255,255,0.08);">';
        echo '<h3>Create PvP Table</h3>';
        
        echo '<form method="post" action="blackjack.php" autocomplete="off" data-balance="' . $balance . '" data-min-bet="' . $minBet . '" data-max-bet="' . $maxBet . '">';
        echo '<input type="hidden" name="csrf" value="' . bj_h(bj_csrf_token()) . '">';
        echo '<input type="hidden" name="action" value="create_table">';
        echo '<input id="blackjackWagerBytes" type="hidden" name="wager_bytes" value="">';
        
        echo '<div class="blackjack-quick-bets">';
        foreach ($quickBets as $index => $bet) {
            if ($bet < $minBet || $bet > $maxBet) {
                continue;
            }
            $disabled = $bet > $balance ? ' disabled' : '';
            echo '<button class="blackjack-button" type="button" data-wager="' . $bet . '" aria-pressed="false"' . $disabled . '>' . bj_h(mksize($bet)) . '</button>';
        }
        echo '</div>';

        $minBetMb = $minBet / 1048576;
        $minBetMbValue = rtrim(rtrim(sprintf("%.8F", $minBetMb), "0"), ".");

        echo '<div class="blackjack-custom">';
        echo '<input id="blackjackAmount" class="blackjack-input" type="number" name="wager_amount" min="' . bj_h($minBetMbValue) . '" step="any" value="' . bj_h($minBetMbValue) . '" autocomplete="off" style="width: 140px;">';
        echo '<select id="blackjackUnit" class="blackjack-input" name="wager_unit" autocomplete="off" style="width: 80px;"><option value="MB" selected>MB</option><option value="GB">GB</option></select>';
        echo '</div>';

        echo '<p style="color:#9ca3af; font-size:13px;">Minimum: ' . mksize($minBet) . ' &nbsp; | &nbsp; Maximum: ' . mksize($maxBet) . '</p>';
        echo '<div class="blackjack-actions">';
        echo '<button class="blackjack-button blackjack-btn-primary" type="submit">Create Table</button>';
        echo '</div>';
        echo '</form>';

    } else {
        echo '<h2 style="margin-top:0;">House Blackjack</h2>';
        echo '<p style="color:#9ca3af;">Dealer stands on 17. Natural blackjack pays 3:2.</p>';

        $minBetMb = $minBet / 1048576;
        $minBetMbValue = rtrim(rtrim(sprintf("%.8F", $minBetMb), "0"), ".");

        echo '<form id="blackjackWagerForm" method="post" action="blackjack.php" autocomplete="off" data-balance="' . $balance . '" data-min-bet="' . $minBet . '" data-max-bet="' . $maxBet . '">';
        echo '<input type="hidden" name="csrf" value="' . bj_h(bj_csrf_token()) . '">';
        echo '<input type="hidden" name="action" value="start">';
        echo '<input id="blackjackWagerBytes" type="hidden" name="wager_bytes" value="">';

        echo '<div class="blackjack-quick-bets">';
        foreach ($quickBets as $index => $bet) {
            if ($bet < $minBet || $bet > $maxBet) {
                continue;
            }
            $disabled = $bet > $balance ? ' disabled' : '';
            echo '<button id="blackjackQuickBet' . $index . '" class="blackjack-button" type="button" data-wager="' . $bet . '" aria-pressed="false"' . $disabled . '>' . bj_h(mksize($bet)) . '</button>';
        }
        echo '</div>';

        echo '<div class="blackjack-custom">';
        echo '<input id="blackjackAmount" class="blackjack-input" type="number" name="wager_amount" min="' . bj_h($minBetMbValue) . '" step="any" value="' . bj_h($minBetMbValue) . '" autocomplete="off" style="width: 140px;">';
        echo '<select id="blackjackUnit" class="blackjack-input" name="wager_unit" autocomplete="off" style="width: 80px;">';
        echo '<option value="MB" selected>MB</option>';
        echo '<option value="GB">GB</option>';
        echo '</select>';
        echo '</div>';

        echo '<p style="color:#9ca3af; font-size:13px;">Minimum: ' . mksize($minBet) . ' &nbsp; | &nbsp; Maximum: ' . mksize($maxBet) . '</p>';

        echo '<div class="blackjack-actions">';
        echo '<button id="blackjackDealButton" class="blackjack-button blackjack-btn-primary" type="submit" disabled>Deal Cards</button>';
        echo '<button class="blackjack-button" style="background: rgba(0,0,0,0.3)!important;" type="button" onclick="window.open(\'blackjack_split_chart.html\',\'blackjackSplitChart\',\'width=760,height=780,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,left=40,top=30\');return false;">Split Chart</button>';
        echo '</div>';
        echo '</form>';
    }

    echo '</div>';

    bj_render_stats($userId);
    bj_page_end();
}

function bj_render_hand(array $game, array $deck, string $animation): void
{
    $userId = (int)$GLOBALS["CURUSER"]["id"];
    
    $dealerCards = bj_codes_from_string((string)$game["dealer_cards"]);
    $playerCards = bj_codes_from_string((string)$game["player_cards"]);
    $split = bj_decode_split_state((string)$game["player_cards"]);
    $balance = bj_balance($userId);
    
    $isCreator = (int)$game['user_id'] === $userId;
    $isOpponent = !empty($game['opponent_id']) && (int)$game['opponent_id'] === $userId;
    $isPvP = !empty($game['opponent_id']) || $game['status'] === 'waiting' || strpos((string)$game['status'], 'pvp') !== false;

    // Place YOUR CARDS always at the BOTTOM and the opponent's at the TOP
    if ($isPvP) {
        if ($isOpponent) {
            $topCards = $playerCards; 
            $topLabel = bj_h($game['creator_name'] ?? 'Creator') . " (Player 1)";
            $topHide = false; 
            $topPoints = (int)$game['player_points'];
            $topHandType = "player";

            $bottomCards = $dealerCards; 
            $bottomLabel = "You (Player 2)";
            $bottomHide = false;
            $bottomPoints = (int)$game['dealer_points'];
            $bottomHandType = "dealer";
        } else {
            $topCards = $dealerCards;
            $topLabel = !empty($game['opponent_name']) ? bj_h($game['opponent_name']) . " (Player 2)" : "Waiting for Player 2...";
            $topHide = ($game['status'] === 'pvp_p1' || $game['status'] === 'waiting'); 
            $topPoints = (int)$game['dealer_points'];
            $topHandType = "dealer";

            $bottomCards = $playerCards;
            $bottomLabel = "You (Player 1)";
            $bottomHide = false;
            $bottomPoints = (int)$game['player_points'];
            $bottomHandType = "player";
        }
    } else {
        $topCards = $dealerCards;
        $topLabel = "House";
        $topHide = ($game['status'] === 'playing');
        $topPoints = (int)$game['dealer_points'];
        $topHandType = "dealer";

        $bottomCards = $playerCards;
        $bottomLabel = "You";
        $bottomHide = false;
        $bottomPoints = (int)$game['player_points'];
        $bottomHandType = "player";
    }

    bj_page_start();

    echo '<div class="blackjack-table">';
    echo '<div class="blackjack-chart-corner">';
    echo '<button class="blackjack-button blackjack-chart-button" type="button" '
        . 'onclick="window.open(\'blackjack_split_chart.html\',\'blackjackSplitChart\','
        . '\'width=760,height=780,toolbar=no,location=no,status=no,menubar=no,'
        . 'scrollbars=yes,resizable=yes,left=40,top=30\');return false;">'
        . 'Split Chart</button>';
    echo '</div>';
    echo '<h2 style="margin-top:0;">Blackjack</h2>';
    echo '<div class="blackjack-credit">';
    echo '<span class="blackjack-credit-label">Current Balance</span>';
    echo '<span class="blackjack-credit-value">'
        . mksize($balance) . '</span>';
    echo '</div>';

    if ($split !== null) {
        echo '<p>Total wager: <b>' . mksize((int)$game["wager"])
            . '</b> &nbsp; <span style="color:#9ca3af;">(' . mksize((int)$split["base_wager"])
            . ' per hand)</span></p>';
    } else {
        echo '<p>Wager: <b>' . mksize((int)$game["wager"]) . '</b></p>';
    }

    echo '<div class="blackjack-hands">';

    echo '<div class="blackjack-hand">';
    echo '<h2>' . $topLabel . '</h2>';
    
    bj_render_cards($topCards, $deck, $topHide, $topHandType, $animation);
    echo '<div class="blackjack-score">';
    if ($topHide) {
        echo 'One card hidden';
    } else {
        echo 'Points: ' . $topPoints;
    }
    echo '</div>';
    echo '</div>';

    if ($split !== null) {
        foreach ($split["hands"] as $index => $hand) {
            $active = (int)$split["active"] === $index
                && (string)$split["status"][$index] === "play";

            echo '<div class="blackjack-hand'
                . ($active ? ' blackjack-split-active' : '')
                . '">';
            echo '<h2>Hand ' . ($index + 1)
                . ($active ? ' — Playing' : '') . '</h2>';
            bj_render_cards($hand, $deck, false, "player", $animation);
            echo '<div class="blackjack-score">Points: '
                . bj_hand_value($hand, $deck) . '</div>';
            echo '</div>';
        }
    } else {
        echo '<div class="blackjack-hand">';
        echo '<h2>' . $bottomLabel . '</h2>';
        bj_render_cards($bottomCards, $deck, $bottomHide, $bottomHandType, $animation);
        echo '<div class="blackjack-score">Points: '
            . $bottomPoints . '</div>';
        echo '</div>';
    }

    echo '</div>';

    $canPlay = false;
    if ($game['status'] === 'playing') $canPlay = true; // Solo Game
    if ($game['status'] === 'pvp_p1' && $isCreator) $canPlay = true; // Creator's turn (plays first)
    if ($game['status'] === 'pvp_p2' && $isOpponent) $canPlay = true; // Joiner's turn (plays second)

    if ($game['status'] === 'waiting' && $isCreator) {
        echo '<div style="margin-top:30px; padding:24px; background:rgba(0,0,0,0.4); border-radius:16px; border:1px solid rgba(251,191,36,0.2);">';
        echo '<p style="margin:0 0 20px 0; font-weight:600; color:#fbbf24; font-size:16px; letter-spacing:0.5px;">⏳ Waiting for opponent to join...</p>';
        echo '<div style="display:flex; justify-content:center; gap:12px; flex-wrap:wrap;">';
        echo '<button class="blackjack-button blackjack-btn-primary" onclick="location.reload()">Refresh Table</button>';
        echo '<button class="blackjack-button" onclick="location.href=\'blackjack.php?mode=pvp\'">Back to Lobby</button>';
        echo '<form method="post" action="blackjack.php" style="margin:0;">';
        echo '<input type="hidden" name="csrf" value="' . bj_h(bj_csrf_token()) . '">';
        echo '<input type="hidden" name="action" value="cancel_table">';
        echo '<input type="hidden" name="game_id" value="' . $game['id'] . '">';
        echo '<button class="blackjack-button blackjack-btn-danger" type="submit">Cancel Table</button>';
        echo '</form>';
        echo '</div>';
        echo '</div>';
    } elseif (!$canPlay && $isPvP) {
        echo '<div style="margin-top:30px; padding:24px; background:rgba(0,0,0,0.4); border-radius:16px; border:1px solid rgba(251,191,36,0.2);">';
        $whoPlays = ($game['status'] === 'pvp_p1') ? 'Player 1 (Creator)' : 'Player 2 (Opponent)';
        echo '<p style="margin:0 0 20px 0; font-weight:600; color:#fbbf24; font-size:16px; letter-spacing:0.5px;">⏳ Waiting for ' . $whoPlays . ' to act...</p>';
        echo '<div style="display:flex; justify-content:center; gap:12px; flex-wrap:wrap;">';
        echo '<button class="blackjack-button blackjack-btn-primary" onclick="location.reload()">Refresh Table</button>';
        echo '<button class="blackjack-button" onclick="location.href=\'blackjack.php?mode=pvp\'">Back to Lobby</button>';
        echo '</div>';
        echo '</div>';
    }

    if ($canPlay) {
        echo '<div class="blackjack-actions">';
        bj_action_form("Hit", "hit", "blackjackHitButton", (int)$game["id"]);
        bj_action_form("Stand", "stand", "blackjackStandButton", (int)$game["id"]);

        if ($split === null && !$isPvP) {
            $doubleCost = (int)$game["wager"];
            $doubleTotal = $doubleCost * 2;

            if (
                count($playerCards) === 2
                && $balance >= $doubleCost
                && $doubleTotal <= $GLOBALS["blackjack_max_bet_runtime"]
            ) {
                bj_action_form(
                    "Double Down — " . mksize($doubleCost),
                    "double",
                    "blackjackDoubleButton",
                    (int)$game["id"]
                );
            }

            if (
                bj_can_split($playerCards, $deck)
                && $balance >= (int)$game["wager"]
            ) {
                bj_action_form(
                    "Split — " . mksize((int)$game["wager"]),
                    "split",
                    "blackjackSplitButton",
                    (int)$game["id"]
                );
            }
        }
        echo '</div>';
    }

    if ($split !== null) {
        echo '<p style="margin:16px 0 0; color:#9ca3af; font-size:13px;">'
            . 'Split hands use one wager per hand. A 21 after splitting pays 1:1.'
            . '</p>';
    }

    echo '</div>';

    echo '<script>
(function(){
    "use strict";

    var cards = document.querySelectorAll(
        "#blackjackApp .blackjack-card-animated[data-card-sequence]"
    );

    for(var i = 0; i < cards.length; i++){
        (function(card){
            var sequence = parseInt(
                card.getAttribute("data-card-sequence"),
                10
            ) || 1;

            window.setTimeout(function(){
                card.classList.add("blackjack-card-show");
                if(window.BlackjackSound){
                    var soundName = card.classList.contains("blackjack-card-flip")
                        ? "flip"
                        : "card";
                    window.BlackjackSound.play(soundName, 0.64);
                }
            }, 110 + ((sequence - 1) * 170));
        })(cards[i]);
    }

    if(window.history && window.history.replaceState){
        var cleanUrl = new URL(window.location.href);
        cleanUrl.searchParams.delete("anim");
        window.history.replaceState({}, "", cleanUrl.toString());
    }
})();
</script>';

    bj_render_stats((int)$game["user_id"]);
    bj_page_end();
}

function bj_render_result(array $game, array $deck, string $animation): void
{
    $userId = (int)$GLOBALS["CURUSER"]["id"];
    
    $dealerCards = bj_codes_from_string((string)$game["dealer_cards"]);
    $playerCards = bj_codes_from_string((string)$game["player_cards"]);
    $split = bj_decode_split_state((string)$game["player_cards"]);
    
    $result = (string)$game["result"];
    $profitCreator = (int)$game["profit"];
    $balance = bj_balance($userId);
    $dealerValue = (int)$game["dealer_points"];
    $playerValue = (int)$game["player_points"];
    $wager = (int)$game['wager'];

    $isCreator = (int)$game['user_id'] === $userId;
    $isOpponent = !empty($game['opponent_id']) && (int)$game['opponent_id'] === $userId;
    $isPvP = !empty($game['opponent_id']);

    if ($isPvP) {
        if ($isOpponent) {
            $topCards = $playerCards;
            $topLabel = bj_h($game['creator_name'] ?? 'Creator') . " (Player 1)";
            $topPoints = $playerValue;
            $topHandType = "player";

            $bottomCards = $dealerCards;
            $bottomLabel = "You (Player 2)";
            $bottomPoints = $dealerValue;
            $bottomHandType = "dealer";
        } else {
            $topCards = $dealerCards;
            $topLabel = bj_h($game['opponent_name'] ?? 'Opponent') . " (Player 2)";
            $topPoints = $dealerValue;
            $topHandType = "dealer";

            $bottomCards = $playerCards;
            $bottomLabel = "You (Player 1)";
            $bottomPoints = $playerValue;
            $bottomHandType = "player";
        }
    } else {
        $topCards = $dealerCards;
        $topLabel = "House";
        $topPoints = $dealerValue;
        $topHandType = "dealer";

        $bottomCards = $playerCards;
        $bottomLabel = "You";
        $bottomPoints = $playerValue;
        $bottomHandType = "player";
    }

    bj_page_start();

    echo '<div class="blackjack-table">';
    echo '<h2 style="margin-top:0;">Blackjack</h2>';

    if ($split !== null) {
        echo '<p>Total wager: <b>' . mksize((int)$game["wager"])
            . '</b> &nbsp; <span style="color:#9ca3af;">(' . mksize((int)$split["base_wager"])
            . ' per hand)</span></p>';
    } else {
        echo '<p>Wager: <b>' . mksize((int)$game["wager"]) . '</b></p>';
    }

    echo '<div class="blackjack-hands">';

    echo '<div class="blackjack-hand">';
    echo '<h2>' . $topLabel . '</h2>';
    bj_render_cards($topCards, $deck, false, $topHandType, $animation);
    echo '<div class="blackjack-score">Points: ' . $topPoints . '</div>';
    echo '</div>';

    if ($split !== null) {
        foreach ($split["hands"] as $index => $hand) {
            $handValue = bj_hand_value($hand, $deck);
            $handResult = bj_split_hand_result($hand, $dealerValue, bj_is_blackjack($dealerCards, $deck), $deck);

            echo '<div class="blackjack-hand">';
            echo '<h2>Hand ' . ($index + 1) . '</h2>';
            bj_render_cards($hand, $deck, false, "player", $animation);
            echo '<div class="blackjack-score">Points: ' . $handValue . '</div>';

            if ($handResult === "win") {
                echo '<div class="blackjack-win" style="margin-top:10px; font-size:18px;"><b>WIN +' . mksize((int)$split["base_wager"]) . '</b></div>';
            } elseif ($handResult === "push") {
                echo '<div class="blackjack-push" style="margin-top:10px; font-size:18px;"><b>PUSH</b></div>';
            } else {
                echo '<div class="blackjack-loss" style="margin-top:10px; font-size:18px;"><b>LOSS -' . mksize((int)$split["base_wager"]) . '</b></div>';
            }
            echo '</div>';
        }
    } else {
        echo '<div class="blackjack-hand">';
        echo '<h2>' . $bottomLabel . '</h2>';
        bj_render_cards($bottomCards, $deck, false, $bottomHandType, $animation);
        echo '<div class="blackjack-score">Points: ' . $bottomPoints . '</div>';
        echo '</div>';
    }

    echo '</div>';

    echo '<div class="blackjack-result" data-result="' . bj_h($result) . '">';

    if ($isPvP) {
        if ($isCreator) {
            $myResult = $result; 
        } else {
            // Reverse the logical result for the Joiner
            if ($result === 'win') { $myResult = 'loss'; }
            elseif ($result === 'loss') { $myResult = 'win'; }
            else { $myResult = 'push'; }
        }

        if ($myResult === 'win') {
            echo '<h2 class="blackjack-win" style="font-size:28px; margin:0 0 10px;">YOU WIN!</h2>';
            echo '<p style="font-size:18px; margin:0;"><b>Profit: +' . mksize($wager) . '</b></p>';
        } elseif ($myResult === 'loss') {
            echo '<h2 class="blackjack-loss" style="font-size:28px; margin:0 0 10px;">YOU LOSE!</h2>';
            echo '<p style="font-size:16px; margin:0; color:#9ca3af;">You lost ' . mksize($wager) . '.</p>';
        } else {
            echo '<h2 class="blackjack-push" style="font-size:28px; margin:0 0 10px;">PUSH (TIE)</h2>';
            echo '<p style="font-size:16px; margin:0; color:#9ca3af;">Wager returned.</p>';
        }
    } else {
        if ($split !== null) {
            if ($profitCreator > 0) {
                echo '<h2 class="blackjack-win" style="font-size:28px; margin:0 0 10px;">SPLIT HANDS WIN</h2>';
                echo '<p style="font-size:18px; margin:0;"><b>Net Profit: +' . mksize($profitCreator) . '</b></p>';
            } elseif ($profitCreator < 0) {
                echo '<h2 class="blackjack-loss" style="font-size:28px; margin:0 0 10px;">HOUSE WINS THE SPLIT</h2>';
                echo '<p style="font-size:18px; margin:0;"><b>Net Loss: -' . mksize(abs($profitCreator)) . '</b></p>';
            } else {
                echo '<h2 class="blackjack-push" style="font-size:28px; margin:0 0 10px;">SPLIT BREAKS EVEN</h2>';
                echo '<p style="font-size:16px; margin:0; color:#9ca3af;">Your two hands finished even overall.</p>';
            }
        } elseif ($result === "blackjack") {
            echo '<h2 class="blackjack-win" style="font-size:28px; margin:0 0 10px;">BLACKJACK!</h2>';
            echo '<p style="font-size:14px; margin:0 0 5px; color:#34d399;">Natural blackjack pays 3:2.</p>';
            echo '<p style="font-size:18px; margin:0;"><b>Profit: +' . mksize($profitCreator) . '</b></p>';
        } elseif ($result === "win") {
            echo '<h2 class="blackjack-win" style="font-size:28px; margin:0 0 10px;">YOU WIN</h2>';
            echo '<p style="font-size:18px; margin:0;"><b>Profit: +' . mksize($profitCreator) . '</b></p>';
        } elseif ($result === "push") {
            echo '<h2 class="blackjack-push" style="font-size:28px; margin:0 0 10px;">PUSH</h2>';
            echo '<p style="font-size:16px; margin:0; color:#9ca3af;">Your wager was returned.</p>';
        } else {
            echo '<h2 class="blackjack-loss" style="font-size:28px; margin:0 0 10px;">HOUSE WINS</h2>';
            echo '<p style="font-size:16px; margin:0; color:#9ca3af;">You lost ' . mksize(abs($profitCreator)) . '.</p>';
        }
    }

    echo '<div class="blackjack-credit" style="margin-top:20px;">';
    echo '<span class="blackjack-credit-label">Current Balance</span>';
    echo '<span class="blackjack-credit-value">' . mksize($balance) . '</span>';
    echo '</div>';

    echo '<div class="blackjack-actions">';

    $repeatWager = $split !== null ? (int)$split["base_wager"] : (int)$game["wager"];

    if ($repeatWager <= $balance && !$isPvP) {
        echo '<form method="post" action="blackjack.php" autocomplete="off">';
        echo '<input type="hidden" name="csrf" value="' . bj_h(bj_csrf_token()) . '">';
        echo '<input type="hidden" name="action" value="start">';
        echo '<input type="hidden" name="wager_bytes" value="' . $repeatWager . '">';
        echo '<button id="blackjackRepeatButton" class="blackjack-button blackjack-btn-primary" type="submit">Repeat ' . bj_h(mksize($repeatWager)) . '</button>';
        echo '</form>';
    }

    if ($isPvP) {
        echo '<button class="blackjack-button" type="button" onclick="location.href=\'blackjack.php?mode=pvp\'">Back to PvP</button>';
    } else {
        echo '<button id="blackjackChangeBetButton" class="blackjack-button" type="button" onclick="location.href=\'blackjack.php\'">Change Bet</button>';
    }
    
    echo '</div>';

    echo '</div>';
    echo '</div>';

    echo '<script>
(function(){
    "use strict";

    var cards = document.querySelectorAll("#blackjackApp .blackjack-card-animated[data-card-sequence]");

    for(var i = 0; i < cards.length; i++){
        (function(card){
            var sequence = parseInt(card.getAttribute("data-card-sequence"), 10) || 1;

            window.setTimeout(function(){
                card.classList.add("blackjack-card-show");
                if(window.BlackjackSound){
                    var soundName = card.classList.contains("blackjack-card-flip") ? "flip" : "card";
                    window.BlackjackSound.play(soundName, 0.64);
                }
            }, 110 + ((sequence - 1) * 170));
        })(cards[i]);
    }

    var blackjackResult = "' . bj_h($result) . '";
    var isCreator = ' . ($isCreator ? 'true' : 'false') . ';
    var isPvP = ' . ($isPvP ? 'true' : 'false') . ';
    var animatedCards = cards.length;
    var lastSequence = 1;

    for(var r = 0; r < cards.length; r++){
        var seq = parseInt(cards[r].getAttribute("data-card-sequence"), 10) || 1;
        if(seq > lastSequence){ lastSequence = seq; }
    }

    var outcomeDelay = animatedCards ? 420 + ((lastSequence - 1) * 170) : 120;

    window.setTimeout(function(){
        if(!window.BlackjackSound){ return; }
        
        var effectiveResult = blackjackResult;
        if (isPvP && !isCreator) {
            if (effectiveResult === "win") effectiveResult = "loss";
            else if (effectiveResult === "loss") effectiveResult = "win";
        }

        if(effectiveResult === "blackjack"){ window.BlackjackSound.play("blackjack", 0.82); }
        else if(effectiveResult === "win"){ window.BlackjackSound.play("win", 0.78); }
        else if(effectiveResult === "push"){ window.BlackjackSound.play("push", 0.68); }
        else if(effectiveResult === "loss"){ window.BlackjackSound.play("lose", 0.66); }
    }, outcomeDelay);

    if(window.history && window.history.replaceState){
        var cleanUrl = new URL(window.location.href);
        cleanUrl.searchParams.delete("anim");
        window.history.replaceState({}, "", cleanUrl.toString());
    }
})();
</script>';

    bj_render_stats((int)$game["user_id"]);
    bj_page_end();
}


/*
 * --------------------------------------------------------------------------
 * Controller
 * --------------------------------------------------------------------------
 */

$deck = bj_deck();
$db = bj_db();

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    bj_require_csrf();

    $action = isset($_POST["action"]) ? (string)$_POST["action"] : "";

    try {
        if ($action === "reset_stats") {
            $targetUserId = isset($_POST["target_user_id"]) ? (int)$_POST["target_user_id"] : 0;
            bj_admin_reset_stats($targetUserId);
            header("Location: blackjack.php");
            exit;
        }

        if ($action === "start") {
            $wager = bj_parse_wager($_POST, $minBet, $maxBet);
            $gameId = bj_start_hand($userId, $wager, $deck);
            bj_redirect_to_hand($gameId, "deal");
        }

        if ($action === "create_table") {
            $wager = bj_parse_wager($_POST, $minBet, $maxBet);
            $gameId = bj_pvp_start_hand($userId, $wager, $deck);
            // Creator plays immediately, send to table to Hit/Stand!
            bj_redirect_to_hand($gameId, "deal");
        }

        if ($action === "join_table") {
            $gameId = isset($_POST["game_id"]) ? (int)$_POST["game_id"] : 0;
            if ($gameId > 0) {
                bj_pvp_join_hand($userId, $gameId, $deck);
                bj_redirect_to_hand($gameId, "deal");
            }
            header("Location: blackjack.php?mode=pvp");
            exit;
        }

        if ($action === "cancel_table") {
            $gameId = isset($_POST["game_id"]) ? (int)$_POST["game_id"] : 0;
            if ($gameId > 0) {
                bj_pvp_cancel_hand($userId, $gameId);
            }
            header("Location: blackjack.php?mode=pvp");
            exit;
        }

        if ($action === "hit" || $action === "stand" || $action === "split" || $action === "double") {
            $gameIdInput = isset($_POST["game_id"]) ? (int)$_POST["game_id"] : 0;
            $gameId = bj_play_action($userId, $action, $deck, $maxBet, $gameIdInput);

            $animation = $action === "stand" ? "dealer" : ($action === "split" ? "split" : ($action === "double" ? "resolve" : "hit"));

            if ($action === "hit" || $action === "split" || $action === "double" || $action === "stand") {
                $finishedGame = bj_query_one($db, "SELECT * FROM blackjack_games WHERE id = $gameId LIMIT 1");
                if ($finishedGame && ((string)$finishedGame["status"] === "settled" || (string)$finishedGame["status"] === "waiting")) {
                    $animation = "resolve";
                }
            }

            bj_redirect_to_hand($gameId, $animation);
        }

        throw new RuntimeException("Unknown blackjack action.");
    } catch (Throwable $e) {
        show_error_msg(
            "Blackjack",
            bj_h($e->getMessage()),
            1
        );
    }
}

$requestedHand = isset($_GET["hand"]) ? (int)$_GET["hand"] : 0;
$animation = isset($_GET["anim"]) ? (string)$_GET["anim"] : "";

if (!in_array($animation, ["deal", "hit", "split", "dealer", "resolve"], true)) {
    $animation = "";
}

if ($requestedHand > 0) {
    $game = bj_get_game($db, $requestedHand, $userId);

    if ($game) {
        if ((string)$game["status"] === "settled") {
            bj_render_result($game, $deck, $animation);
        } else {
            bj_render_hand($game, $deck, $animation);
        }
        exit;
    }
}

$activeGame = bj_get_active_game($db, $userId, false);

// Ensure you are blocked on an active game only if it's your turn to move!
if ($activeGame && empty($_GET['mode'])) {
    bj_redirect_to_hand((int)$activeGame["id"]);
}

bj_render_wager_screen($userId, $minBet, $maxBet);