<?php

use Insallah\Db, Insallah\Tournament, Insallah\TournamentModel;

require_once '_incl_data/__config.php';
require_once '_incl_data/class/Insallah/Core/Db.php';
require_once '_incl_data/class/Insallah/Tournament/Tournament.php';
require_once '_incl_data/class/Insallah/Tournament/TournamentModel.php';

$db = new Db();
$uid = $db::getValue('select id from users where login = ?', [$_COOKIE['login']]);

$tournamentsList = $db::getRows('select * from tournaments');
$tournaments = '<ul>';
foreach ($tournamentsList as $tournament) {
    $level = $tournament['tid'];
    $time = $tournament['start_time'];
    $tournament_members_id = TournamentModel::getFreeFighters($tournament['tid']);
    $members = [];
    foreach ($tournament_members_id as $member) {
        $members[] = TournamentModel::uidToLogin($member['uid']);
    }
    $tournaments .= "<li>Турнир для {$tournament['tid']} уровней.<br>
Время подачи заявки: " . date('G:i', $tournament['start_time']) . "<br>
Участники:" . implode(', ', $members) . '</li>';
}
$tournaments .= '</ul>';

if (array_key_exists('tournament_start', $_POST)) {
    (new Tournament())->join($uid);
}
?>

<h3>Турнир для <?=$_COOKIE['login']?></h3>
<?= $tournaments ?>
<?php if (!TournamentModel::getTournamentIdByUserId($uid)): ?>
    <form method="post">
        <input type="submit" name="tournament_start" value="Принять участие в турнире">
    </form>
<?php else: ?>
    Вы уже учавствуете в турнире!
<?php endif; ?>