<?php
declare(strict_types=1);


require_once __DIR__ . '/_bootstrap.php';

use Zoo\Database;
use Zoo\Game\RoundRuntimeService;
use Zoo\Game\RoundService;

try {
    $id = (int)($_GET['round_id'] ?? 0);

    $db = Database::connect();

    $roomQ=$db->prepare("
        SELECT room_id,state,closes_at
        FROM rounds
        WHERE id=?
        LIMIT 1
    ");
    $roomQ->execute([$id]);
    $target=$roomQ->fetch(PDO::FETCH_ASSOC);

    if($target){
        $roomId=(int)$target['room_id'];

        // Guarantee the RNG result for the exact round the browser is drawing.
        if(
            $target['state']==='BETTING_CLOSED'
            || (
                $target['state']==='BETTING_OPEN'
                && !empty($target['closes_at'])
                && strtotime((string)$target['closes_at'])<=time()
            )
        ){
            try{
                (new RoundService($db))->closeAndGenerate($id);
            }catch(Throwable $ignored){}
        }

        // May settle, but can never create the next round.
        (new RoundRuntimeService($db))->tickRoom($roomId,false);
    }

    $q = $db->prepare("
        SELECT id, room_id, public_round_id, state, opened_at, closes_at,
               result_at, server_seed_hash, rng_number, winner, settled_at
        FROM rounds
        WHERE id = ?
    ");

    $q->execute([$id]);
    $r = $q->fetch();

    if (!$r) {
        json_out([
            'ok' => false,
            'db_connected' => true,
            'error' => 'Round not found'
        ], 404);
    }

    json_out([
        'ok' => true,
        'db_connected' => true,
        'round' => $r
    ]);

} catch (Throwable $e) {
    json_out([
        'ok' => false,
        'db_connected' => false,
        'error' => $e->getMessage()
    ], 500);
}