<?php

class SportController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();
        $categories = $db->fetchAll("SELECT * FROM sport_categories WHERE is_active = 1 ORDER BY sort_order");
        $sports = $db->fetchAll(
            "SELECT s.*, sc.name_en as category_name, sc.color_hex,
                    (SELECT COUNT(*) FROM sport_classes cl WHERE cl.sport_id = s.id AND cl.status IN ('active','enrollment_open')) as active_classes,
                    (SELECT COUNT(*) FROM sport_teams t WHERE t.sport_id = s.id AND t.status = 'active') as active_teams
             FROM sports s LEFT JOIN sport_categories sc ON s.category_id = sc.id
             WHERE s.is_active = 1 ORDER BY s.sort_order");

        $this->view('sports/index', [
            'title' => lang('sports.title'),
            'breadcrumbs' => [['label' => lang('sports.title')]],
            'categories' => $categories,
            'sports' => $sports,
        ]);
    }

    public function create(Request $request): void
    {
        $categories = $this->db()->fetchAll("SELECT * FROM sport_categories WHERE is_active = 1 ORDER BY sort_order");
        $this->view('sports/create', [
            'title' => lang('sports.create'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('common.create')]],
            'categories' => $categories,
        ]);
    }

    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(), [
            'sport_code' => 'required|string|max:20|unique:sports,sport_code',
            'category_id' => 'required|integer|exists:sport_categories,id',
            'name_en' => 'required|string|max:200',
            'name_ar' => 'required|string|max:200',
            'description_en' => 'nullable|string',
            'description_ar' => 'nullable|string',
            'team_sport' => 'nullable|boolean',
            'min_players' => 'nullable|integer',
            'max_players' => 'nullable|integer',
            'gender_restriction' => 'required|in:male,female,both,mixed',
            'requires_medical_clearance' => 'nullable|boolean',
            'sort_order' => 'nullable|integer',
        ]);

        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }

        $data = $validator->validated();
        $data['team_sport'] = !empty($data['team_sport']) ? 1 : 0;
        $data['requires_medical_clearance'] = !empty($data['requires_medical_clearance']) ? 1 : 0;
        $data['is_active'] = 1;
        $data['sort_order'] = $data['sort_order'] ?? 0;

        $id = $this->db()->insert('sports', $data);
        $this->audit('create', 'sport', $id, "Created sport: {$data['name_en']}");
        $this->json(['success' => true, 'message' => 'Sport created successfully', 'redirect' => '/sports']);
    }

    public function show(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = $this->db();
        $sport = $db->fetchOne("SELECT s.*, sc.name_en as category_name FROM sports s LEFT JOIN sport_categories sc ON s.category_id = sc.id WHERE s.id = ?", [$id]);
        if (!$sport) { $this->abort(404); return; }

        $classes = $db->fetchAll("SELECT cl.*, CONCAT(co.first_name_en,' ',co.last_name_en) as coach_name FROM sport_classes cl LEFT JOIN sport_coaches co ON cl.coach_id = co.id WHERE cl.sport_id = ? AND cl.is_active = 1 ORDER BY cl.name_en", [$id]);
        $teams = $db->fetchAll("SELECT * FROM sport_teams WHERE sport_id = ? AND status = 'active' ORDER BY name_en", [$id]);
        $rules = $db->fetchAll("SELECT * FROM sport_rules WHERE sport_id = ? AND is_active = 1 ORDER BY sort_order", [$id]);
        $seasons = $db->fetchAll("SELECT * FROM sport_seasons WHERE sport_id = ? ORDER BY start_date DESC LIMIT 5", [$id]);

        $this->view('sports/show', [
            'title' => $sport['name_en'],
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => $sport['name_en']]],
            'sport' => $sport, 'classes' => $classes, 'teams' => $teams, 'rules' => $rules, 'seasons' => $seasons,
        ]);
    }

    public function edit(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $sport = $this->db()->fetchOne("SELECT * FROM sports WHERE id = ?", [$id]);
        if (!$sport) { $this->abort(404); return; }
        $categories = $this->db()->fetchAll("SELECT * FROM sport_categories WHERE is_active = 1 ORDER BY sort_order");

        $this->view('sports/edit', [
            'title' => 'Edit: ' . $sport['name_en'],
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('common.edit')]],
            'sport' => $sport, 'categories' => $categories,
        ]);
    }

    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(), [
            'category_id' => 'required|integer|exists:sport_categories,id',
            'name_en' => 'required|string|max:200',
            'name_ar' => 'required|string|max:200',
            'description_en' => 'nullable|string',
            'description_ar' => 'nullable|string',
            'team_sport' => 'nullable|boolean',
            'min_players' => 'nullable|integer',
            'max_players' => 'nullable|integer',
            'gender_restriction' => 'required|in:male,female,both,mixed',
            'requires_medical_clearance' => 'nullable|boolean',
            'is_active' => 'nullable|boolean',
            'sort_order' => 'nullable|integer',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }

        $old = $this->db()->fetchOne("SELECT * FROM sports WHERE id = ?", [$id]);
        $data = $validator->validated();
        $data['team_sport'] = !empty($data['team_sport']) ? 1 : 0;
        $data['requires_medical_clearance'] = !empty($data['requires_medical_clearance']) ? 1 : 0;
        $data['is_active'] = !empty($data['is_active']) ? 1 : 0;

        $this->db()->update('sports', $data, 'id = ?', [$id]);
        $this->audit('update', 'sport', $id, "Updated sport: {$data['name_en']}", $old, $data);
        $this->json(['success' => true, 'message' => 'Sport updated successfully', 'redirect' => '/sports']);
    }

    public function destroy(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $this->db()->update('sports', ['is_active' => 0], 'id = ?', [$id]);
        $this->audit('delete', 'sport', $id, 'Deactivated sport');
        $this->json(['success' => true, 'message' => 'Sport deactivated']);
    }

    public function categories(Request $request): void
    {
        $categories = $this->db()->fetchAll("SELECT * FROM sport_categories ORDER BY sort_order");
        $this->view('categories/index', [
            'title' => lang('sports.categories'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.categories')]],
            'categories' => $categories,
        ]);
    }

    public function storeCategory(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $validator = new Validator($request->all(), [
            'category_code' => 'required|string|max:20|unique:sport_categories,category_code',
            'name_en' => 'required|string|max:200',
            'name_ar' => 'required|string|max:200',
            'sort_order' => 'nullable|integer',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['is_active'] = 1;
        $id = $this->db()->insert('sport_categories', $data);
        $this->audit('create', 'sport_category', $id, "Created category: {$data['name_en']}");
        $this->json(['success' => true, 'message' => 'Category created', 'redirect' => '/sports/categories']);
    }

    public function updateCategory(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',
            'sort_order' => 'nullable|integer',
            'is_active' => 'nullable|boolean',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['is_active'] = !empty($data['is_active']) ? 1 : 0;
        $this->db()->update('sport_categories', $data, 'id = ?', [$id]);
        $this->audit('update', 'sport_category', $id, "Updated category: {$data['name_en']}");
        $this->json(['success' => true, 'message' => 'Category updated', 'redirect' => '/sports/categories']);
    }
}