<?php

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

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

    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(), [
            'member_id' => 'required|integer|exists:members,id',
            'sport_id' => 'required|integer|exists:sports,id',
            'achievement_type' => 'required|in:medal,trophy,certificate,record,award,ranking,other',
            'title_en' => 'required|string|max:300',
            'title_ar' => 'nullable|string|max:300',
            'description' => 'nullable|string',
            'achievement_date' => 'required|date',
            'competition_name' => 'nullable|string|max:300',
            'position' => 'nullable|integer',
            'medal_type' => 'nullable|in:gold,silver,bronze',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['verified'] = 0;
        $id = $this->db()->insert('sport_member_achievements', $data);
        $this->audit('create', 'sport_member_achievement', $id, "Created achievement: {$data['title_en']}");
        $this->json(['success' => true, 'message' => 'Achievement recorded', 'redirect' => '/sports/achievements']);
    }
}