<?php

namespace App\Services;

use App\Contracts\PaymentGatewayContract;
use App\Factories\PaymentGatewayFactory;
use App\PaymentGateways\AuthorizeNet\AuthorizeNetGateway;
use App\PaymentGateways\Braintree\BraintreeGateway;
use App\PaymentGateways\OfflinePayments\OfflinePaymentsGateway;
use App\PaymentGateways\PayPal\PayPalGateway;
use App\PaymentGateways\Razorpay\RazorpayGateway;
use App\PaymentGateways\Stripe\StripeGateway;

class PaymentGatewayManager
{
    protected $factory;

    public function __construct(PaymentGatewayFactory $factory)
    {
        $this->factory = $factory;
    }

    public function getConfiguredGateways(): array
    {
        $gateways = config('payment_gateways', [
            'offline_payments' => OfflinePaymentsGateway::class,
            'authorize_net' => AuthorizeNetGateway::class,
            'stripe' => StripeGateway::class,
            'paypal' => PayPalGateway::class,
            'braintree' => BraintreeGateway::class,
            'razorpay' => RazorpayGateway::class,
        ]);

        $configuredGateways = [];

        foreach ($gateways as $identifier => $className) {
            try {
                $gateway = $this->factory->make($identifier);

                if ($gateway->isConfigured()) {
                    $configuredGateways[] = [
                        'id' => $identifier,
                        'name' => $gateway->getLabel(),
                    ];
                }
            } catch (\Exception $e) {
                // Log errors if needed
            }
        }

        return $configuredGateways;
    }

    public function getGateway(string $identifier): PaymentGatewayContract
    {
        return $this->factory->make($identifier);
    }

    public function getAvailableGateways(): array
    {
        $paymentGateways = [];

        foreach ($this->getConfiguredGateways() as $gateway) {
            $gateway = $this->getGateway($gateway['id']);
            $paymentGateways[] = [
                'id' => $gateway->getIdentifier(),
                'name' => $gateway->getLabel(),
                'formParams' => $gateway->renderForm(),
            ];
        }

        return $paymentGateways;
    }
}
