<?php
require __DIR__.'/_bootstrap.php';

use Zoo\Database;
use Zoo\Auth\PlayerAuthService;
use Zoo\Room\RoomManagerService;
use Zoo\Room\BotActivityService;

try {
    $db=Database::connect();
    $player=(new PlayerAuthService($db))->authenticate([]);
    $room=(new RoomManagerService($db))->assign((int)$player['user_id']);

    $q=$db->prepare("
        SELECT id,public_round_id,state,opened_at,closes_at
        FROM rounds
        WHERE room_id=?
        ORDER BY id DESC LIMIT 1
    ");
    $q->execute([$room['room_id']]);
    $round=$q->fetch();

    if(!$round) throw new RuntimeException('Room has no round');

    $q=$db->prepare("
        SELECT COUNT(*) AS real_bets,COALESCE(SUM(amount),0) AS real_stake
        FROM bets WHERE round_id=?
    ");
    $q->execute([$round['id']]);
    $real=$q->fetch();

    $botsSvc=new BotActivityService($db);
    $bots=$botsSvc->summary((int)$room['room_id'],(int)$round['id']);

    json_out([
        'ok'=>true,
        'room'=>[
            'id'=>(int)$room['room_id'],
            'code'=>$room['code'],
            'name'=>$room['name']
        ],
        'round'=>$round,
        'real_activity'=>[
            'bets'=>(int)$real['real_bets'],
            'stake'=>(float)$real['real_stake']
        ],
        'bot_activity'=>$bots,
        'bot_actions'=>$botsSvc->actions((int)$room['room_id'],(int)$round['id'],100),
        'disclosure'=>'Zoo Bots are simulated house activity. They do not use real wallets, do not affect RNG, and are excluded from real settlement/revenue.'
    ]);
} catch(Throwable $e) {
    json_out(['ok'=>false,'error'=>$e->getMessage()],401);
}
