<?php

class LeagueController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('leagues/index', [
            'title' => lang('sports.leagues'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.leagues')]],
        ]);
    }

    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");
        $seasons = $db->fetchAll("SELECT ss.id, CONCAT(sp.name_en,' - ',ss.name_en) as name FROM sport_seasons ss LEFT JOIN sports sp ON ss.sport_id = sp.id ORDER BY ss.start_date DESC LIMIT 20");
        $this->view('leagues/create', [
            'title' => lang('sports.create_league'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.leagues'), 'url' => '/sports/leagues'], ['label' => lang('common.create')]],
            'sports' => $sports, 'seasons' => $seasons,
        ]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $validator = new Validator($request->all(), [
            'league_code' => 'required|string|max:20|unique:sport_leagues,league_code',
            'sport_id' => 'required|integer|exists:sports,id',
            'season_id' => 'required|integer|exists:sport_seasons,id',
            'name_en' => 'required|string|max:300',
            'name_ar' => 'nullable|string|max:300',
            'league_type' => 'required|in:round_robin,knockout,group_stage,swiss,custom',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date',
            'max_teams' => 'nullable|integer',
            'status' => 'required|in:registration,scheduled,in_progress,completed,cancelled',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $id = $this->db()->insert('sport_leagues', $validator->validated());
        $this->audit('create', 'sport_league', $id, 'Created league');
        $this->json(['success' => true, 'message' => 'League created', 'redirect' => '/sports/leagues/' . $id]);
    }

    public function show(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = $this->db();
        $league = $db->fetchOne("SELECT l.*, sp.name_en as sport_name, ss.name_en as season_name FROM sport_leagues l LEFT JOIN sports sp ON l.sport_id = sp.id LEFT JOIN sport_seasons ss ON l.season_id = ss.id WHERE l.id = ?", [$id]);
        if (!$league) { $this->abort(404); return; }

        $standings = $db->fetchAll(
            "SELECT lt.*, t.name_en as team_name, t.team_code
             FROM sport_league_teams lt LEFT JOIN sport_teams t ON lt.team_id = t.id
             WHERE lt.league_id = ? ORDER BY lt.points DESC, lt.goal_difference DESC, lt.goals_for DESC", [$id]);

        $matches = $db->fetchAll(
            "SELECT m.*, ht.name_en as home_name, at.name_en as away_name
             FROM sport_matches m LEFT JOIN sport_teams ht ON m.home_team_id = ht.id LEFT JOIN sport_teams at ON m.away_team_id = at.id
             WHERE m.league_id = ? ORDER BY m.match_date, m.start_time", [$id]);

        $availableTeams = $db->fetchAll("SELECT id, name_en, team_code FROM sport_teams WHERE sport_id = ? AND status = 'active' AND id NOT IN (SELECT team_id FROM sport_league_teams WHERE league_id = ?) ORDER BY name_en", [$league['sport_id'], $id]);

        $this->view('leagues/show', [
            'title' => $league['name_en'],
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.leagues'), 'url' => '/sports/leagues'], ['label' => $league['name_en']]],
            'league' => $league, 'standings' => $standings, 'matches' => $matches, 'availableTeams' => $availableTeams,
        ]);
    }

    public function edit(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $league = $this->db()->fetchOne("SELECT * FROM sport_leagues WHERE id = ?", [$id]);
        if (!$league) { $this->abort(404); return; }
        $sports = $this->db()->fetchAll("SELECT id, name_en FROM sports WHERE is_active = 1 ORDER BY name_en");
        $seasons = $this->db()->fetchAll("SELECT ss.id, CONCAT(sp.name_en,' - ',ss.name_en) as name FROM sport_seasons ss LEFT JOIN sports sp ON ss.sport_id = sp.id ORDER BY ss.start_date DESC LIMIT 20");
        $this->view('leagues/edit', [
            'title' => 'Edit: ' . $league['name_en'],
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.leagues'), 'url' => '/sports/leagues'], ['label' => lang('common.edit')]],
            'league' => $league, 'sports' => $sports, 'seasons' => $seasons,
        ]);
    }

    public function update(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $validator = new Validator($request->all(), [
            'name_en' => 'required|string|max:300',
            'name_ar' => 'nullable|string|max:300',
            'league_type' => 'required|in:round_robin,knockout,group_stage,swiss,custom',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date',
            'status' => 'required|in:registration,scheduled,in_progress,completed,cancelled',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $this->db()->update('sport_leagues', $validator->validated(), 'id = ?', [$id]);
        $this->audit('update', 'sport_league', $id, 'Updated league');
        $this->json(['success' => true, 'message' => 'League updated', 'redirect' => '/sports/leagues/' . $id]);
    }

    public function registerTeam(Request $request): void
    {
        $leagueId = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $teamId = (int) $request->post('team_id');
        $this->db()->insert('sport_league_teams', [
            'league_id' => $leagueId, 'team_id' => $teamId,
            'registration_date' => date('Y-m-d'), 'status' => 'registered',
        ]);
        $this->audit('create', 'sport_league_team', null, "Registered team #{$teamId} in league #{$leagueId}");
        $this->json(['success' => true, 'message' => 'Team registered', 'redirect' => '/sports/leagues/' . $leagueId]);
    }
}