<?php
declare(strict_types=1);

namespace App\Modules\Sports\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\EventBus;
use App\Modules\Sports\Models\SportsMember;
use App\Modules\Sports\Services\SportsConversionCalculator;

class SportsController extends Controller
{
    public function index(Request $request): Response
    {
        $rows = SportsMember::getAllActive();
        return $this->view('Sports.Views.index', ['rows' => $rows]);
    }

    public function create(Request $request, string $memberId): Response
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [(int) $memberId]);
        if (!$member) return $this->redirect('/members')->withError('العضو غير موجود');
        if (($member['membership_type'] ?? 'working') !== 'sports') {
            return $this->redirect("/members/{$memberId}")->withError('هذا العضو ليس عضواً رياضياً');
        }

        $existing = SportsMember::getForMember((int) $memberId);
        if ($existing) return $this->redirect("/members/{$memberId}")->withError('العضو لديه سجل رياضي بالفعل');

        $disciplines = $db->select(
            "SELECT id, name_ar FROM sport_disciplines WHERE is_active = 1 ORDER BY sort_order, name_ar"
        );

        return $this->view('Sports.Views.create', ['member' => $member, 'disciplines' => $disciplines]);
    }

    public function store(Request $request, string $memberId): Response
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [(int) $memberId]);
        if (!$member) return $this->redirect('/members')->withError('العضو غير موجود');
        if (($member['membership_type'] ?? 'working') !== 'sports') {
            return $this->redirect("/members/{$memberId}")->withError('هذا العضو ليس عضواً رياضياً');
        }

        $data = $request->all();
        unset($data['_csrf_token']);

        $errors = [];
        if (empty(trim($data['sport_name'] ?? ''))) $errors[] = 'اسم الرياضة مطلوب';
        if (empty($data['years_of_service'] ?? '')) $errors[] = 'عدد سنوات الخدمة مطلوب';

        if (!empty($errors)) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', array_map(fn($e) => ['type' => 'error', 'message' => $e], $errors));
            $session->flash('_old_input', $data);
            return $this->redirect("/members/{$memberId}/sports/create");
        }

        $yearsOfService = (int) ($data['years_of_service'] ?? 0);
        $minYearsData = \App\Modules\Rules\Services\RuleEngine::get('SPORTS_MIN_YEARS');
        $minYears = $minYearsData['years'] ?? 8;

        $sports = SportsMember::create([
            'member_id'                 => (int) $memberId,
            'sport_name'                => trim($data['sport_name']),
            'federation_name'           => trim($data['federation_name'] ?? ''),
            'federation_registration'   => trim($data['federation_registration'] ?? ''),
            'registration_date'         => $data['registration_date'] ?: null,
            'years_of_service'          => $yearsOfService,
            'highest_competitive_level' => trim($data['highest_competitive_level'] ?? ''),
            'is_conversion_eligible'    => $yearsOfService >= $minYears ? 1 : 0,
            'status'                    => 'active',
            'notes'                     => $data['notes'] ?? null,
        ]);

        EventBus::dispatch('sports.registered', ['member_id' => (int) $memberId, 'sports_id' => (int) $sports->id]);

        return $this->redirect("/members/{$memberId}")->withSuccess('تم تسجيل العضوية الرياضية' . ($yearsOfService >= $minYears ? ' — مؤهل للتحويل لعضو عامل' : ''));
    }

    public function checkConversion(Request $request, string $memberId): Response
    {
        $result = SportsConversionCalculator::checkEligibility((int) $memberId);
        return $this->json($result);
    }
}