<?php

namespace Modules\Additional\Specifique\Client13\Html;

use Entity\Model\Dilispec;
use Helpers\Trad\ITrad;
use Modules\Additional\Specifique\Client37\Modules\Signature\Service\WorkflowSpecifique;
use Modules\Panier\Repository\PanierEntete;
use Psr\Container\ContainerInterface;
use TwigExtension\FormExtension;
use Skeleton\Router;

class HtmlExtension extends \Twig\Extension\AbstractExtension
{
    /** @phpstan-ignore-next-line */
    private Router $router;
    /** @phpstan-ignore-next-line */
    private ContainerInterface $contenaire;
    /** @phpstan-ignore-next-line */
    private \PDO $pdo;
    private ITrad $trad;
    
    public function __construct(Router $router, ContainerInterface $contenaire, \PDO $pdo)
    {
        $this->router = $router;
        $this->pdo = $pdo;
        $this->contenaire = $contenaire;
        $this->trad = $contenaire->get(ITrad::class);
    }

    public function getFunctions()
    {
        return [
            new \Twig\TwigFunction('specifiqueCsPanier', [
                $this,
                'specifiqueCsPanier'
            ], [
                'is_safe' => [
                    'html'
                ]
            ])
        ];
    }
    
    /**
     * @return string
     */
    public function specifiqueCsPanier():string
    {

        $panierEntete = (new PanierEntete($this->pdo))->getEntetePanier($_SESSION['id_panier'], $_SESSION['id_user']);

        $infoSpecifique = $this->getCsPanierSEM($panierEntete['CODE_STE']);
        //Dilispec

        if (($infoSpecifique['VALEUR']??'') != 'O') {
            return '';
        }

        $path = $this->router->generateUri('Specifique13.CSPanier.popupCSPanier');
        return '<a class="button secondaire" href="'.$path.'">'.$this->trad->t('Champs suppl.').'</a>
            <script>
                $( document ).ready(function() {
                    $(\'#rowCs\').html(\'\');
                    $(\'#rowCs\').removeClass(); 
                });
            </script>
        ';
    }

    /**
     * @return array<mixed>|null
     */
    private function getCsPanierSEM(?string $codeSte = null)
    {
        if (!$codeSte) {
            return null;
        }
        $req = "select * 
                from CS_DON 
                where COD_TAB = 'SOCIETE' and COD_ENR = :societe and NUM_FIX = (SELECT LIB01DICO FROM DILISPEC WHERE TYPEDICO='SEMPARAM' AND CODEDICO='NCS_SOCIETE_AFFICHE_CS_SPECIF')";
   
        $arrayReq = [
            ':societe' => $codeSte
        ];

        $requete = $this->pdo->prepare($req);
        $requete->execute($arrayReq);

        return $requete->fetch();
    }
}
