<?php
// Team.php
class Team
{
    private $conn;

    public function __construct($db)
    {
        $this->conn = $db;
    }

    public function getTeamsByTournament($tournamentId)
    {
        $tournament = new Tournament($this->conn);
        $tournamentCode = $tournament->getTournamentCodeById($tournamentId);

        if ($tournamentCode === null) {
            return [];
        }

        $sql = "SELECT t.*, p1.pApellido AS p1_lastname, p2.pApellido AS p2_lastname
                FROM team t
                LEFT JOIN player p1 ON t.p1 = p1.code
                LEFT JOIN player p2 ON t.p2 = p2.code
                WHERE t.tournament = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $tournamentCode);
        $stmt->execute();
        return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }

    public function getTeamById($id)
    {
        $sql = "SELECT * FROM team WHERE id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('i', $id);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc();
    }

    public function getTeamCodeById($id)
    {
        $sql = "SELECT code FROM team WHERE id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('i', $id);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc()['code'] ?? null;
    }

    public function getTeamIdByCode($code)
    {
        $sql = "SELECT id FROM team WHERE code = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $code);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc()['id'] ?? null;
    }

    public function createTeam($data)
    {
        $tournament = new Tournament($this->conn);
        $data['tournament'] = $tournament->getTournamentCodeById($data['tournament']);

        $player = new Player($this->conn);
        $data['p1'] = $player->getPlayerCodeById($data['p1']);
        $data['p2'] = $player->getPlayerCodeById($data['p2']);

        if ($data['tournament'] === null || $data['p1'] === null || $data['p2'] === null) {
            throw new Exception('Uno o más códigos de relaciones son nulos. Verifica los datos.');
        }

        $sql = "INSERT INTO team (p1, p2, `group`, tournament, code) VALUES (?, ?, ?, ?, ?)";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param(
            'ssiss',
            $data['p1'],
            $data['p2'],
            $data['group'],
            $data['tournament'],
            $data['code']
        );
        return $stmt->execute();
    }

    public function updateTeam($data)
    {
        $tournament = new Tournament($this->conn);
        $data['tournament'] = $tournament->getTournamentCodeById($data['tournament']);

        $player = new Player($this->conn);
        $data['p1'] = $player->getPlayerCodeById($data['p1']);
        $data['p2'] = $player->getPlayerCodeById($data['p2']);

        if ($data['tournament'] === null || $data['p1'] === null || $data['p2'] === null) {
            throw new Exception('Uno o más códigos de relaciones son nulos. Verifica los datos.');
        }

        $sql = "UPDATE team 
                SET p1 = ?, p2 = ?, `group` = ?, tournament = ?
                WHERE id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('ssisi', $data['p1'], $data['p2'], $data['group'], $data['tournament'], $data['id']);
        return $stmt->execute();
    }
}
