<?php
namespace App\Core;

class AffiliateService {
    public static array $rankThresholds=['IBO'=>0,'EO'=>25000,'SEO'=>2500000,'AGM'=>5000000,'GM'=>7500000,'ED'=>10000000,'CM'=>50000000];

    public static function calculatePsa(float $purchase, float $sales): array {
        $profit=max(0,$sales-$purchase);$management=round($profit*.5,2);$marketing=round($profit*.5,2);
        return ['profit'=>$profit,'management'=>$management,'marketing'=>$marketing,'affiliate_distribution'=>round($marketing*.6,2),'global_royalty'=>round($marketing*.25,2),'leadership_royalty'=>round($marketing*.10,2),'incentive_fund'=>round($marketing*.05,2)];
    }

    public static function upgradeRank(int $memberId): ?string {
        $m=Database::fetchOne('SELECT id,total_psa FROM affiliate_members WHERE id=? LIMIT 1',[$memberId]);if(!$m)return null;
        $rank='IBO';foreach(self::$rankThresholds as $code=>$threshold){if((float)$m['total_psa']>=$threshold)$rank=$code;}
        Database::execute('UPDATE affiliate_members SET rank_code=?,updated_at=NOW() WHERE id=?',[$rank,$memberId]);return $rank;
    }

    public static function distributeSale(int $orderId,int $memberId,float $purchase,float $sales): array {
        $existing=Database::safeFetchOne('SELECT id FROM psa_transactions WHERE order_id=? AND affiliate_member_id=? LIMIT 1',[$orderId,$memberId]);
        if($existing)return self::calculatePsa($purchase,$sales);
        $psa=self::calculatePsa($purchase,$sales);
        Database::execute('INSERT INTO psa_transactions (order_id,affiliate_member_id,purchase_price,sales_price,profit_amount,management_psa,marketing_psa,created_at) VALUES (?,?,?,?,?,?,?,NOW())',[$orderId,$memberId,$purchase,$sales,$psa['profit'],$psa['management'],$psa['marketing']]);
        Database::execute('UPDATE affiliate_members SET total_psa=total_psa+?,weekly_personal_sales=weekly_personal_sales+?,updated_at=NOW() WHERE id=?',[$psa['marketing'],$sales,$memberId]);
        $u=Database::fetchOne('SELECT user_id FROM affiliate_members WHERE id=? LIMIT 1',[$memberId]);
        if($u&&$psa['affiliate_distribution']>0)WalletService::credit((int)$u['user_id'],'commission',$psa['affiliate_distribution'],'Affiliate PSA distribution',$orderId);
        Database::safeExecute('INSERT INTO affiliate_conversions (affiliate_member_id,order_id,amount,commission,status,processed_at,created_at) VALUES (?,?,?,?,"completed",NOW(),NOW()) ON DUPLICATE KEY UPDATE amount=VALUES(amount),commission=VALUES(commission),status="completed",processed_at=NOW()',[$memberId,$orderId,$sales,$psa['affiliate_distribution']]);
        self::upgradeRank($memberId);return $psa;
    }

    public static function processOrder(int $orderId): bool {
        if($orderId<1)return false;
        return (bool)Database::transaction(function()use($orderId){
            $order=Database::fetchOne('SELECT * FROM orders WHERE id=? FOR UPDATE',[$orderId]);
            if(!$order||(string)$order['order_status']!=='delivered'||(string)$order['payment_status']!=='paid'||empty($order['affiliate_member_id']))return false;
            if(Database::safeFetchOne('SELECT id FROM psa_transactions WHERE order_id=? AND affiliate_member_id=? LIMIT 1',[$orderId,$order['affiliate_member_id']]))return false;
            $totals=Database::fetchOne('SELECT COALESCE(SUM(purchase_price*qty),0) purchase_total,COALESCE(SUM(total_price),0) sales_total FROM order_items WHERE order_id=?',[$orderId]);
            self::distributeSale($orderId,(int)$order['affiliate_member_id'],(float)($totals['purchase_total']??0),(float)($totals['sales_total']??0));
            return true;
        });
    }

    public static function eligibleForGlobalRoyalty(array $m): bool {
        return ($m['rank_code']??'IBO')!=='IBO'&&(float)($m['weekly_personal_sales']??0)>=2000&&($m['status']??'active')==='active';
    }
}
