<?php

namespace GriffinForms\Includes\Integrations\Categories;

use GriffinForms\Includes\Integrations\Categories\Base;

/**
 * Registry for mailing providers.
 */
class Mailer extends Base
{
    protected $category_key = 'mailer';
    protected $active_option = 'mailing_system';
    protected $base_provider_id = 'server_mail';

    protected function setProvidercache()
    {
        parent::setProvidercache();

        $base = $this->getBaseProviderMetadata();
        $this->provider_cache = array_merge([$this->base_provider_id => $base], $this->provider_cache);
    }

    protected function getBaseProviderMetadata(): array
    {
        return [
            'id'          => $this->base_provider_id,
            'name'        => __('Webserver (wp_mail)', 'griffinforms-form-builder'),
            'category'    => __('Email', 'griffinforms-form-builder'),
            'scope'       => [
                'is_global'      => true,
                'allow_override' => false,
            ],
        ];
    }

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

        return $configured;
    }

    public function getActiveProviderId(): string
    {
        $selected = sanitize_key($this->settings->getOption($this->active_option, $this->base_provider_id));

        if (empty($selected) || $selected === 'none') {
            $selected = $this->base_provider_id;
        }

        if ($selected === $this->base_provider_id) {
            return $this->base_provider_id;
        }

        if (isset($this->provider_cache[$selected]) && $this->isProviderConfigured($selected)) {
            return $selected;
        }

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

        return $this->base_provider_id;
    }

    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;
    }

    public function getActiveIntegration()
    {
        $active_id = $this->getActiveProviderId();
        if ($active_id === $this->base_provider_id) {
            return null;
        }

        return $this->providers_service->getIntegration($active_id);
    }

    public function saveActiveProvider(string $provider_id): bool
    {
        if ($provider_id !== $this->base_provider_id && !isset($this->provider_cache[$provider_id])) {
            return false;
        }

        $this->settings->updateOption($this->active_option, sanitize_key($provider_id), 'mail');
        return true;
    }

    public function ensureActiveProvider(string $provider_id): void
    {
        $current = sanitize_key($this->settings->getOption($this->active_option));
        if (empty($current) || $current === $this->base_provider_id) {
            $this->saveActiveProvider($provider_id);
        }
    }

    public function providerIsConfigured(string $provider_id): bool
    {
        return $this->isProviderConfigured($provider_id);
    }

    private function isProviderConfigured(string $provider_id): bool
    {
        if ($provider_id === $this->base_provider_id) {
            return true;
        }

        $integration = $this->providers_service->getIntegration($provider_id);
        return $integration ? (bool) $integration->isConfigured() : false;
    }
}
