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

        // Foreign membership: spouse + 3 children included in the $10k fee — no extra charges
        if (($member['membership_type'] ?? 'working') === 'foreign' && $isOnInitialForm) {
            $totalChildren = Child::countActiveForMember($memberId);
            $childOrder = $totalChildren + 1;
            $childDob = $childData['date_of_birth'] ?? null;
            $childAge = $childDob ? age_from_dob($childDob)['years'] : 0;
            return [
                'child_order'           => $childOrder,
                'child_age'             => $childAge,
                'children_under_18'     => Child::countActiveUnder18ForMember($memberId),
                'membership_value'      => '0.00',
                'classification'        => 'included',
                'fee'                   => '0.00',
                'percentage'            => '0.00',
                'form_fee'              => '0.00',
                'annual_subscription'   => '0.00',
                'total_fee'             => '0.00',
                'rule_applied'          => 'العضوية الأجنبية — الأبناء مشمولون في رسوم العضوية',
                'error'                 => null,
                'breakdown'             => ['✅ مشمول/ة في رسوم العضوية الأجنبية — بدون رسوم إضافية'],
            ];
        }

        // Always use current membership value from pricing_configs
        $qualId = !empty($member['qualification_id']) ? (int) $member['qualification_id'] : null;
        $branchId = (int) ($member['branch_id'] ?? 1);
        $mType = $member['membership_type'] ?? 'working';
        if ($qualId) {
            $currentPricing = $db->selectOne(
                "SELECT price FROM pricing_configs WHERE branch_id = ? AND qualification_id = ? AND membership_type = ? AND is_active = 1 AND effective_from <= CURDATE() AND (effective_to IS NULL OR effective_to >= CURDATE()) ORDER BY effective_from DESC LIMIT 1",
                [$branchId, $qualId, $mType]
            );
        } else {
            $currentPricing = $db->selectOne(
                "SELECT price FROM pricing_configs WHERE branch_id = ? AND membership_type = ? AND is_active = 1 AND effective_from <= CURDATE() AND (effective_to IS NULL OR effective_to >= CURDATE()) ORDER BY price ASC LIMIT 1",
                [$branchId, $mType]
            );
        }
        if ($currentPricing && bccomp($currentPricing['price'], '0.01', 2) >= 0) {
            $membershipValue = $currentPricing['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) {
                $breakdown[] = '📅 اشتراك سنوي: ' . 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) {
                $breakdown[] = '📅 اشتراك سنوي: ' . 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,
        ];
    }
}
