<?php

namespace App\Services;

use App\Models\AppSetting;
use App\Models\FoodOrder;
use App\Models\GasOrder;
use App\Models\Referral;
use App\Models\TaxiRequest;
use App\Models\User;
use App\Models\WalletTransaction;

class ReferralWithdrawalGate
{
    /**
     * مجموع واردات المحفظة المصنّفة كأرباح دعوات (referral_earning).
     */
    public static function referralCreditSum(int $userId): float
    {
        return (float) WalletTransaction::query()
            ->where('user_id', $userId)
            ->where('source', 'referral_earning')
            ->where('type', 'credit')
            ->sum('amount');
    }

    /**
     * عدد المدعوين المؤهلين: إحالة مكتملة + المدعو نشط وموثّق + ≥ N طلب مكتمل في التطبيق.
     */
    public static function qualifiedInviteeCount(int $referrerId): int
    {
        $settings = AppSetting::query()->first();
        $minOrders = max(1, (int) ($settings->referral_withdraw_min_orders_per_invitee ?? 10));

        $referrals = Referral::query()
            ->where('referrer_id', $referrerId)
            ->where('status', 'completed')
            ->get();

        $qualified = 0;

        foreach ($referrals as $ref) {
            $referred = User::query()->find($ref->referred_id);
            if (! $referred) {
                continue;
            }
            if (($referred->status ?? '') !== 'active') {
                continue;
            }
            if (! (bool) ($referred->is_verified ?? false)) {
                continue;
            }
            if (self::completedOrdersCountForUser((int) $referred->id) < $minOrders) {
                continue;
            }
            $qualified++;
        }

        return $qualified;
    }

    public static function requiredInviteeCount(): int
    {
        $settings = AppSetting::query()->first();

        return max(1, (int) ($settings->referral_withdraw_min_invitees ?? 60));
    }

    /**
     * إجمالي الطلبات المكتملة (طعام + غاز + تاكسي) للمستخدم كراكب.
     */
    public static function completedOrdersCountForUser(int $userId): int
    {
        $food = FoodOrder::query()->where('customer_id', $userId)->where('status', 'delivered')->count();
        $gas = GasOrder::query()->where('customer_id', $userId)->where('status', 'delivered')->count();

        $phone = optional(User::query()->find($userId))->phone;

        $taxi = TaxiRequest::query()
            ->where('status', 'completed')
            ->where(function ($q) use ($userId, $phone) {
                $q->where('passenger_id', (string) $userId);
                if ($phone) {
                    $q->orWhere('passenger_phone', $phone);
                }
            })
            ->count();

        return (int) ($food + $gas + $taxi);
    }

    /**
     * جزء من الرصيد يُقفل ولا يُسحب حتى استيفاء شروط المدعوين (أرباح الدعوات).
     */
    public static function lockedReferralBalance(int $userId, float $availableBalance): float
    {
        $refSum = self::referralCreditSum($userId);
        if ($refSum <= 0) {
            return 0.0;
        }

        if (self::qualifiedInviteeCount($userId) >= self::requiredInviteeCount()) {
            return 0.0;
        }

        return min($availableBalance, $refSum);
    }

    public static function maxWithdrawable(float $walletBalance, float $pendingWithdrawal, int $userId): float
    {
        $available = max(0.0, $walletBalance - $pendingWithdrawal);
        $locked = self::lockedReferralBalance($userId, $available);

        return max(0.0, $available - $locked);
    }
}
