<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class PaymentGatewayFee extends Model
{
    protected $fillable = [
        'gateway',
        'percentage_fee',
        'fixed_fee',
        'currency',
        'country_code',
        'is_active',
        'notes',
    ];

    protected $casts = [
        'percentage_fee' => 'decimal:3',
        'fixed_fee' => 'decimal:2',
        'is_active' => 'boolean',
    ];

    /**
     * Get fees for a specific gateway and currency.
     */
    public static function getForGateway(string $gateway, string $currency = 'USD', ?string $countryCode = null): ?self
    {
        return static::where('gateway', $gateway)
            ->where('currency', $currency)
            ->where('is_active', true)
            ->when($countryCode, function ($q) use ($countryCode) {
                $q->where(function ($query) use ($countryCode) {
                    $query->where('country_code', $countryCode)
                        ->orWhereNull('country_code');
                })->orderByRaw('country_code IS NULL ASC');
            })
            ->first();
    }

    /**
     * Calculate the fee for a given amount.
     */
    public function calculateFee(float $amount): float
    {
        $percentageFee = $amount * ((float) $this->percentage_fee / 100);
        $totalFee = $percentageFee + (float) $this->fixed_fee;
        
        return round($totalFee, 2);
    }

    /**
     * Calculate the amount to charge so that after fees we receive the desired amount.
     * Formula: charge = (desired + fixed_fee) / (1 - percentage/100)
     */
    public function calculateChargeAmount(float $desiredAmount): float
    {
        $percentageMultiplier = 1 - ((float) $this->percentage_fee / 100);
        
        if ($percentageMultiplier <= 0) {
            return $desiredAmount + (float) $this->fixed_fee;
        }
        
        $chargeAmount = ($desiredAmount + (float) $this->fixed_fee) / $percentageMultiplier;
        
        return round($chargeAmount, 2);
    }

    /**
     * Get a summary of all active gateway fees.
     */
    public static function getAllActiveFees(): array
    {
        return static::where('is_active', true)
            ->get()
            ->groupBy('gateway')
            ->map(function ($fees, $gateway) {
                return [
                    'gateway' => $gateway,
                    'fees' => $fees->map(function ($fee) {
                        return [
                            'currency' => $fee->currency,
                            'percentage' => (float) $fee->percentage_fee,
                            'fixed' => (float) $fee->fixed_fee,
                            'country_code' => $fee->country_code,
                        ];
                    })->values(),
                ];
            })
            ->values()
            ->toArray();
    }

    /**
     * Scope for active fees.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
}
