<?php
namespace Modules\DemandeAchat\TwigExtension;

use Helpers\Trad\ITrad;
use Psr\Container\ContainerInterface;
use Skeleton\Router;
use TwigExtension\ButtonExtention;
use Modules\DemandeAchat\Repository\CreationDemandeAchat;

class OutilDemandeAchatExtension extends \Twig\Extension\AbstractExtension
{
    protected $pdo;
    protected $contenaire;
    private $router;
    private ITrad $trad;
    
    public function __construct(\PDO $pdo, ContainerInterface $contenaire, Router $router)
    {
        $this->pdo = $pdo;
        $this->contenaire = $contenaire;
        $this->router = $router;
        $this->trad = $contenaire->get(ITrad::class);
    }
    
    public function getFunctions()
    {
        return [
            new \Twig\TwigFunction('navBar_modifDA', [
                $this,
                'navBar_modifDA'
            ], [
                'is_safe' => [
                    'html'
                ]
            ]),
            new \Twig\TwigFunction('blockEnteteDA', [
                $this,
                'blockEnteteDA'
            ], [
                'is_safe' => [
                    'html'
                ]
            ]),
            new \Twig\TwigFunction('bouton_modifDA', [
                $this,
                'bouton_modifDA'
            ], [
                'is_safe' => [
                    'html'
                ]
            ]),
            new \Twig\TwigFunction('liAl', [
                $this,
                'liAl'
            ], [
                'is_safe' => [
                    'html'
                ]
            ])
        ];
    }
    
    // phpcs:ignore
    public function navBar_modifDA($id, $mode, $MODULE, $ficheDA = false, $onglet = '', $ongletFicheDA = false)
    {
        $trad = $this->trad;
        $html = '<ul class="nav nav-tabs sous_onglet">';
        
        if ($ficheDA) {
            $html.= '   
                <li id="onglet_Article" class="'.($onglet == 'Article' ? 'active' : '').'"><a data-toggle="tab" href="#Article">'.$trad->t('Article').'<span id="nb_affectation_ligne" class="nb_affectation"></span></a></li>
                <li id="onglet_Detail" class="'.($onglet == 'Detail' ? 'active' : '').'"><a data-toggle="tab" href="#Detail">'.$trad->t('Détail').'</a></li>
                <li id="onglet_Fournisseur" class="'.($onglet == 'Fournisseur' ? 'active' : '').'"><a data-toggle="tab" href="#Fournisseur">'.$trad->t('Fournisseur').'</a></li>
                <li id="onglet_Info" class="'.($onglet == 'Info' ? 'active' : '').'"><a data-toggle="tab" href="#Info">'.$trad->t('Info').'</a></li>
                <li id="onglet_Livraison" class="'.($onglet == 'Livraison' ? 'active' : '').'"><a data-toggle="tab" href="#Livraison">'.$trad->t('Livraison').'</a></li>
                <li id="onglet_CondPart" class="'.($onglet == 'CondPart' ? 'active' : '').'"><a data-toggle="tab" href="#CondPart">'.$trad->t('Cond. Part.').'</a></li>
                <li id="onglet_Supp" class="'.($onglet == 'Supp' ? 'active' : '').'"><a data-toggle="tab" href="#Supp">'.$trad->t('Chps supp.').'</a></li>
                <li id="onglet_Clauses" class="'.($onglet == 'Clauses' ? 'active' : '').'"><a data-toggle="tab" href="#Clauses">'.$trad->t('Clauses').'</a></li>

                <li id="onglet_DivModulable" style="display:none"><a data-toggle="tab" href="#DivModulable" class="ephemere"></a></li>
                <li id="onglet_DivModulableCreation" style="display:none"><a data-toggle="tab" href="#DivModulableCreation" class="ephemere"></a></li>';
                // <li id="onglet_DocRat"><a data-toggle="tab" href="#DocRat">'.$trad->t('Doc. Ratt.').'</a></li>
                // <li id="onglet_PJ"><a data-toggle="tab" href="#PJ">'.$trad->t('PJ').'</a></li>
        } elseif ($ongletFicheDA) {
            $html .= "  
                <li><a onClick=\"window.location.href = '".$this->router->generateUri('DemandeAchat.ModificationDemandeAchat.index', ['idDA' => $id, 'mode' => $mode, 'MODULE' => $MODULE, 'onglet' => 'Article'])."'\">".$trad->t('Article')."</a></li>
                <li><a onClick=\"window.location.href = '".$this->router->generateUri('DemandeAchat.ModificationDemandeAchat.index', ['idDA' => $id, 'mode' => $mode, 'MODULE' => $MODULE, 'onglet' => 'Detail'])."'\">".$trad->t('Détail')."</a></li>
                <li><a onClick=\"window.location.href = '".$this->router->generateUri('DemandeAchat.ModificationDemandeAchat.index', ['idDA' => $id, 'mode' => $mode, 'MODULE' => $MODULE, 'onglet' => 'Fournisseur'])."'\">".$trad->t('Fournisseur')."</a></li>
                <li><a onClick=\"window.location.href = '".$this->router->generateUri('DemandeAchat.ModificationDemandeAchat.index', ['idDA' => $id, 'mode' => $mode, 'MODULE' => $MODULE, 'onglet' => 'Info'])."'\">".$trad->t('Info')."</a></li>
                <li><a onClick=\"window.location.href = '".$this->router->generateUri('DemandeAchat.ModificationDemandeAchat.index', ['idDA' => $id, 'mode' => $mode, 'MODULE' => $MODULE, 'onglet' => 'Livraison'])."'\">".$trad->t('Livraison')."</a></li>
                <li><a onClick=\"window.location.href = '".$this->router->generateUri('DemandeAchat.ModificationDemandeAchat.index', ['idDA' => $id, 'mode' => $mode, 'MODULE' => $MODULE, 'onglet' => 'CondPart'])."'\">".$trad->t('Cond. Part.')."</a></li>
                <li><a onClick=\"window.location.href = '".$this->router->generateUri('DemandeAchat.ModificationDemandeAchat.index', ['idDA' => $id, 'mode' => $mode, 'MODULE' => $MODULE, 'onglet' => 'Supp'])."'\">".$trad->t('Chps supp.')."</a></li>
                <li><a onClick=\"window.location.href = '".$this->router->generateUri('DemandeAchat.ModificationDemandeAchat.index', ['idDA' => $id, 'mode' => $mode, 'MODULE' => $MODULE, 'onglet' => 'Clauses'])."'\">".$trad->t('Clauses')."</a></li>";
                // <li><a onClick=\"window.location.href = '".$pathURL."'\">".$trad->t('Doc. Ratt.')."</a></li>";
                // <li><a onClick=\"window.location.href = '".$pathURL."'\">".$trad->t('PJ')."</a></li>";
        }
        
        if ($onglet == 'ModifGroupee') {
            $html .= '  <li class="active"><a>'.$trad->t('Modif. Lignes').'</a></li>';
        }
        if ($onglet == 'ModifPrix') {
            $html .= '  <li class="active"><a>'.$trad->t('Modif. Prix').'</a></li>';
        }
        

        $html .='</ul>';

        return $html;
    }
    
    // phpcs:ignore
    public function blockEnteteDA($id, $mode)
    {
        $trad = $this->trad;
        $creationDARepo = new CreationDemandeAchat($this->pdo);
        $DaEntet = $creationDARepo->blockEnteteDA($id);

        $typeChiffExec = [
            'E' => $trad->t('Exécution'),
            'C' => $trad->t('Chiffrage'),
        ];
        
        $html =
        '<div class="block_edition">
            <div class="titre_block">
                '.$trad->t('Demande d\'achat').'
            </div>
            <div class="colonne3">
                <div class="informations">
                    <p>
                        <span class="champs_label">'.$trad->t('Demande d\'achat').'</span>
                        <span class="resultat" id="idDA">'.$id.'</span>
                    </p>
                    <p>
                        <span class="champs_label">'.$trad->t('Société').'</span>
                        <span class="resultat">'.$DaEntet['libelleSociete'].($DaEntet['CODE_STE'] != '' ? ' ('.$DaEntet['CODE_STE'].')' : '').'</span>
                    </p>
                </div>
            </div>
            <div class="colonne3">
                <div class="informations">                   	    	
                    <p>
                        <span class="champs_label">'.$trad->t('Chiffrage/Exécution').'</span>
                        <span class="resultat">'.$typeChiffExec[$DaEntet['CHIF_EXEC']].'</span>
                    </p>';
        if ($mode != 'Creation') {
            $html .=
            '<p>
                        <span class="champs_label">'.$trad->t('Type de DA').'</span>
                        <span class="resultat">'.$DaEntet['libelleTypeDoc'].($DaEntet['TYP_DOC'] != '' ? ' ('.$DaEntet['TYP_DOC'].')' : '').'</span>
                    </p>';
        }
            $html .=
                '</div>
            </div>
            <div class="colonne3 last">
                <div class="informations">
                    <p>
                        <span class="champs_label">'.$trad->t('Montant HT').'</span>
                        <span class="resultat"><span id="montantHT">'.number_format((float)$DaEntet['TOTAL_DA'], 2, '.', ' ').'</span> <span class="deviseMontant">'.$DaEntet['DEVISE'].'</span></span>
                    </p>
                    <p>
                        <span class="champs_label">'.$trad->t('Montant TTC').'</span>
                        <span class="resultat"><span id="montantTTC">'.number_format((float)$DaEntet['TOTAL_DA_TTC'], 2, '.', ' ').'</span> <span class="deviseMontant">'.$DaEntet['DEVISE'].'</span></span>
                    </p>
                </div>
            </div>
        </div>';

        return $html;
    }
    
    // phpcs:ignore
    public function bouton_modifDA($id, $MODULE, $SOUSMODULE = '')
    {
        $trad = $this->trad;
        $button = new ButtonExtention($this->router, $this->pdo, $this->contenaire);

        if ($SOUSMODULE == '') {
            $pathValidationDetail = $this->router->generateUri('DemandeAchat.ModificationDemandeAchat.validationDetail', ['idDA' => $id, 'MODULE' => $MODULE]);
        } else {
            $pathValidationDetail = $this->router->generateUri('DemandeAchat.ModificationDemandeAchat.validationDetail', ['idDA' => $id, 'MODULE' => $MODULE, 'SOUSMODULE' => $SOUSMODULE]);
        }

        $valideButton = $button->Button($trad->t('Valider'), true, '', "validationDA('".$pathValidationDetail."', '".$this->router->generateUri('DemandeAchat.ModificationLigneDemandeAchat.validationLigne', ['idDA' => $id])."', '".$this->router->generateUri('DemandeAchat.ModificationClauseDemandeAchat.validationLigne', ['idDA' => $id])."');", [], false, '', false, 'valider');

        switch ($MODULE) {
            case 'SignatureDA':
                $pathAnnuler = $this->router->generateUri('Signature.SignatureDa.listeDoc');
                break;
            case 'DelegationSignatureDA':
                $pathAnnuler = $this->router->generateUri('Signature.DelegationSignature.delegation', ['MODULE' => 'demandeAchat']);
                break;
            default:
                $pathAnnuler = $this->router->generateUri('DemandeAchat.GestionDemandeAchat.index');
                break;
        }
        $cancelButton = $button->Button($trad->t('Annuler'), false, $pathAnnuler);
        
        $script =
        "<script>
        function validationDA(path, pathValidationLigne, pathValidationClause)
        {
            var modeModifActif = $('#idLigneModeModif').val();
            var modeModifClauseActif = $('#idClauseModeModif').val();
            if(modeModifActif)
            {
                validationLigne(pathValidationLigne, modeModifActif, 'validationDA', path, pathValidationClause);
            }
            else if(modeModifClauseActif)
            {
                validationClause(pathValidationClause, modeModifActif, 'validationDA', path);
            }
            else
            {
                activeLoader();
                $.ajax({
                    url: path,
                    type: 'POST',
                    dataType: 'JSON',
                    data: $('#form_creationDA').serialize(),
                    success: function(data) {
                        if(data.statut == 'redirect'){
                            redirectJSWithPost(data.path);
                        }
                    }, 
                    error: function (data){
                        desactiveLoader();
                        $(\"#modal-content\").addClass(\"modal_small\");
                        $(\"#modal-body\").html(data.responseText);
                        activePopup();
                    } 
                });
            }
        }
        </script>";

        $html = $valideButton.$cancelButton.$script;

        return $html;
    }

    public function liAl(string $pathLi, string $params = '', string $classAl = '', string $libelleAl = '') : string
    {
        $html = "
        <script>
            function redirect(url)
            {
                redirectJSWithPost( url ,'', 'GET');
            }
        </script>";

        $html .= '<li onclick ="redirect(\''.$pathLi.'\')">';

        $html .= '<a class="'.$classAl.'">'.$libelleAl.'</a></li>';
        
        return $html;
    }
}
