<?php

namespace App\Repositories;

final class TeamRepository extends BaseRepository
{
    public function all(): array
    {
        $params = [];
        $sql = 'SELECT teams.*, tournaments.name AS tournament_name
                FROM teams JOIN tournaments ON tournaments.id = teams.tournament_id';
        if (!empty($_GET['tournament_id'])) {
            $sql .= ' WHERE teams.tournament_id = :tournament_id';
            $params['tournament_id'] = (int) $_GET['tournament_id'];
        }
        $sql .= ' ORDER BY teams.name';
        return $this->paginate($sql, $params);
    }

    public function create(array $data): array
    {
        $token = bin2hex(random_bytes(16));
        $stmt = $this->db->prepare(
            'INSERT INTO teams (tournament_id, name, logo_path, coach_name, delegate_user_id, registration_token)
             VALUES (:tournament_id, :name, :logo_path, :coach_name, :delegate_user_id, :registration_token)'
        );
        $stmt->execute([
            'tournament_id' => $data['tournament_id'],
            'name' => $data['name'],
            'logo_path' => $data['logo_path'] ?? null,
            'coach_name' => $data['coach_name'] ?? null,
            'delegate_user_id' => $data['delegate_user_id'] ?? null,
            'registration_token' => $token,
        ]);
        return $this->find((int) $this->db->lastInsertId());
    }

    public function find(int $id): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM teams WHERE id = :id');
        $stmt->execute(['id' => $id]);
        return $stmt->fetch() ?: null;
    }

    public function findByToken(string $token): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM teams WHERE registration_token = :token');
        $stmt->execute(['token' => $token]);
        return $stmt->fetch() ?: null;
    }
}
