<?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.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',
                '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'] ?? '';

        $formFee = FormFeeService::getFormFee($memberId, $member);
        $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($formFee, '0', 2) <= 0) {
            $breakdown[] = '✅ مشمول في قيمة العضوية — بدون رسوم إضافية';
        } elseif ($classification === 'included' && bccomp($formFee, '0', 2) > 0) {
            $breakdown[] = '✅ مشمول (بدون رسوم عضوية)';
            $breakdown[] = '📝 رسوم استمارة إضافة: ' . money($formFee);
        } else {
            if (bccomp($childFee, '0', 2) > 0) {
                $breakdown[] = '📊 نسبة ' . $percentage . '% × ' . money($membershipValue) . ' = ' . money($childFee);
            }
            if (bccomp($formFee, '0', 2) > 0) {
                $breakdown[] = '📝 رسوم استمارة إضافة: ' . money($formFee);
            }
        }
        $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'          => $formFee,
            'total_fee'         => $totalFee,
            'rule_applied'      => $ruleApplied,
            'error'             => null,
            'breakdown'         => $breakdown,
        ];
    }
}
