<?php

namespace Modules\Consultation\Controller;

use Entity\Model\AoContFour;
use Entity\Model\AoContribGrp;
use Entity\Model\AoDaRep;
use Entity\Model\OxalinkUser;
use Entity\Model\Paravrac;
use Helpers\Ariane\ArianeSub;
use Helpers\Outil\Date;
use Helpers\Session\Enums\MenuTopEnum;
use Helpers\Session\Session;
use Modules\Consultation\Enums\TypeConsultationsEnums;
use Modules\ProjetAchat\Repository\Modele;
use Skeleton\Controller\Controller;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Sql;
use GuzzleHttp\Psr7\Response;
use Helpers\ChampsSupplementaire\ChampSupp;
use Entity\Model\AoEntet;
use Modules\Consultation\Repository\AoEvent;
use Modules\Consultation\Repository\GestionConsultation;
use Modules\GlobalApplication\Repository\DocumentsRattaches;
use Modules\Consultation\Service\ConsultationService;
use Helpers\Outil\Roles;
use Entity\Model\AoDocAttendus;
use Modules\Consultation\Repository\Consultation;
use Modules\Consultation\Repository\Reponse;
use Entity\Model\AoRep;
use Entity\Model\AoRepPijo;
use Entity\Model\AoRepQst;
use Entity\Model\AoRepSl;
use Entity\Model\AoRetParLigne;
use Modules\ProjetAchat\Repository\Action;
use Entity\Model\DoarEtatAv;
use Entity\Model\DoarType;
use Entity\Model\DoarOpe;
use Modules\ProjetAchat\Service\ModeleProjetService;
use Entity\Model\AoQstTh;
use Entity\Model\AoFour;
use Entity\Model\ConsultDocDefault;
use Entity\Model\Metadata\AoEntetExt;
use Entity\Model\Metadata\EntityMetaQb;
use Helpers\Outil\Mail;
use Helpers\Pagination\PaginatorGestion;
use Modules\Consultation\MenuContextuel\GestionMenuContextuel;
use Modules\Consultation\MenuContextuel\FournisseurMenuContextuel;
use Modules\Consultation\Service\SendEmailService;

class ConsultationController extends Controller
{
    public function detailsAction(): string|Response
    {
        $idAO   = $this->request->getAttribute('idAO');
        $onglet = $this->request->getAttribute('onglet');
        $post   = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $paginator = new PaginatorGestion;
        $paginator->generate(0, 'NO_AO');

        // Check for old consultations before 1200ab for AO_CONTFOUR

        if (!$post) {
            $post['ACHETEUR'] = $_SESSION["Session_Login"];
        }

        $gestionConsu = new GestionConsultation($this->pdo);
        Ariane::generate(1, $trad->t('Détails consultation'));

        $consultation = $gestionConsu->getInfoAo($idAO);

        if (empty($consultation)) {
            return $this->create404Response();
        }

        $typeConsult = TypeConsultationsEnums::tryFrom($consultation['RFI_Q']) ?? TypeConsultationsEnums::RFQ;

        $onglet = $onglet ?? (($typeConsult != TypeConsultationsEnums::RFI) ? 'Ligne' : 'Fournisseur');
        $this->generateArianeSub($consultation, $onglet);
        $actionRepo    = new Action($this->pdo);
        $listeIdProjet = $actionRepo->checkLienExterneProjetExist($idAO, 'NO_AO');

        $droit   = Roles::droitsUtilMulti($this->pdo, [
            'HA_AO_ADM',
            'HA_AO_CMV',
            'HA_AO_TRA',
            'HA_AO_SUP',
            'HA_AO_SRF',
        ]);
        $canEdit =
            $droit['HA_AO_ADM']
            || (
                $droit['HA_AO_CMV']
                && $consultation['ACH'] == $_SESSION["Session_Login"]
            );

        $aoEvent      = new AoEvent($this->pdo);
        $AOEventCreat = $aoEvent->getNameCreate($idAO);
        $existsContribQuestionnaire = false;
        
        $menuContextuel = new GestionMenuContextuel($this->pdo, $this->router, $trad, $droit);
        $menuContextuel = $menuContextuel->generate($consultation, 'Consultation');

        $enCours = $consultation['DTE_VALID_AO'] != '00000000';

        // $data = $this->_processTab($consultation, $onglet);


        $common = [
            'idAO' => $idAO,
            'menuActive' => Session::verifySessionTypeMenuTop(MenuTopEnum::P2P) ? 'eproc' : 'Consultations',
            'menuLeft' => 'gestionAO',
            'consultation' => $consultation,
            'canEdit' => $canEdit,
            'enCours' => $enCours,
            'droit' => $droit,
            'menuContextuel' => $menuContextuel,
            'container' => $this->contenaire,
        ];

        if ($onglet == 'Fournisseur' || (($onglet == '') && ($typeConsult == TypeConsultationsEnums::RFI))) {
            $listeFournisseurBase = (new AoFour($this->pdo))->findAll(['NO_AO' => $idAO]);

            foreach ($listeFournisseurBase as $frs) {
                $consultationService = new ConsultationService($this->pdo, $this->getTranslationService());
                $consultationService->checkAoFourContactWithAoContFour($idAO, $frs['CODE_FOU'], $frs['TYPE_FG']);
            }

            $paginator = new PaginatorGestion();
            $paginator->generate(0, 'CODE_FOU');

            $listeFournisseur = $gestionConsu->getListeFourniss($idAO, $post);
            $infoPagination = $paginator->getInfoPagination();

            $reponseRepo = new Reponse($this->pdo);
            $AoContFour  = new AoContFour($this->pdo);
            $OxalinkUser = new OxalinkUser($this->pdo);

            // on vérifie s'il existe un questionnaire pour acheteur/contributeur
            $countContribQuestions = count($reponseRepo->getContributorsQuestions($idAO));
            $existsContribQuestionnaire = $countContribQuestions > 0;

            $menuContextuel = new FournisseurMenuContextuel($this->pdo, $this->router, $this->getTranslationService(), $droit);
            foreach ($listeFournisseur as &$frs) {
                $contribQuestionnaireAnswered = false;

                // TODO : merge queries from getLastReponseAo
                //on récupere la liste des réponses fournisseur, si c'est un fournisseur oxalink avec au moins 1 contact valide, on n'affique que les réponses validé
                $reponseFrs = $reponseRepo->getLastReponseAo($frs['NO_AO'], $frs['CODE_FOU'], (Sql::boolSql($frs['GEREPORTAIL']) == true && $frs['ctcOxalinkActif'] != 0));

                // s'il existe un questionnaire contributeur, on vérifie s'il existe une réponse pour chaque question qui le compose
                if ($existsContribQuestionnaire) {
                    $contribQuestionnaireAnswered = $reponseFrs[0]['COUNT_REP_CONTRIB'] == $countContribQuestions;
                }

                if ($reponseFrs) {
                    $frs['listeReponse'] = $reponseFrs;

                    $frs['EVE_REP']             = $reponseFrs[0]['EVE_REP'] ?? '';
                    $frs['DTE_REP']             = $reponseFrs[0]['DTE_REP'] ?? '';
                    $frs['C_V']                 = $reponseFrs[0]['C_V'] ?? '';
                    $frs['COUNT_REP_CONTRIB']   = $reponseFrs[0]['COUNT_REP_CONTRIB'] ?? '';
                }
                if (trim($frs['FIC_ACC_CONF_SIGNE'])) {
                    $path_info            = pathinfo($frs['FIC_ACC_CONF_SIGNE']);
                    $frs['FILE_ACC_CONF'] = 'Consult_' . $idAO . '_' . $frs['CODE_FOU'] . '.' . ($path_info['extension'] ?? '');
                }

                $frs['listeContact'] = $AoContFour->findAll(['NO_AO' => $idAO, 'TYPE_FG' => $frs['TYPE_FG'], 'CODE_FOUR' => $frs['CODE_FOU']], [], ['tri_NUM_ORDRE' => 'ASC']);

                $frs['dateEnvoieAccord']     = $aoEvent->getLastDate($idAO, $frs['CODE_FOU'] ?? '', $frs['TYPE_FG'] ?? '', 'ENV', 'Demande de signature de l\'accord de confidentialité')['DTE'];
                $frs['dateAjoutAccordSigne'] = $aoEvent->getLastDate($idAO, $frs['CODE_FOU'] ?? '', $frs['TYPE_FG'] ?? '', 'ACS')['DTE'];
                $frs['dateAccordValider']    = $aoEvent->getLastDate($idAO, $frs['CODE_FOU'] ?? '', $frs['TYPE_FG'] ?? '', 'ACV')['DTE'];
                $frs['dateEnvoie']           = $aoEvent->getLastDate($idAO, $frs['CODE_FOU'] ?? '', $frs['TYPE_FG'] ?? '', 'ENV')['DTE'];
                $frs['dateAccordRefuse']     = $aoEvent->getLastDate($idAO, $frs['CODE_FOU'] ?? '', $frs['TYPE_FG'] ?? '', 'ACR')['DTE'];

                /** @var array<mixed> $frs */
                if (($frs['EMAILCONT'] ?? '') != '' || ($frs['NOM_CTCT'] ?? '') != '') {
                    $frs['listeContact'][] = [
                        'NO_AO'     => $idAO,
                        'CODE_FOUR' => ($frs['CODE_FOU'] ?? ''),
                        'TYPE_FG'   => ($frs['TYPE_FG'] ?? ''),
                        'NUM_ORDRE' => 0,
                        'NOM_CTCT'  => ($frs['NOM_CTCT'] ?? ''),
                        'TEL_CTCT'  => ($frs['TEL_CTCT'] ?? ''),
                        'FAX_CTCT'  => ($frs['FAX_CTCT'] ?? ''),
                        'POR_CTCT'  => ($frs['POR_CTCT'] ?? ''),
                        'EMAILCONT' => ($frs['EMAILCONT'] ?? ''),
                    ];
                }

                $consultrepo = new Consultation($this->pdo);
                foreach ($frs['listeContact'] as &$ctct) {
                    $ctct['ISOXALINK']  = $consultrepo->checkIfCtcHasOxalinkAccess($idAO, $ctct['TYPE_FG'], $ctct['CODE_FOUR'], $ctct['EMAILCONT']);
                    $ctct['OXALINK_ID'] = ($OxalinkUser->find(['EMAIL' => $ctct['EMAILCONT']])['USER_ID']) ?? '';
                }

                $frs['menuContextuel'] = $menuContextuel->generate($idAO, $consultation, $frs, $canEdit, $reponseFrs);
                $frs['contribQuestionnaireAnswered'] = $contribQuestionnaireAnswered;
            }

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

            $typeReponse = [
                'C' => $trad->t('Conforme'),
                'V' => $trad->t('Variante'),
            ];
        } elseif ($onglet == 'Ligne' || (($onglet == '') && ($typeConsult != TypeConsultationsEnums::RFI))) {
            $ligneConsultation = $gestionConsu->listeLigneConsultation($idAO);

            $aoQstTh = new AoQstTh($this->pdo);

            $poidsAPRIX = $aoQstTh->find(['NO_AO' => $idAO, 'ID_THEME' => 'APRIX'])['POIDS'] ?? null;
        } elseif ($onglet == 'DocConsult') {
            return $this->renderer->render('@Consultation/Consultation/pageTabDocConsult', $common + [
                'typeConsult' => $typeConsult,
                'listeClause' => $gestionConsu->getListClause($idAO),
                'listePJ' => $gestionConsu->getListPJ($idAO),
                'listDocAttendu' => (new ConsultDocDefault($this->pdo))->findAll(
                    [
                        'TYPE_DOC' => 'P',
                        'COD_LNG ' => $consultation['COD_LNG'],
                        'POUR_'.$typeConsult->name => true,
                    ],
                    [],
                    ['tri_NUM_ORDRE' => 'ASC']
                )
            ]);
        } elseif ($onglet == 'DocRep') {
            $AoDocAttendus   = new AoDocAttendus($this->pdo);
            $listeDocReponse = $AoDocAttendus->findAll(
                ['NO_AO' => $idAO],
                [],
                ['tri_NUM_ORDRE' => 'asc']
            );
            $listeDocReponseDefault = array_column(
                (new ConsultDocDefault($this->pdo))->findAll(
                    [
                    'TYPE_DOC' => 'A',
                    'COD_LNG ' => $consultation['COD_LNG'],
                    'POUR_' . $typeConsult->name => true,
                    ],
                    [],
                    ['tri_NUM_ORDRE' => 'ASC']
                ),
                'TITRE_DOC'
            );
        } elseif ($onglet == 'DocInt') {
            $onglet        = 'DocInt';
            $post['NO_DA'] = 'AO_ENTET';
            $idDoc         = str_pad($idAO, 9, '0', STR_PAD_LEFT);

            $docAtt        = new DocumentsRattaches($this->pdo);
            $listeDocument = $docAtt->detail($idDoc, $post + [
                'tri_TITRE' => 'ASC'
            ]);
            foreach ($listeDocument as &$doc) {
                if (strlen($doc['COMMENTAIRE']) > 20) {
                    //@phpstan-ignore-next-line
                    $doc['COMMENTAIRE_SHOW'] = substr($doc['COMMENTAIRE'], 0, 20);
                }
            }
        } elseif ($onglet == 'projetLie') {
            $DoarEtatAv = new DoarEtatAv($this->pdo);
            $listeTMP   = $DoarEtatAv->fetchAll();

            foreach ($listeTMP as $item) {
                $ListeEtatAv[$item['ID']] = $item['LIB'];
            }

            $DoarType = new DoarType($this->pdo);
            $listeTMP = $DoarType->fetchAll();

            foreach ($listeTMP as $item) {
                $listeType[$item['ID']] = $item['LIB'];
            }

            $DoarOpe  = new DoarOpe($this->pdo);
            $listeTMP = $DoarOpe->fetchAll();

            foreach ($listeTMP as $item) {
                $ListeOpe[$item['CODE_OPE']] = $item['LIB'];
            }

            $projetService = new ModeleProjetService($this->pdo);
            $listeStatus   = $projetService->listeStatut($trad);

            // TODO : merge queries
            $listeIdProjet = (new Action($this->pdo))->checkLienExterneProjetExist($idAO, 'NO_AO');
            $listeProjet   = (new Modele($this->pdo))->listLinkedProjet(
                array_column($listeIdProjet, 'ID_OBJET')
            );
        }

        // TODO : defactorize
        return $this->renderer->render('@Consultation/Consultation/details', $common + [

            'pathBack' => ariane::getBackPath(),
            
            'AOEventCreat' => $AOEventCreat,
            'infoPagination' => $infoPagination??[],
            'login' => $_SESSION["Session_Login"],
            'onglet' => $onglet,
            'typeFournisseur' => $typeFournisseur ?? [],
            'listeFournisseur' => $listeFournisseur ?? [],
            'ligneConsultation' => $ligneConsultation ?? [],
            'listeDocReponse' => $listeDocReponse ?? [],
            'listeDocument' => $listeDocument ?? [],
            'listeDocReponseDefault' => $listeDocReponseDefault ?? [],
            'idForDoc' => $idDoc ?? '',
            'typeReponse' => $typeReponse ?? [],
            'ListeEtatAv' => $ListeEtatAv ?? [],
            'listeType' => $listeType ?? [],
            'ListeOpe' => $ListeOpe ?? [],
            'listeProjet' => $listeProjet ?? [],
            'listeStatut' => $listeStatus ?? [],
            'poidsAPRIX' => $poidsAPRIX ?? null,
            'droit' => $droit,
            'existsContribQuestionnaire' => $existsContribQuestionnaire,
            'accConfValAch' => Sql::toBool((new Paravrac($this->pdo))->find(['CODEPARV' => 'AO_ACC_CONF_VAL_ACH'])['LIB01PARV']??'N')
        ]);
    }
    
    /**
     * @param array<mixed> $consultation
     * @return void
     */
    private function generateArianeSub(array $consultation, string $onglet)
    {
        $trad = $this->getTranslationService();
        $idAO = $consultation['NO_AO'];

        ArianeSub::init();

        ArianeSub::generate(
            0,
            0,
            $trad->t('Détails consultation'),
            $this->router->generateUri(
                'Consultation.Consultation.details',
                ['idAO' => $idAO, 'onglet' => $onglet]
            ),
            1,
            [],
        );
    }

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

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

        $composant = match ($post['COMPOSANT']) {
            'ongletLigne'       => 'COMP_LIGNE',
            'ongletPJ'          => 'COMP_PJ',
            'ongletDocRep'      => (function () use ($AoEntet, $idAO): string {
                    $AoEntet->update(['CTRL_DOSSIER_FOURNISSEUR' => ''], ['NO_AO' => $idAO]);
                    return 'COMP_DOC_ATT';
            })(),
            'ongletDocInt'      => 'COMP_DOC_INT',
            'ongletQst'         => 'COMP_QUEST',
            'ongletDocConsult'  => 'COMP_PJ',
            default => ''
        };

        $composant2 = match ($post['COMPOSANT']) {
            'ongletDocConsult'  => (function () use ($AoEntet, $post, $idAO): string {
                $AoEntet->update([
                    'numerique_COMP_CLAUSE' => ($post['STATUT'] == 'show' ? '0x54' : '0x46')
                ], $idAO);
                return 'COMP_CLAUSE';
            })(),
            default => ''
        };

        $infoEntete = $AoEntet->find($idAO);

        $consultationService->deleteComposant($idAO, $composant, false, $infoEntete['ACC_CONF_NODOC']);

        $AoEntet->update([
            'numerique_' . $composant => ($post['STATUT'] == 'show' ? '0x54' : '0x46')
        ], $idAO);

        return new Response();
    }

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

        $AoEntet = new AoEntet($this->pdo);

        $AoEntet->update([
            'ENVOI_EMAIL_AUTO_FRS' => !Sql::toBool(
                $AoEntet->find(
                    ['NO_AO' => $idAO],
                    ['ENVOI_EMAIL_AUTO_FRS']
                )['ENVOI_EMAIL_AUTO_FRS'] ?? ''
            ),
        ], ['NO_AO' => $idAO]);

        return new Response(200);
    }

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

        /** delete entete **/
        $aoEntet    = new AoEntet($this->pdo);
        $infoEntete = $aoEntet->find($idAO);
        $aoEntet->delete($idAO);
        sql::deleteMemos($this->pdo, $infoEntete['NM_TITRE']);
        sql::deleteMemos($this->pdo, $infoEntete['NM_COMENT']);

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

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

        // on delete tout les onglet de la consultation
        $consultationService->deleteComposant($idAO, 'COMP_FOURNISS');
        $consultationService->deleteComposant($idAO, 'COMP_LIGNE');
        $consultationService->deleteComposant($idAO, 'COMP_PJ');
        $consultationService->deleteComposant($idAO, 'COMP_DOC_ATT');
        $consultationService->deleteComposant($idAO, 'COMP_DOC_INT');
        $consultationService->deleteComposant($idAO, 'COMP_CLAUSE');
        $consultationService->deleteComposant($idAO, 'COMP_QUEST');
        $consultationService->deleteComposant($idAO, 'AO_FOUR_QR');

        $aoRep         = new AoRep($this->pdo);
        $aoRepPijo     = new AoRepPijo($this->pdo);
        $aoRepQst      = new AoRepQst($this->pdo);
        $aoRepSl       = new AoRepSl($this->pdo);
        $aoDaRep       = new AoDaRep($this->pdo);
        $aoRetParLigne = new AoRetParLigne($this->pdo);

        // on delete toute les réponses de la consultation
        $aoRep->delete(['NO_AO' => $idAO]);
        $aoRepPijo->delete(['NO_AO' => $idAO]);
        $aoRepQst->delete(['NO_AO' => $idAO]);
        $aoRepSl->delete(['NO_AO' => $idAO]);
        $aoRetParLigne->delete(['NO_AO' => $idAO]);
        $aoDaRep->delete(['NO_AO' => $idAO]);

        $idCS = str_pad($idAO, 9, '0', STR_PAD_LEFT);
        ChampSupp::deleteCS('AO_ENTET', $idCS, $this->pdo);

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

        $actionRepo    = new Action($this->pdo);
        $listeIdProjet = $actionRepo->checkLienExterneProjetExist($idAO, 'NO_AO');

        // on supprime les liens consultation/projet achat
        foreach ($listeIdProjet as $projet) {
            $actionRepo->deleteLiensExterne($projet['ID_OBJET'], $projet['ID_DONNEE']);
            $listeDonnee = $actionRepo->getListDataLie($projet['ID_OBJET'], 'AO_FOUR');

            foreach ($listeFrs as $frs) {
                foreach ($listeDonnee as $donnee) {
                    $champsKeyUnique = $actionRepo->getIdChampsForUpdate($projet['ID_OBJET'], 'FOURNISS', 'CODE', $donnee['ID_DONNEE']);

                    $actionRepo->suppresionLienTableSecondaire($projet['ID_OBJET'], $donnee['ID_DONNEE'], $champsKeyUnique['ID_DATA'], 'AO_FOUR', $frs['CODE_FOU']);
                }
            }
        }

        return new Response(200, [], (string) \json_encode([
            'statut' => 'O',
            'path' => $this->router->generateUri('Consultation.GestionConsultation.index'),
            'pathOnlyRedirect' => true,
        ]));
    }

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

        $aoEntet = new AoEntet($this->pdo);
        $aoEntet->update([
            'VALCHXFOU' => date("dmY")
        ], $idAO);

        $AoFour      = new AoFour($this->pdo);
        $allFourniss = $AoFour->findAll(["NO_AO" => $idAO]);

        foreach ($allFourniss as $fourniss) {
            $AoFour->update(
                ["FOU_RETEN" => Sql::boolSql2(false)],
                ["NO_AO" => $idAO, "CODE_FOU" => $fourniss["CODE_FOU"]]
            );
        }

        $AoRetParLigne = new AoRetParLigne($this->pdo);
        $AoRetParLigne->delete(["NO_AO" => $idAO]);

        $consultEmailService = new SendEmailService($this->pdo, $this->getTranslationService(), $idAO);
        $consultEmailService->clotureInfructueuse();

        return new Response(200, [], (string) \json_encode([
            'statut' => 'O',
            'path' => $this->router->generateUri('Consultation.GestionConsultation.index'),
            'pathOnlyRedirect' => true,
        ]));
    }

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

        $trad = $this->getTranslationService();

        $gestionConsu = new GestionConsultation($this->pdo);
        $consultation = $gestionConsu->getInfoAo($idAO);

        $consultationRepo = new Consultation($this->pdo);
        $infoBlocNote     = $consultationRepo->getBlocNote($idAO);

        if ($post && isset($post['contmemo'])) {
            $validator = $this->createValidator();
            $validator->isStringAvecEspace($trad->t('Bloc-note'), $post['contmemo'], 0, 3000);

            if ($validator->isValid()) {
                $idMemo = sql::updateMemo($this->pdo, $infoBlocNote['NODEMEMO'] ?? null, $post['contmemo']);

                $consultationRepo->insertBnote($idAO, $idMemo);

                return new Response(200);
            } else {
                return new Response(443, [], $validator->getError());
            }
        }

        $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"]),
        ];


        return $this->renderer->render('@Consultation/Consultation/blocknote', [
            'canEdit' => ($droit['HA_AO_ADM'] || ($droit['HA_AO_CMV'] && $consultation['ACH'] == $_SESSION["Session_Login"])),
            'idAO' => $idAO,
            'post' => $infoBlocNote,
        ]);
    }


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

        $aoFour  = new AoFour($this->pdo);
        $infoFou = $aoFour->find(['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'TYPE_FG' => $typeFG]);

        $aoEventRepo          = new AoEvent($this->pdo);
        $dateEnvoieAccord     = $aoEventRepo->getLastDate($idAO, $idFrs, $typeFG, 'ENV', 'Demande de signature de l\'accord de confidentialité');
        $dateAjoutAccordSigne = $aoEventRepo->getLastDate($idAO, $idFrs, $typeFG, 'ACS');
        $dateAccordValider    = $aoEventRepo->getLastDate($idAO, $idFrs, $typeFG, 'ACV');
        $dateEnvoie           = $aoEventRepo->getLastDate($idAO, $idFrs, $typeFG, 'ENV');
        $dateAccordRefuse     = $aoEventRepo->getLastDate($idAO, $idFrs, $typeFG, 'ACR');

        return $this->renderer->render('@Consultation/Consultation/popupStepBar', [
            'idFrs' => $idFrs,
            'infoFou' => $infoFou,
            'dateEnvoieAccord' => $dateEnvoieAccord['DTE'] ?? '',
            'dateAjoutAccordSigne' => $dateAjoutAccordSigne['DTE'] ?? '',
            'dateAccordValider' => $dateAccordValider['DTE'] ?? '',
            'dateEnvoie' => $dateEnvoie['DTE'] ?? '',
            'dateAccordRefuse' => $dateAccordRefuse['DTE'] ?? ''
        ]);
    }

    public function popupUpdateDateAction(): string|Response
    {
        $idAO = $this->request->getAttribute('idAO');
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $gestionConsu = new GestionConsultation($this->pdo);
        $consultation = $gestionConsu->getInfoAo($idAO);

        if ($post && (isset($post['DEL_REP']) || isset($post['HEURE_CLOTURE']))) {
            $validator = $this->createValidator();
            $validator->isDate($post['DEL_REP'], date('Ymd'), '', false, $trad->t('Réponse attendue pour le'));
            $validator->isHourWithSeconde($trad->t('Heure de clôture'), $post["HEURE_CLOTURE"], true);

            if ($validator->isValid()) {
                $AoEntet = new AoEntet($this->pdo);
                $oldAo   = $AoEntet->find($idAO);

                if (($oldAo["DEL_REP"] !== $post['DEL_REP']) || ($oldAo["HEURE_CLOTURE"] !== $post['HEURE_CLOTURE'])) {
                    $AoEntet->update(['DEL_REP' => $post['DEL_REP'], 'HEURE_CLOTURE' => str_replace(':', '', $post['HEURE_CLOTURE'])], $idAO);

                    if ($oldAo["DEL_REP"] !== $post['DEL_REP']) {
                        $consultEmailService = new SendEmailService($this->pdo, $trad, $idAO);
                        $consultEmailService->dateRepChanged(Date::dateConverte($oldAo["DEL_REP"]));
                    }
                }

                return new Response(200);
            } else {
                return new Response(443, [], $validator->getError());
            }
        }

        $consultation['DEL_REP']       = Date::dateConverte($consultation['DEL_REP']);
        $consultation['HEURE_CLOTURE'] = Date::heureConverte($consultation['HEURE_CLOTURE']);
        return $this->renderer->render('@Consultation/Consultation/popupUpdateDate', [
            'idAO' => $idAO,
            'post' => $post,
            'consultation' => $consultation
        ]);
    }

    public function delegToDemAction() :Response
    {
        $id = $this->request->getAttribute('idAO');
        $trad = $this->getTranslationService();

        $listInfoMail = (new GestionConsultation($this->pdo))
            ->getInfoMailEnvoieInfoToDem($id);

        if (empty($listInfoMail)) {
            return new Response(400, [], $trad->t('Aucun demandeur n\'est présent sur cette consultation.'));
        }

        $qb = new EntityMetaQb($this->pdo);

        foreach ($listInfoMail as $infoMail) {
            $aoId = $infoMail['NO_AO'];
            /** @see \Container\Mail\DaAoTerminer::class */
            Mail::generateMail(
                $this->pdo,
                $this->getTranslationService(),
                $infoMail['Demandeur_EMAIL'],
                'AO_TERMINE_INFODEM',
                $infoMail['Demandeur_COD_LNG'],
                [
                    'NAO' => $infoMail['NO_AO'],
                    'NDA' => $infoMail['NO_DA'],
                    'CODE_ACH' => $infoMail['Acheteur_CODE'],
                    'NOM_ACH' => $infoMail['Acheteur_NOM'],
                ]
            );
            
            $meta = $qb->find(AoEntet::class, $aoId, AoEntetExt::class, 0) ?? new AoEntetExt($aoId);
            $meta->setDemDeleg(true);
            $qb->persist([$meta]);
        }

        return new Response(200);
    }
}
