<?php

declare(strict_types=1);

namespace Plugin\tnt_stabila_shop\adminmenu\Controller;

use JTL\Plugin\PluginInterface;
use JTL\Shop;
use JTL\Smarty\JTLSmarty;

/**
 * @method string|void handleRequest(array<string, mixed> $args = [])
 */
class BaseController
{
    public const SMARTY_PATH               = '../plugins/tnt_stabila_shop/adminmenu/templates/';
    public const TAIL_ADMIN_PATH           = '../plugins/tnt_stabila_shop/adminmenu/tailadmin/';
    protected const RESERVED_REQUEST_PARAM = [
        'io',
        'uri',
        'token',
        'params',
        'name',
    ];
    protected JTLSmarty $smarty;

    public function __construct(protected PluginInterface $plugin)
    {
        $this->smarty = Shop::Smarty()
            ->assign(tpl_var: 'pluginURI', value: $this->plugin->getPaths()->getAdminPath())
            ->assign(tpl_var: 'pluginURL', value: $this->plugin->getPaths()->getAdminURL())
            ->assign(tpl_var: 'tailadminURI', value: $this->plugin->getPaths()->getAdminPath() . 'tailadmin/')
            ->assign(tpl_var: 'tailadminURL', value: $this->plugin->getPaths()->getAdminURL() . 'tailadmin/');

        if (\get_class($this) !== AjaxEndpoint::class) {
            $html = $this->handleRequest();
            if ($html !== '') {
                echo $html;
            }
        } else {
            $ajaxRequest = $this->getAjaxRequest();
            if ($ajaxRequest !== null) {
                foreach ($_REQUEST as $offset => $value) {
                    if (\in_array($offset, self::RESERVED_REQUEST_PARAM, true)) {
                        continue;
                    }
                    $ajaxRequest[$offset] = $value;
                }
                $this->handleRequest($ajaxRequest);
            }
        }
    }

    /**
     * @return array<string, mixed>|null
     */
    private function getAjaxRequest(): array|null
    {
        if (\get_class($this) !== AjaxEndpoint::class) {
            return null;
        }
        $arguments = $_REQUEST['io'] ?? null;
        if ($arguments === null) {
            return null;
        }
        try {
            $arguments = \json_decode($arguments, true, 512, JSON_THROW_ON_ERROR);
        } catch (\JsonException) {
            return null;
        }
        if (\is_array($arguments) === false) {
            return null;
        }
        if (($arguments['name'] ?? '') === 'tntStabilaEndpoint') {
            $params = $arguments['params'] ?? null;
            return \is_array($params) ? $params : null;
        }

        return null;
    }
}
