<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Database;
use App\Core\Request;
use App\Core\Response;

final class MatchSheetController
{
    public function index(array $params): void
    {
        Auth::requireRole(['admin', 'delegate']);
        Response::json($this->details((int) $params['id']));
    }

    public function save(array $params): void
    {
        Auth::requireRole(['admin', 'delegate']);
        $matchId = (int) $params['id'];
        $data = Request::json();
        $db = Database::connection();
        $stmt = $db->prepare(
            'INSERT INTO match_sheet_details (match_id, team_id, captain_player_id, coach_name, observations)
             VALUES (:match_id, :team_id, :captain_player_id, :coach_name, :observations)
             ON DUPLICATE KEY UPDATE captain_player_id = VALUES(captain_player_id), coach_name = VALUES(coach_name), observations = VALUES(observations)'
        );
        $stmt->execute([
            'match_id' => $matchId,
            'team_id' => $data['team_id'] ?? null,
            'captain_player_id' => $data['captain_player_id'] ?: null,
            'coach_name' => $data['coach_name'] ?? null,
            'observations' => $data['observations'] ?? null,
        ]);

        Response::json($this->details($matchId), 201);
    }

    private function details(int $matchId): array
    {
        $stmt = Database::connection()->prepare(
            'SELECT d.*, t.name team_name, CONCAT(p.first_name, " ", p.last_name) captain_name
             FROM match_sheet_details d
             LEFT JOIN teams t ON t.id = d.team_id
             LEFT JOIN players p ON p.id = d.captain_player_id
             WHERE d.match_id = :id
             ORDER BY d.team_id'
        );
        $stmt->execute(['id' => $matchId]);
        return $stmt->fetchAll();
    }
}
