<?php
declare(strict_types=1);

namespace App\Modules\Transfers\Services;

use App\Core\App;
use App\Modules\Rules\Services\RuleEngine;
use App\Modules\Pricing\Services\PricingEngine;
use App\Modules\ServiceCatalog\Models\ServicePrice;

final class SeparationFeeCalculator
{
    /**
     * Calculate separation/transfer fee based on years since acquisition.
     */
    public static function calculate(int $sourceMemberId, ?int $childId = null, ?string $qualificationCode = null): array
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ?", [$sourceMemberId]);
        if (!$member) {
            return ['error' => 'العضو غير موجود', 'success' => false];
        }

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

        // Get new membership value at current date
        $branchId = (int) $member['branch_id'];
        $priceInfo = PricingEngine::getMembershipPrice($branchId, $qualificationCode ?? 'high');
        $newMembershipValue = $priceInfo['price'] ?? '0.00';

        // Calculate years since acquisition
        $acquisitionDate = $member['created_at'] ?? $member['form_date'] ?? date('Y-m-d');
        $yearsSince = self::calculateYearsSince($acquisitionDate);

        // Get fee percentage based on years
        $feePercentage = self::getFeePercentageByYear($yearsSince);

        // Calculate separation fee
        $separationFee = bcdiv(bcmul($newMembershipValue, (string) $feePercentage, 4), '100', 2);

        // Form fee
        $formFeeData = RuleEngine::get('FORM_TRANSFER_FEE');
        $formFee = $formFeeData['amount'] ?? '570.00';

        // Annual subscription (basic member subscription)
        $annualSub = ServicePrice::getPrice('SVC_ANNUAL_MEMBER', '492.00');
        $devFeeData = RuleEngine::get('DEVELOPMENT_FEE');
        $devFee = $devFeeData['amount'] ?? '35.00';
        $annualSubscriptionFee = bcadd($annualSub, $devFee, 2);

        $totalFee = bcadd(bcadd($separationFee, $formFee, 2), $annualSubscriptionFee, 2);

        return [
            'success'                => true,
            'source_member_id'       => $sourceMemberId,
            'child_id'               => $childId,
            'qualification_code'     => $qualificationCode,
            'new_membership_value'   => $newMembershipValue,
            'years_since_acquisition'=> $yearsSince,
            'fee_percentage'         => $feePercentage,
            'separation_fee'         => $separationFee,
            'form_fee'               => $formFee,
            'annual_subscription_fee'=> $annualSubscriptionFee,
            'total_fee'              => $totalFee,
            'acquisition_date'       => $acquisitionDate,
        ];
    }

    public static function calculateYearsSince(string $date): int
    {
        $then = new \DateTime(substr($date, 0, 10));
        $now = new \DateTime();
        $diff = $now->diff($then);
        return max(1, $diff->y + ($diff->m > 0 || $diff->d > 0 ? 1 : 0)); // partial year rounds up
    }

    public static function getFeePercentageByYear(int $year): string
    {
        if ($year <= 1) {
            $data = RuleEngine::get('SEPARATION_FEE_YEAR_1');
            return $data['percentage'] ?? '30.00';
        }
        if ($year === 2) {
            $data = RuleEngine::get('SEPARATION_FEE_YEAR_2');
            return $data['percentage'] ?? '20.00';
        }
        if ($year === 3) {
            $data = RuleEngine::get('SEPARATION_FEE_YEAR_3');
            return $data['percentage'] ?? '15.00';
        }
        if ($year === 4) {
            $data = RuleEngine::get('SEPARATION_FEE_YEAR_4');
            return $data['percentage'] ?? '10.00';
        }
        if ($year === 5) {
            $data = RuleEngine::get('SEPARATION_FEE_YEAR_5');
            return $data['percentage'] ?? '5.00';
        }
        $data = RuleEngine::get('SEPARATION_FEE_YEAR_6_PLUS');
        return $data['percentage'] ?? '2.50';
    }
}