<?php
namespace Modules\Consultation\Controller;

use Entity\Model\AoContribGrp;
use Entity\Model\AoFour;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Roles;
use Helpers\Session\Enums\MenuTopEnum;
use Helpers\Session\ParseBase1;
use Helpers\Session\Session;
use Skeleton\Controller\Controller;
use Helpers\Ariane\Ariane;
use Helpers\Trad\Trad;
use Entity\Model\AoEntet;
use Helpers\Ariane\ArianeSub;
use Modules\Consultation\Repository\Reponse;
use Entity\Model\AoRep;
use Helpers\Outil\Sql;
use Entity\Model\AoLigne;
use Entity\Model\Fourniss;
use Helpers\Validator\Validator;
use GuzzleHttp\Psr7\Response;
use Entity\Model\AoDaRep;
use Entity\Model\Pays;
use Entity\Model\AoRepSl;
use Entity\Model\AoDocAttendus;
use Modules\Consultation\Repository\AoEvent;
use Entity\Model\AoRepPijo;
use Entity\Model\AoRepQst;
use Entity\Model\AoRetParLigne;
use Helpers\Outil\Date;
use Entity\Model\Grpfou;
use Helpers\Parametres\Constante;
use Symfony\Component\String\Slugger\SluggerInterface;

class SaisieReponsesController extends Controller
{
    /**  Partie entête de reponse **/
    public function createEditEntetAction(): string
    {
        $idAO   = $this->request->getAttribute('idAO');
        $typeFG = $this->request->getAttribute('typeFG');
        $idFrs  = $this->request->getAttribute('idFrs');
        $idRep  = $this->request->getAttribute('idRep');
        $CV     = $this->request->getAttribute('CV');

        $trad = $this->getTranslationService();

        $aoEntet  = new AoEntet($this->pdo);
        $fourniss = new Fourniss($this->pdo);
        $grpFou   = new Grpfou($this->pdo);

        $infoEnteteConsult = $aoEntet->find($idAO);
        if ($typeFG == 'F') {
            $infoFrs = $fourniss->find($idFrs);
        } else {
            $infoFrs = $grpFou->find($idFrs);
        }

        $listeCV = [
            'C' => $trad->t('Conforme'),
            'V' => $trad->t('Variant'),
        ];

        if ($idRep) {
            Ariane::generate(3, $trad->t('Modification entête de réponse'));

            $aoDaRep             = new AoDaRep($this->pdo);
            $reponse             = $aoDaRep->find(['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'TYPE_FG' => $typeFG, 'DTE_REP' => $idRep, 'C_V' => $CV]);
            $reponse['COMFOURN'] = sql::getMemo($this->pdo, $reponse['COMMENT1']);
        } else {
            Ariane::generate(2, $trad->t('Création entête de réponse'));

            if (sql::boolSql($infoEnteteConsult['REPDEV']) == true) {
                $reponse['DEVISE'] = $infoEnteteConsult['DEVISE'];
            } else {
                $reponse['DEVISE'] = $infoFrs['DEVISE'];
            }
        }
        return $this->renderer->render('@Consultation/SaisieReponses/createEditEntete', [
            'idAO' => $idAO,
            'idFrs' => $idFrs,
            'idRep' => $idRep,
            'typeFG' => $typeFG,
            'CV' => $CV,

            'pathBack' => ariane::getBackPath(),
            'menuActive' => Session::verifySessionTypeMenuTop(MenuTopEnum::P2P) ? 'eproc' : 'Consultations',
            'menuLeft' => 'gestionAO',
            'reponse' => $reponse,
            'infoEnteteConsult' => $infoEnteteConsult,
            'listeCV' => $listeCV,
        ]);
    }

    public function validateEnteteAction()
    {
        $idAO   = $this->request->getAttribute('idAO');
        $typeFG = $this->request->getAttribute('typeFG');
        $idFrs  = $this->request->getAttribute('idFrs');
        $idRep  = $this->request->getAttribute('idRep');
        $CV     = $this->request->getAttribute('CV');

        $trad = $this->getTranslationService();

        $post = $this->request->getParsedBody();

        $validator = $this->createValidator();
        $validator->isDate($post['DTELIMIT'], date('Ymd'), '', false, $trad->t('Date limite de l\'offre'));
        $validator->zoom('Devise', $post['DEVISE'], $trad->t('Devise'), $this->pdo, true);
        $validator->isStringAvecEspace($trad->t('Référence de l\'offre'), $post['REFRPFOU'], 0, 60);
        $validator->isStringAvecEspace($trad->t('Commentaire fournisseur'), $post['COMFOURN'], 0, 3000);

        $aoDaRep = new AoDaRep($this->pdo);


        if ($idRep == null || ($idRep != null && $CV != $post['C_V'])) {
            if ($post['C_V'] == 'C') {
                $message = $trad->t('Une réponse conforme existe déjà avec cette date de réception.');
            } else {
                $message = $trad->t('Une réponse variante existe déjà avec cette date de réception.');
            }

            if ($idRep) {
                $dateTest = $idRep;
            } else {
                $dateTest = date('Ymd');
            }

            $validator->isTrue($aoDaRep->find(['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'TYPE_FG' => $typeFG, 'DTE_REP' => $dateTest, 'C_V' => $post['C_V']]), $message);
        }

        if ($validator->isValid()) {
            if ($idRep != null) {
                $repSave = $aoDaRep->find(['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'TYPE_FG' => $typeFG, 'DTE_REP' => $idRep, 'C_V' => $CV]);

                $idMemo = sql::updateMemo($this->pdo, $repSave['COMMENT1'], $post['COMFOURN']);


                $aoDaRep->update([
                    'REFRPFOU' => $post['REFRPFOU'],
                    'DEVISE' => $post['DEVISE'],
                    'DTELIMIT' => $post['DTELIMIT'],
                    'C_V' => $post['C_V'],
                    'TYPE_FG' => $typeFG,
                    'VAL_DEVIS' => '0',
                    'VAL_DEVSTE' => '0',
                    'COMMENT1' => $idMemo,
                ], ['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'DTE_REP' => $idRep, 'C_V' => $CV]);

                if ($CV != $post['C_V']) {
                    /* Si le type de réponse change, alors il faut update tout les composant de la réponse */

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

                    $primKeyAo = [
                        'NO_AO' => $idAO,
                        'CODE_FOU' => $idFrs,
                        'DTE_REP' => $idRep,
                        'C_V' => $CV
                    ];
                    $aoRep->update(['C_V' => $post['C_V']], $primKeyAo);
                    $aoRepPijo->update(['C_V' => $post['C_V']], $primKeyAo);
                    $aoRepSl->update(['C_V' => $post['C_V']], $primKeyAo);
                    $aoRetParLigne->delete([
                        'NO_AO' => $idAO,
                        'CODE_FOU' => $idFrs,
                        'TYPE_FG' => $typeFG,
                        'RET_CV' => $CV,
                    ]);
                }

                $path = Ariane::getBackPath();
            } else {
                $idRep  = date('Ymd');
                $CV     = $post['C_V'];
                $idMemo = sql::updateMemo($this->pdo, '', $post['COMFOURN']);

                if (count($aoDaRep->findAll(
                    [
                            'NO_AO' => $idAO,
                            'CODE_FOU' => $idFrs,
                            'DTE_REP' => $idRep,
                            'C_V' => $post['C_V'],
                            'TYPE_FG' => $typeFG,
                        ]
                ))
                ) {
                    $aoDaRep->update(
                        [
                            'REFRPFOU' => $post['REFRPFOU'],
                            'DEVISE' => $post['DEVISE'],
                            'DTELIMIT' => $post['DTELIMIT'],
                            'COMMENT1' => $idMemo,
                            'VAL_DEVIS' => '0',
                            'VAL_DEVSTE' => '0',
                        ],
                        [
                            'NO_AO' => $idAO,
                            'CODE_FOU' => $idFrs,
                            'DTE_REP' => $idRep,
                            'C_V' => $post['C_V'],
                            'TYPE_FG' => $typeFG,
                        ]
                    );
                } else {
                    $aoDaRep->insert([
                        'NO_AO' => $idAO,
                        'CODE_FOU' => $idFrs,
                        'DTE_REP' => $idRep,
                        'REFRPFOU' => $post['REFRPFOU'],
                        'DEVISE' => $post['DEVISE'],
                        'DTELIMIT' => $post['DTELIMIT'],
                        'C_V' => $post['C_V'],
                        'TYPE_FG' => $typeFG,
                        'COMMENT1' => $idMemo,
                        'VAL_DEVIS' => '0',
                        'VAL_DEVSTE' => '0',
                    ]);
                }
                
                $aoEntet      = new AoEntet($this->pdo);
                $consultation = $aoEntet->find($idAO);
                if ($consultation['RFI_Q'] == 'Q') {
                    $path = $this->router->generateUri('Consultation.SaisieReponses.listeLigne', ['idAO' => $idAO, 'typeFG' => $typeFG, 'idFrs' => $idFrs, 'idRep' => $idRep, 'CV' => $CV]);
                } else {
                    $path = $this->router->generateUri('Consultation.SaisieReponsesPJ.listePJ', ['typeDoc' => 'P', 'idAO' => $idAO, 'typeFG' => $typeFG, 'idFrs' => $idFrs, 'idRep' => $idRep, 'CV' => $CV]);
                }
            }

            return new Response(443, [

            ], (string) \json_encode([
                    'statut' => 'O',
                    'path' => $path,
                ]));
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]);
        }
    }

    /* */
    public function validateReponseAction()
    {
        $idFrs = $this->request->getAttribute('idFrs');

        //Secifique a Oxalink
        $idAO   = $this->request->getAttribute('idAO');
        $typeFG = $this->request->getAttribute('typeFG');
        $idRep  = $this->request->getAttribute('idRep');
        $CV     = $this->request->getAttribute('CV');

        $aoDaRep     = new AoDaRep($this->pdo);
        $reponseRepo = new Reponse($this->pdo);
        $aoEvent     = new AoEvent($this->pdo);

        $trad = $this->getTranslationService();

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

        $message = '';
        foreach ($reponseRepo->getListDocAtt($idAO, $typeFG, $idFrs, $CV, $idRep) as $rep) {
            if (Sql::toBool($rep['OBLIGATOIRE']) && $rep['NOM_ORI'] == '') {
                if (!$message) {
                    $message = $trad->t('Le document attendu') . ' ' . $rep['TITRE_DOC'] . ' ' . $trad->t('est obligatoire') . '<br />';
                } else {
                    $message .= $trad->t('Le document attendu') . ' ' . $rep['TITRE_DOC'] . ' ' . $trad->t('est obligatoire') . '<br />';
                }
            }
        }

        if ($message) {
            return new Response(443, [

            ], $this->renderer->render('@popup-erreur/ErreurCreation', [
                            'ErreurValid' => $message,
                        ]));
        }

        $listeCV = [
            'C' => $trad->t('Conforme'),
            'V' => $trad->t('Variant'),
        ];

        $aoEvent = new AoEvent($this->pdo);
        $aoEvent->rqInsertEventAO($idAO, 'REP', Trad::strBuild(
            $trad->t('Validation de la réponse du fournisseur @1@ du @2@ de type @3@.'),
            $idFrs,
            Date::dateConverte($idRep),
            $listeCV[$CV],
        ), $idFrs, $typeFG);

        $idEvent = $aoEvent->getLastOrder($idAO, 'REP');

        $aoDaRep = new AoDaRep($this->pdo);
        $aoDaRep->update([
            'EVE_REP' => $idEvent['MAX_NUM_ORDRE'],
        ], ['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'DTE_REP' => $idRep, 'C_V' => $CV, 'TYPE_FG' => $typeFG]);

        //TODO à reporter avec la date de fin notation fournisseur
        // // vérification de l'existence d'un questionnaire pour contributeur
        // $contribQuestions = (new Reponse($this->pdo))->getContributorsQuestions($idAO);
        // $existsContribQuestionnaire = count($contribQuestions) > 0;

        // // si le questionnaire contributeur existe, on crée les réponses vides dans AO_REP_QST
        // if ($existsContribQuestionnaire) {
        //     $aoRepQst = new AoRepQst($this->pdo);
        //     $supplierList = (new AoFour($this->pdo))->findAll(['NO_AO' => $idAO]);
        //     $aoContribGrp = new AoContribGrp($this->pdo);
        //     foreach ($supplierList as $supplier) {
        //         foreach ($contribQuestions as $value) {
        //             // si les contributeurs devant répondre sont des contributeurs membres d'un groupe, on va chercher la liste des membres
        //             if ($value['PROFNOTEUR1'] == 'G') {
        //                 $contribList = $aoContribGrp->findAll(['NO_AO' => $idAO, 'GROUPE_CONTRIB' => $value['PROFNOTEUR2']]);
        //                 foreach ($contribList as $contrib) {
        //                     $aoRepQst->insert([
        //                         'NO_AO' => $idAO,
        //                         'DTE_REP' => $idRep,
        //                         'CODE_FOU' => $supplier['CODE_FOU'],
        //                         'TYPE_FG' => $supplier['TYPE_FG'],
        //                         'ID_THEME' => $value['ID_THEME'],
        //                         'ID_QUEST' => $value['ID_QUEST'],
        //                         'CONTRIB' => $contrib['CONTRIB'],
        //                     ]);
        //                 }
        //             } elseif ($value['PROFNOTEUR1'] == 'A') {
        //                 $aoRepQst->insert([
        //                     'NO_AO' => $idAO,
        //                     'DTE_REP' => $idRep,
        //                     'CODE_FOU' => $supplier['CODE_FOU'],
        //                     'TYPE_FG' => $supplier['TYPE_FG'],
        //                     'ID_THEME' => $value['ID_THEME'],
        //                     'ID_QUEST' => $value['ID_QUEST'],
        //                     'CONTRIB' => $_SESSION['Session_Login'],
        //                 ]);
        //             } else {
        //                 $aoRepQst->insert([
        //                     'NO_AO' => $idAO,
        //                     'DTE_REP' => $idRep,
        //                     'CODE_FOU' => $supplier['CODE_FOU'],
        //                     'TYPE_FG' => $supplier['TYPE_FG'],
        //                     'ID_THEME' => $value['ID_THEME'],
        //                     'ID_QUEST' => $value['ID_QUEST'],
        //                     'CONTRIB' => $value['PROFNOTEUR2'],
        //                 ]);
        //             }
        //         }
        //     }
        // }

        return new Response(200, [], (string) \json_encode([
            'path' => $this->router->generateUri('Consultation.Consultation.details', ['idAO' => $idAO, 'onglet' => 'Fournisseur']),
        ]));
    }

    public function devalidateReponseAction()
    {
        $idAO   = $this->request->getAttribute('idAO');
        $typeFG = $this->request->getAttribute('typeFG');
        $idFrs  = $this->request->getAttribute('idFrs');
        $idRep  = $this->request->getAttribute('idRep');
        $CV     = $this->request->getAttribute('CV');

        $aoDaRep   = new AoDaRep($this->pdo);

        $trad = $this->getTranslationService();

        $listeCV = [
            'C' => $trad->t('Conforme'),
            'V' => $trad->t('Variant'),
        ];

        $aoEvent = new AoEvent($this->pdo);
        $aoEvent->rqInsertEventAO($idAO, 'DRE', 'Dévalidation de la réponse du fournisseur ' . $idFrs . ' du ' . Date::dateConverte($idRep) . ' de type ' . $listeCV[$CV] . '.', $idFrs, $typeFG);

        $critereRecherche = [
            'NO_AO' => $idAO,
            'CODE_FOU' => $idFrs,
            'DTE_REP' => $idRep,
            'C_V' => $CV,
            'TYPE_FG' => $typeFG,
        ];

        $aoDaRep->update(['EVE_REP' => '0'], $critereRecherche);

        if (!$this->request->isAjax()) {
            return $this->redirect302(
                'Consultation.SaisieReponses.listeLigne',
                [
                    'idAO' => $idAO,
                    'typeFG' => $typeFG,
                    'idFrs' => $idFrs,
                    'idRep' => $idRep,
                    'CV' => $CV,
                ]
            );
        }

        return new Response(200, [], json_encode([
            "path" => $this->router->generateUri(
                'Consultation.SaisieReponses.listeLigne',
                [
                    'idAO' => $idAO,
                    'typeFG' => $typeFG,
                    'idFrs' => $idFrs,
                    'idRep' => $idRep,
                    'CV' => $CV,
                ]
            )
        ]));
    }

    /** Partie ligne de reponse **/

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

        $aoRep                    = new AoRep($this->pdo);
        $aoLigne                  = new AoLigne($this->pdo);
        $aoRepSl                  = new AoRepSl($this->pdo);
        $aoEntet                  = new AoEntet($this->pdo);
        $aoDaRep                  = new AoDaRep($this->pdo);
        $consultation             = $aoEntet->find($idAO);
        $infoEnteteRep            = $aoDaRep->find(['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'DTE_REP' => $idRep, 'C_V' => $CV, 'TYPE_FG' => $typeFG]);
        $infoEnteteRep['COM_FRS'] = sql::getMemo($this->pdo, $infoEnteteRep['COMMENT1']);

        $reponseRepo     = new Reponse($this->pdo);
        $derniereReponse = Sql::toBool($reponseRepo->isLastResponse($idAO, $idFrs, $idRep, $typeFG, $CV));
        $listeReponse    = $reponseRepo->listeReponseAO($idAO, $idFrs, $idRep, $typeFG, $CV);

        $pays    = new Pays($this->pdo);
        $paysTmp = $pays->fetchAll(['CODE_PAYS, LIBELLE'], ['tri_LIBELLE' => 'asc']);

        $listePays = [];
        foreach ($paysTmp as $val) {
            $listePays[$val['CODE_PAYS']] = $val['LIBELLE'];
        }

        $ligneConsultation = [];
        foreach ($listeReponse as $reponse) {
            if ($reponse['NO_AO']) {
                $reponse['listeVariant'] = $aoRepSl->findAll(['NO_AO' => $idAO, 'NO_PO_AO' => $reponse['NO_PO'], 'DTE_REP' => $idRep, 'CODE_FOU' => $idFrs, 'TYPE_FG' => $typeFG, 'C_V' => $CV]);
                // @phpstan-ignore-next-line
                $reponse['QTE']      = round($reponse['QTE'], 2);
                $ligneConsultation[] = $reponse;
            } else {
                $ligneAO    = $aoLigne->find(['NO_AO' => $idAO, 'NO_PO' => $reponse['NO_PO']]);
                $desComp = Sql::getMemo($this->pdo, $ligneAO['NM_DCOMP']);
                $idDesCompl = Sql::updateMemo($this->pdo, '', $desComp);

                $newReponse = [
                    'NO_AO' => $idAO,
                    'NO_PO_AO' => $ligneAO['NO_PO'],
                    'CODE_FOU' => $idFrs,
                    'DTE_REP' => $idRep,
                    'QTE' => round($ligneAO['QTE'], 2),
                    'UNITE' => $ligneAO['UNITE'],
                    'PU' => 0,
                    'DELAI' => $ligneAO['DELAI'],
                    'CODE_STE' => $ligneAO['CODE_STE'],
                    'DESCOMPL' => $idDesCompl,
                    'QTECOND' => '',
                    'C_V' => $CV,
                    'COMFOURN' => '',
                    'CODE_ART' => $ligneAO['CODE_ART'],
                    'DES_ART' => $ligneAO['DES'],
                    'DELAIJ' => '',
                    'DELAIT' => '',
                    'TYPE_FG' => $infoEnteteRep['TYPE_FG'] ?? '',
                    'REF_FOUR' => '',
                    'DES_FOUR' => '',
                    'COD_FAB' => $ligneAO['COD_FAB'],
                    'COD_GAM' => $ligneAO['COD_GAM'],
                    'REF_FAB' => $ligneAO['REF_FAB'],
                    'PAY_ORI' => '',
                    'PAY_PROV' => '',
                ];

                $aoRep->insert($newReponse);
                $newReponse['titre']      = $reponse['titre'] ?? '';
                $newReponse['sous_titre'] = $reponse['sous_titre'] ?? '';
                $ligneConsultation[]      = $newReponse;
            }
        }

        $devise = $aoEntet->find(['NO_AO' => $idAO], ['DEVISE'])['DEVISE'];

        $trad = $this->getTranslationService();

        Ariane::generate(2, $trad->t('Saisie réponse'));

        ArianeSub::init();
        if ($consultation['RFI_Q'] == 'Q') {
            ArianeSub::generate(0, 1, $trad->t('Postes'), $_SERVER['REQUEST_URI'], 1);
        }
        ArianeSub::generate(0, 2, $trad->t('Pièces jointes'), $this->router->generateUri('Consultation.SaisieReponsesPJ.listePJ', ['typeDoc' => 'P', 'idAO' => $idAO, 'typeFG' => $typeFG, 'idFrs' => $idFrs, 'idRep' => $idRep, 'CV' => $CV]));

        if (Sql::boolSql($consultation['COMP_QUEST']) == true) {
            ArianeSub::generate(0, 3, $trad->t('Questionnaire'), $this->router->generateUri('Consultation.SaisieReponsesQst.questionnaire', ['idAO' => $idAO, 'typeFG' => $typeFG, 'idFrs' => $idFrs, 'idRep' => $idRep, 'CV' => $CV]));
        }

        if (Sql::boolSql($consultation['COMP_DOC_ATT']) == true) {
            ArianeSub::generate(0, 4, $trad->t('Documents de la réponse'), $this->router->generateUri('Consultation.SaisieReponsesPJ.listePJ', ['typeDoc' => 'D', 'idAO' => $idAO, 'typeFG' => $typeFG, 'idFrs' => $idFrs, 'idRep' => $idRep, 'CV' => $CV]));
        }

        if (($infoEnteteRep['EVE_REP'] ?? '0') == '0' || ($infoEnteteRep['EVE_REP'] ?? 'P') == 'P') {
            $twig = '@Consultation/SaisieReponses/listeLigne';
        } else {
            $twig = '@Consultation/SaisieReponses/listeLigneNoEdit';
        }

        // le fournisseur a accès à oxalink ? si non, on peut répondre aux questions fournisseur
        $isSupplierOxalink = Sql::boolSql((new Fourniss($this->pdo))->find(['CODE' => $idFrs], ['GEREPORTAIL'])['GEREPORTAIL']);

        $userCanEdit =  Roles::droitsUtilisateur($this->pdo, 'HA_AO_ADM')
            || (Roles::droitsUtilisateur($this->pdo, 'HA_AO_CMV')
            && $consultation['ACH'] == $_SESSION["Session_Login"]);

        return $this->renderer->render($twig, [
            'idAO' => $idAO,
            'typeFG' => $typeFG,
            'idFrs' => $idFrs,
            'idRep' => $idRep,
            'CV' => $CV,
            'devise' => $devise,
            'pathBack' => ariane::getBackPath(),
            'consultation' => $consultation,
            'typeDel' => $consultation['TYPEDEL'],
            'menuActive' => Session::verifySessionTypeMenuTop(MenuTopEnum::P2P) ? 'eproc' : 'Consultations',
            'menuLeft' => 'gestionAO',
            'reponseEntete' => $infoEnteteRep,
            'ligneConsultation' => $ligneConsultation,
            'ligneSelect' => $ligneConsultation['0'] ?? [],
            'listePays' => $listePays,
            'canEdit' => ((($infoEnteteRep['EVE_REP'] ?? '0') == '0')
                && (!$isSupplierOxalink || Roles::droitsUtilisateur($this->pdo, 'HA_AO_SRF'))),
            'canDevalidate' => Roles::droitsUtilisateur($this->pdo, 'HA_AO_ADM')
                || (Roles::droitsUtilisateur($this->pdo, 'HA_AO_CMV')
                    && $consultation['ACH'] == $_SESSION["Session_Login"]),
            'contrib' => false,
            'derniereReponse' => $derniereReponse,
            'userCanEdit' => $userCanEdit
        ]);
    }

    public function ajaxInformationLigneAction(): string
    {
        $idAO    = $this->request->getAttribute('idAO');
        $typeFG  = $this->request->getAttribute('typeFG');
        $idFrs   = $this->request->getAttribute('idFrs');
        $idRep   = $this->request->getAttribute('idRep');
        $CV      = $this->request->getAttribute('CV');
        $idLigne = $this->request->getAttribute('idLigne');

        $reponseRepo = new Reponse($this->pdo);
        $ligneSelect = $reponseRepo->listeReponseAO($idAO, $idFrs, $idRep, $typeFG, $CV, $idLigne);

        return $this->renderer->render('@Consultation/SaisieReponses/ajaxZoneInfoLigne', [
            'idAO' => $idAO,
            'typeFG' => $typeFG,
            'idFrs' => $idFrs,
            'CV' => $CV,
            'idRep' => $idRep,
            'ligneSelect' => $ligneSelect['0'] ?? '',
        ]);
    }

    public function deleteReponseAction()
    {
        $idAO   = $this->request->getAttribute('idAO');
        $typeFG = $this->request->getAttribute('typeFG');
        $idFrs  = $this->request->getAttribute('idFrs');
        $idRep  = $this->request->getAttribute('idRep');
        $CV     = $this->request->getAttribute('CV');

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

        $aoDaRep->delete(['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'DTE_REP' => $idRep, 'C_V' => $CV, 'TYPE_FG' => $typeFG]);
        $aoRep->delete(['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'DTE_REP' => $idRep, 'C_V' => $CV, 'TYPE_FG' => $typeFG]);
        $aoRepPijo->delete(['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'DTE_REP' => $idRep, 'C_V' => $CV, 'TYPE_FG' => $typeFG]);
        $aoRepQst->delete(['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'DTE_REP' => $idRep, 'C_V' => 'C', 'TYPE_FG' => $typeFG]);
        $aoRepSl->delete(['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'DTE_REP' => $idRep, 'C_V' => $CV, 'TYPE_FG' => $typeFG]);
        $aoRetParLigne->delete(['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'RET_CV' => $CV, 'TYPE_FG' => $typeFG]);

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

        if ($consultation['RFI_Q'] == 'Q') {
            $path = $this->router->generateUri('Consultation.Consultation.details', ['idAO' => $idAO]);
        } else {
            $path = $this->router->generateUri('Consultation.Consultation.details', ['idAO' => $idAO, 'onglet' => 'Fournisseur']);
        }

        return new Response(200, [], (string) \json_encode([
            'path' => $path,
        ]));
    }

    public function ajaxUpdateValueAction()
    {
        $idAO   = $this->request->getAttribute('idAO');
        $typeFG = $this->request->getAttribute('typeFG');
        $idFrs  = $this->request->getAttribute('idFrs');
        $idRep  = $this->request->getAttribute('idRep');
        $CV     = $this->request->getAttribute('CV');

        $post      = $this->request->getParsedBody();
        $validator = $this->createValidator();


        $infoChps = explode('-', $post['chps']);
        $champs   = $infoChps[0];
        $idLigne  = $infoChps[1];

        if ($champs == 'DELAI') {
            Date::dateToSql($post['value']);
        }

        if ($champs == 'PU' || $champs == 'QTECOND') {
            // Format into float
            $isValid = $validator->isFloat('', $post['value'], Constante::formatQTE);
            if (!$isValid) {
                $post['value'] = '0';
            }
        }

        if (isset($infoChps[2])) {
            $aoRepSl = new AoRepSl($this->pdo);
            $aoRepSl->update([
                $champs => $post['value'],
            ], ['NO_AO' => $idAO, 'TYPE_FG' => $typeFG, 'CODE_FOU' => $idFrs, 'DTE_REP' => $idRep, 'C_V' => $CV, 'NO_PO_AO' => $idLigne, 'NO_SSLIG' => $infoChps[2]]);
        } else {
            $aoRep = new AoRep($this->pdo);
            $aoRep->update([
                $champs => $post['value'],
            ], ['NO_AO' => $idAO, 'TYPE_FG' => $typeFG, 'CODE_FOU' => $idFrs, 'DTE_REP' => $idRep, 'C_V' => $CV, 'NO_PO_AO' => $idLigne]);
        }


        return new Response(200);
    }

    public function addVarianteAction(): string
    {
        $idAO    = $this->request->getAttribute('idAO');
        $typeFG  = $this->request->getAttribute('typeFG');
        $idFrs   = $this->request->getAttribute('idFrs');
        $idRep   = $this->request->getAttribute('idRep');
        $CV      = $this->request->getAttribute('CV');
        $idLigne = $this->request->getAttribute('idLigne');

        $pays    = new Pays($this->pdo);
        $paysTmp = $pays->fetchAll(['CODE_PAYS, LIBELLE'], ['tri_LIBELLE' => 'asc']);

        $listePays = [];
        foreach ($paysTmp as $val) {
            $listePays[$val['CODE_PAYS']] = $val['LIBELLE'];
        }

        $reponseRepo  = new Reponse($this->pdo);
        $maxSousLigne = $reponseRepo->getMaxSousLigne($idAO, $idFrs, $idRep, $typeFG, $idLigne);
        $newSsLigne   = (int) $maxSousLigne['maxSousLigne'];

        $aoRepSl = new AoRepSl($this->pdo);
        $aoRepSl->insert([
            'NO_AO' => $idAO,
            'NO_PO_AO' => $idLigne,
            'DTE_REP' => $idRep,
            'CODE_FOU' => $idFrs,
            'TYPE_FG' => $typeFG,
            'C_V' => $CV,
            'NO_SSLIG' => $newSsLigne + 1,
        ]);

        return $this->renderer->render('@Consultation/SaisieReponses/addVariante', [
            'idAO' => $idAO,
            'typeFG' => $typeFG,
            'idFrs' => $idFrs,
            'idRep' => $idRep,
            'CV' => $CV,
            'listePays' => $listePays,
            'variant' => ['NO_PO_AO' => $idLigne, 'NO_SSLIG' => $newSsLigne + 1]
        ]);
    }

    public function deleteVariantAction()
    {
        $idAO      = $this->request->getAttribute('idAO');
        $typeFG    = $this->request->getAttribute('typeFG');
        $idFrs     = $this->request->getAttribute('idFrs');
        $idRep     = $this->request->getAttribute('idRep');
        $CV        = $this->request->getAttribute('CV');
        $idLigne   = $this->request->getAttribute('idLigne');
        $idVariant = $this->request->getAttribute('idVariant');

        $aoRepSl = new AoRepSl($this->pdo);
        $aoRepSl->delete([
            'NO_AO' => $idAO,
            'NO_PO_AO' => $idLigne,
            'DTE_REP' => $idRep,
            'CODE_FOU' => $idFrs,
            'TYPE_FG' => $typeFG,
            'C_V' => $CV,
            'NO_SSLIG' => $idVariant,
        ]);

        return new Response(200);
    }
}
