<?php
// Tournament.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 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;
    }

    public function createTournament($data)
    {
        $sql = "INSERT INTO tournament (name, description, date, code, entity) VALUES (?, ?, ?, ?, ?)";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param(
            'sssss',
            $data['name'],
            $data['description'],
            $data['date'],
            $data['code'],
            $_SESSION["entity"]
        );
        return $stmt->execute();
    }

    public function updateTournament($data)
    {
        $sql = "UPDATE tournament SET name = ?, description = ?, date = ?, entity = ?
                WHERE id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param(
            'ssssi',
            $data['name'],
            $data['description'],
            $data['date'],
            $_SESSION["entity"],
            $data['id']
        );
        return $stmt->execute();
    }
}
