<?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';
        if (bccomp($membershipValue, '0.00', 2) <= 0) {
            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;

        $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';

        $formFee = FormFeeService::getFormFee($memberId, $member);

        return [
            'child_order'       => $childOrder,
            'child_age'         => $childAge,
            'children_under_18' => Child::countActiveUnder18ForMember($memberId),
            'membership_value'  => $membershipValue,
            'classification'    => $classification,
            'fee'               => $childFee,
            'percentage'        => $feeResult['percentage'] ?? '0.00',
            'form_fee'          => $formFee,
            'total_fee'         => bcadd($childFee, $formFee, 2),
            'rule_applied'      => $feeResult['rule_applied'] ?? '',
            'error'             => null,
        ];
    }
}
