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

final class ChildFeeCalculator
{
    /**
     * Calculate the fee and classification for adding a child.
     */
    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'];
        }

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

        // Count existing children under 18 to determine order
        $childrenUnder18 = Child::countActiveUnder18ForMember($memberId);
        $totalChildren = Child::countActiveForMember($memberId);
        $childOrder = $totalChildren + 1;

        // Use PricingEngine
        $feeResult = PricingEngine::calculateChildFee($membershipValue, $childAge, $childOrder);

        // Add form fee if post-creation
        $formFee = '0.00';
        if ($member['status'] !== 'potential') {
            $formFeeData = RuleEngine::get('FORM_ADDITION_FEE');
            $formFee = $formFeeData['amount'] ?? '570.00';
        }

        // Determine classification
        $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';

        return [
            'child_order'      => $childOrder,
            'child_age'        => $childAge,
            'children_under_18' => $childrenUnder18,
            '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,
        ];
    }
}