<?php
namespace App\Core;

class FinanceEngine {
    public const WALLET_TYPES = ['cash','purchase','incentive_admin','vat_tax_admin','point','royalty','commission','withdraw','bonus','reward'];
    public static function calculatePsa(float $purchasePrice, float $salesPrice): array {
        $profit = max(0, $salesPrice - $purchasePrice);
        $management = round($profit * 0.50, 2);
        $marketing = round($profit * 0.50, 2);
        return [
            'profit' => $profit,
            'management_psa' => $management,
            'marketing_psa' => $marketing,
            'marketing_distribution' => [
                'affiliate_distribution' => round($marketing * 0.60, 2),
                'global_royalty' => round($marketing * 0.25, 2),
                'leadership_royalty' => round($marketing * 0.10, 2),
                'incentive_fund' => round($marketing * 0.05, 2),
            ],
            'management_distribution' => [
                'company' => round($management * 0.10, 2),
                'share_holders' => round($management * 0.15, 2),
                'logistics' => round($management * 0.15, 2),
                'employees' => round($management * 0.20, 2),
                'office' => round($management * 0.20, 2),
                'sales' => round($management * 0.10, 2),
                'training' => round($management * 0.10, 2),
            ],
        ];
    }
    public static function withdrawal(float $amount): array {
        $fee = round($amount * (WITHDRAWAL_CHARGE_PERCENT / 100), 2);
        return ['gross' => $amount, 'fee' => $fee, 'net' => round($amount - $fee, 2)];
    }
    public static function canTransfer(string $from, string $to, bool $admin = false): bool {
        if ($admin) return in_array($to, ['cash','purchase'], true);
        return $from === 'cash' && $to === 'purchase';
    }
    public static function rankForPsa(float $psa): string {
        $thresholds = ['CM'=>50000000,'ED'=>10000000,'GM'=>7500000,'AGM'=>5000000,'SEO'=>2500000,'EO'=>25000,'IBO'=>0];
        foreach ($thresholds as $rank=>$min) if ($psa >= $min) return $rank;
        return 'IBO';
    }
}
