<?php

namespace App\Repositories;

final class TournamentRepository extends BaseRepository
{
    public function all(): array
    {
        $where = [];
        $params = [];
        if (!empty($_GET['category'])) {
            $where[] = 'category = :category';
            $params['category'] = $_GET['category'];
        }
        if (!empty($_GET['status'])) {
            $where[] = 'status = :status';
            $params['status'] = $_GET['status'];
        }
        $sql = 'SELECT * FROM tournaments';
        if ($where) {
            $sql .= ' WHERE ' . implode(' AND ', $where);
        }
        $sql .= ' ORDER BY starts_at DESC, id DESC';
        return $this->paginate($sql, $params);
    }

    public function create(array $data): array
    {
        $stmt = $this->db->prepare(
            'INSERT INTO tournaments (name, category, age_subcategory, format, status, starts_at, ends_at)
             VALUES (:name, :category, :age_subcategory, :format, :status, :starts_at, :ends_at)'
        );
        $stmt->execute([
            'name' => $data['name'],
            'category' => $data['category'],
            'age_subcategory' => $data['age_subcategory'] ?? null,
            'format' => $data['format'],
            'status' => $data['status'] ?? 'draft',
            'starts_at' => $data['starts_at'] ?? null,
            'ends_at' => $data['ends_at'] ?? null,
        ]);
        return $this->find((int) $this->db->lastInsertId());
    }

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