<?php

class TeamController extends Controller
{
    public function index(Request $request): void
    {
        $sports = $this->db()->fetchAll("SELECT id, name_en FROM sports WHERE is_active = 1 AND team_sport = 1 ORDER BY name_en");
        $this->view('teams/index', [
            'title' => lang('sports.teams'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.teams')]],
            '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");
        $coaches = $db->fetchAll("SELECT id, CONCAT(first_name_en,' ',last_name_en) as name FROM sport_coaches WHERE status = 'active' ORDER BY first_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('teams/create', [
            'title' => lang('sports.create_team'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.teams'), 'url' => '/sports/teams'], ['label' => lang('common.create')]],
            'sports' => $sports, 'coaches' => $coaches, '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(), [
            'team_code' => 'required|string|max:20|unique:sport_teams,team_code',
            'sport_id' => 'required|integer|exists:sports,id',
            'name_en' => 'required|string|max:200',
            'name_ar' => 'required|string|max:200',
            'team_type' => 'required|in:club,amateur,youth,senior,women,mixed',
            'coach_id' => 'nullable|integer',
            'season_id' => 'nullable|integer',
            'max_players' => 'nullable|integer',
            'color_primary' => 'nullable|string|max:7',
            'color_secondary' => 'nullable|string|max:7',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['status'] = 'active';
        $id = $this->db()->insert('sport_teams', $data);
        $this->audit('create', 'sport_team', $id, "Created team: {$data['name_en']}");
        $this->json(['success' => true, 'message' => 'Team created', 'redirect' => '/sports/teams/' . $id]);
    }

    public function show(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = $this->db();
        $team = $db->fetchOne(
            "SELECT t.*, sp.name_en as sport_name, CONCAT(co.first_name_en,' ',co.last_name_en) as coach_name, ss.name_en as season_name
             FROM sport_teams t LEFT JOIN sports sp ON t.sport_id = sp.id LEFT JOIN sport_coaches co ON t.coach_id = co.id LEFT JOIN sport_seasons ss ON t.season_id = ss.id
             WHERE t.id = ?", [$id]);
        if (!$team) { $this->abort(404); return; }

        $members = $db->fetchAll(
            "SELECT tm.*, m.full_name_en as member_name, m.membership_number, m.photo_path
             FROM sport_team_members tm LEFT JOIN members m ON tm.member_id = m.id
             WHERE tm.team_id = ? AND tm.status = 'active' ORDER BY tm.jersey_number", [$id]);

        $recentMatches = $db->fetchAll(
            "SELECT sm.*, ht.name_en as home_name, at.name_en as away_name
             FROM sport_matches sm LEFT JOIN sport_teams ht ON sm.home_team_id = ht.id LEFT JOIN sport_teams at ON sm.away_team_id = at.id
             WHERE (sm.home_team_id = ? OR sm.away_team_id = ?) ORDER BY sm.match_date DESC LIMIT 10", [$id, $id]);

        $this->view('teams/show', [
            'title' => $team['name_en'],
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.teams'), 'url' => '/sports/teams'], ['label' => $team['name_en']]],
            'team' => $team, 'members' => $members, 'recentMatches' => $recentMatches,
        ]);
    }

    public function edit(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = $this->db();
        $team = $db->fetchOne("SELECT * FROM sport_teams WHERE id = ?", [$id]);
        if (!$team) { $this->abort(404); return; }
        $sports = $db->fetchAll("SELECT id, name_en FROM sports WHERE is_active = 1 ORDER BY name_en");
        $coaches = $db->fetchAll("SELECT id, CONCAT(first_name_en,' ',last_name_en) as name FROM sport_coaches WHERE status = 'active' ORDER BY first_name_en");
        $this->view('teams/edit', [
            'title' => 'Edit: ' . $team['name_en'],
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.teams'), 'url' => '/sports/teams'], ['label' => lang('common.edit')]],
            'team' => $team, 'sports' => $sports, 'coaches' => $coaches,
        ]);
    }

    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:200',
            'name_ar' => 'required|string|max:200',
            'team_type' => 'required|in:club,amateur,youth,senior,women,mixed',
            'coach_id' => 'nullable|integer',
            'max_players' => 'nullable|integer',
            'status' => 'required|in:active,inactive,disbanded,suspended',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $this->db()->update('sport_teams', $validator->validated(), 'id = ?', [$id]);
        $this->audit('update', 'sport_team', $id, 'Updated team');
        $this->json(['success' => true, 'message' => 'Team updated', 'redirect' => '/sports/teams/' . $id]);
    }

    public function addMember(Request $request): void
    {
        $teamId = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $memberId = (int) $request->post('member_id');
        $this->db()->insert('sport_team_members', [
            'team_id' => $teamId, 'member_id' => $memberId,
            'jersey_number' => $request->post('jersey_number') ?: null,
            'position' => $request->post('position', ''),
            'role' => $request->post('role', 'player'),
            'joined_date' => date('Y-m-d'), 'status' => 'active',
        ]);
        $this->audit('create', 'sport_team_member', null, "Added member #{$memberId} to team #{$teamId}");
        $this->json(['success' => true, 'message' => 'Member added to team', 'redirect' => '/sports/teams/' . $teamId]);
    }

    public function removeMember(Request $request): void
    {
        $teamId = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $teamMemberId = (int) $request->post('team_member_id');
        $this->db()->update('sport_team_members', ['status' => 'left', 'left_date' => date('Y-m-d')], 'id = ? AND team_id = ?', [$teamMemberId, $teamId]);
        $this->audit('update', 'sport_team_member', $teamMemberId, "Removed from team #{$teamId}");
        $this->json(['success' => true, 'message' => 'Member removed from team', 'redirect' => '/sports/teams/' . $teamId]);
    }
}