<?php
declare(strict_types=1);

namespace App\Modules\Divorce\Services;

use App\Core\App;
use App\Modules\Rules\Services\RuleEngine;

final class DivorceFeeCalculator
{
    /**
     * Determine divorce case type and calculate fee.
     */
    public static function calculate(int $memberId, int $spouseId, string $divorceDate): array
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ?", [$memberId]);
        $spouse = $db->selectOne("SELECT * FROM spouses WHERE id = ?", [$spouseId]);

        if (!$member || !$spouse) {
            return ['success' => false, 'error' => 'بيانات العضو أو الزوج غير موجودة'];
        }

        // Check 1-year window from divorce date
        $divorceTs = strtotime($divorceDate);
        $windowData = RuleEngine::get('DIVORCE_REQUEST_WINDOW');
        $maxYears = $windowData['max_years'] ?? 1;
        $deadline = strtotime("+{$maxYears} years", $divorceTs);
        if (time() > $deadline) {
            return ['success' => false, 'error' => "انتهت مهلة تقديم الطلب ({$maxYears} سنة من تاريخ الطلاق)"];
        }

        // Determine case type
        $memberCreated = $member['created_at'] ?? $member['form_date'];
        $spouseJoinDate = $spouse['join_date'] ?? $spouse['created_at'];
        $membershipValue = $member['membership_value'] ?? '0.00';

        // Check children
        $childCount = (int) ($db->selectOne(
            "SELECT COUNT(*) as cnt FROM children WHERE member_id = ? AND is_archived = 0",
            [$memberId]
        )['cnt'] ?? 0);
        $hasChildren = $childCount > 0;

        // Check 5-year minimum (waived if children)
        $minYearsData = RuleEngine::get('DIVORCE_MIN_MEMBERSHIP_YEARS');
        $minYears = $minYearsData['min_years'] ?? 5;
        $waivedIfChildren = $minYearsData['waived_if_children'] ?? true;

        $yearsMembership = (int) ((time() - strtotime($memberCreated)) / (365.25 * 86400));
        if ($yearsMembership < $minYears && !($waivedIfChildren && $hasChildren)) {
            return ['success' => false, 'error' => "الحد الأدنى لسنوات العضوية {$minYears} سنوات (يُعفى في حالة وجود أبناء)"];
        }

        // Determine case type and fee
        $caseType = 'joined_after'; // default: most common
        $feePercentage = '50.00';
        $feeType = 'acquired_member';

        // Case 1: Both working before marriage
        // Simplified detection: if spouse join_date == member creation date (same form)
        $memberCreatedDate = substr($memberCreated, 0, 10);
        $spouseJoinDateStr = substr($spouseJoinDate, 0, 10);

        if ($memberCreatedDate === $spouseJoinDateStr) {
            // Could be Case 2: same form
            $sameFormData = RuleEngine::get('DIVORCE_SAME_FORM_FEE');
            $caseType = 'same_form';
            $feePercentage = $sameFormData['percentage'] ?? '10.00';
            $feeType = $sameFormData['treat_as'] ?? 'membership_basis';
        } else {
            // Case 3: joined after
            $joinedAfterData = RuleEngine::get('DIVORCE_JOINED_AFTER_FEE');
            $caseType = 'joined_after';
            $feePercentage = $joinedAfterData['percentage'] ?? '50.00';
            $feeType = $joinedAfterData['treat_as'] ?? 'acquired_member';
        }

        $feeAmount = bcdiv(bcmul($membershipValue, $feePercentage, 4), '100', 2);

        // Form fee
        $formFeeData = RuleEngine::get('FORM_TRANSFER_FEE');
        $formFee = $formFeeData['amount'] ?? '570.00';

        $totalFee = bcadd($feeAmount, $formFee, 2);

        return [
            'success'              => true,
            'case_type'            => $caseType,
            'fee_type'             => $feeType,
            'fee_percentage'       => $feePercentage,
            'fee_amount'           => $feeAmount,
            'form_fee'             => $formFee,
            'total_fee'            => $totalFee,
            'membership_value'     => $membershipValue,
            'years_of_membership'  => $yearsMembership,
            'has_children'         => $hasChildren,
            'child_count'          => $childCount,
        ];
    }
}