<?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;
use App\Modules\Members\Services\MembershipRulesService;
use App\Modules\Cashier\Services\PaymentRequestService;

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]);

        $membershipValue = $member['membership_value'] ?? '0.00';
        if (bccomp($membershipValue, '0.01', 2) < 0 && !empty($member['branch_id'])) {
            if (!empty($member['qualification_id'])) {
                $pricing = $db->selectOne(
                    "SELECT price FROM pricing_configs WHERE branch_id = ? AND qualification_id = ? AND membership_type = 'working' AND is_active = 1 AND effective_from <= CURDATE() AND (effective_to IS NULL OR effective_to >= CURDATE()) ORDER BY effective_from DESC LIMIT 1",
                    [(int) $member['branch_id'], (int) $member['qualification_id']]
                );
            } else {
                $pricing = $db->selectOne(
                    "SELECT price FROM pricing_configs WHERE branch_id = ? AND membership_type = 'working' AND is_active = 1 AND effective_from <= CURDATE() AND (effective_to IS NULL OR effective_to >= CURDATE()) ORDER BY price DESC LIMIT 1",
                    [(int) $member['branch_id']]
                );
            }
            if ($pricing && bccomp($pricing['price'], '0.01', 2) >= 0) {
                $membershipValue = $pricing['price'];
            }
        }

        $conversionRules = MembershipRulesService::getAthleticMemberConversionRules();
        $pct = $conversionRules['conversion_percentage'] ?? '50';
        $sportsFee = bcdiv(bcmul($membershipValue, $pct, 4), '100', 2);

        if (bccomp($sportsFee, '0.01', 2) >= 0) {
            $breakdown = [
                '🏅 رسوم عضوية رياضية',
                'قيمة العضوية الأساسية: ' . number_format((float) $membershipValue, 2) . ' ج.م',
                'نسبة التحويل: ' . $pct . '%',
                '═══════════════════════════',
                '💵 رسوم العضوية الرياضية: ' . number_format((float) $sportsFee, 2) . ' ج.م',
            ];

            PaymentRequestService::createRequest([
                'member_id'           => (int) $memberId,
                'amount'              => $sportsFee,
                'payment_type'        => 'sports_membership_fee',
                'related_entity_type' => 'members',
                'related_entity_id'   => (int) $memberId,
                'description_ar'      => 'رسوم عضوية رياضية — استمارة ' . ($member['form_number'] ?? ''),
                'notes'               => json_encode(['fee_breakdown' => $breakdown], JSON_UNESCAPED_UNICODE),
            ]);

            return $this->redirect("/members/{$memberId}")->withSuccess(
                'تم تسجيل العضوية الرياضية — الرسوم: ' . money($sportsFee) . ' — تم إرسالها للخزينة'
            );
        }

        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);
    }
}