<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class RechargeSettings extends Model
{
    use HasFactory;

    // Currency conversion rates: 1 USD = 50 EGP
    const USD_TO_EGP_RATE = 50;
    const EGP_TO_USD_RATE = 0.02; // 1/50

    protected $fillable = [
        'payment_method',
        'is_active',
        'fee_percentage',
        'minimum_amount',
        'maximum_amount',
        'currency',
        'diamond_rate',
        'phone_number',
        'paypal_username',
        'additional_settings'
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'fee_percentage' => 'decimal:3',
        'minimum_amount' => 'decimal:2',
        'maximum_amount' => 'decimal:2',
        'diamond_rate' => 'decimal:4',
        'additional_settings' => 'array'
    ];

    /**
     * Get settings for a specific payment method
     */
    public static function getByPaymentMethod(string $method): ?self
    {
        return static::where('payment_method', $method)
                    ->where('is_active', true)
                    ->first();
    }

    /**
     * Calculate fee for given amount
     */
    public function calculateFee(float $amount): float
    {
        return $amount * ($this->fee_percentage / 100);
    }

    /**
     * Calculate diamonds for given amount
     */
    public function calculateDiamonds(float $amount): int
    {
        return (int) ($amount * $this->diamond_rate);
    }

    /**
     * Check if amount meets minimum requirement
     */
    public function meetsMinimum(float $amount): bool
    {
        return $amount >= $this->minimum_amount;
    }

    /**
     * Check if amount is within maximum limit
     */
    public function withinMaximum(float $amount): bool
    {
        return $this->maximum_amount === null || $amount <= $this->maximum_amount;
    }

    /**
     * Convert amount to USD equivalent for history calculations
     */
    public static function convertToUsdEquivalent(float $amount, string $currency): float
    {
        if ($currency === 'USD') {
            return $amount;
        }

        if ($currency === 'EGP') {
            return $amount / self::USD_TO_EGP_RATE; // Divide EGP by 50
        }

        return $amount; // fallback
    }

    /**
     * Get currency symbol
     */
    public static function getCurrencySymbol(string $currency): string
    {
        return match ($currency) {
            'USD' => '$',
            'EGP' => 'EGP',
            default => $currency
        };
    }
}
