<?php

namespace Modules\Parametrage\Controller;

use Entity\Model\Paravrac;
use Firebase\JWT\Key;
use Helpers\Ariane\Ariane;
use Helpers\Framework\Debug;
use Helpers\Outil\Sql;
use Skeleton\Controller\Controller;

class ParametrageAPIController extends Controller
{
    /** @var int */
    const SECRET_ID_LENGTH = 25;

    /** @var string $menuActive */
    protected string $menuActive;

    /** @var string $menuLeft */
    protected string $menuLeft;

    /** @var int $indexAriane */
    protected int $indexAriane;

    /** @var Paravrac $paravrac */
    protected Paravrac $paravrac;

    /**
     * @return void
     */
    public function init(): void
    {
        if (($_SESSION['ariane'][0]['path']??null) == $this->router->generateUri('Parametrage.Parametrage.index')) {
            $this->indexAriane = 1;
            $this->menuActive = 'Parametrage';
            $this->menuLeft = 'Parametrage';
        } else {
            $this->indexAriane = 0;
            $this->menuActive = 'API';
            $this->menuLeft = 'Parametrage';
        }

        $this->paravrac = new Paravrac($this->pdo);
    }

    /**
     * @return \GuzzleHttp\Psr7\Response|string
     * @throws \Exception
     */
    public function indexAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $reset = $this->request->getAttribute('reset');

        Ariane::generate($this->indexAriane, $trad->t('Paramétrage API'), []);
        $appParam = [
            'CLIENT_ID' => $this->paravrac->find(['TYPEPARV' => 'AUTHAPIOXA', 'CODEPARV' => 'CLIENT_ID'])['LIB01PARV'] ?? '',
            'SECRET_ID' => $this->paravrac->find(['TYPEPARV' => 'AUTHAPIOXA', 'CODEPARV' => 'SECRET_ID'])['LIB01PARV'] ?? '',
        ];

        if ($appParam['CLIENT_ID'] === '') {
            $appParam['CLIENT_ID'] = "OXA{$_SESSION['Session_NumClient']}Client";
            $this->paravrac->set('AUTHAPIOXA', 'CLIENT_ID', $appParam['CLIENT_ID']);
        }

        if ($appParam['SECRET_ID'] === '' || $reset) {
            $appParam['SECRET_ID'] = Sql::generateSecret(self::SECRET_ID_LENGTH);
            $jwt = \Firebase\JWT\JWT::encode((array)$appParam['SECRET_ID'], $this->JWTKEY, 'HS256');
            $this->paravrac->set('AUTHAPIOXA', 'SECRET_ID', $jwt);

            if ($reset) {
                return $this->redirect('Parametrage.ParametrageAPI.index');
            }
        } else {
            $jwtDecode = (array)\Firebase\JWT\JWT::decode(trim($appParam['SECRET_ID']), new Key($this->JWTKEY, 'HS256'));
            $appParam['SECRET_ID'] = $jwtDecode[0];
        }

        return $this->renderer->render('@Parametrage/ParametrageAPI/index', [
            'appParam' => $appParam,
        ]);
    }
}
