<?php

class SportMembershipController extends Controller
{
    public function index(Request $request): void
    {
        $sports = $this->db()->fetchAll("SELECT id, name_en FROM sports WHERE is_active = 1 ORDER BY name_en");
        $this->view('memberships/index', [
            'title' => lang('sports.sport_memberships'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.sport_memberships')]],
            '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',
            'membership_level' => 'required|in:basic,standard,premium,elite',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date',
            'fee_amount' => 'nullable|decimal',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['status'] = 'active';
        $data['fee_amount'] = $data['fee_amount'] ?? 0;
        $id = $this->db()->insert('sport_memberships', $data);
        $this->audit('create', 'sport_membership', $id, 'Created sport membership');
        $this->json(['success' => true, 'message' => 'Sport membership created', 'redirect' => '/sports/memberships']);
    }
}