<?php
declare(strict_types=1);

namespace App\Modules\Children\Services;

use App\Core\App;
use App\Modules\Children\Models\Child;
use App\Modules\Pricing\Services\PricingEngine;
use App\Modules\Rules\Services\RuleEngine;
use App\Modules\Members\Services\FormFeeService;

final class ChildFeeCalculator
{
    public static function calculate(int $memberId, array $childData): array
    {
        $db = App::getInstance()->db();

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

        $membershipValue = $member['membership_value'] ?? '0.00';
        $isOnInitialForm = FormFeeService::isOnInitialForm($member);

        if (bccomp($membershipValue, '0.01', 2) < 0 && !empty($member['qualification_id']) && !empty($member['branch_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']]
            );
            if ($pricing && bccomp($pricing['price'], '0.01', 2) >= 0) {
                $membershipValue = $pricing['price'];
            }
        }

        if (bccomp($membershipValue, '0.00', 2) <= 0 && !$isOnInitialForm) {
            return ['error' => 'قيمة العضوية غير محددة', 'fee' => '0.00', 'classification' => 'included'];
        }

        $childDob = $childData['date_of_birth'] ?? null;
        $childAge = 0;
        if ($childDob) {
            $age = age_from_dob($childDob);
            $childAge = $age['years'];
        }

        $totalChildren = Child::countActiveForMember($memberId);
        $childOrder = $totalChildren + 1;

        $relationship = $childData['relationship'] ?? '';

        // Stepchildren (ابناء الزوجة/الزوج) always cost 10% — never counted as free
        if ($relationship === 'stepchild') {
            $stepData = RuleEngine::require('STEPCHILD_FEE');
            $stepPct = $stepData['percentage'];
            $stepFee = bcmul($membershipValue, bcdiv($stepPct, '100', 4), 2);
            $feeResult = [
                'fee' => $stepFee,
                'rule_applied' => 'STEPCHILD_FEE',
                'percentage' => $stepPct,
                'classification' => 'dependent_with_fee',
            ];
        } else {
            $feeResult = PricingEngine::calculateChildFee($membershipValue, $childAge, $childOrder);
        }

        $classification = $feeResult['classification'] ?? 'included';
        if ($classification === 'not_accepted') {
            return [
                'child_order'          => $childOrder,
                'child_age'            => $childAge,
                'membership_value'     => $membershipValue,
                'classification'       => 'not_accepted',
                'fee'                  => '0.00',
                'percentage'           => '0.00',
                'form_fee'             => '0.00',
                'annual_subscription'  => '0.00',
                'total_fee'            => '0.00',
                'rule_applied'         => $feeResult['rule_applied'] ?? '',
                'error'                => $feeResult['error'] ?? 'سن الابن/الابنة يتجاوز الحد المسموح',
            ];
        }

        $childFee = $feeResult['fee'] ?? '0.00';
        $percentage = $feeResult['percentage'] ?? '0.00';
        $ruleApplied = $feeResult['rule_applied'] ?? '';

        $formFeeOnly = FormFeeService::getFormFeeOnly($memberId, $member);
        $annualSubscription = !FormFeeService::isOnInitialForm($member)
            ? FormFeeService::getAnnualSubscriptionForAddition()
            : '0.00';
        $formFee = bcadd($formFeeOnly, $annualSubscription, 2);
        $totalFee = bcadd($childFee, $formFee, 2);

        $classLabels = [
            'included' => 'مشمول (بدون رسوم)',
            'dependent_with_fee' => 'تابع (برسوم)',
            'temporary' => 'مؤقت',
        ];

        $breakdown = [];
        $breakdown[] = '📋 القاعدة المطبقة: ' . ($ruleApplied ?: 'تلقائي');
        $breakdown[] = '💰 قيمة العضوية: ' . money($membershipValue);
        $breakdown[] = '👶 الترتيب: #' . $childOrder . ' — السن: ' . $childAge . ' سنة';
        $breakdown[] = '📌 التصنيف: ' . ($classLabels[$classification] ?? $classification);

        if ($classification === 'included' && bccomp($formFeeOnly, '0', 2) <= 0 && bccomp($annualSubscription, '0', 2) <= 0) {
            $breakdown[] = '✅ مشمول في قيمة العضوية — بدون رسوم إضافية';
        } elseif ($classification === 'included') {
            $breakdown[] = '✅ مشمول (بدون رسوم عضوية)';
            if (bccomp($formFeeOnly, '0', 2) > 0) {
                $breakdown[] = '📝 رسوم استمارة إضافة: ' . money($formFeeOnly);
            }
            if (bccomp($annualSubscription, '0', 2) > 0) {
                $devFee = RuleEngine::get('DEVELOPMENT_FEE')['amount'] ?? '35.00';
                $breakdown[] = '📅 اشتراك سنوي: ' . money(bcsub($annualSubscription, $devFee, 2)) . ' + تنمية: ' . money($devFee) . ' = ' . money($annualSubscription);
            }
        } else {
            if (bccomp($childFee, '0', 2) > 0) {
                $breakdown[] = '📊 نسبة ' . $percentage . '% × ' . money($membershipValue) . ' = ' . money($childFee);
            }
            if (bccomp($formFeeOnly, '0', 2) > 0) {
                $breakdown[] = '📝 رسوم استمارة إضافة: ' . money($formFeeOnly);
            }
            if (bccomp($annualSubscription, '0', 2) > 0) {
                $devFee = RuleEngine::get('DEVELOPMENT_FEE')['amount'] ?? '35.00';
                $breakdown[] = '📅 اشتراك سنوي: ' . money(bcsub($annualSubscription, $devFee, 2)) . ' + تنمية: ' . money($devFee) . ' = ' . money($annualSubscription);
            }
        }
        $breakdown[] = '═══════════════════════════';
        $breakdown[] = '💵 الإجمالي المطلوب: ' . money($totalFee);

        return [
            'child_order'           => $childOrder,
            'child_age'             => $childAge,
            'children_under_18'     => Child::countActiveUnder18ForMember($memberId),
            'membership_value'      => $membershipValue,
            'classification'        => $classification,
            'fee'                   => $childFee,
            'percentage'            => $percentage,
            'form_fee'              => $formFeeOnly,
            'annual_subscription'   => $annualSubscription,
            'total_fee'             => $totalFee,
            'rule_applied'          => $ruleApplied,
            'error'                 => null,
            'breakdown'             => $breakdown,
        ];
    }
}
