<?php
declare(strict_types=1);

namespace App\Modules\Transfers\Services;

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

final class TransferEligibility
{
    public static function canChildSeparate(int $childId): array
    {
        $db = App::getInstance()->db();
        $child = $db->selectOne("SELECT * FROM children WHERE id = ? AND is_archived = 0", [$childId]);
        if (!$child) {
            return ['eligible' => false, 'reason' => 'لم يتم العثور على بيانات الابن/الابنة'];
        }

        $age = self::calculateAge($child['date_of_birth']);
        $gender = $child['gender'];

        if ($gender === 'female') {
            return ['eligible' => true, 'reason' => 'البنات: يتم الفصل عند الزواج', 'condition' => 'marriage'];
        }

        $maxAge = 25;
        $ruleData = RuleEngine::get('MALE_CHILD_FREEZE_AGE');
        if ($ruleData) {
            $maxAge = (int) ($ruleData['value'] ?? 25);
        }

        if ($age >= $maxAge) {
            return ['eligible' => true, 'reason' => 'بلوغ سن ' . $maxAge . ' عام', 'condition' => 'age'];
        }

        return [
            'eligible' => true,
            'reason' => 'الأبناء: التخرج من الجامعة ويعمل بأجر أو بلوغ 25 عام إيهما اسبق',
            'condition' => 'graduation_or_age',
            'requires_verification' => true,
        ];
    }

    public static function canSpouseSeparateDivorce(int $spouseId, ?string $divorceDate = null): array
    {
        $db = App::getInstance()->db();
        $spouse = $db->selectOne("SELECT * FROM spouses WHERE id = ? AND is_archived = 0", [$spouseId]);
        if (!$spouse) {
            return ['eligible' => false, 'reason' => 'لم يتم العثور على بيانات الزوج/الزوجة'];
        }

        $member = $db->selectOne("SELECT * FROM members WHERE id = ?", [(int) $spouse['member_id']]);
        if (!$member) {
            return ['eligible' => false, 'reason' => 'العضو الأساسي غير موجود'];
        }

        $divorceWindowData = RuleEngine::get('DIVORCE_REQUEST_WINDOW');
        $maxYears = (int) ($divorceWindowData['max_years'] ?? 1);

        if ($divorceDate) {
            $divorceDateTime = new \DateTime($divorceDate);
            $now = new \DateTime();
            $diff = $now->diff($divorceDateTime);
            if ($diff->y >= $maxYears) {
                return ['eligible' => false, 'reason' => 'مر أكثر من ' . $maxYears . ' عام على تاريخ الطلاق'];
            }
        }

        $minYearsData = RuleEngine::get('DIVORCE_MIN_MEMBERSHIP_YEARS');
        $minYears = (int) ($minYearsData['min_years'] ?? 5);
        $waivedIfChildren = (bool) ($minYearsData['waived_if_children'] ?? true);

        $membershipDate = $spouse['join_date'] ?? $spouse['marriage_date'] ?? $member['created_at'];
        $membershipYears = self::calculateAge($membershipDate);

        if ($membershipYears < $minYears) {
            if ($waivedIfChildren) {
                $childCount = (int) ($db->selectOne(
                    "SELECT COUNT(*) as cnt FROM children WHERE member_id = ? AND is_archived = 0",
                    [(int) $spouse['member_id']]
                )['cnt'] ?? 0);

                if ($childCount === 0) {
                    return [
                        'eligible' => false,
                        'reason' => 'لم تمر ' . $minYears . ' سنوات على اكتساب العضوية ولا يوجد أبناء',
                    ];
                }
            } else {
                return [
                    'eligible' => false,
                    'reason' => 'لم تمر ' . $minYears . ' سنوات على اكتساب العضوية',
                ];
            }
        }

        return ['eligible' => true, 'reason' => 'مستوفي شروط التحويل'];
    }

    public static function getDivorceTransferFee(int $spouseId, string $membershipValue): array
    {
        $db = App::getInstance()->db();
        $spouse = $db->selectOne("SELECT * FROM spouses WHERE id = ?", [$spouseId]);
        if (!$spouse) {
            return ['error' => 'الزوج/الزوجة غير موجود'];
        }

        $classification = $spouse['classification'] ?? 'working';

        if ($classification === 'working') {
            return [
                'scenario' => 'both_working',
                'fee_type' => 'annual_subscription_only',
                'percentage' => '0.00',
                'separation_fee' => '0.00',
                'description' => 'زوج/زوجة أعضاء عاملين — الاشتراك السنوي فقط',
            ];
        }

        if ($classification === 'initial_form' || $spouse['spouse_order'] == 1) {
            $data = RuleEngine::get('DIVORCE_SAME_FORM_FEE');
            $pct = $data['percentage'] ?? '10.00';
            $fee = bcdiv(bcmul($membershipValue, $pct, 4), '100', 2);
            return [
                'scenario' => 'same_form',
                'fee_type' => 'percentage',
                'percentage' => $pct,
                'separation_fee' => $fee,
                'treat_as' => 'membership_basis',
                'description' => 'تم قبولهم في استمارة العضوية — 10% من قيمة العضوية',
            ];
        }

        $data = RuleEngine::get('DIVORCE_JOINED_AFTER_FEE');
        $pct = $data['percentage'] ?? '50.00';
        $fee = bcdiv(bcmul($membershipValue, $pct, 4), '100', 2);
        return [
            'scenario' => 'joined_after',
            'fee_type' => 'percentage',
            'percentage' => $pct,
            'separation_fee' => $fee,
            'treat_as' => 'acquired_member',
            'description' => 'تم الانضمام بعد الحصول على العضوية — 50% من قيمة العضوية',
        ];
    }

    public static function canWaiver(int $memberId): array
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [$memberId]);
        if (!$member) {
            return ['eligible' => false, 'reason' => 'العضو غير موجود'];
        }

        if ($member['status'] !== 'active') {
            return ['eligible' => false, 'reason' => 'العضوية غير فعالة'];
        }

        $unpaidSubs = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM subscriptions WHERE member_id = ? AND status IN ('pending','overdue')",
            [$memberId]
        );
        if ((int) ($unpaidSubs['cnt'] ?? 0) > 0) {
            return ['eligible' => false, 'reason' => 'يجب سداد جميع الاشتراكات المتأخرة قبل التنازل'];
        }

        return [
            'eligible' => true,
            'reason' => 'مستوفي شروط التنازل — يتطلب موافقة مجلس الأمناء',
            'requires_board_approval' => true,
        ];
    }

    private static function calculateAge(string $dateOfBirth): int
    {
        $dob = new \DateTime(substr($dateOfBirth, 0, 10));
        $now = new \DateTime();
        return $now->diff($dob)->y;
    }
}
