<?php
require_once '../../../4p1c_4cc45t0db._.php';
require_once '../utils/helpers.php';
require_once '../models/Team.php';
require_once '../models/Tournament.php';
require_once '../models/Player.php';

class TeamController
{
    private $teamModel;
    private $tournamentModel;
    private $playerModel;

    public function __construct()
    {
        $db = Database::connect();
        $this->teamModel = new Team($db);
        $this->tournamentModel = new Tournament($db);
        $this->playerModel = new Player($db);
    }

    public function index($tournamentId)
    {
        $teams = $this->teamModel->getTeamsByTournament($tournamentId);
        require '../views/tournaments.php';
    }

    public function show($teamId)
    {
        $players = $this->playerModel->getAllPlayers();
        $team = $this->teamModel->getTeamById($teamId);
        $team['p1'] = $this->playerModel->getPlayerByCode($team['p1']);
        $team['p2'] = $this->playerModel->getPlayerByCode($team['p2']);
        require '../views/team_form.php';
    }

    public function create($tournamentId)
    {
        $players = $this->playerModel->getAllPlayers();
        require '../views/team_form.php';
    }

    public function store()
    {
        $_POST['code'] = generateUUID();
        $this->teamModel->createTeam($_POST);
        $team =  $this->teamModel->getTeamIdByCode($_POST['code']);
        header('Location: ../public/team.php?action=edit&id=' . $team . '&tournament=' . $_POST['tournament']);
    }

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