<?php
namespace Modules\Consultation\Controller;

use Helpers\Outil\ArrayHelper;
use Modules\Consultation\Service\ConsultationPanierService;
use Modules\Consultation\Service\CreatePanierService;
use Modules\Consultation\Service\EnvoieExcelService;
use Modules\GlobalApplication\Repository\Societe;
use Skeleton\Controller\Controller;
use Modules\Consultation\Repository\GestionConsultation;
use Helpers\Trad\Trad;
use Helpers\Ariane\Ariane;
use Entity\Model\AoEntet;
use Modules\Consultation\Repository\Consultation;
use GuzzleHttp\Psr7\Response;
use Helpers\Outil\Mail;
use Entity\Model\Hastutil;
use Modules\Consultation\Repository\AoEvent;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Entity\Model\Docatt;
use Entity\Model\AoFour;
use Entity\Model\AoLigne;
use Modules\Consultation\Service\ConsultationService;
use Helpers\Fichier\Fichier;
use Entity\Model\Contfour;
use Entity\Model\ContGF;
use Helpers\Validator\Validator;
use Helpers\Parametres\Constante;
use Entity\Model\AoQstQ;
use Entity\Model\AoDocAttendus;
use Entity\Model\AoPijo;
use Entity\Model\AoClaus;
use Modules\Consultation\Repository\Reponse;
use Helpers\ChargeDocument\ChargeDocument;
use Helpers\Outil\Outils;
use Helpers\Outil\Date;
use Entity\Model\AoExcFofo;
use Entity\Model\Fourniss;
use Helpers\Securite\Securite;
use Modules\Ajax\Repository\Listes;
use Modules\Consultation\MenuContextuel\GestionMenuContextuel;
use Modules\Consultation\Repository\ExportExcel;
use Modules\Consultation\Service\ExportExcelService;

class GestionConsultationController extends Controller
{
    public function indexAction() : string
    {
        $post = $this->request->getParsedBody();
        $filtre = $this->request->getAttribute('filtre');

        $listeAO = [];
        if (isset($post['listeAO'])) {
            $listeAO = unserialize($post['listeAO'], ["allowed_classes" => false]);
            unset($post['listeAO']);
        }
        if (!$post) {
            $post['tri_NO_AO'] = 'desc';

            if ($filtre == 'A_ENVOYER') {
                $post['filter_STATUT'] = 'ENVO';
                $post['ACHETEUR'] = $_SESSION["Session_Login"];
            } elseif ($filtre == 'MES_CONSUTATION') {
                $post['filter_STATUT'] = 'PRCO';
                $post['ACHETEUR'] = $_SESSION["Session_Login"];
            } elseif ($filtre == 'NON_CLOS') {
                $post['filter_STATUT'] = 'NON_CLOS';
            } else {
                $post['ACHETEUR'] = $_SESSION["Session_Login"];
            }
        }

        $trad = $this->getTranslationService();

        if ($listeAO) {
            $post['recharge_'] = $trad->t('Consultations créées');
        } else {
            $listeAO = [];
        }

        $listeStatut = [
            ''     => $trad->t('Toutes les consultations'),
            'PREP' => $trad->t('Préparation'),
            'VALC' => $trad->t('Validation en cours'),
            'PRCO' => $trad->t('En préparation ou en cours'),
            'ENCO' => $trad->t('En cours'),
            'ENVO' => $trad->t('A envoyer'),
            'VALF' => $trad->t('Validation choix fournisseur'),
            'TERM'  => $trad->t('Terminé'),
            'NON_CLOS' => $trad->t('Non closes'),
        ];

        $droit = [
            'HA_AO_ADM' => Roles::droitsUtilisateur($this->pdo, 'HA_AO_ADM', $_SESSION["Session_Login"]),
            'HA_AO_CMV' => Roles::droitsUtilisateur($this->pdo, 'HA_AO_CMV', $_SESSION["Session_Login"]),
            'HA_AO_TRA' => Roles::droitsUtilisateur($this->pdo, 'HA_AO_TRA', $_SESSION["Session_Login"]),
            'HA_AO_SUP' => Roles::droitsUtilisateur($this->pdo, 'HA_AO_SUP', $_SESSION["Session_Login"]),
        ];
        
        $gestionAO_REPO = new GestionConsultation($this->pdo);
        $listeConsultation = $gestionAO_REPO->listeConsultation($post, $listeAO);

        $menuContextuel = new GestionMenuContextuel($this->pdo, $this->router, $trad, $droit);
        foreach ($listeConsultation as &$consult) {
            $consult['menuContextuel'] = $menuContextuel->generate($consult);
        }

        Ariane::generate(0, $trad->t('Gestion Consultations'), $post, count($listeConsultation));

        $paginator = new \Helpers\Pagination\Paginator();
        $infopagination = $paginator->generate($listeConsultation, 0, $post, $this->renderer);

        $filtreAvance                   = new \Helpers\Filter\FiltreAvance\GeneratorCs($post, 'AO_ENTET', 'NO_AO', $this->pdo, $this->getTranslationService());
        $filtreAvance->setFiltre('DTE_AO', 'date', $trad->t('Date de création'));
        $filtreAvance->setFiltre('DTE_VALID_AO', 'date', $trad->t('Date de validation'));
        $filtreAvance->setFiltre('EMETTEUR', 'liste', $trad->t('Centre emetteur'), '', 'Ajax.liste.centreEmetteur', 'Centre');
        $filtreAvance->setFiltre('CODE_FAM', 'liste', $trad->t('Famille'), '', 'Ajax.liste.famille', 'famille');
        $filtreAvance->setFiltre('COD_LNG', 'liste', $trad->t('Langue'), '', 'Ajax.liste.langues', 'langues');
        $filtreAvance->setFiltre('PRESCRIPTEUR', 'liste', $trad->t('Prescripteur'), '', 'Ajax.liste.utilisateur', 'hastutil');
        $filtreAvance->setFiltre('ACH', 'liste', $trad->t('Acheteur'), '', 'Ajax.liste.utilisateur', 'hastutil');
        $filtreAvance->setFiltre('DEL_REP', 'date', $trad->t('Réponse attendue le'));

        $filtreAvance->setFiltre('OBJET_AO', 'text', $trad->t('Objet'));

        $filtreAvance->setFiltre('VARIANTE', 'bool', $trad->t('Variante autorisée ?'), '', null, null, 'bdd');
        $filtreAvance->setFiltre('ACC_CONF', 'bool', $trad->t('Accord de confidentialité ?'), '', null, null, 'bdd');
        $filtreAvance->setFiltre('REPDEV', 'bool', $trad->t('Réponse obligatoire dans la devise de la consultation ?'), '', null, null, 'bdd');

        $filtreAvance->setFiltre('ARTICLE', 'liste', $trad->t('Article'), '', 'Ajax.liste.articles', 'articles', null, true);
        

        $listeTypeConsultation = [
            ''  => $trad->t('Toutes les consultations'),
            'I' => $trad->t('RFI'),
            'Q' => $trad->t('RFQ'),
        ];
                
        if (array_key_exists('DA_CreatModif', $_SESSION) && $_SESSION['DA_CreatModif'] ||Roles::GetALL()) {
            $P2PActive = 1;
        } else {
            $P2PActive =0;
        }

        $listeRepo = new Listes($this->pdo);
        $listeGrpSoc = $listeRepo->findGroupedCompanies();

        return $this->renderer->render('@Consultation/GestionConsultation/index', [
            'menuActive' => $_SESSION['typeMenu'] == 'P2P'? 'eproc':'Consultations',
            'menuLeft' => 'gestionAO',
            'infoPagination'    => $infopagination,
            'listeConsultation' => $listeConsultation,
            'user' => (new Hastutil($this->pdo))->find($_SESSION['Session_Login']),
            'post' => $post,
            'listeStatut' => $listeStatut,
            'filtreAvance'      => $filtreAvance->getFiltres(),
            'initFiltreAvance'  => $filtreAvance->getInit(),
            'listeTypeConsultation' => $listeTypeConsultation,
            'listeAO' => serialize($listeAO),
            'droit' => $droit,
            'P2PActive'=> $P2PActive,
            'listeGrpSoc' => $listeGrpSoc,
            'container' => $this->contenaire,
        ]);
    }

    public function ajaxDetailEnteteAction() : string
    {
        $idAO = $this->request->getAttribute('idAO');

        $gestionAO_REPO = new GestionConsultation($this->pdo);
        $ligneConsultation = $gestionAO_REPO->listeLigneConsultation($idAO);

        return $this->renderer->render('@Consultation/GestionConsultation/detailConsultation', [
            'listeLigneConsultation' => $ligneConsultation,
        ]);
    }

    public function popupListeFournisseurAction() : string
    {
        $idAO = $this->request->getAttribute('idAO');

        $trad = $this->getTranslationService();

        $gestionAO_REPO = new GestionConsultation($this->pdo);
        $listeFourniss = $gestionAO_REPO->listeFournisseurConsultation($idAO);

        return $this->renderer->render('@Consultation/GestionConsultation/popupListeFournisseur', [
            'listeFourniss' => $listeFourniss,
            ]);
    }

    public function popupTransfereAction() : string
    {
        $idAO = $this->request->getAttribute('idAO');

        $aoEntetEntity = new AoEntet($this->pdo);
        $infoEntete = $aoEntetEntity->find($idAO);

        $consultation = new Consultation($this->pdo);
        $listeAcheteurTMP = $consultation->getListeAcheteurForTransfere($infoEntete['TYPE_SG'], $infoEntete['CODE_STE']);

        if (!$listeAcheteurTMP) {
            return $this->renderer->render('@popup-erreur/information', [
                'message' => $this->getTranslationService()->t('Il n\'y a pas d\'acheteur pouvant recevoir cette consultation.'),
            ]);
        }

        $listeAcheteur = [];
        foreach ($listeAcheteurTMP as $acheteur) {
            if ($acheteur['CODE'] != $_SESSION["Session_Login"]) {
                $listeAcheteur[$acheteur['CODE']] = $acheteur['NOM'];
            }
        }

        return $this->renderer->render('@Consultation/GestionConsultation/popuptransmettre', [
            'listeAcheteur' => $listeAcheteur,
            'idAO' => $idAO,
        ]);
    }

    public function ajaxTransfereAction()
    {
        $idAO = $this->request->getAttribute('idAO');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $aoEntete = new AoEntet($this->pdo);
        $consultation = $aoEntete->find($idAO);

        $newProprio = $post['DESTINATAIRE'];
        $oldPoprio = $consultation['ACH'];

        $hastutilEntity = new Hastutil($this->pdo);

        $infoProprio =  $hastutilEntity->find($newProprio);
        $infoOldProprio =  $hastutilEntity->find($oldPoprio);

        $message = Trad::strbuild(
            $trad->t('Consultation transmise de @1@ à @2@'),
            $infoOldProprio['NOM'],
            $infoProprio['NOM']
        );

        $aoEvent = new AoEvent($this->pdo);
        $aoEvent->rqInsertEvent($idAO, 'TRA', $message);

        $aoEntete->update(['ACH' => $newProprio], $idAO);

        $listeCS = (new ChampSupp($this->pdo))->getInfoValueCs('AO_ENTET', ChampSupp::autoCompletCodeEnr($idAO));

        Mail::generateMail(
            $this->pdo,
            $this->getTranslationService(),
            $infoProprio['EMAIL'],
            'AO_TRANSFERT',
            $infoProprio['COD_LNG'],
            [
                'NAO'       => $idAO,
                'TITREAO'   => Sql::getMemo($this->pdo, $consultation['NM_TITRE']),
                'OBJETAO'   => $consultation['OBJET_AO'],
                'NOM_ACH'   => $infoOldProprio['NOM'],
                'NOMACH'    => $infoOldProprio['NOM'],
            ],
            $listeCS
        );

        return new Response(200);
    }

    public function ajaxValiderAction()
    {
        $idAO = $this->request->getAttribute('idAO');
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $aoEntete = new AoEntet($this->pdo);
        $aoFour = new AoFour($this->pdo);
        $aoLigne = new AoLigne($this->pdo);
        $docAttEntity = new Docatt($this->pdo);
        $aoqst = new AoQstQ($this->pdo);
        $aoDocInt = new AoDocAttendus($this->pdo);
        $aoPijo = new AoPijo($this->pdo);
        $aoClause = new AoClaus($this->pdo);

        $consultation = $aoEntete->find($idAO);
        $listeFrs = $aoFour->findAll(['NO_AO' => $idAO]);
        $listeLigne = $aoLigne->findAll(['NO_AO' => $idAO]);

        $listeQst = $aoqst->findAll(['NO_AO' => $idAO]);
        $listeDocInt = $aoDocInt->findAll(['NO_AO' => $idAO]);
        $listePj = $aoPijo->findAll(['NO_AO' => $idAO]);
        $listeClause = $aoClause->findAll(['NO_AO' => $idAO]);

        $messageBloquant = '';
        $messageNonBloquant = '';

        if (Sql::boolSql($consultation['ACC_CONF']) == true) {
            $infoDoc = $docAttEntity->find(['NO_DA' => 'AO_ENTET', 'COD_ENR' => str_pad($idAO, 9, '0', STR_PAD_LEFT), 'NO_ORDRE' => $consultation['ACC_CONF_NODOC']]);

            if (!$infoDoc) {
                $messageBloquant .= '<br />'.$trad->t('L\'accord de confidentialité n\'est pas renseigné.');
            }
        }

        if (empty($listeLigne) && Sql::boolSql($consultation['COMP_LIGNE']) == true) {
            $messageBloquant .= '<br />'.$trad->t('La consultation n\'a aucun poste');
        }
        if (empty($listeFrs)) {
            if (sql::boolSql($consultation['AO_PUBLIC']) == true) {
                $messageNonBloquant .= '<br />'.$trad->t('Il n\'y a pas de fournisseur pour cette consultation');
            } else {
                $messageBloquant .= '<br />'.$trad->t('Il faut au moins 1 fournisseur pour une consultation non "publique".');
            }
        }

        if (!$listeQst && !$listeDocInt && !$listePj && !$listeLigne && !$listeClause) {
            if ($consultation['RFI_Q'] == 'I') {
                $messageBloquant .= '<br />'.$trad->t('Il doit y avoir au moins une question, un document interne, un document attendu, une clause ou une pièce jointe pour une consultation.');
            }
        }

        /*$paramDoc = sql::paravrac($this->pdo, 'PARAMGEN', 'CTRL_DOC_ATT_FOURN_SUR_AO');
        $explodeParamDoc = explode('|', $paramDoc);*/

        if ($messageBloquant == '' && $messageNonBloquant == '') {
            $consultationService = new ConsultationService($this->pdo, $this->getTranslationService());
            $consultationService->validateConsultation($idAO);

            return new Response(200);
        } else {
            return new Response(443, [], $this->renderer->render('@popup-erreur/erreurAlerteEtAvertissement', [
                'params' => [
                    'statut' =>  $messageBloquant? 'B':'O',
                    'alerte' => $messageBloquant,
                    'avertissement' => $messageNonBloquant,
                ],
                'pathURL' => $this->router->generateUri('Consultation.GestionConsultation.confirmationValidate', ['idAO' => $idAO]),
                'entity' => $post['entity'],
                'div' => $post['div'],
                'form' => $post['form'],
            ]));
        }
    }

    public function confirmationValidateAction()
    {
        $idAO = $this->request->getAttribute('idAO');

        $consultationService = new ConsultationService($this->pdo, $this->getTranslationService());
        $consultationService->validateConsultation($idAO);

        return new Response(200);
    }


    public function ajaxDevaliserAction()
    {
        $idAO = $this->request->getAttribute('idAO');

        $aoEvent = new AoEvent($this->pdo);
        $aoEvent->rqInsertEventAO($idAO, 'DEV');

        $AoEntet = new AoEntet($this->pdo);
        $AoEntet->update([
            'DTE_VALID_AO' => '00000000',
            'EVE_VALPREP' => '0',
        ], $idAO);

        $aoFour = new AoFour($this->pdo);
        $aoFour->update(['EVE_IMP' => '0'], ['NO_AO' => $idAO]);

        return new Response(200);
    }

    public function ajaxDevaliserSelectFrsAction()
    {
        $idAO = $this->request->getAttribute('idAO');

        $aoEvent = new AoEvent($this->pdo);
        $aoEvent->rqInsertEventAO($idAO, 'DCH');

        $AoEntet = new AoEntet($this->pdo);
        $AoEntet->update([
            'VALCHXFOU' => '00000000',
        ], $idAO);


        return new Response(200);
    }

    public function ajaxImpressionAction() : string
    {
        $idAO = $this->request->getAttribute('idAO');
        $tousFournisseur =  $this->request->getAttribute('tousFournisseur'); //Tout = T, Fournisseur = U
        $typeFG =  $this->request->getAttribute('typeFG');
        $codeFrs =  $this->request->getAttribute('codeFrs');

        $consultationWSDL = new \Modules\Consultation\WebService\Consultation();
        $xmlResult = $consultationWSDL->impressionConsultation($idAO, false, $tousFournisseur, $typeFG, $codeFrs);


        $reponse = new \SimpleXMLElement($xmlResult->responseData);

        $url = Fichier::URLDownload($reponse->FichierPDF);

        $message = Fichier::UploadClient($url, $reponse->FichierPDF);

        return $message;
    }

    public function envoyerAction() : string
    {
        $idAO = $this->request->getAttribute('idAO');

        $trad = $this->getTranslationService();

        $listeType = [
            'M' => $trad->t('Marché'),
            'P' => $trad->t('Ponctuelle')
        ];

        $listeReponse = [
            'T' => $trad->t('Tous les fournisseurs'),
            'U' => $trad->t('Un fournisseur'),
        ];

        $aoEntet = new AoEntet($this->pdo);
        $consultation = $aoEntet->find($idAO);

        $AoExcFofo = new AoExcFofo($this->pdo);
        $paramExcelDefaut = $AoExcFofo->find(['SOCIETE' => $consultation['CODE_STE'], 'CTRE' => $consultation['EMETTEUR'], 'CODE_FOU' => '']);
        if (!$paramExcelDefaut) {
            $paramExcelDefaut = $AoExcFofo->find(['SOCIETE' => $consultation['CODE_STE'], 'CTRE' => '', 'CODE_FOU' => '']);

            if (!$paramExcelDefaut) {
                $paramExcelDefaut = $AoExcFofo->find(['SOCIETE' => '', 'CTRE' => '', 'CODE_FOU' => '']);
            }
        }

        $aoEvent = new AoEvent($this->pdo);
        $AOEventCreat = $aoEvent->getNameCreate($idAO);

        $GestionConsultationRepo = new GestionConsultation($this->pdo);
        $listeFrs = $GestionConsultationRepo->getListeFourniss($idAO);

        $contFour = new Contfour($this->pdo);
        $contGF = new ContGF($this->pdo);
        foreach ($listeFrs as &$frs) {
            $listeContact = [];
            $listeContact[''] = $trad->t('Choisir un contact');

            // on récupère le contact défini dans AO_FOUR si l'email est remplis.
            if ($frs['EMAILCONT'] != '') {
                $listeContact[$frs['EMAILCONT']] = trim($frs['NOM_CTCT']) == '' ? $trad->t('Inconnu'):$frs['NOM_CTCT'];
            }

            if ($frs['TYPE_FG'] == 'F') {
                // TODO : merge query
                //si le fournisseur est géré sur OXA.LINK on vérifie qu'il y ai au moins 1 contact oxalink d'actif.
                if (Sql::boolSql($frs['GEREPORTAIL']) == true && $frs['ctcOxalinkActif'] != '0') {
                    $listeContactTMP = $GestionConsultationRepo->getListeUserOxalinkActif($frs['CODE_FOU']);
                } else {
                    $listeContactTMP = $contFour->fetchAll(['NOM', 'EMAIL'], ['filter_egal_CODE_FOU' => $frs['CODE_FOU'], 'filter_egal_VIBOXAP' => 'T']);
                }

                foreach ($listeContactTMP as $ctc) {
                    if ($ctc['EMAIL'] != '') {
                        $listeContact[$ctc['EMAIL']] = $ctc['NOM'];
                    }
                }
            } else {
                $listeContactTMP = $contGF->fetchAll(['NOM', 'EMAIL'], ['filter_egal_CODE_GF' => $frs['CODE_FOU']]);

                foreach ($listeContactTMP as $ctc) {
                    if ($ctc['EMAIL'] != '') {
                        $listeContact[$ctc['EMAIL']] = $ctc['NOM'];
                    }
                }
            }
            
            $paramExcelByfrs = $AoExcFofo->find(['SOCIETE' => $consultation['CODE_STE'], 'CTRE' => $consultation['EMETTEUR'], 'CODE_FOU' => $frs['CODE_FOU']]);
            
            $frs['listeContact'] = $listeContact;
            if ($paramExcelByfrs) {
                $frs['typeFormatExcel'] = $paramExcelByfrs['CODEFORM'];
                $frs['versionFormat'] = $paramExcelByfrs['VERSFORM'];
            } else {
                $frs['typeFormatExcel'] = $paramExcelDefaut['CODEFORM'];
                $frs['versionFormat'] = $paramExcelDefaut['VERSFORM'];
            }
        }

        Ariane::generate(3, $trad->t('Envoyer consultation'));

        return $this->renderer->render('@Consultation/GestionConsultation/envoyer', [
            'idAO' => $idAO,
            'menuActive' => $_SESSION['typeMenu'] == 'P2P'? 'eproc':'Consultations',
            'menuLeft' => 'gestionAO',
            'listeType' => $listeType,
            'listeReponse' => $listeReponse,
            'listeFrs' => $listeFrs,
            'consultation' => $consultation,
            'AOEventCreat' => $AOEventCreat,
        ]);
    }

    public function ajaxEnvoieAction()
    {
        $idAO = $this->request->getAttribute('idAO');
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $validator = $this->createValidator();

        $validator->isCheck($post['formatExcel']);
        $validator->isCheck($post['parMail']);

        $listeFrs = [];
        $listeFrsAcc = [];
        $listeExcel = [];
        /* On récupere les informations des fournisseurs, si ils ont selectionné ou pas etc.. */
        $aoExFofo = new AoExcFofo($this->pdo);

        foreach (array_keys($post) as $key) {
            if (strpos($key, 'ligneFrs') === 0) {
                $infoFrs = substr($key, 8);
                $explode = explode(Constante::spliter, $infoFrs);

                $validator->isCheck($post['parMail'.$explode[0].constante::spliter.$explode[1]]);
                $validator->isCheck($post['formatExcel'.$explode[0].constante::spliter.$explode[1]]);

                if ($post['parMail'.$explode[0].constante::spliter.$explode[1]]) {
                    $validator->adresseMail($trad->t('Email'), $post['email'.$explode[0].constante::spliter.$explode[1]], 1, 120);
                }

                if ($post['formatExcel'.$explode[0].constante::spliter.$explode[1]]) {
                    $splitFormat = explode('|', $post['typeFormatExcel'.$explode[0].constante::spliter.$explode[1]]);

                    $testFileExist = false;
                    $formatExcel = $aoExFofo->find(['CODEFORM' => $splitFormat[0], 'VERSFORM' => $splitFormat[1]]);
                    if ($formatExcel) {
                        $fileExcel = explode('|', $formatExcel['CHEMFORM']);
                        $infoExcel = pathinfo($fileExcel[0]);

                        $testFileExist = file_exists($_SESSION['chemin_pj'].'\\'.$fileExcel[1].'.'.$infoExcel['extension']);
                    }
                    
                    $validator->isFalse($testFileExist, Trad::strBuild($trad->t('Le fichier du format @1@ version @2@ est introuvable.'), $splitFormat[0], $splitFormat[1]));
                } else {
                    $splitFormat = [];
                }

                $infoLigne = [
                    'ACC_CONF' => $post['ACC_CONF'.$explode[0].constante::spliter.$explode[1]],
                    'CODE_FOU' =>  $explode[1],
                    'TYPE_FG' =>  $explode[0],
                    'parMail' => $post['parMail'.$explode[0].constante::spliter.$explode[1]],
                    'formatExcel' => $post['formatExcel'.$explode[0].constante::spliter.$explode[1]],
                    'email' => $post['email'.$explode[0].constante::spliter.$explode[1]],
                    'typeFormatExcel' => $splitFormat[0]??'',
                    'versionFormat' => $splitFormat[1]??'',
                ];

                if ($post['ACC_CONF'.$explode[0].constante::spliter.$explode[1]] == '1') {
                    $listeFrsAcc[$explode[1]] = $infoLigne;
                } elseif ($post['formatExcel'.$explode[0].constante::spliter.$explode[1]]) {
                    $listeExcel[$explode[1]] = $infoLigne;
                } else {
                    $listeFrs[$explode[1]] = $infoLigne;
                }
            }
        }

        $listeUrl = [];
        if ($validator->isValid()) {
            $chargeDoc = new ChargeDocument();

            $aoEntet = new AoEntet($this->pdo);
            $consultation = $aoEntet->find($idAO);

            $hastutilEntity = new Hastutil($this->pdo);
            $user = $hastutilEntity->find($consultation['ACH']);

            /* Si un accord de confidentialité à été selectionné */
            if (Sql::boolSql($consultation['ACC_CONF']) == true) {
                /* On duplique dans TMP pour chaque fournisseur selectionné l'accord de confidentialité, pour l'envoie par mail ou pour chaque l'afficher a l'utilisateur */
                $docAtt = new Docatt($this->pdo);
                $idDoc = str_pad($idAO, 9, '0', STR_PAD_LEFT);

                $infoDoc = $docAtt->find(['NO_DA' => 'AO_ENTET', 'COD_ENR' => $idDoc, 'NO_ORDRE' => $consultation['ACC_CONF_NODOC']]);
                $path_info = pathinfo($infoDoc['NOM_FIC']);

                foreach ($listeFrsAcc as &$frs) {
                    $new_name = 'Consult_'.$idAO.'_'.$frs['CODE_FOU'].'_'.str_replace('t| ', '', $trad->t('Accord de Confidentialité')).'.' . $path_info['extension'];

                    $oldFic = $_SESSION['chemin_pj'].$infoDoc['NOM_FIC'];
                    $newFic = $_SESSION['dir_tmp'].$new_name;

                    copy($oldFic, $newFic);

                    $frs['pj'] = $new_name;
                    $frs['sourcePJ'] = $newFic;

                    if ($frs['parMail']) {
                        $infoMail = [
                            'NAO'       => $idAO,
                            'TITREAO'   => sql::getMemo($this->pdo, $consultation['NM_TITRE']),
                            'OBJETAO'   => $consultation['OBJET_AO'],
                            'NOM_ACH'   => $user['NOM'],
                            'RS_SOC'    => Outils::convertLibelleGlobal($this->pdo, $consultation['TYPE_SG']=='S'? 'Societe':'GrpSociete.php.php', '', $consultation['CODE_STE']),
                            'URL'       => Sql::paravrac($this->pdo, 'PF_OXALINK', 'URLACCESOXALINK')
                        ];

                        $consultRepo = new Consultation($this->pdo);
                        $infoFrs = $consultRepo->getFrsOxalink($idAO, $frs['TYPE_FG'], $frs['CODE_FOU']);

                        if (sql::boolSql($infoFrs['GEREPORTAIL']) == true && $infoFrs['ctcOxalinkActif']) {
                            Mail::generateMail(
                                $this->pdo,
                                $this->getTranslationService(),
                                $frs['email'],
                                'EXT_FOU_ACCCONF_LINK',
                                $infoFrs['COD_LNG'],
                                $infoMail,
                                []
                            );
                        } else {
                            Mail::generateMail(
                                $this->pdo,
                                $this->getTranslationService(),
                                $frs['email'],
                                'AO_FOU_ACCORD_CONF',
                                $infoFrs['COD_LNG'],
                                $infoMail,
                                [],
                                [0 => ($frs['sourcePJ'])]
                            );
                        }
                    } else {
                        $url = $frs['pj'];
                        $param = '?uniq=' . Sql::guidGenerate();
                        $param .= '&token=' . password_hash($_SESSION['Session_Login'].session_id(), PASSWORD_DEFAULT);
                        $urlJS = $this->base. 'charge_document.php'.$param.'&EmplacementFichier=tmp&UrlFichier='.$url;

                        $listeUrl [] = $urlJS;
                    }

                    $aoEvent = new AoEvent($this->pdo);
                    $aoEvent->rqInsertEventAO($idAO, 'ENV', $trad->t('Demande de signature de l\'accord de confidentialité'), $frs['CODE_FOU'], $frs['TYPE_FG']);

                    $aoDaRep = new AoFour($this->pdo);
                    $aoDaRep->update([
                        'FIC_ACC_CONF_SIGNE' => '',
                    ], ['NO_AO' => $idAO, 'CODE_FOU' => $frs['CODE_FOU'], 'TYPE_FG' => $frs['TYPE_FG']]);
                }
            }
            
            $reponse = null;
            if ($listeFrs) {
                $consultWsdl = new \Modules\Consultation\WebService\Consultation();
                $xmlResult = $consultWsdl->sendConsultation($idAO, $post['typeConsult'], $listeFrs);
                $reponse = new \SimpleXMLElement($xmlResult->responseData);
            }

            if ($listeExcel) {
                $envoieExcelService = new EnvoieExcelService($this->pdo, $this->getTranslationService(), $this->base);
                foreach ($listeExcel as $excel) {
                    $envoieExcelService->generationEnvoieExcel(
                        $idAO,
                        $excel,
                        $consultation,
                        $user
                    );
                }
            }

            if (is_null($reponse) || $reponse->Retour == "O") {
                if ($reponse) {
                    foreach ($reponse->ListeDoc->Doc as $doc) {
                        if ($doc->Fichier != '') {
                            if (($listeFrs[(string)$doc->Message]['parMail']??null) === 0) {
                                //$urlJS = $chargeDoc->chargeDoc($this->pdo, $doc->Fichier, 'tmp', true);

                                $url = $doc->Fichier;
                                $param = '?uniq=' . Sql::guidGenerate();
                                $param .= '&token=' . password_hash($_SESSION['Session_Login'].session_id(), PASSWORD_DEFAULT);
                                $urlJS = $this->base. 'charge_document.php'.$param.'&EmplacementFichier=tmp&UrlFichier='.$url;


                                $listeUrl [] = $urlJS;
                            }
                        }
                    }
                }

                return new Response(200, [], json_encode([
                    'statut'    => 'O',
                    'file'      => $listeUrl,
                    'content' => $this->renderer->render('@popup-erreur/information', [
                        'message'    => $trad->t('La consultation a bien été envoyée au(x) fournisseur(s).'),
                    ])
                ]));
            } else {
                return new Response(200, [], json_encode([
                    'statut' => 'O',
                    'content' => $this->renderer->render('@popup-erreur/ErreurXml', [
                        'ErreurValid'    => $reponse,
                    ]),
                ]));
            }
        } else {
            return new Response(200, [], json_encode([
                'statut' => 'E',
                'content' => $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid'    => $validator->getError(),
                ])
            ]));
        }
    }

    public function creerPanierAction() : string
    {
        $idAO = $this->request->getAttribute('idAO');

        $trad = $this->getTranslationService();

        $listeType = [
            'F' => $trad->t('Fournisseur'),
            'G' => $trad->t('Groupement'),
        ];

        $aoEntet = new AoEntet($this->pdo);
        $consult = $aoEntet->find($idAO);

        if ($consult['TYPE_SG'] == 'G') {
            if ($_SESSION['Session_Login'] && ! Societe::hasMultiSoc()) {
                $societe = new \Modules\Ajax\Repository\Listes($this->pdo);
                $societes = $societe->societe($consult['CODE_STE']);
            } else {
                $societes = new \Entity\Model\Societe($this->pdo);
                $societes = $societes->fetchAll([], ['filter_egal_GROUPE' => $consult['CODE_STE']]);
            }

            $listeSoc = [];
            foreach ($societes as $soc) {
                $listeSoc[$soc['CODE_STE']] = $soc['RAIS_SOC'].' ('.$soc['CODE_STE'].')';
            }
        }

        $aoFour = new AoFour($this->pdo);
        $listeFrs = $aoFour->findAll(['NO_AO' => $idAO, 'FOU_RETEN' => 'T'], []);

        $reponse = new Reponse($this->pdo);

        foreach ($listeFrs as &$frs) {
            if ($frs['TYPE_FG'] == 'G') {
                $listeTmp = $reponse->getFrsByGrp($frs['CODE_FOU']);

                $listeFrsOnGrp = [];
                foreach ($listeTmp as $val) {
                    $listeFrsOnGrp[$val['CODE']] = $val['RS'].' ('.$val['CODE'].')';
                    ;
                }
                $frs['listeFrs'] = $listeFrsOnGrp;
            }
        }

        Ariane::generate(1, $trad->t('Sélection de fournisseur'));

        return $this->renderer->render('@Consultation/GestionConsultation/creerPanier', [
            'menuActive' => $_SESSION['typeMenu'] == 'P2P'? 'eproc':'Consultations',
            'menuLeft' => 'gestionAO',
            'idAO' => $idAO,
            'listeType' => $listeType,
            'listeFrs' => $listeFrs,
            'listeSoc' => $listeSoc??[],
        ]);
    }

    public function ajaxCreerPanierAction()
    {
        $idAO = $this->request->getAttribute('idAO');
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $aoEntet = new AoEntet($this->pdo);
        $consult = $aoEntet->find($idAO);

        $frsRet = [];
        $validator = $this->createValidator();
        if ($consult['TYPE_SG'] == 'G') {
            $validator->isFalse($post['SOCIETE'], Trad::strBuild($trad->t('Le champ @1@  est un champ obligatoire.'), $trad->t('Choix de la société')));

            $frsRet['entete']['!value'] = $post['SOCIETE'];
        }

        $aoFour = new AoFour($this->pdo);
        $listeFrs = $aoFour->findAll(['NO_AO' => $idAO, 'FOU_RETEN' => 'T'], []);

        $frsSelectionner = false;
        $frsRet['FRS'] = [];
        $listeFrsFinal = [];
        foreach ($listeFrs as $frs) {
            if ($frs['TYPE_FG'] == 'G') {
                $validator->isFalse($post['choixFrs'.$frs['CODE_FOU']], Trad::strBuild($this->getTranslationService()->t('Veuillez saisir le fournisseur lié au groupement @1@.'), $frs['CODE_FOU']));
                $listeFrsFinal[$frs['TYPE_FG'].Constante::spliter.$frs['CODE_FOU']] = $post['choixFrs'.$frs['CODE_FOU']];
            }


            $frsRet['FRS'][] = [
                '!TYPE_FG' => $frs['TYPE_FG'],
                '!CODE' => $frs['CODE_FOU'],
                '_chk' => ['!value' => ($post['frsSelected'.$frs['TYPE_FG'].Constante::spliter.$frs['CODE_FOU']]??null)],
                '_select' => ['!value' => ($post['choixFrs'.$frs['CODE_FOU']]??null)]
            ];

            if (isset($post['frsSelected'.$frs['TYPE_FG'].Constante::spliter.$frs['CODE_FOU']])) {
                $frsSelectionner = true;
            }
        }

        $validator->isFalse($frsSelectionner, $trad->t('Veuillez sélectionner au moins un fournisseur'));

        if ($validator->isValid()) {
            /*$consultationPanierService = new ConsultationPanierService($this->pdo, $trad, $idAO);
            $controleSociete = $consultationPanierService->controleSociete($post['SOCIETE']??'');

            if (!is_null($controleSociete)) {
                return new Response(200, [], json_encode([
                    'statut' => 'E',
                    'responseText' => $this->renderer->render('@popup-erreur/ErreurCreation', ['ErreurValid' => $controleSociete]),
                ]));
            }
            $consultationPanierService->createPanier($this->pdoOxaFT, $listeFrsFinal, $post['SOCIETE']??'');*/

           
            $_SESSION['AO_FRS_RET'] = serialize($frsRet);

            $ch = curl_init();

            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_COOKIESESSION, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
            curl_setopt($ch, CURLOPT_URL, Outils::getRootUrl(true) . $this->contenaire->get('base').'passerelleV1V2.php?fonction=CreerPanierConsultation&idAO='.$idAO);
            session_write_close();
            $response = curl_exec($ch);
            curl_close($ch);

            $position = strpos($response, '<retour><STATUT>');
            $reponse = substr($response, $position);
            try {
                $responseXML = new \SimpleXMLElement($reponse);
            } catch (\Exception $e) {
                // Re-throw with more info
                throw new \Exception('Exception : "'.$e->getMessage().'" for string "'.$reponse.'"');
            }
            

            if ($responseXML->STATUT == 'O') {
                $_SESSION['typeMenu'] = 'P2P';
                return new Response(200, [], json_encode(['statut' => 'O']));
            } else {
                return new Response(200, [], json_encode([
                    'statut' => 'E',
                    'responseText' => $this->renderer->render('@popup-erreur/ErreurCreation', ['ErreurValid' => $responseXML->ERREUR]),
                ]));
            }
        } else {
            return new Response(200, [], json_encode([
                'statut' => 'E',
                'responseText' => $this->renderer->render('@popup-erreur/ErreurCreation', ['ErreurValid' => $validator->getError()]),
            ]));
        }
    }

    public function popupExportAction() : string
    {
        $post['multiSelectexportRFOBLI1'] = 'AO_ENTET.NO_AO';

        return $this->renderer->render('@GlobalApplication/Popup/popupExport', [
            'pathExport' => $this->router->generateUri('Consultation.GestionConsultation.export'),
            'formFilter' => 'filtre_Consultation',
            'coloneExport' => $this->_exportGetTab(),
            'tabObli' => ['AO_ENTET.CODE'],
            'post' => $post,
        ]);
    }

    public function exportAction() : string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $arrayMultiSelect = array_filter($post, function ($k) {
            return stristr($k, 'multiSelect');
        }, ARRAY_FILTER_USE_KEY);

        // Filter any unauthorized fields
        $arrayMultiSelect = array_intersect(
            $arrayMultiSelect,
            array_keys($this->_exportGetTab())
        );

        $listeCS = [];
        foreach ($arrayMultiSelect as $key => &$multiSelect) {
            if (substr($multiSelect, 0, 12) == 'CS_EXTENSION') {
                $listeCS[] = substr($multiSelect, 12);
                unset($arrayMultiSelect[$key]);
            }
        }

        $listeSelect = implode(',', $arrayMultiSelect);

        if (empty($post['okFilter'])) {
            $post= [];
        }

        $listeAO = [];
        if (isset($post['listeAO'])) {
            $listeAO = unserialize($post['listeAO'], ["allowed_classes" => false]);
            unset($post['listeAO']);
        }

        $gestionAO_REPO = new GestionConsultation($this->pdo);
        $listeConsultation = $gestionAO_REPO->listeConsultation($post, $listeAO, $listeSelect);

        $aoEntet = new AoEntet($this->pdo);
        $listeChps = $aoEntet->getArchitecture($this->getTranslationService());

        $champSupp = new ChampSupp($this->pdo);

        //On récupère la liste des champs DATE & BOOL afin de les traités après
        $listeChpsDate = [];
        $listeChpsBool = [];
        $listeChpsMemo = [];
        $keyValue = [];
        foreach ($listeChps as $key => $value) {
            $keyValue['AO_ENTET.'.$key] = $value['nomChamp'];

            if (isset($value['type'])) {
                if ($value['type']=='DATE') {
                    $listeChpsDate[] = $key;
                }
                if ($value['type']=='RADIO') {
                    $listeChpsBool[] = $key;
                }
                if ($value['type']=='MEMO') {
                    $listeChpsMemo[] = $key;
                }
            }
        }

        $tab = [];
        //On génère l'entete du fichier d'export
        foreach ($arrayMultiSelect as $value) {
            $tab[$value] = $keyValue[$value];
        }

        $repoChampSup = new ChampSupp($this->pdo);
        foreach ($listeCS as &$cs) {
            $cs = $repoChampSup->getinfoOneCs('AO_ENTET', $cs);
            $tab['CS_EXTENSION'.$cs['NUM_FIX']] = $cs['NOM'];
        }

        $oui = $trad->t('Oui');
        $non = $trad->t('Non');
        foreach ($listeConsultation as &$ligne) {
            foreach ($listeCS as $csRFx) {
                $value = null;
                $idCS = $champSupp->autoCompletCodeEnr($ligne['NO_AO'], '', 'AO_ENTET');
                /** @phpstan-ignore-next-line */
                $value = $champSupp->generateChampSupp('AO_ENTET', $idCS, $csRFx['NUM_FIX']);
                $value = $value[0]['VALUECHAMPSUPP'];

                /** @phpstan-ignore-next-line */
                if ($csRFx['TYPE']=='LOGIQUE') {
                    $value = $value=='O'? $oui : $non;
                }

                /** @phpstan-ignore-next-line */
                $ligne['CS_EXTENSION'.$csRFx['NUM_FIX']] = $value;
            }

            foreach ($listeChpsDate as $chps) {
                if (isset($ligne[$chps])) {
                    $ligne[$chps] = Date::dateConverte($ligne[$chps]);
                }
            }

            foreach ($listeChpsBool as $chps) {
                if (isset($ligne[$chps])) {
                    $ligne[$chps] = Sql::toBool($ligne[$chps]) ? $oui : $non;
                }
            }

            foreach ($listeChpsMemo as $chps) {
                if (isset($ligne[$chps])) {
                    $ligne[$chps] = Sql::getMemo($this->pdo, $ligne[$chps]);
                }
            }
        }

        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            'export_RFx_'.date('Ymd'),
            $listeConsultation,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService(),
            $tab
        );

        return 'ok';
    }

    /**
     * @return mixed[]
     */
    private function _exportGetTab() :array
    {
        $tab = [];
        $listeChps = (new AoEntet($this->pdo))->getArchitecture($this->getTranslationService());
        foreach ($listeChps as $key => $value) {
            $tab['AO_ENTET.'.$key] = $value['nomChamp'];
        }

        $listeTmpCS = (new ChampSupp($this->pdo))
            ->getInfoCS('AO_ENTET');
        foreach ($listeTmpCS as $cs) {
            $tab['CS_EXTENSION'.$cs['NUM_FIX']] = 'CS - '.$cs['NOM'];// TODO : translate CS ?
        }
        return $tab;
    }
}
