<?php

namespace App\Models;

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

class PaymentGateway extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'display_name',
        'is_active',
        'public_key',
        'secret_key',
        'webhook_url',
        'settings',
        'sort_order'
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'settings' => 'array',
        'sort_order' => 'integer'
    ];

    /**
     * Get active payment gateways
     */
    public static function getActive()
    {
        return self::where('is_active', true)
            ->orderBy('sort_order', 'asc')
            ->get();
    }

    /**
     * Get gateway by name
     */
    public static function getByName($name)
    {
        return self::where('name', $name)->first();
    }

    /**
     * Check if gateway is in test mode
     */
    public function isTestMode()
    {
        return $this->settings['test_mode'] ?? false;
    }

    /**
     * Get supported currencies
     */
    public function getSupportedCurrencies()
    {
        return $this->settings['supported_currencies'] ?? [];
    }

    /**
     * Encrypt secret key before saving
     */
    public function setSecretKeyAttribute($value)
    {
        if ($value) {
            $this->attributes['secret_key'] = encrypt($value);
        }
    }

    /**
     * Decrypt secret key when retrieving
     */
    public function getSecretKeyAttribute($value)
    {
        if ($value) {
            try {
                return decrypt($value);
            } catch (\Exception $e) {
                return $value; // Return as-is if decryption fails
            }
        }
        return null;
    }

    /**
     * Get logo URL
     */
    public function getLogoUrl()
    {
        $logo = $this->settings['logo'] ?? null;
        if ($logo) {
            return asset('assets/images/payment-gateways/' . $logo);
        }
        return asset('assets/images/payment-gateways/default.png');
    }

    /**
     * Transactions using this gateway
     */
    public function transactions()
    {
        return $this->hasMany(Transaction::class, 'payment_gateway', 'name');
    }

    /**
     * Payment logs for this gateway
     */
    public function logs()
    {
        return $this->hasMany(PaymentLog::class, 'gateway', 'name');
    }
}
