<?php

namespace Modules\Consultation\Controller;

use Entity\Model\AoContFour;
use Entity\Model\AoDaRep;
use Entity\Model\OxalinkUser;
use Helpers\Ariane\ArianeSub;
use Helpers\Outil\Date;
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 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();
        }

        $onglet = $onglet ?? ($consultation['RFI_Q'] != 'I' ? 'Ligne' : 'Fournisseur');
        $this->generateArianeSub($consultation, $onglet ?? ($consultation['RFI_Q'] != 'I' ? 'Ligne' : 'Fournisseur'));
        $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;

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

        if ($onglet == 'Fournisseur' || ($onglet == '' && $consultation["RFI_Q"] == 'I')) {
            $_SESSION['PaginatorGestion']['infoPagination']['nbrArticle'] = null;
            $paginator = new PaginatorGestion;
            $paginator->generate(0, 'CODE_FOU');

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

                /** @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 == '' && $consultation["RFI_Q"] != 'I')) {
            $ligneConsultation = $gestionConsu->listeLigneConsultation($idAO);

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

            $poidsAPRIX = $aoQstTh->find(['NO_AO' => $idAO, 'ID_THEME' => 'APRIX'])['POIDS'] ?? null;
        } elseif ($onglet == 'DocConsult') {
            $listPJ     = $gestionConsu->getListPJ($idAO);
            $listClause = $gestionConsu->getListClause($idAO);
        } elseif ($onglet == 'DocRep') {
            $AoDocAttendus   = new AoDocAttendus($this->pdo);
            $listeDocReponse = $AoDocAttendus->findAll(
                ['NO_AO' => $idAO],
                [],
                ['tri_NUM_ORDRE' => 'asc']
            );
        } 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')
            );
        }

        if (Roles::droitsUtilisateur($this->pdo, 'HA_DA_CRE') || Roles::GetALL()) {
            $P2PActive = 1;
        } else {
            $P2PActive = 0;
        }

        $menuContextuel = new GestionMenuContextuel($this->pdo, $this->router, $trad, $droit);
        $menuContextuel = $menuContextuel->generate($consultation, 'Consultation');

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

        return $this->renderer->render('@Consultation/Consultation/details', [
            'idAO' => $idAO,
            'pathBack' => ariane::getBackPath(),
            'menuActive' => $_SESSION['typeMenu'] == 'P2P' ? 'eproc' : 'Consultations',
            'menuLeft' => 'gestionAO',
            'consultation' => $consultation,
            'AOEventCreat' => $AOEventCreat,
            'login' => $_SESSION["Session_Login"],
            'onglet' => $onglet,
            'typeFournisseur' => $typeFournisseur ?? [],
            'listeFournisseur' => $listeFournisseur ?? [],
            'ligneConsultation' => $ligneConsultation ?? [],
            'listeClause' => $listClause ?? [],
            'listePJ' => $listPJ ?? [],
            'listeDocReponse' => $listeDocReponse ?? [],
            'listeDocument' => $listeDocument ?? [],
            'canEdit' => $canEdit,
            'enCours' => $enCours,
            'idForDoc' => $idDoc ?? '',
            'typeReponse' => $typeReponse ?? [],
            'ListeEtatAv' => $ListeEtatAv ?? [],
            'listeType' => $listeType ?? [],
            'ListeOpe' => $ListeOpe ?? [],
            'listeProjet' => $listeProjet ?? [],
            'listeStatut' => $listeStatus ?? [],
            'poidsAPRIX' => $poidsAPRIX ?? null,
            'droit' => $droit,
            'P2PActive' => $P2PActive,
            'infoPagination' => $infoPagination ?? [],
            'menuContextuel' => $menuContextuel,
            'container' => $this->contenaire,
            'existsContribQuestionnaire' => $existsContribQuestionnaire,
        ]);
    }

    /**
     * @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()
    {
        $idAO = $this->request->getAttribute('idAO');
        $post = $this->request->getParsedBody();

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

        $composant  = '';
        $composant2 = '';
        if ($post['COMPOSANT'] == 'ongletLigne') {
            $composant = 'COMP_LIGNE';
        } elseif ($post['COMPOSANT'] == 'ongletPJ') {
            $composant = 'COMP_PJ';
        } elseif ($post['COMPOSANT'] == 'ongletDocRep') {
            $composant = 'COMP_DOC_ATT';
        } elseif ($post['COMPOSANT'] == 'ongletDocInt') {
            $composant = 'COMP_DOC_INT';
        } elseif ($post['COMPOSANT'] == 'ongletQst') {
            $composant = 'COMP_QUEST';
        } elseif ($post['COMPOSANT'] == 'ongletDocConsult') {
            $composant  = 'COMP_PJ';
            $composant2 = 'COMP_CLAUSE';
        }

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

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

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

        if ($composant2) {
            $aoEntete->update([
                'numerique_' . $composant2 => ($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');

        $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');

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