<?php
declare(strict_types=1);

namespace App\Modules\Sports\Services;

use App\Core\App;
use App\Modules\Rules\Services\RuleEngine;
use App\Modules\Pricing\Services\PricingEngine;

final class SportsConversionCalculator
{
    public static function checkEligibility(int $memberId): array
    {
        $db = App::getInstance()->db();
        $sports = $db->selectOne("SELECT * FROM sports_members WHERE member_id = ? AND is_archived = 0", [$memberId]);
        if (!$sports) {
            return ['eligible' => false, 'error' => 'لا يوجد سجل رياضي'];
        }

        $minYearsData = RuleEngine::get('SPORTS_MIN_YEARS');
        $minYears = $minYearsData['years'] ?? 8;

        if ((int) $sports['years_of_service'] < $minYears) {
            return [
                'eligible'   => false,
                'years'      => (int) $sports['years_of_service'],
                'min_years'  => $minYears,
                'remaining'  => $minYears - (int) $sports['years_of_service'],
                'error'      => "الحد الأدنى {$minYears} سنوات خدمة. لديك " . $sports['years_of_service'] . " سنوات",
            ];
        }

        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [$memberId]);
        if (!$member) {
            return ['eligible' => false, 'error' => 'العضو غير موجود'];
        }

        $qualCode = 'high';
        if ($member['qualification_id']) {
            $qual = $db->selectOne("SELECT code FROM qualifications WHERE id = ?", [(int) $member['qualification_id']]);
            $qualCode = $qual['code'] ?? 'high';
        }

        $priceInfo = PricingEngine::getMembershipPrice((int) $member['branch_id'], $qualCode);
        $newValue = $priceInfo['price'] ?? '0.00';

        $feeData = RuleEngine::get('SPORTS_CONVERSION_FEE');
        $pct = $feeData['percentage'] ?? '50.00';
        $fee = bcmul($newValue, bcdiv($pct, '100', 4), 2);

        return [
            'eligible'          => true,
            'years'             => (int) $sports['years_of_service'],
            'min_years'         => $minYears,
            'new_membership_value' => $newValue,
            'fee_percentage'    => $pct,
            'conversion_fee'    => $fee,
            'error'             => null,
        ];
    }
}