<?php

namespace GriffinForms\Includes\Integrations\Categories;

use GriffinForms\Traits\Singleton;
use GriffinForms\Includes\Integrations\Providers;
use GriffinForms\Settings;

/**
 * Base registry for integration categories.
 */
abstract class Format
{
    use Singleton;

    protected $category_key = '';
    protected $active_option = '';
    protected $providers_service;
    protected $settings;
    protected $provider_cache = [];

    protected function setProvidersservice()
    {
        $this->providers_service = Providers::getInstance();
    }

    protected function setSettings()
    {
        $this->settings = Settings::getInstance();
    }

    protected function setProvidercache()
    {
        if (!$this->providers_service) {
            $this->setProvidersservice();
        }

        $records = $this->providers_service ? $this->providers_service->getAll() : [];
        foreach ($records as $id => $provider) {
            if (($provider['category_type'] ?? '') === $this->category_key) {
                $this->provider_cache[$id] = $provider;
            }
        }
    }

    public function getProviders(): array
    {
        return $this->provider_cache;
    }

    public function getProvider(string $provider_id): ?array
    {
        return $this->provider_cache[$provider_id] ?? null;
    }

    protected function resolveFormContextId(): int
    {
        if (isset($_REQUEST['form_id'])) {
            return absint(wp_unslash($_REQUEST['form_id']));
        }

        return 0;
    }
}
