<?php

namespace GriffinForms\Includes\Integrations\Categories;

/**
 * Registry for payment providers/gateways.
 */
class Payment extends Base
{
    protected $category_key = 'payment';
    protected $active_option = 'allowed_payment_gateways';

    /**
     * Return configured gateways.
     */
    public function getConfiguredProviders(): array
    {
        $configured = [];
        foreach ($this->provider_cache as $id => $provider) {
            if ($this->isProviderConfigured($id)) {
                $configured[$id] = $provider;
            }
        }

        return $configured;
    }

    /**
     * Resolve active provider id or null when disabled/unavailable.
     */
    public function getActiveProviderId(): ?string
    {
        $allowed = $this->getAllowedProviderIds();
        foreach ($allowed as $provider_id) {
            if (isset($this->provider_cache[$provider_id]) && $this->isProviderConfigured($provider_id)) {
                return $provider_id;
            }
        }

        foreach ($this->getConfiguredProviders() as $id => $provider) {
            return $id;
        }

        return null;
    }

    /**
     * Get allowed provider IDs from settings.
     */
    public function getAllowedProviderIds(): array
    {
        $raw = $this->settings->getOption($this->active_option, []);
        if (is_string($raw)) {
            $raw = [$raw];
        }
        if (!is_array($raw)) {
            return [];
        }

        $allowed = array_filter(array_map('sanitize_key', $raw));
        return array_values(array_intersect(array_keys($this->provider_cache), $allowed));
    }

    /**
     * Return active integration instance.
     */
    public function getActiveIntegration(int $form_id = 0)
    {
        $active_id = $this->getActiveProviderId();
        if (!$active_id) {
            return null;
        }

        $integration = $this->providers_service->getIntegration($active_id);
        if ($integration && method_exists($integration, 'setFormContextId')) {
            $integration->setFormContextId($form_id);
        }

        return $integration;
    }

    /**
     * Gateway dropdown options.
     */
    public function getProviderOptions(): array
    {
        $options = [];
        foreach ($this->provider_cache as $id => $provider) {
            $options[] = [
                'id'         => $id,
                'label'      => $provider['name'] ?? $id,
                'configured' => $this->isProviderConfigured($id),
            ];
        }

        return $options;
    }

    /**
     * Persist admin-selected gateway.
     */
    public function saveAllowedProviders(array $provider_ids): bool
    {
        $sanitized = [];
        foreach ($provider_ids as $provider_id) {
            $provider_id = sanitize_key($provider_id);
            if ($provider_id === 'none') {
                continue;
            }
            if (isset($this->provider_cache[$provider_id]) && $this->isProviderConfigured($provider_id)) {
                $sanitized[] = $provider_id;
            }
        }

        $this->settings->updateOption($this->active_option, $sanitized, 'payments');
        return true;
    }

    public function ensureActiveProvider(string $provider_id): void
    {
        $allowed = $this->getAllowedProviderIds();
        if (empty($allowed)) {
            $this->saveAllowedProviders([$provider_id]);
        }
    }

    private function isProviderConfigured(string $provider_id): bool
    {
        $integration = $this->providers_service->getIntegration($provider_id);
        return $integration ? (bool) $integration->isConfigured() : false;
    }
}
