<?php

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

    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");
        $facilities = $db->fetchAll("SELECT id, name_en FROM facilities 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 WHERE ss.status IN ('upcoming','registration','active') ORDER BY ss.start_date DESC");
        $this->view('tournaments/create', [
            'title' => lang('sports.create_tournament'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.tournaments'), 'url' => '/sports/tournaments'], ['label' => lang('common.create')]],
            'sports' => $sports, 'facilities' => $facilities, 'seasons' => $seasons,
        ]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $tCode = SequenceGenerator::next('tournament_code');
        $validator = new Validator($request->all(), [
            'sport_id' => 'required|integer|exists:sports,id',
            'name_en' => 'required|string|max:300',
            'name_ar' => 'nullable|string|max:300',
            'tournament_type' => 'required|in:individual,doubles,team,mixed',
            'format' => 'required|in:single_elimination,double_elimination,round_robin,swiss,group_knockout,custom',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date',
            'registration_start' => 'nullable|date',
            'registration_end' => 'nullable|date',
            'max_participants' => 'nullable|integer',
            'entry_fee' => 'nullable|decimal',
            'prize_pool' => 'nullable|decimal',
            'facility_id' => 'nullable|integer',
            'season_id' => 'nullable|integer',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['tournament_code'] = $tCode;
        $data['status'] = 'planned';
        $data['entry_fee'] = $data['entry_fee'] ?? 0;
        $data['prize_pool'] = $data['prize_pool'] ?? 0;
        $data['created_by'] = auth_id();
        $id = $this->db()->insert('sport_tournaments', $data);
        $this->audit('create', 'sport_tournament', $id, "Created tournament: {$data['name_en']}");
        $this->json(['success' => true, 'message' => 'Tournament created', 'redirect' => '/sports/tournaments/' . $id]);
    }

    public function show(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = $this->db();
        $tournament = $db->fetchOne("SELECT t.*, sp.name_en as sport_name, f.name_en as facility_name FROM sport_tournaments t LEFT JOIN sports sp ON t.sport_id = sp.id LEFT JOIN facilities f ON t.facility_id = f.id WHERE t.id = ?", [$id]);
        if (!$tournament) { $this->abort(404); return; }

        $registrations = $db->fetchAll(
            "SELECT r.*, m.full_name_en as member_name, m.membership_number, t.name_en as team_name
             FROM sport_tournament_registrations r LEFT JOIN members m ON r.member_id = m.id LEFT JOIN sport_teams t ON r.team_id = t.id
             WHERE r.tournament_id = ? ORDER BY r.seed_number, r.registration_date", [$id]);

        $this->view('tournaments/show', [
            'title' => $tournament['name_en'],
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.tournaments'), 'url' => '/sports/tournaments'], ['label' => $tournament['name_en']]],
            'tournament' => $tournament, 'registrations' => $registrations,
        ]);
    }

    public function edit(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $tournament = $this->db()->fetchOne("SELECT * FROM sport_tournaments WHERE id = ?", [$id]);
        if (!$tournament) { $this->abort(404); return; }
        $sports = $this->db()->fetchAll("SELECT id, name_en FROM sports WHERE is_active = 1 ORDER BY name_en");
        $facilities = $this->db()->fetchAll("SELECT id, name_en FROM facilities WHERE is_active = 1 ORDER BY name_en");
        $this->view('tournaments/edit', [
            'title' => 'Edit: ' . $tournament['name_en'],
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.tournaments'), 'url' => '/sports/tournaments'], ['label' => lang('common.edit')]],
            'tournament' => $tournament, 'sports' => $sports, 'facilities' => $facilities,
        ]);
    }

    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',
            'status' => 'required|in:planned,registration,in_progress,completed,cancelled',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date',
            'max_participants' => 'nullable|integer',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $this->db()->update('sport_tournaments', $validator->validated(), 'id = ?', [$id]);
        $this->audit('update', 'sport_tournament', $id, 'Updated tournament');
        $this->json(['success' => true, 'message' => 'Tournament updated', 'redirect' => '/sports/tournaments/' . $id]);
    }

    public function register(Request $request): void
    {
        $tournamentId = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $memberId = $request->post('member_id') ? (int) $request->post('member_id') : null;
        $teamId = $request->post('team_id') ? (int) $request->post('team_id') : null;
        $this->db()->insert('sport_tournament_registrations', [
            'tournament_id' => $tournamentId, 'member_id' => $memberId, 'team_id' => $teamId,
            'registration_date' => date('Y-m-d'), 'status' => 'registered',
        ]);
        $this->db()->update('sport_tournaments', ['current_participants' => $this->db()->fetchColumn("SELECT COUNT(*) FROM sport_tournament_registrations WHERE tournament_id = ?", [$tournamentId])], 'id = ?', [$tournamentId]);
        $this->audit('create', 'sport_tournament_registration', null, "Registered for tournament #{$tournamentId}");
        $this->json(['success' => true, 'message' => 'Registration successful', 'redirect' => '/sports/tournaments/' . $tournamentId]);
    }
}