<?php
declare(strict_types=1);

namespace App\Modules\Divorce\Services;

use App\Core\App;
use App\Modules\Rules\Services\RuleEngine;
use App\Modules\ServiceCatalog\Models\ServicePrice;

final class DivorceFeeCalculator
{
    public static function getFormFee(): string
    {
        $feeData = RuleEngine::get('FORM_TRANSFER_FEE');
        if ($feeData && isset($feeData['amount'])) {
            return $feeData['amount'];
        }
        return ServicePrice::getPrice('SVC_ADDITION_FORM', '570.00');
    }

    public static function getAnnualSubscription(): string
    {
        $month = (int) date('n');
        $year = (int) date('Y');
        $fy = $month >= 7 ? $year . '/' . ($year + 1) : ($year - 1) . '/' . $year;

        $ratesData = RuleEngine::get('membership.annual_rates.' . $fy);
        $childRate = $ratesData['child'] ?? '222';
        $devFee = $ratesData['dev'] ?? '35';

        return bcadd($childRate, $devFee, 2);
    }

    /**
     * Validate eligibility and determine case type (without calculating final fee —
     * the board sets the percentage).
     */
    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
        $caseType = 'joined_after';
        $memberCreatedDate = substr($memberCreated, 0, 10);
        $spouseJoinDateStr = substr($spouseJoinDate, 0, 10);

        if ($memberCreatedDate === $spouseJoinDateStr) {
            $caseType = 'same_form';
        }

        return [
            'success'              => true,
            'case_type'            => $caseType,
            'membership_value'     => $membershipValue,
            'years_of_membership'  => $yearsMembership,
            'has_children'         => $hasChildren,
            'child_count'          => $childCount,
        ];
    }
}