<?php

namespace App\Repositories;

final class MatchRepository extends BaseRepository
{
    public function all(): array
    {
        $params = [];
        $sql = 'SELECT m.*, ht.name AS home_team, at.name AS away_team, c.name AS court_name
                FROM matches m
                JOIN teams ht ON ht.id = m.home_team_id
                JOIN teams at ON at.id = m.away_team_id
                LEFT JOIN courts c ON c.id = m.court_id';
        if (!empty($_GET['tournament_id'])) {
            $sql .= ' WHERE m.tournament_id = :tournament_id';
            $params['tournament_id'] = (int) $_GET['tournament_id'];
        }
        $sql .= ' ORDER BY m.scheduled_at ASC, m.id ASC';
        return $this->paginate($sql, $params);
    }

    public function create(array $data): array
    {
        $stmt = $this->db->prepare(
            'INSERT INTO matches (tournament_id, phase, scheduled_at, court_id, home_team_id, away_team_id, status)
             VALUES (:tournament_id, :phase, :scheduled_at, :court_id, :home_team_id, :away_team_id, :status)'
        );
        $stmt->execute([
            'tournament_id' => $data['tournament_id'],
            'phase' => $data['phase'] ?? 'regular',
            'scheduled_at' => $data['scheduled_at'] ?? null,
            'court_id' => $data['court_id'] ?? null,
            'home_team_id' => $data['home_team_id'],
            'away_team_id' => $data['away_team_id'],
            'status' => $data['status'] ?? 'scheduled',
        ]);
        return $this->find((int) $this->db->lastInsertId());
    }

    public function find(int $id): ?array
    {
        $stmt = $this->db->prepare(
            'SELECT m.*, ht.name AS home_team, at.name AS away_team
             FROM matches m
             JOIN teams ht ON ht.id = m.home_team_id
             JOIN teams at ON at.id = m.away_team_id
             WHERE m.id = :id'
        );
        $stmt->execute(['id' => $id]);
        return $stmt->fetch() ?: null;
    }
}
