<?php
namespace Modules\Catalogue\Controller;

use Entity\Model\ArtAssoc;
use Entity\Model\ArtEquiv;
use Entity\Model\CataEnt;
use Entity\Model\CatCaracInfo;
use Entity\Model\CCataSrc;
use Entity\Model\RQteCat;
use Entity\Model\TypeCarSel;
use Entity\Model\VersCata;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Ariane\ArianeSub;
use Helpers\Fichier\Fichier;
use Helpers\Fichier\Gestion_Fic_PJ;
use Helpers\Filter\FiltreAvance\Generator;
use Helpers\Outil\Sql;
use Helpers\Pagination\PaginatorGestion;
use Helpers\Parametres\Constante;
use Helpers\Securite\Securite;
use Helpers\Session\ParseBase1;
use Helpers\User\User;
use Modules\Catalogue\Enum\TypeArticleAssocies;
use Modules\Catalogue\Enum\TypeAssociesA;
use Modules\Catalogue\MenuContextuel\ArticlesAssocierMenuContextuel;
use Modules\Catalogue\Repository\ControleRepository;
use Modules\Catalogue\Validator\ArticlesAssocierValidator;
use Modules\Catalogue\Validator\ControleArticleValidator;
use Modules\RechercheArticles\Service\OutilRechercheService;
use Skeleton\Controller\Controller;

class ControleVersionController extends Controller
{
    public function init():void
    {
        Securite::setHeaderContentSecurityPolicyWithoutSelf();
    }

    public function listeArticlesAction():string
    {
        $idVersion      = $this->request->getAttribute('idVersion');
        $trad           = $this->getTranslationService();
        $post           = $this->request->getParsedBody();

        $paginator = new \Helpers\Pagination\PaginatorGestion();
        $paginator->generate(100, 'CCATASRC.REFARTFOU', 'asc');

        $listeArticle = (new ControleRepository($this->pdo))->getListeArticleCatalogue($idVersion, $post);
        
        foreach ($listeArticle as &$article) {
            $article['IMGART'] = $article['IMAGE'];
            OutilRechercheService::clearPathUrl($article);
        }

        if (!isset($post['clickTR'])) {
            $post['clickTR'] = $listeArticle[0]['IDLIGNE'];
        }

        Ariane::generate(2, $trad->t('Catalogues de base'), $post);
        $filtreAvance = new Generator($post);

        $filtreAvance->setFiltre('REFARTFAB', 'text', $trad->t('Article fabricant'));
        $filtreAvance->setFiltre('REFARTFOU', 'text', $trad->t('Article fournisseur'));
        $filtreAvance->setFiltre('DESIGNCRT', 'text', $trad->t('Désignation courte'));
        $filtreAvance->setFiltre('DESIGNLG', 'text', $trad->t('Désignation étendue'));

        $filtreAvance->setFiltre('FABRICANT', 'liste', $trad->t('Fabricant'), '', 'Ajax.liste.fabricant', 'Fabricant');
        $filtreAvance->setFiltre('GAMFABRIC', 'liste', $trad->t('Gamme fabricant'), '', 'Ajax.liste.gamme', 'Gamme');
        $filtreAvance->setFiltre('UNITE', 'liste', $trad->t('Unité'), '', 'Ajax.liste.unites', 'Unites');
        $filtreAvance->setFiltre('SOUSFAMI', 'liste', $trad->t('Sous-famille'), '', 'Ajax.liste.sousFamille', 'SousFamille');
        $filtreAvance->setFiltre('CODOUANE', 'liste', $trad->t('Code douane'), '', 'Ajax.liste.douanes', 'Douanes');
        $filtreAvance->setFiltre('CODEFOUR', 'liste', $trad->t('Fournisseur'), '', 'Ajax.liste.fournisseur', 'Fourniss');
        $filtreAvance->setFiltre('CODEARTI', 'liste', $trad->t('Article HaPlus'), '', 'Ajax.liste.articles', 'Articles');
        $filtreAvance->setFiltre('CODEACDR', 'liste', $trad->t('Accord-cadre'), '', 'Ajax.liste.accadre', 'Acccadre');
        $filtreAvance->setFiltre('IDRAYON', 'liste', $trad->t('Rayon'), '', 'Ajax.liste.rayon', 'Rayon');
        $filtreAvance->setFiltre('DEVISE_CAT', 'liste', $trad->t('Devise'), '', 'Ajax.liste.devise', 'Devise');
        $filtreAvance->setFiltre('TAUX_TVA', 'liste', $trad->t('TVA (%)'), '', 'Ajax.liste.TVA', 'TVA');

        $filtreAvance->setFiltre('PRIXBASE', 'numeric', $trad->t('Prix de base'));
        $filtreAvance->setFiltre('PRIXNET', 'numeric', $trad->t('Prix net'));
        $filtreAvance->setFiltre('REMISE', 'numeric', $trad->t('Remise'));
        $filtreAvance->setFiltre('CONDITNT', 'numeric', $trad->t('Quantité de conditionnement'));

        $filtreAvance->setFiltre('LONGUEUR', 'numeric', $trad->t('Longueur'));
        $filtreAvance->setFiltre('LARGEUR', 'numeric', $trad->t('Largeur'));
        $filtreAvance->setFiltre('HAUTEUR', 'numeric', $trad->t('Hauteur'));
        $filtreAvance->setFiltre('VOLUME', 'numeric', $trad->t('Volume'));
        $filtreAvance->setFiltre('POIDSBRUT', 'numeric', $trad->t('Poids brut'));
        $filtreAvance->setFiltre('POIDSNET', 'numeric', $trad->t('Poids net'));

        $filtreAvance->setFiltre('VALIDITEDU', 'date', $trad->t('Validité du'));
        $filtreAvance->setFiltre('VALIDITEAU', 'date', $trad->t('Validité au'));

        $filtreAvance->setFiltre('DELAIREA', 'numeric', $trad->t('Délai'));
        $filtreAvance->setFiltre('TXTCOND', 'text', $trad->t('Libellé de conditionnement'));

        $nombreArticle  = PaginatorGestion::getNbrArticle();
        $infopagination = PaginatorGestion::getInfoPagination();

        return $this->renderer->render('@catalogue/Controle/listeArticles', [
            'idVersion' => $idVersion,
            'listeArticles' => $listeArticle,
            'post'  => $post,
            'initFiltreAvance'  => $filtreAvance->getInit(),
            'filtreAvance'      => $filtreAvance->getFiltres(),
            'infoPagination'    => $infopagination,
        ]+ $this->_articleContent($idVersion));
    }

    public function ajaxArticlesAction():string
    {
        $trad           = $this->getTranslationService();
        $idLigne = $this->request->getAttribute('idLigne');
        $article = (new CCataSrc($this->pdo))->find(['IDLIGNE' => $idLigne]);
        $articleEqui = (new ArtEquiv($this->pdo))->find([
            'CODEART'   => $article['CODEARTI'],
            'CODEFOUR'  => $article['CODEFOUR'],
            'ARTFOUR'   => $article['REFARTFOU'],
            'CODEFAB'   => $article['FABRICANT'],
            'ARTFAB'    => $article['REFARTFAB'],
        ]);
        
        $article['IMGART'] = $article['IMAGE'];
        OutilRechercheService::clearPathUrl($article);

        $article['CLASSNUM'] = $articleEqui['CLASSNUM']??null;

        //pour le retour a l'écran etre bien replacer sur l'idligne selectionné
        $_SESSION['ariane'][$_SESSION['ariane']['last']]['post']['clickTR'] = $idLigne;

        return $this->renderer->render('@catalogue/Controle/_articles', [
            'article' => $article,
        ]+ $this->_articleContent($article['IDVERCATA']));
    }

    public function updateValueAction():Response
    {
        $idLigne = $this->request->getAttribute('idLigne');
        $post           = $this->request->getParsedBody();

        $validator = (new ControleArticleValidator($this->pdo, $this->getTranslationService()));

        if (str_starts_with($post['field'], 'CARACTER')) {
            $getId = str_replace('CARACTER', '', $post['field']);

            if ($getId) {
                $idLigne = $getId;
                $post['field'] = 'CARACTER';
            }
        }

        $validator->validatorField($post['field'], $post['value']);

        if (!$validator->isValid()) {
            return new Response(200, [

            ], (string) \json_encode([
                'statut' => 'B',
                'message' => substr($validator->getError(), 6),
            ]));
        }

        if ($idLigne) {
            (new CCataSrc($this->pdo))->update([
                (string)str_replace('text_', '', $post['field']) => $post['value'],
            ], ['IDLIGNE' => $idLigne]);
        }

        if ($post['field'] == 'TYPIMAGE' || $post['field'] == 'IMAGE') {
            $article = (new CCataSrc($this->pdo))->find(['IDLIGNE' => $idLigne]);

            $article['IMGART'] = $article['IMAGE'];
            OutilRechercheService::clearPathUrl($article);

            $content = $this->renderer->render('@catalogue/Controle/_articles', [
                'article' => $article,
            ]+ $this->_articleContent($article['IDVERCATA']));
        }

        return new Response(200, [], (string) \json_encode([
            'statut'            => 'O',
            'content'           => $content??null,
        ]));
    }

    public function ajoutArticleAction():response
    {
        $idVersion      = $this->request->getAttribute('idVersion');

        $ccataSrc = new CCataSrc($this->pdo);
        $ccataSrc->insert([
            'IDVERCATA' => $idVersion
        ]);

        $lastId = $ccataSrc->getLastInsertId('CCATASRC', 'IDLIGNE');

        return new Response(200, [], (string) \json_encode([
            'statut'            => 'O',
            'lastID'            => $lastId,
        ]));
    }

    public function deleteArticleAction():response
    {
        $idLigne = $this->request->getAttribute('idLigne');

        (new RQteCat($this->pdo))->delete(['IDLIGNE' => $idLigne]);
        (new CatCaracInfo($this->pdo))->delete(['ID_LIGNE' => $idLigne]);

        $infoArticle = (new CCataSrc($this->pdo))->find(['IDLIGNE' => $idLigne]);
        $versCata = (new VersCata($this->pdo))->find(['IDATACATA' => $infoArticle['IDVERCATA']]);
        $infoCata = (new CataEnt($this->pdo))->find(['ID_CATAL' => $versCata['ID_CATAL']]);

        $idObjet = implode('|', [
            $infoCata['ID_CATAL'],
            $infoArticle['CODEARTI'],
            $infoArticle['CODEFOUR'],
            $infoArticle['REFARTFOU'],
            $infoArticle['FABRICANT'],
            $infoArticle['REFARTFAB']
        ]);

        (new ArtAssoc($this->pdo))->delete(['T_ASS' => 'C', 'ID_OBJ' => $idObjet]);
        (new ArtAssoc($this->pdo))->delete(['T_OBJ_ASS' => 'C', 'ID_OBJ_ASS' => $idObjet]);

        (new CCataSrc($this->pdo))->delete(['IDLIGNE' => $idLigne]);

        return new Response(200);
    }

    public function ajaxChargeImageAction():response
    {
        $idLigne = $this->request->getAttribute('idLigne');
        $file = $this->request->getUploadedFiles();
        $trad           = $this->getTranslationService();

        $validator = $this->createValidator();

        if ($file) {
            $fileName = $file['importfichierCopie']->getClientFilename();
            $fileSize = $file['importfichierCopie']->getSize();
        }

        $validator->fileCheck($trad->t('Fichier d\'import'), $fileName ?? '', [], '', $fileSize ?? 0);

        if (!$validator->isValid()) {
            return new Response(400, [], (string) json_encode([
                'statut'    => 'E',
                    'content'   => $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                    'desactiveRow' => true,
                ])
            ]));
        }

        $newPath = Fichier::UploadDocAtt($fileName ?? '');
        $file['importfichierCopie']->moveTo($newPath["racine"] . $newPath["new_name"]);

        $ficPj = new Gestion_Fic_PJ($this->pdo, true);
        $newPath = $ficPj->insertFichier($newPath["new_name"]);

        (new CCataSrc($this->pdo))->update([
            'IMAGE' => $newPath
        ], [
            'IDLIGNE' => $idLigne
        ]);

        $article = (new CCataSrc($this->pdo))->find(['IDLIGNE' => $idLigne]);

        $article['IMGART'] = $article['IMAGE'];
        OutilRechercheService::clearPathUrl($article);
        
        return new Response(200, [], (string) json_encode([
            'statut'    => 'O',
            'content'   => $this->renderer->render('@catalogue/Controle/_articles', [
                'article' => $article,
            ]+ $this->_articleContent($article['IDVERCATA']))
        ]));
    }

    public function listeUNSPSCAction():string
    {
        $post           = $this->request->getParsedBody();
        $listeUNSPSC = (new ControleRepository($this->pdo))->getUNSPSC();

        return $this->renderer->render('@catalogue/Controle/UNSPSC/listeUNSPSC', [
            'listeUNSPSC' => $listeUNSPSC,
            'post' => $post
        ]);
    }

    public function ajaxUNSPSCAction():string
    {
        $post           = $this->request->getParsedBody();
        $listeUNSPSC = (new ControleRepository($this->pdo))->getUNSPSC($post['parent']);

        return $this->renderer->render('@catalogue/Controle/UNSPSC/_UNSPSC', [
            'listeUNSPSC'   => $listeUNSPSC,
            'post'          => $post,
        ]);
    }
    
    //----------------------------------------------------
    //__________________ PRIX DEGRESSIF __________________
    //----------------------------------------------------

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

        $listeQte = (new RQteCat($this->pdo))->findAll(['IDLIGNE' => $idLigne]);
        
        return $this->renderer->render('@catalogue/Controle/PrixDegressif/popupPrixDegressif', [
            'listeQte' => $listeQte,
            'IdLigne' => $idLigne,
        ]);
    }

    public function ajaxPrixDegressifAction():string
    {
        return $this->renderer->render('@catalogue/Controle/PrixDegressif/_prixDegressif', [
            'rand' => rand(),
        ]);
    }

    public function validatePrixDegressifAction():Response
    {
        $idLigne = $this->request->getAttribute('idLigne');
        $post           = $this->request->getParsedBody();
        $validator      = $this->createValidator();
        $trad           = $this->getTranslationService();

        $prix = [];
        foreach ($post['TRANCHE'] as $k => $tranche) {
            $validator->isInteger($trad->t('Tranche'), $post['TRANCHE'][$k], 1);
            $validator->isFloat($trad->t('Qte tranche'), $post['QTETRANCHE'][$k], Constante::formatQTE, true);
            $validator->isFloat($trad->t('Taux remise'), $post['QTETRANCHE'][$k], 13.2, false);
            $validator->isFloat($trad->t('Prix net'), $post['QTETRANCHE'][$k], Constante::formatPU, false);

            $prix[] = [
                'TRANCHE' => $post['TRANCHE'][$k],
                'QTETRANCHE' => $post['QTETRANCHE'][$k],
                'REMQTE' => $post['REMQTE'][$k],
                'PRIXNET' => $post['PRIXNET'][$k],
            ];
        }

        if ($validator->isValid()) {
            $infoLigne = (new CCataSrc($this->pdo))->find(['IDLIGNE' => $idLigne], ['IDVERCATA','IDLIGNE', 'CODEARTI']);
            $infoVers = (new VersCata($this->pdo))->find(['IDATACATA' => $infoLigne['IDVERCATA']], ['ID_CATAL']);

            (new RQteCat($this->pdo))->delete(['IDLIGNE' => $idLigne]);

            foreach ($prix as $p) {
                (new RQteCat($this->pdo))->insert([
                    'IDCAT'         => $infoVers['ID_CATAL'],
                    'IDVERCATA'     => $infoLigne['IDVERCATA'],
                    'IDLIGNE'       => $infoLigne['IDLIGNE'],
                    'COD_ART'       => $infoLigne['CODEARTI'],

                    'TRANCHE'       => $p['TRANCHE'],
                    'QTETRANCHE'    => $p['QTETRANCHE'],
                    'REMQTE'        => $p['REMQTE'],
                    'PRIXNET'       => $p['PRIXNET'],
                ]);
            }
            
            return new Response(200);
        } else {
            return new Response(400, [], (string) json_encode([
                'statut'    => 'E',
                'msgError'  => substr($validator->getError(), 6),
            ]));
        }
    }

    //----------------------------------------------------
    //__________________ Caracteristique _________________
    //----------------------------------------------------

    public function listeCaracAction():string
    {
        $idLigne = $this->request->getAttribute('idLigne');
        $typeCar = $this->request->getAttribute('typeCar');

        $trad = $this->getTranslationService();

        ariane::generate(3, $trad->t('Caractéristiques'));
        ArianeSub::init();
        ArianeSub::generate(
            0,
            0,
            $trad->t('Caractéristique Informatives'),
            $this->router->generateUri('Catalogue.ControleVersion.listeCarac', ['idLigne' => $idLigne, 'typeCar' => 'N']),
            $typeCar == 'N'? 1:0
        );
        ArianeSub::generate(
            0,
            1,
            $trad->t('Caractéristique Sélectives'),
            $this->router->generateUri('Catalogue.ControleVersion.listeCarac', ['idLigne' => $idLigne, 'typeCar' => 'S']),
            $typeCar == 'S'? 1:0
        );
        ArianeSub::generate(
            0,
            2,
            $trad->t('Images'),
            $this->router->generateUri('Catalogue.ControleVersion.listeCarac', ['idLigne' => $idLigne, 'typeCar' => 'I']),
            $typeCar == 'I'? 1:0
        );
        ArianeSub::generate(
            0,
            3,
            $trad->t('Fiche technique'),
            $this->router->generateUri('Catalogue.ControleVersion.listeCarac', ['idLigne' => $idLigne, 'typeCar' => 'U']),
            $typeCar == 'U'? 1:0
        );

        $infoArticle = (new CCataSrc($this->pdo))->find(['IDLIGNE' => $idLigne]);

        $versCata = (new VersCata($this->pdo))->find(['IDATACATA' => $infoArticle['IDVERCATA']]);
        $infoCata = (new CataEnt($this->pdo))->find(['ID_CATAL' => $versCata['ID_CATAL']]);

        $listeCarac = (new ControleRepository($this->pdo))->getListeCarac($idLigne, $typeCar);

        $libelleSave = (string)match ((string)$typeCar) {
            'N' => $trad->t('Enregistrer les caractéristiques informatives'),
            'S' => $trad->t('Enregistrer les caractéristiques sélectives'),
            'I' => $trad->t('Enregistrer les images'),
            'U' => $trad->t('Enregistrer les fiches techniques'),
            default => '',
        };

        return $this->renderer->render('@catalogue/Controle/caracteristique/listeCarac', [
            'versCata' => $versCata,
            'infoArticle' => $infoArticle,
            'infoCata' => $infoCata,
            'idLigne' => $idLigne,
            'typeCar' => $typeCar,
            'listeCarac' => $listeCarac,
            'libelleSave' => $libelleSave
        ]);
    }

    public function ajaxCaracAction():string
    {
        return $this->renderer->render('@catalogue/Controle/caracteristique/_carac', [
            'rand' => rand(),
        ]);
    }

    public function validateCaracAction():Response
    {
        $idLigne = $this->request->getAttribute('idLigne');
        $typeCar = $this->request->getAttribute('typeCar');
        $post           = $this->request->getParsedBody();
        $validator      = $this->createValidator();
        $trad           = $this->getTranslationService();

        $listeCarac = [];
        $maxIdCar = 0;
        foreach ($post['listeInput'] as $id) {
            if ($typeCar == 'S') {
                $validator->zoom('TypeCarSel', $post['COD_CAR'][$id], $trad->t('Code'), $this->pdo, false);
            } else {
                $validator->isStringAvecEspace($trad->t('Titre'), $post['TITRE_CAR'][$id], 0, 60);
            }
            $validator->isStringAvecEspace($trad->t('Description'), $post['VAL_CAR'][$id], 0, 512);

            $listeCarac[] = [
                'COD_CAR'       => $post['COD_CAR'][$id]??'',
                'TITRE_CAR'     => $post['TITRE_CAR'][$id]??'',
                'VAL_CAR'       => $post['VAL_CAR'][$id]??'',
                'ID_CAR'        => $post['ID_CAR'][$id]??'',
                'ISSU_CHARG'    => $post['ISSU_CHARG'][$id]? true:false,
            ];

            if ($maxIdCar<$post['ID_CAR'][$id]) {
                $maxIdCar = $post['ID_CAR'][$id];
            }
        }

        if ($validator->isValid()) {
            $infoLigne = (new CCataSrc($this->pdo))->find(['IDLIGNE' => $idLigne], ['IDVERCATA','IDLIGNE', 'CODEARTI']);
            $infoVers = (new VersCata($this->pdo))->find(['IDATACATA' => $infoLigne['IDVERCATA']], ['ID_CATAL']);

            (new CatCaracInfo($this->pdo))->delete(['ID_LIGNE' => $idLigne, 'TYP_CAR' => $typeCar]);
            foreach ($listeCarac as $carac) {
                if ($carac['ID_CAR'] == '') {
                    $maxIdCar++;
                    $carac['ID_CAR'] = $maxIdCar;
                }

                (new CatCaracInfo($this->pdo))->insert([
                    'ID_LIGNE'      => $idLigne,
                    'COD_ART'       => $infoLigne['CODEARTI'],
                    'ID_CAR'        => $carac['ID_CAR'],
                    'TYP_CAR'       => $typeCar,
                    'COD_CAR'       => $carac['COD_CAR'],
                    'TITRE_CAR'     => $carac['TITRE_CAR'],
                    'VAL_CAR'       => $carac['VAL_CAR'],
                    'ISSU_CHARG'    => $carac['ISSU_CHARG'],
                    'IDCATVER'      => $infoLigne['IDVERCATA']
                ]);
            }

            return new Response(443, [], (string) json_encode(['path' => $this->router->generateUri('Catalogue.ControleVersion.listeCarac', ['idLigne' => $idLigne, 'typeCar' => $typeCar])]));
        } else {
            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]));
        }
    }

    //-------------------------------------------------------
    //__________________ Article associés  __________________
    //-------------------------------------------------------
    //? articles associer

    public function listeArticleAssociesAction():string
    {
        $idLigne = $this->request->getAttribute('idLigne');
        $trad           = $this->getTranslationService();

        $infoArticle = (new CCataSrc($this->pdo))->find(['IDLIGNE' => $idLigne]);

        $versCata = (new VersCata($this->pdo))->find(['IDATACATA' => $infoArticle['IDVERCATA']]);
        $infoCata = (new CataEnt($this->pdo))->find(['ID_CATAL' => $versCata['ID_CATAL']]);

        $idObjet = implode('|', [
            $infoCata['ID_CATAL'],
            $infoArticle['CODEARTI'],
            $infoArticle['CODEFOUR'],
            $infoArticle['REFARTFOU'],
            $infoArticle['FABRICANT'],
            $infoArticle['REFARTFAB']
        ]);

        $idObjetURL = implode(constante::oxaPipe, [
            $infoCata['ID_CATAL'],
            $infoArticle['CODEARTI'],
            $infoArticle['CODEFOUR'],
            $infoArticle['REFARTFOU'],
            $infoArticle['FABRICANT'],
            $infoArticle['REFARTFAB']
        ]);

        $listeArtAssoc = (new ControleRepository($this->pdo))->getArticlesAssocies($idObjet);

        $menuContextuel = new ArticlesAssocierMenuContextuel($this->pdo, $this->router, $trad);

        foreach ($listeArtAssoc as &$articles) {
            $articles['ID_URL'] = str_replace('|', Constante::oxaPipe, $articles['ID_OBJ_ASS']);
            $articles['menuContextuel'] = $menuContextuel->generateArticlesAssocier($idLigne, $articles);
        }

        ariane::generate(3, $trad->t('Caractéristiques'));
        ArianeSub::init();
        ArianeSub::generate(
            0,
            0,
            $trad->t('Articles associés'),
            $this->router->generateUri('Catalogue.ControleVersion.listeArticleAssocies', ['idLigne' => $idLigne]),
            1
        );
        ArianeSub::generate(
            0,
            1,
            $trad->t('Associés à'),
            $this->router->generateUri('Catalogue.ControleVersion.listeAssociesA', ['idLigne' => $idLigne]),
        );

        return $this->renderer->render('@catalogue/Controle/ArticleAssocies/listeArticleAssocies', [
            'versCata' => $versCata,
            'infoArticle' => $infoArticle,
            'infoCata' => $infoCata,
            'idLigne' => $idLigne,
            'listeArtAssoc' => $listeArtAssoc,
            'idObjetURL'   => $idObjetURL,
            'typeArticles' => [...TypeArticleAssocies::getAsAssoc($trad)]
        ]);
    }

    public function createEditArticleAssociesAction():string
    {
        $idObjet = $this->request->getAttribute('idObjet');
        $typeObjetAss = $this->request->getAttribute('typeObjetAss');
        $idObjetAss = $this->request->getAttribute('idObjetAss');
        $idLigne = $this->request->getAttribute('idLigne');

        $idObjetClear = str_replace(Constante::oxaPipe, '|', $idObjet);
        $idObjetAssClear = str_replace(Constante::oxaPipe, '|', $idObjetAss);

        if ($typeObjetAss && $idObjetAss) {
            $infoArticles = (new ControleRepository($this->pdo))->getArticlesAssocies($idObjetClear, $typeObjetAss, $idObjetAssClear);
        } else {
            $infoArticles = [];
        }

        $trad           = $this->getTranslationService();

        $infoArticle = (new CCataSrc($this->pdo))->find(['IDLIGNE' => $idLigne]);

        $versCata = (new VersCata($this->pdo))->find(['IDATACATA' => $infoArticle['IDVERCATA']]);
        $infoCata = (new CataEnt($this->pdo))->find(['ID_CATAL' => $versCata['ID_CATAL']]);

        ArianeSub::generate(
            1,
            0,
            $trad->t('Ajout articles associés'),
            $this->router->generateUri('Catalogue.ControleVersion.listeArticleAssocies', ['idLigne' => $idLigne]),
            1
        );

        return $this->renderer->render('@catalogue/Controle/ArticleAssocies/createEditArticleAssocies', [
            'versCata' => $versCata,
            'infoArticle' => $infoArticle,
            'infoCata' => $infoCata,
            'idLigne' => $idLigne,

            'idObjet' => $idObjet,
            'typeObjetAss' => $typeObjetAss,
            'idObjetAss' => $idObjetAss,

            'article' => $infoArticles,

            'edit'      => ($typeObjetAss && $idObjetAssClear),

            'typeArticles' => [...TypeArticleAssocies::getAsAssoc($trad)]
        ]);
    }

    public function validateArticleAssociesAction():Response
    {
        $idObjet = $this->request->getAttribute('idObjet');
        $typeObjetAss = $this->request->getAttribute('typeObjetAss');
        $idObjetAss = $this->request->getAttribute('idObjetAss');
        $idLigne = $this->request->getAttribute('idLigne');
        $post = $this->request->getParsedBody();

        $idObjetClear = str_replace(Constante::oxaPipe, '|', $idObjet);
        $idObjetAssClear = str_replace(Constante::oxaPipe, '|', $idObjetAss);

        $validator = (new ArticlesAssocierValidator($this->pdo, $this->getTranslationService()));
        $validator->controleArticlesAssocier($post, $typeObjetAss && $idObjetAssClear);

        if ($validator->isValid()) {
            if ($typeObjetAss && $idObjetAssClear) {
                (new ArtAssoc($this->pdo))->update([
                    'COEFF'         => $post['COEFF'],
                    'OBLIG'         => $post['OBLIG']? true:false,
                ], [
                    'T_ASS'         => 'C',
                    'ID_OBJ'        => $idObjetClear,
                    'T_OBJ_ASS'     => $typeObjetAss,
                    'ID_OBJ_ASS'    => $idObjetAssClear,
                ]);
            } else {
                (new ArtAssoc($this->pdo))->insert([
                    'T_ASS'         => 'C',
                    'ID_OBJ'        => $idObjetClear,
                    'T_OBJ_ASS'     => $post['T_OBJ_ASS'],
                    'ID_OBJ_ASS'    => $post['ID_OBJ_ASS'],
                    'COEFF'         => $post['COEFF'],
                    'OBLIG'         => $post['OBLIG']? true:false,
                ]);
            }

            return new Response(443, [], (string) json_encode(['path' => $this->router->generateUri('Catalogue.ControleVersion.listeArticleAssocies', ['idLigne' => $idLigne]), 'post' => []]));
        } else {
            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]));
        }
    }

    public function deleteArticleAssociesAction():Response
    {
        $idObjet = $this->request->getAttribute('idObjet');
        $typeObjetAss = $this->request->getAttribute('typeObjetAss');
        $idObjetAss = $this->request->getAttribute('idObjetAss');

        $idObjetClear = str_replace(Constante::oxaPipe, '|', $idObjet);
        $idObjetAssClear = str_replace(Constante::oxaPipe, '|', $idObjetAss);

        (new ArtAssoc($this->pdo))->delete([
            'T_ASS'         => 'C',
            'ID_OBJ'        => $idObjetClear,
            'T_OBJ_ASS'     => $typeObjetAss,
            'ID_OBJ_ASS'    => $idObjetAssClear,
        ]);

        return new Response(200);
    }

    //? associer a

    public function listeAssociesAAction():string
    {
        $idLigne = $this->request->getAttribute('idLigne');
        $trad           = $this->getTranslationService();

        $infoArticle = (new CCataSrc($this->pdo))->find(['IDLIGNE' => $idLigne]);

        $versCata = (new VersCata($this->pdo))->find(['IDATACATA' => $infoArticle['IDVERCATA']]);
        $infoCata = (new CataEnt($this->pdo))->find(['ID_CATAL' => $versCata['ID_CATAL']]);

        $idObjet = implode('|', [
            $infoCata['ID_CATAL'],
            $infoArticle['CODEARTI'],
            $infoArticle['CODEFOUR'],
            $infoArticle['REFARTFOU'],
            $infoArticle['FABRICANT'],
            $infoArticle['REFARTFAB']
        ]);

        $idObjetURL = implode(constante::oxaPipe, [
            $infoCata['ID_CATAL'],
            $infoArticle['CODEARTI'],
            $infoArticle['CODEFOUR'],
            $infoArticle['REFARTFOU'],
            $infoArticle['FABRICANT'],
            $infoArticle['REFARTFAB']
        ]);

        $listeArtAssoc = (new ControleRepository($this->pdo))->getAssociesA($idObjet);

        $menuContextuel = new ArticlesAssocierMenuContextuel($this->pdo, $this->router, $trad);
        foreach ($listeArtAssoc as &$articles) {
            $articles['ID_URL'] = str_replace('|', Constante::oxaPipe, $articles['ID_OBJ']);
            $articles['menuContextuel'] = $menuContextuel->generateAssocierA($idLigne, $articles);
        }

        ariane::generate(3, $trad->t('Caractéristiques'));
        ArianeSub::generate(
            0,
            1,
            $trad->t('Associés à'),
            $this->router->generateUri('Catalogue.ControleVersion.listeAssociesA', ['idLigne' => $idLigne]),
            1
        );

        return $this->renderer->render('@catalogue/Controle/ArticleAssocies/ListeAssocieA', [
            'versCata' => $versCata,
            'infoArticle' => $infoArticle,
            'infoCata' => $infoCata,
            'idLigne' => $idLigne,
            'listeArtAssoc' => $listeArtAssoc,
            'idObjetURL' => $idObjetURL,
            'typeArticles' => [...TypeAssociesA::getAsAssoc($trad)]
        ]);
    }

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

        $idObjet = $this->request->getAttribute('idObjet');
        $typeAss = $this->request->getAttribute('typeAss');
        $idLigne = $this->request->getAttribute('idLigne');

        $idObjetClear = str_replace(Constante::oxaPipe, '|', $idObjet);
        $idObjetAssClear = str_replace(Constante::oxaPipe, '|', $idObjetAss);

        if ($typeAss && $idObjetAss) {
            $infoArticles = (new ControleRepository($this->pdo))->getAssociesA($idObjetAssClear, $typeAss, $idObjetClear);
        } else {
            $infoArticles = [];
        }

        $trad           = $this->getTranslationService();

        $infoArticle = (new CCataSrc($this->pdo))->find(['IDLIGNE' => $idLigne]);

        $versCata = (new VersCata($this->pdo))->find(['IDATACATA' => $infoArticle['IDVERCATA']]);
        $infoCata = (new CataEnt($this->pdo))->find(['ID_CATAL' => $versCata['ID_CATAL']]);

        ArianeSub::generate(
            1,
            0,
            $trad->t('Ajout articles associés'),
            $this->router->generateUri('Catalogue.ControleVersion.listeArticleAssocies', ['idLigne' => $idLigne]),
            1
        );

        return $this->renderer->render('@catalogue/Controle/ArticleAssocies/createEditlisteAssociesA', [
            'versCata' => $versCata,
            'infoArticle' => $infoArticle,
            'infoCata' => $infoCata,
            'idLigne' => $idLigne,

            'idObjet' => $idObjet,
            'typeAss' => $typeAss,
            'idObjetAss' => $idObjetAss,

            'article' => $infoArticles,

            'edit'      => ($typeAss && $idObjetAssClear),

            'typeArticles' => [...TypeAssociesA::getAsAssoc($trad)]
        ]);
    }

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

        $idObjet = $this->request->getAttribute('idObjet');
        $typeAss = $this->request->getAttribute('typeAss');
        
        $idLigne = $this->request->getAttribute('idLigne');

        $post = $this->request->getParsedBody();
        
        $idObjetClear = str_replace(Constante::oxaPipe, '|', $idObjet);
        $idObjetAssClear = str_replace(Constante::oxaPipe, '|', $idObjetAss);

        $validator = (new ArticlesAssocierValidator($this->pdo, $this->getTranslationService()));
        $validator->controleAssocierA($post, $typeAss && $idObjetAssClear);

        if ($validator->isValid()) {
            if ($typeAss && $idObjetAssClear) {
                (new ArtAssoc($this->pdo))->update([
                    'COEFF'         => $post['COEFF'],
                    'OBLIG'         => $post['OBLIG']? true:false,
                ], [
                    'T_ASS'         => $typeAss,
                    'ID_OBJ'        => $idObjetClear,
                    'T_OBJ_ASS'     => 'C',
                    'ID_OBJ_ASS'    => $idObjetAssClear,
                ]);
            } else {
                (new ArtAssoc($this->pdo))->insert([
                    'T_ASS'         => $post['T_ASS'],
                    'ID_OBJ'        => $post['ID_OBJ'],
                    'T_OBJ_ASS'     => 'C',
                    'ID_OBJ_ASS'    => $idObjetAssClear,

                    'COEFF'         => $post['COEFF'],
                    'OBLIG'         => $post['OBLIG']? true:false,
                ]);
            }

            return new Response(443, [], (string) json_encode(['path' => $this->router->generateUri('Catalogue.ControleVersion.listeAssociesA', ['idLigne' => $idLigne]), 'post' => []]));
        } else {
            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]));
        }
    }

    public function deleteAssociesAAction():Response
    {
        $idObjetAss = $this->request->getAttribute('idObjetAss');
        
        $idObjet = $this->request->getAttribute('idObjet');
        $typeAss = $this->request->getAttribute('typeAss');
        
        $idObjetClear = str_replace(Constante::oxaPipe, '|', $idObjet);
        $idObjetAssClear = str_replace(Constante::oxaPipe, '|', $idObjetAss);

        (new ArtAssoc($this->pdo))->delete([
            'T_ASS'         => $typeAss,
            'ID_OBJ'        => $idObjetClear,
            'T_OBJ_ASS'     => 'C',
            'ID_OBJ_ASS'    => $idObjetAssClear,
        ]);

        return new Response(200);
    }

    //!___________________________________________________________________________________

    /**
     * @return array<mixed>
     */
    private function _articleContent(?string $idversionCata = null)
    {
        $trad           = $this->getTranslationService();

        $versCata = (new VersCata($this->pdo))->find(['IDATACATA' => $idversionCata]);
        $infoCata = (new CataEnt($this->pdo))->find(['ID_CATAL' => $versCata['ID_CATAL']]);

        return [
            'versCata' => $versCata,
            'infoCata' => $infoCata,
            'urlOxadata' => (new ParseBase1())->getPath()->oxadataWeb,
            'urlImgart' => (new ParseBase1())->getPath()->Imgart,
            'typeImage' => [
                'C' => $trad->t('Copie'),
                'U' => $trad->t('Url interne'),
                'V' => $trad->t('Url variable'),
                'E' => $trad->t('Url externe')
            ],
        ];
    }
}
