<?php
class Tournament
{
    private $conn;

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

    public function getAllTournaments()
    {
        $sql = "SELECT t.*, e.name AS entity_name FROM tournament t
                LEFT JOIN entity e ON t.entity = e.code";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute();
        return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }

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

    public function getTournamentByPlayer($playerId)
    {
        
        $player = new Player($this->conn);
        $playerCode = $player->getPlayerCodeById($playerId);

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

        $sql = "SELECT t.* FROM tournament t
                LEFT JOIN team te ON t.code = te.tournament
                WHERE te.p1 = ? OR te.p2 = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('ss', $playerCode, $playerCode);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc();
    }

    public function getTournamentsByEntity($entityId)
    {
        
        $entity = new Entity($this->conn);
        $entityCode = $entity->getEntityCodeById($entityId);

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

        $sql = "SELECT t.*, e.name AS entity_name FROM tournament t
                LEFT JOIN entity e ON t.entity = e.code
                WHERE t.entity = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $entityCode);
        $stmt->execute();
        return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }

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