<?php

class MatchController extends Controller
{
    public function index(Request $request): void
    {
        $sports = $this->db()->fetchAll("SELECT id, name_en FROM sports WHERE is_active = 1 ORDER BY name_en");
        $this->view('matches/index', [
            'title' => lang('sports.matches'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.matches')]],
            'sports' => $sports,
        ]);
    }

    public function create(Request $request): void
    {
        $db = $this->db();
        $sports = $db->fetchAll("SELECT id, name_en FROM sports WHERE is_active = 1 ORDER BY name_en");
        $leagues = $db->fetchAll("SELECT l.id, CONCAT(sp.name_en,' - ',l.name_en) as name FROM sport_leagues l LEFT JOIN sports sp ON l.sport_id = sp.id WHERE l.status IN ('registration','scheduled','in_progress') ORDER BY l.start_date DESC");
        $facilities = $db->fetchAll("SELECT id, name_en FROM facilities WHERE is_active = 1 AND is_bookable = 1 ORDER BY name_en");
        $this->view('matches/create', [
            'title' => lang('sports.create_match'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.matches'), 'url' => '/sports/matches'], ['label' => lang('common.create')]],
            'sports' => $sports, 'leagues' => $leagues, 'facilities' => $facilities,
        ]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $matchNumber = SequenceGenerator::next('match_number');
        $validator = new Validator($request->all(), [
            'sport_id' => 'required|integer|exists:sports,id',
            'home_team_id' => 'required|integer|exists:sport_teams,id',
            'away_team_id' => 'required|integer|exists:sport_teams,id',
            'match_date' => 'required|date',
            'start_time' => 'nullable|string',
            'facility_id' => 'nullable|integer',
            'league_id' => 'nullable|integer',
            'tournament_id' => 'nullable|integer',
            'match_type' => 'required|in:league,friendly,tournament,playoff,final,exhibition',
            'round_number' => 'nullable|integer',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['match_number'] = $matchNumber;
        $data['status'] = 'scheduled';
        $id = $this->db()->insert('sport_matches', $data);
        $this->audit('create', 'sport_match', $id, "Created match: {$matchNumber}");
        $this->json(['success' => true, 'message' => 'Match created', 'redirect' => '/sports/matches/' . $id]);
    }

    public function show(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = $this->db();
        $match = $db->fetchOne(
            "SELECT m.*, sp.name_en as sport_name, ht.name_en as home_name, at.name_en as away_name,
                    f.name_en as facility_name, l.name_en as league_name
             FROM sport_matches m LEFT JOIN sports sp ON m.sport_id = sp.id
             LEFT JOIN sport_teams ht ON m.home_team_id = ht.id LEFT JOIN sport_teams at ON m.away_team_id = at.id
             LEFT JOIN facilities f ON m.facility_id = f.id LEFT JOIN sport_leagues l ON m.league_id = l.id
             WHERE m.id = ?", [$id]);
        if (!$match) { $this->abort(404); return; }

        $events = $db->fetchAll(
            "SELECT mr.*, t.name_en as team_name, m.full_name_en as member_name
             FROM sport_match_results mr LEFT JOIN sport_teams t ON mr.team_id = t.id LEFT JOIN members m ON mr.member_id = m.id
             WHERE mr.match_id = ? ORDER BY mr.event_minute", [$id]);

        $this->view('matches/show', [
            'title' => $match['match_number'],
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.matches'), 'url' => '/sports/matches'], ['label' => $match['match_number']]],
            'match' => $match, 'events' => $events,
        ]);
    }

    public function recordResult(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $homeScore = (int) $request->post('home_score', 0);
        $awayScore = (int) $request->post('away_score', 0);
        $this->db()->update('sport_matches', [
            'home_score' => $homeScore, 'away_score' => $awayScore,
            'status' => 'completed', 'end_time' => date('H:i:s'),
        ], 'id = ?', [$id]);
        $this->audit('update', 'sport_match', $id, "Recorded result: {$homeScore} - {$awayScore}");
        $this->json(['success' => true, 'message' => 'Result recorded', 'redirect' => '/sports/matches/' . $id]);
    }

    public function updateStatus(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $status = $request->post('status');
        if (!in_array($status, ['scheduled','in_progress','completed','postponed','cancelled','forfeited'])) {
            $this->json(['success' => false, 'message' => 'Invalid status'], 422); return;
        }
        $this->db()->update('sport_matches', ['status' => $status], 'id = ?', [$id]);
        $this->audit('update', 'sport_match', $id, "Changed match status to {$status}");
        $this->json(['success' => true, 'message' => 'Status updated', 'redirect' => '/sports/matches/' . $id]);
    }
}