<?php
declare(strict_types=1);

namespace Help4BuilderSuite\Modules\Commerce;

use Help4BuilderSuite\Support\ContactRoutes;

if (! defined('ABSPATH')) {
    exit;
}

final class GatewayRegistry
{
    /**
     * @var array<string, mixed>
     */
    private array $settings;

    /**
     * @param array<string, mixed> $settings
     */
    public function __construct(array $settings)
    {
        $this->settings = $settings;
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    public function all(): array
    {
        $defaults = [
            [
                'slug'        => 'stripe_router',
                'label'       => 'Stripe (Basil Track)',
                'description' => 'Supports a configured Stripe router pipeline and Stripe embedded checkout builder.',
                'setting_key' => 'stripe_secret_key',
                'endpoint_setting_key' => 'stripe_router_endpoint',
            ],
            [
                'slug'        => 'square',
                'label'       => 'Square',
                'description' => 'Square card present and online processing.',
                'setting_key' => 'square_application_id',
                'endpoint_setting_key' => 'square_router_endpoint',
            ],
            [
                'slug'        => 'braintree',
                'label'       => 'Braintree',
                'description' => 'PayPal-owned multi-method processor.',
                'setting_key' => 'braintree_merchant_id',
                'endpoint_setting_key' => 'braintree_router_endpoint',
            ],
            [
                'slug'        => 'hosted_payments',
                'label'       => 'Hosted Payments',
                'description' => 'Hosted card processing through a configured payment route.',
                'setting_key' => 'hosted_payments_profile',
                'endpoint_setting_key' => 'hosted_payments_router_endpoint',
                'legacy_setting_key' => 'godaddy_payments_profile',
                'legacy_endpoint_setting_key' => 'godaddy_router_endpoint',
            ],
            [
                'slug'        => 'paypal',
                'label'       => 'PayPal',
                'description' => 'Wallet and card checkout options.',
                'setting_key' => 'paypal_client_id',
                'endpoint_setting_key' => 'paypal_router_endpoint',
            ],
            [
                'slug'        => 'authorize_net',
                'label'       => 'Authorize.Net',
                'description' => 'Enterprise-grade gateway and fraud tools.',
                'setting_key' => 'authorize_net_login_id',
                'endpoint_setting_key' => 'authorize_net_router_endpoint',
            ],
            [
                'slug'        => 'wise',
                'label'       => 'Wise',
                'description' => 'Cross-border transfer support.',
                'setting_key' => 'wise_profile_id',
                'endpoint_setting_key' => 'wise_router_endpoint',
            ],
        ];

        $providers = apply_filters('h4bs_gateway_registry', $defaults);
        if (! is_array($providers)) {
            return [];
        }

        $supportUrl = ContactRoutes::supportTicketUrl($this->settings);
        $out = [];
        foreach ($providers as $provider) {
            if (! is_array($provider)) {
                continue;
            }

            $accountKey = (string) ($provider['setting_key'] ?? '');
            $endpointKey = (string) ($provider['endpoint_setting_key'] ?? '');
            $legacyAccountKey = (string) ($provider['legacy_setting_key'] ?? '');
            $legacyEndpointKey = (string) ($provider['legacy_endpoint_setting_key'] ?? '');

            $accountConfigured = $accountKey !== '' && ! empty($this->settings[$accountKey]);
            $processorEndpoint = $endpointKey !== ''
                ? esc_url_raw((string) ($this->settings[$endpointKey] ?? ''))
                : '';
            if (! $accountConfigured && $legacyAccountKey !== '') {
                $accountConfigured = ! empty($this->settings[$legacyAccountKey]);
            }
            if ($processorEndpoint === '' && $legacyEndpointKey !== '') {
                $processorEndpoint = esc_url_raw((string) ($this->settings[$legacyEndpointKey] ?? ''));
            }
            $hasEndpoint = $processorEndpoint !== '';
            $isConfigured = $hasEndpoint;

            if (($provider['slug'] ?? '') === 'stripe_router') {
                $hasStripeKeys = ! empty($this->settings['stripe_publishable_key']) && ! empty($this->settings['stripe_secret_key']);
                $accountConfigured = $accountConfigured || $hasStripeKeys;
                $provider['api_track'] = (string) ($this->settings['stripe_api_track'] ?? 'basil');
                $provider['api_version_override'] = (string) ($this->settings['stripe_api_version_override'] ?? '');
                $provider['embedded_checkout_enabled'] = ! empty($this->settings['stripe_embedded_checkout_enabled']);
                $provider['customer_data_mode'] = (string) ($this->settings['commerce_customer_data_mode'] ?? 'both');
            }

            $provider['processor_endpoint'] = $processorEndpoint;
            $provider['endpoint_setting_key'] = $endpointKey;
            $provider['endpoint_locked'] = true;
            $provider['account_setting_key'] = $accountKey;
            $provider['account_configured'] = $accountConfigured;
            $provider['requires_account_key'] = $accountKey !== '';
            $provider['configured'] = $isConfigured;
            $provider['contact_url'] = $supportUrl;
            $out[] = $provider;
        }

        return $out;
    }

    /**
     * @return array<string, mixed>|null
     */
    public function get(string $slug): ?array
    {
        $slug = sanitize_key($slug);
        if ($slug === 'godaddy_payments') {
            $slug = 'hosted_payments';
        }
        foreach ($this->all() as $provider) {
            if (($provider['slug'] ?? '') === $slug) {
                return $provider;
            }
        }

        return null;
    }
}
