<?php
require_once '../../../4p1c_4cc45t0db._.php';
require_once '../utils/helpers.php';
require_once '../models/Game.php';
require_once '../models/Team.php';
require_once '../models/Club.php';
require_once '../models/Court.php';

class GameController
{
    private $teamModel;
    private $gameModel;
    private $clubModel;
    private $courtModel;

    public function __construct()
    {
        $db = Database::connect();
        $this->teamModel = new Team($db);
        $this->gameModel = new Game($db);
        $this->clubModel = new Club($db);
        $this->courtModel = new Court($db);
    }

    public function show($id, $tournamentId)
    {
        $game = null;
        if ($id) {
            $game = $this->gameModel->getGameById($id);
            $game['t1'] = $this->teamModel->getTeamIdByCode($game['t1']);
            $game['t2'] = $this->teamModel->getTeamIdByCode($game['t2']);
            $courts = isset($game['club']) ? $this->courtModel->getCourtsByClub($game['club']) : [];
            $game['club'] = $this->clubModel->getClubIdByCode($game['club']);
            $game['court'] = $this->courtModel->getCourtIdByCode($game['court']);
        }

        $teams = $this->teamModel->getTeamsByTournament($tournamentId);
        $clubs = $this->clubModel->getClubs();

        require '../views/game_form.php';
    }

    public function create($tournamentId)
    {
        $teams = $this->teamModel->getTeamsByTournament($tournamentId);
        $clubs = $this->clubModel->getClubs();
        $courts = isset($game['club']) ? $this->courtModel->getCourtsByClub($game['club']) : [];
        require '../views/game_form.php';
    }

    public function store()
    {
        $_POST['code'] = generateUUID();
        $response = $this->gameModel->createGame($_POST);
        $game = $this->gameModel->getGameIdByCode($_POST['code']);
        header('Location: ../public/game.php?action=edit&id=' . $game . '&tournament=' . $_POST['tournament']);
    }

    public function update()
    {
        $response = $this->gameModel->updateGame($_POST);
        header('Location: ../public/game.php?action=edit&id=' . $_POST['id'] . '&tournament=' . $_POST['tournament']);
    }
}
