<?php
declare(strict_types=1);

require __DIR__.'/_bootstrap.php';

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

try {
    $db=Database::connect();
    $player=(new PlayerAuthService($db))->authenticate([]);

    $manager=new RoomManagerService($db);
    $room=$manager->assign((int)$player['user_id']);

    $q=$db->prepare("
        SELECT id, public_round_id, winner, settled_at
        FROM rounds
        WHERE room_id=?
          AND state='SETTLED'
          AND winner IS NOT NULL
        ORDER BY id DESC
        LIMIT 10
    ");
    $q->execute([(int)$room['room_id']]);

    $winners=[];
    foreach($q->fetchAll() as $row){
        $winners[]=[
            'round_id'=>(int)$row['id'],
            'public_round_id'=>$row['public_round_id'],
            'winner'=>$row['winner'],
            'settled_at'=>$row['settled_at']
        ];
    }

    json_out([
        'ok'=>true,
        'room'=>[
            'id'=>(int)$room['room_id'],
            'code'=>$room['code'],
            'name'=>$room['name']
        ],
        'winners'=>$winners
    ]);
} catch(Throwable $e) {
    json_out(['ok'=>false,'error'=>$e->getMessage()],401);
}
