<?php

namespace App\Support;

use App\Models\Payment;
use App\Models\Setting;

class PaymentGatewayManager
{
    public static function activeProvider(): string
    {
        $provider = (string) Setting::getValue('payment_default_provider', 'razorpay');

        return in_array($provider, ['razorpay', 'payu'], true) ? $provider : 'razorpay';
    }

    public static function availableMethods(): array
    {
        return [
            'upi' => 'UPI',
            'card' => 'Debit / Credit Card',
            'netbanking' => 'Net Banking',
        ];
    }

    public static function createProviderOrderId(Payment $payment): string
    {
        $prefix = strtoupper(substr(static::activeProvider(), 0, 3));

        return $prefix . '-DEMO-' . str_pad((string) $payment->id, 6, '0', STR_PAD_LEFT);
    }

    public static function sign(string $payload, string $secret): string
    {
        return hash_hmac('sha256', $payload, $secret);
    }

    public static function verify(string $payload, ?string $signature, ?string $secret): bool
    {
        if (!$signature || !$secret) {
            return false;
        }

        return hash_equals(static::sign($payload, $secret), $signature);
    }

    public static function secretFor(string $provider): ?string
    {
        return match ($provider) {
            'payu' => Setting::getValue('payment_payu_salt'),
            default => Setting::getValue('payment_razorpay_secret'),
        };
    }
}
