<?php
namespace Skeleton\Renderer;

class TwigRenderer implements RendererInterface
{

    private $twig;

    private $loader;

    public function __construct(\Twig\Loader\FilesystemLoader $loader, \Twig\Environment $twig)
    {
        $this->loader = $loader;
        $this->twig = $twig;
    }

    public function addPath(string $namespace, ?string $path = null)
    {
        $this->loader->prependPath($path, $namespace);
    }

    public function render(string $view, array $params = []) :string
    {
        $pathSession = $_SESSION['ariane']['0']['path']??'';
        if ($pathSession == $_SERVER['REQUEST_URI'] || strpos($pathSession, 'CallUrl') !== false) {
            $_SESSION['navigation'] = [
                'menuActive'    => $params['menuActive']??'',
                'menuLeft'      => $params['menuLeft']??'',
            ];
        }

        $render =  $this->twig->render($view . '.twig', $params);

        /**
         * Prise en compte du CSRF
         */

        $token = \Helpers\Securite\CSRF::generateCSRFTokenPair();

        $input = '<input type="hidden" value="'. $token["tokenCSRF_value"]. '" name="'. $token["tokenCSRF_name"]. '" id="tokenCSRF" />';

        if (strpos($render, '</form>') === false) {
            $render = str_replace('</body>', '</body><form>'.$input.'</form>', $render);
        } else {
            $render = str_replace('</form>', $input . '</form>', $render);
        }

        /*$render = str_replace(
            '</form>',
            '<input type="hidden" value="'. $token["tokenCSRF_value"]. '" name="'. $token["tokenCSRF_name"]. '" id="tokenCSRF" /></form>',
            $render
        );*/

        /**
         * En Mode recette on enregistre les textes non traduits dans TMP
         */
        \Helpers\Environnement\Recette\Traduction::setFileNoTrad('Portail utilisateur');

        return $render;
    }

    public function addGlobal(string $key, $value)
    {
        $this->twig->addGlobal($key, $value);
    }
}
