<?php
/**
 * @package   BaForms
 * @author    Balbooa http://www.balbooa.com/
 * @copyright Copyright @ Balbooa
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace Balbooa\Component\Forms\Site\Helper;

use Joomla\CMS\Factory;
use Joomla\Database\DatabaseInterface;

defined('_JEXEC') or die;

class ServiceHelper
{
    static self $instance;
    protected array $services = [];

    protected function __construct()
    {
    }

    public static function getInstance(): ServiceHelper
    {
        if (!isset(self::$instance)) {
            self::$instance = new ServiceHelper();
        }

        return self::$instance;
    }

    protected function load(string $service): void
    {
        $db = Factory::getContainer()->get(DatabaseInterface::class);
        $query = $db->getQuery(true)
            ->select('*')
            ->from('#__baforms_api')
            ->where('service = ' . $db->quote($service));
        $db->setQuery($query);
        $data = $db->loadObject();
        if (!$data) {
            $this->services[$service] = null;
            return;
        }
        $item = json_decode($data->key);
        if (!$item) {
            $item = $data->key;
        }
        $this->services[$service] = $item;
    }

    public function get(string $service): mixed
    {
        if (!isset($this->services[$service])) {
            $this->load($service);
        }

        return $this->services[$service];
    }
}