<?php
namespace Modules\ProjetAchat\Controller;

use Entity\Model\AoEntet;
use Entity\Model\DoaStruct;
use Helpers\Validator\Validator;
use Modules\GlobalApplication\Repository\DocumentsRattaches;
use Modules\ProjetAchat\Repository\Action;
use Modules\ProjetAchat\Service\ActionService;
use Skeleton\Controller\Controller;
use Helpers\Ariane\Ariane;
use Helpers\Trad\Trad;
use Modules\ProjetAchat\Repository\ProjetAchat;
use Entity\Model\DoarType;
use Entity\Model\DoarEtatAv;
use Entity\Model\DoarOpe;
use Modules\ProjetAchat\WebService\planning;
use Modules\ProjetAchat\Repository\TableauDeBord;
use Entity\Model\Doa;
use Modules\GlobalApplication\Repository\Utilisateur;
use Entity\Model\Centre;
use Modules\ProjetAchat\Service\ModeleProjetService;
use Psr\Container\ContainerInterface;
use Skeleton\Renderer\RendererInterface;
use Skeleton\Router;
use Helpers\Outil\Sql;
use Entity\Model\Hastutil;
use Modules\ProjetAchat\Repository\DoaEvent;
use Helpers\Outil\Date;
use Helpers\Outil\Mail;
use Helpers\ChampsSupplementaire\ChampSupp;
use Modules\ProjetAchat\WebService\Projet;
use GuzzleHttp\Psr7\Response;
use Helpers\Outil\Roles;
use Modules\ProjetAchat\Repository\Modele;
use Modules\ProjetAchat\Repository\ElementConcerned;
use Entity\Model\DoaData;
use Entity\Model\Societe;
use Modules\GlobalApplication\Repository\Societe as SocieteRepo;
use Helpers\Fichier\Fichier;
use Modules\ProjetAchat\MenuContextuel\GestionProjetMenuContextuel;
use Helpers\Parametres\Constante;

class GestionProjetAchatController extends Controller
{
    protected $modeleProjetService;

    public function __construct(RendererInterface $renderer, \PDO $pdo, Router $router, ContainerInterface $contenaire)
    {
        parent::__construct($renderer, $pdo, $router, $contenaire);
        $this->modeleProjetService = new ModeleProjetService($this->pdo);
    }
    
    public function tableauBordAction() : string
    {
        ModeleProjetService::resetDoaSession();
        $trad = $this->getTranslationService();
        
        $tableauDeBordRepo = new TableauDeBord($this->pdo);
        $listeAction = $tableauDeBordRepo->getListeAction(true);
        $listeProjet = $tableauDeBordRepo->getListeProjet();
        
        foreach ($listeAction as &$action) {
            $dateDepartTimestamp = strtotime($action['LIB_date_fin']);
            $date = $dateDepartTimestamp + ($action['DELAI_PREAVIS'] * -3600 * 24);
            $datePreavis = date('Ymd', $date);
            
            $action['LIB_date_prev'] = $datePreavis;
        }
        
        Ariane::generate(0, $trad->t('Tableau de bord'));
        
        return $this->renderer->render('@projetAchat/tableauDeBord/index', [
            'menuActive'    => 'ProjetAchat',
            'listeProjet'   => $listeProjet,
            'listeAction'   => $listeAction,
            'dateDuJours'   => date('Ymd'),
            'login'         => $_SESSION["Session_Login"],
        ]);
    }
    
    public function mesActionsAction() : string
    {
        $post = $this->request->getParsedBody();
        
        $trad = $this->getTranslationService();
        
        $tableauDeBordRepo = new TableauDeBord($this->pdo);
        $listeAction = $tableauDeBordRepo->getListeAction(true);
        
        foreach ($listeAction as &$action) {
            $dateDepartTimestamp = strtotime($action['LIB_date_fin']);
            $date = $dateDepartTimestamp + ($action['DELAI_PREAVIS'] * -3600 * 24);
            $datePreavis = date('Ymd', $date);
            
            $action['LIB_date_prev'] = $datePreavis;
        }
        
        Ariane::generate(0, $trad->t('Mes actions à traiter'), $post, count($listeAction));
        
        return $this->renderer->render('@projetAchat/tableauDeBord/listeAction', [
            'menuActive'    => 'ProjetAchat',
            'listeAction'   => $listeAction,
            'dateDuJours'   => date('Ymd'),
        ]);
    }
    
    public function indexAction() : string
    {
        ModeleProjetService::resetDoaSession();
        
        $post = $this->request->getParsedBody();
        
        if (!$post) {
            //$post['filter_PROPRIETAIRE'] = $_SESSION["Session_Login"];
            $post['MASQUER'] = true;
        }
        
        $droit = [
            'DOA_DOA_CM'    => Roles::droitsUtilisateur($this->pdo, 'DOA_DOA_CM', $_SESSION["Session_Login"]),
            'DOA_DOA_TT'    => Roles::droitsUtilisateur($this->pdo, 'DOA_DOA_TT', $_SESSION["Session_Login"]),
            'DOA_VIA_UO'    => Roles::droitsUtilisateur($this->pdo, 'DOA_VIA_UO', $_SESSION["Session_Login"]),
            'DOA_VIA_CT'    => Roles::droitsUtilisateur($this->pdo, 'DOA_VIA_CT', $_SESSION["Session_Login"]),
            'DOA_MACT'      => Roles::droitsUtilisateur($this->pdo, 'DOA_MACT', $_SESSION["Session_Login"]),
            'DOA_AJ_REP'    => Roles::droitsUtilisateur($this->pdo, 'DOA_AJ_REP', $_SESSION["Session_Login"]),
            'HA_AO_CMV'     => Roles::droitsUtilisateur($this->pdo, 'HA_AO_CMV', $_SESSION['Session_Login']),
            'HA_AO_ADM'     => Roles::droitsUtilisateur($this->pdo, 'HA_AO_ADM', $_SESSION['Session_Login']),
        ];

        $ProjetAchat = new ProjetAchat($this->pdo);
        $liste = $ProjetAchat->listeProjetAchat($post, $droit);

        $societes = (new SocieteRepo($this->pdo))->listRestrictedSocieteForUser();
        
        if ($societes !== null) {
            $societeArray = array_column($societes, 'CODE_STE');

            $aoEntet = new AoEntet($this->pdo);
            $societe = new Societe($this->pdo);
            foreach ($liste as &$consult) {
                if ($consult['NO_AO_LIE']) {
                    $infoAo = $aoEntet->find($consult['NO_AO_LIE']);
    
                    if ($infoAo['TYPE_SG'] == 'S' && !in_array($infoAo['CODE_STE'], $societeArray)) {
                        unset($consult['NO_AO_LIE']);
                    } elseif ($infoAo['TYPE_SG'] == 'G') {
                        $getSoc = $societe->fetchAll(['filter_egal_GROUPE' => $infoAo['CODE_STE']]);

                        $present = false;
                        foreach ($getSoc as $grpSoc) {
                            if (in_array($grpSoc['CODE_STE'], $societeArray)) {
                                $present = true;
                                break;
                            }
                        }

                        if (!$present) {
                            unset($consult['NO_AO_LIE']);
                        }
                    }
                }
            }
        }

        $trad = $this->getTranslationService();

        $menuContextuel = new GestionProjetMenuContextuel($this->pdo, $this->router, $trad);
        foreach ($liste as &$projet) {
            $projet['menuContextuel'] = $menuContextuel->generate($projet, true);
        }
        
        $listeStatut = $this->modeleProjetService->listeStatut($trad);
        
        $doa = new Doa($this->pdo);
        $doaFamilleExist = $doa->fetchAll([], ['IS_PERE' => 'T']);
        
        $DoarType = new DoarType($this->pdo);
        $listeTMP = $DoarType->fetchAll();

        foreach ($listeTMP as $item) {
            $listeType[$item['ID']] = $item['LIB'];
        }
        
        $DoarEtatAv = new DoarEtatAv($this->pdo);
        $listeTMP = $DoarEtatAv->fetchAll();
        
        foreach ($listeTMP as $item) {
            $ListeEtatAv[$item['ID']] = $item['LIB'];
        }
        
        $DoarOpe = new DoarOpe($this->pdo);
        $listeTMP = $DoarOpe->fetchAll();
        
        foreach ($listeTMP as $item) {
            $ListeOpe[$item['CODE_OPE']] = $item['LIB'];
        }

        Ariane::generate(0, $trad->t('Gestion'), $post, count($liste));
        
        $paginator = new \Helpers\Pagination\Paginator();
        $infopagination = $paginator->generate($liste, 0, $post, $this->renderer);

        $filtreAvance = new \Helpers\Filter\FiltreAvance\GeneratorCs(
            $post,
            'DOA',
            'ID',
            $this->pdo,
            $trad
        );

        $elementConcernedRepo = new ElementConcerned($this->pdo);
        $elementConcerned = $elementConcernedRepo->getListElementsConcerned();

        $champSupp = new ChampSupp($this->pdo);
        $getAllTsDonTMP = $champSupp->getAllTsDonExist();
        $getAllTsDon = [];
        foreach ($getAllTsDonTMP as $tsDon) {
            $getAllTsDon[$tsDon['TYPEDICO']] = $tsDon['TYPEDICO'];
        }

        $filtreAvance->setFiltre('DESCR', 'text', $trad->t('Description'));
        
        if ($elementConcerned) {
            $listStd =  ChampSupp::getListeTableStd();
            foreach ($elementConcerned as $element) {
                if ($listStd[$element['TYPE_ELEM']]??[]) {
                    $valueSTD = $listStd[$element['TYPE_ELEM']];
                    $filtreAvance->setFiltre('DOAELEM_'.$element['TYPE_ELEM'], 'liste', $trad->t($element['LIBELLE']), '', 'Ajax.liste.'.$valueSTD[1], $valueSTD[0], null, true);
                } else {
                    if ($getAllTsDon[$element['TYPE_ELEM']]??null) {
                        $filtreAvance->setFiltre('DOAELEM_'.$element['TYPE_ELEM'], 'liste', $trad->t($element['LIBELLE']), '', ['path' => 'Ajax.liste.tsDon', 'params' => ['typeDico' => $element['TYPE_ELEM']]], 'tsDon', null, true);
                    }
                }
            }
        }
        
        return $this->renderer->render('@projetAchat/gestion/index', [
            'menuActive'        => 'ProjetAchat',
            'infoPagination'    => $infopagination,
            'login'             => $_SESSION["Session_Login"],
            'user'              => (new Hastutil($this->pdo))
                                    ->find($_SESSION["Session_Login"]),
            'post'              => $post,
            'liste'             => $liste,
            'listeStatut'       => $listeStatut,
            'listeType'         => $listeType,
            'ListeEtatAv'       => $ListeEtatAv,
            'ListeOpe'          => $ListeOpe,
            'droit'             => $droit,
            'doaFamilleExist'   => $doaFamilleExist,
            'filtreAvance'      => $filtreAvance->getFiltres(),
            'initFiltreAvance'  => $filtreAvance->getInit(),
        ]);
    }
    
    public function ajaxDetailAction() : string
    {
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');
        
        $ProjetAchat = new ProjetAchat($this->pdo);
        $detail = $ProjetAchat->detailProjetAchatFull($idProjetAchat);
        
        return $this->renderer->render('@projetAchat/gestion/detail', [
            'filtreAvance'      => [],
            'initFiltreAvance'  => [],
            'pa'                => $detail,
        ]);
    }
    
    public function ajaxPlanningAction() : string
    {
        $post = $this->request->getParsedBody();
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');
        
        $idPlanning = $post['idPlanning']??'0';

        /*if($idPlanning == 'last')
        {
            $planningRepo = new \Modules\ProjetAchat\Repository\Planning($this->pdo);
            $planningMaxValue = $planningRepo->planning_GetMaxVersion($idProjetAchat);

            $idPlanning = $planningMaxValue['max_id']??'0';
        }*/

        $webService = new planning();
        $retourWSDL = $webService->generatePlanning($idProjetAchat, $idPlanning);

        $retour = new \SimpleXMLElement($retourWSDL->responseData);
        $pathInfoFile = pathinfo($retour->NomFichier);
        
        $url = $pathInfoFile['basename'];

        $url = $this->router->generateUri('GlobalApplication.ChargeDocument.chargeDocument', [
            'emplacement' => 'tmp',
            'urlFichier' => $url,
            'modeAffichage' => 0
        ]);

        return $this->renderer->render('@projetAchat/gestion/planning', [
            'urlPlanning' => $url,
        ]);
    }
    
    public function popupTransfereAction() : string
    {
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');
        
        $doaEntity = new Doa($this->pdo);
        $doa = $doaEntity->find($idProjetAchat);
        
        /** Specifique **/
        $specifique = new \Helpers\Additional\Specifique\Specifique();
        
        $classSpecifique = $specifique->specifique(
            '\\Modules\\ProjetAchat\\Service\\projetAchatSpecifique',
            'popupTransfereSpecifique',
            $this->pdo,
            $this->renderer,
            $this->getTranslationService(),
            $idProjetAchat
        );
        if ($classSpecifique) {
            return $classSpecifique;
        }
        /** ********** **/

        
        $utilisateurRepo = new Utilisateur($this->pdo);
        /* Liste des acheuteurs sur le perimetre utilisateurs */
        if ($listeUserTmp = $utilisateurRepo->rqGetListUserMultiSoc($_SESSION['Session_Login'], true)) {
            foreach ($listeUserTmp as $userTmp) {
                $listeUser[$userTmp['CODE']] = $userTmp['NOM'];
            }

            if ($doa['CTR_EMETT']) {
                $centreEntity = new Centre($this->pdo);
                $acheteurParDefaut = $centreEntity->find($doa['CTR_EMETT'])['ACHETEUR'];
            }
        }
        
        return $this->renderer->render('@projetAchat/ProjetAchat/popuptransmettre', [
            'listeUser'         => $listeUser,
            'acheteurParDefaut' => $acheteurParDefaut??'',
            'pa'                => $doa,
            'idProjetAchat'     => $idProjetAchat
        ]);
    }
    
    public function ajaxTransmettreAction() : string
    {
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        
        $doaEntity = new Doa($this->pdo);
        $hastutilEntity = new Hastutil($this->pdo);
        $doaEventEntity = new DoaEvent($this->pdo);
        $projetAchatEntity = new ProjetAchat($this->pdo);
        
        $doa = $doaEntity->find($idProjetAchat);
        
        $newProprio = $post['DESTINATAIRE'];
        $oldPoprio = $doa['PROPRIETAIRE'];
        
        $infoProprio =  $hastutilEntity->find($newProprio);
        $nomProprio = $infoProprio['NOM']??'';
        $nomOldProprio = $hastutilEntity->find($oldPoprio)['NOM']??'';
        
        $message = Trad::strbuild(
            $trad->t('Dossier transmis de @1@ à @2@'),
            $nomOldProprio,
            $nomProprio
        );
        
        $projetAchatEntity->updateResponsableAction($idProjetAchat, $oldPoprio, $newProprio);
        $projetAchatEntity->updateResponsableTaches($idProjetAchat, $oldPoprio, $newProprio);
        $projetAchatEntity->updateResponsableRaciAction($idProjetAchat, $oldPoprio, $newProprio);
        
        $doaEventEntity->rqInsertEventDOA($idProjetAchat, 'TRA', $message);
        $doaEventEntity->rqUpdateStatutDOA($idProjetAchat, 'P', $newProprio, $doa['STATUT']);
        
        $infoMail = $projetAchatEntity->rqGetInfoForMail($idProjetAchat);
        $infoMail['NOM_ANCIEN_PROPRIETAIRE'] = $nomOldProprio;
        $infoMail['NOM_NOUVEAU_PROPRIETAIRE'] = $nomProprio;
        $infoMail['NOM_UTILISATEUR_CONNECTE'] = $hastutilEntity->find($_SESSION["Session_Login"])['NOM']??'';
        
        $infoMail['DATE_DEB'] = Date::dateConverte($infoMail['DATE_DEB']);
        $infoMail['DATE_FIN'] = Date::dateConverte($infoMail['DATE_FIN']);
        
        $listeCS = (new ChampSupp($this->pdo))->getInfoValueCs('DOA', ChampSupp::autoCompletCodeEnr($idProjetAchat));
        
        Mail::generateMail(
            $this->pdo,
            $this->getTranslationService(),
            $infoProprio['EMAIL'],
            'DOA_TRANSMISSION',
            $infoProprio['COD_LNG'],
            $infoMail,
            $listeCS
        );
        
        return '';
    }
    
    public function devaliderAction()
    {
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');
        
        /*$doaEntity = new Doa($this->pdo);
        $doa = $doaEntity->find($idProjetAchat);*/
        
        $projetWSDL = new Projet();
        $xmlResult = $projetWSDL->wsdlDevaliderProjet($idProjetAchat);
        
        $reponse = new \SimpleXMLElement($xmlResult->responseData);
        if ($reponse->Statut == "O") {
            return new Response(200, [
                
            ], (string) \json_encode([
                'statut' => 'O',
            ]));
        } else {
            return new Response(443, [
                
            ], $this->renderer->render('@popup-erreur/ErreurXml', [
                'ErreurValid' => $reponse,
            ]));
        }
    }
    
    public function validateAction()
    {
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');
        
        /*$doaEntity = new Doa($this->pdo);
        $doa = $doaEntity->find($idProjetAchat);*/
        
        $doaData = new DoaData($this->pdo);
        $countConsultData = $doaData->findAll(['OBJET' => 'NO_AO', 'OBJET_DATA' => 'AO_ENTET', 'ID_OBJET' => $idProjetAchat]);
        $trad = $this->getTranslationService();

        $messageErreur = false;
        if (count($countConsultData)>1) {
            $messageErreur = $trad->t('Une seule donnée consultation peut être liée sur un même projet.');
        }
        
        if ($messageErreur) {
            return new Response(443, [
                
            ], $this->renderer->render('@popup-erreur/confirmationSuppresion', [
                'message'       => $messageErreur,
            ]));
        }
         
        $projetWSDL = new Projet();
        $xmlResult = $projetWSDL->wsdlValiderProjet($idProjetAchat, false);
        
        $reponse = new \SimpleXMLElement($xmlResult->responseData);
        if ($reponse->Statut == "O") {
            $planningRepository = new \Modules\ProjetAchat\Repository\Planning($this->pdo);
            $planningRepository->planning_Histo_InsertEntete($idProjetAchat, 0);
            $planningRepository->planning_Histo_InsertLignes('D', $idProjetAchat, 0);
            
            return new Response(200, [
                
            ], (string) \json_encode([
                'statut' => 'O',
            ]));
        } else {
            return new Response(443, [
                
            ], $this->renderer->render('@popup-erreur/ErreurXml', [
                    'ErreurValid'       => $reponse,
                    'pathValidation'    => $this->router->generateUri('ProjetAchat.GestionProjetAchat.confirmationValidate', ['idProjetAchat' => $idProjetAchat]),
                ]));
        }
    }

    /**
     * @return Response|string
     */
    public function confirmationValidateAction()
    {
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');
        
        $doaEntity = new Doa($this->pdo);
        $doa = $doaEntity->find($idProjetAchat);
        
        $projetWSDL = new Projet();
        $xmlResult = $projetWSDL->wsdlValiderProjet($idProjetAchat, true);
        
        $reponse = new \SimpleXMLElement($xmlResult->responseData);
        
        if ($reponse->Statut == "O") {
            $planningRepository = new \Modules\ProjetAchat\Repository\Planning($this->pdo);
            $planningRepository->planning_Histo_InsertEntete($idProjetAchat, 0);
            $planningRepository->planning_Histo_InsertLignes('D', $idProjetAchat, 0);
            
            return new Response(443, [
                
            ], (string) \json_encode([
                'statut'    => 'O',
                'path'      => $this->router->generateUri('ProjetAchat.ModeleProjet.details', ['typeObjet' => Sql::boolSql($doa['MODELE'])?'M':'D', 'idObjet' => $idProjetAchat]),
            ]));
        } else {
            $Xml_erreur = str_replace('"', '\'', $xmlResult->responseData);
            $Xml_erreur= preg_replace("#\n|\t|\r#", "", $Xml_erreur);
            
            return $this->renderer->render('@popup-erreur/ErreurXml', [
                'ErreurValid' => $reponse,
            ]);
        }
    }
    
    /**
     * @return Response
     */
    public function clotureAction()
    {
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');

        $projetWSDL = new Projet();
        $xmlResult = $projetWSDL->wsdlClotureProjet($idProjetAchat, false);
        
        $reponse = new \SimpleXMLElement($xmlResult->responseData);
        if ($reponse->Statut == "O") {
            return new response(200);
        } else {
            return new Response(443, [], $this->renderer->render('@popup-erreur/ErreurXml', [
                    'ErreurValid'    => $reponse,
                    'pathValidation' => $this->router->generateUri('ProjetAchat.GestionProjetAchat.confirmationCloture', ['idProjetAchat' => $idProjetAchat]),
                ]));
        }
    }
    
    /**
     * @return Response|string
     */
    public function confirmationClotureAction()
    {
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');
        
        $projetWSDL = new Projet();
        $xmlResult = $projetWSDL->wsdlClotureProjet($idProjetAchat, true);
        
        $reponse = new \SimpleXMLElement($xmlResult->responseData);
        
        if ($reponse->Statut == "O") {
            return new Response(443, [
                
            ], (string) \json_encode([
                'path'          => $_SESSION['ariane'][$_SESSION['ariane']['last']]['path'],
                'postGestion'   => $_SESSION['ariane'][$_SESSION['ariane']['last']]['post'],
            ]));
        } else {
            $Xml_erreur = str_replace('"', '\'', $xmlResult->responseData);
            $Xml_erreur= preg_replace("#\n|\t|\r#", "", $Xml_erreur);
            
            return $this->renderer->render('@popup-erreur/ErreurXml', [
                'ErreurValid' => $reponse,
            ]);
        }
    }

    /**
     * @return mixed
     */
    public function duplicateAction()
    {

        $post           = $this->request->getParsedBody();
        $typeObjet      = $this->request->getAttribute('typeObjet');
        $idProjet       = $this->request->getAttribute('idProjetAchat');
        $idObjet        = $this->request->getAttribute('idObjet');
        $idAction       = $this->request->getAttribute('idAction');
        $idRecord       = $this->request->getAttribute('idRecord');
        $idDonnee       = $this->request->getAttribute('idDonnee');
        $ligne          = $this->request->getAttribute('ligne');
        $idCategorie    = $this->request->getAttribute('idCategorie');

        $actionService = new ActionService($this->pdo);
        $actionRepo = new Action($this->pdo);
        $docAttRepo = new DocumentsRattaches($this->pdo);
        $doaStructEntity = new DoaStruct($this->pdo);
        $infoData = $doaStructEntity->find($idDonnee);
        $champSupp = new ChampSupp($this->pdo);

        if ($idAction == 'noId') {
            $datas = $actionService->getData($idObjet, null, $idCategorie);
        } else {
            $datas = $actionService->getData($idObjet, $idAction);
        }

        $listeData = $actionRepo->getInfoData($idAction, $idDonnee, $idRecord);

        $typeInput = [
            'A' => 'TEXT',
            'L' => 'SWITCH',
            'T' => 'DEVISE',
            'N' => 'TEXT',
            'D' => 'DATE',
            'H' => 'HEURE',
            'F' => 'FILE',
            'C' => 'TEXT',
        ];

        $droit = [
            'HA_AO_LIS' => Roles::droitsUtilisateur($this->pdo, 'HA_AO_LIS', $_SESSION["Session_Login"]),
            'HA_AO_CMV' => Roles::droitsUtilisateur($this->pdo, 'HA_AO_CMV', $_SESSION["Session_Login"]),
            'HA_AO_ADM' => Roles::droitsUtilisateur($this->pdo, 'HA_AO_ADM', $_SESSION["Session_Login"]),
        ];


        foreach ($listeData as &$data) {
            $data['TYPE'] = $typeInput[$data['TYPE_DATA']]??'';
            if ($data['TYPE_DATA'] == 'A') {
                $data['pathValidator'] = $this->router->generateUri('Ajax.validator.isStringAvecEspace');
                $data['paramValidator'] = "{'sizeMin' : '0', 'sizeMax' : '".$data['A_LONG']."'}";

                if ($data['A_LONG']>=60) {
                    $data['TYPE'] = 'TEXTAREA';
                }
            } elseif ($data['TYPE_DATA'] == 'L') {
                $data['VALEUR'] = ($data['VALEUR']??'')=='O'? 1:0;
            } elseif ($data['TYPE_DATA'] == 'T') {
                $data['pathValidator'] = $this->router->generateUri('Ajax.validator.float');
                $data['paramValidator'] = "{'format' : ".Constante::formatMontant."}";
                $data['VALEUR'] = number_format($data['VALEUR'], 2, '.', ' ');
            } elseif ($data['TYPE_DATA'] == 'N') {
                $data['pathValidator'] = $this->router->generateUri('Ajax.validator.float');
                $data['paramValidator'] = "{'format': ".$data['N_PARTIE_ENT'].".".$data['N_PARTIE_DEC']."}";
            } elseif ($data['TYPE_DATA'] == 'D') {
                $data['pathValidator'] = $this->router->generateUri('Ajax.validator.date');
                $data['paramValidator'] = "{'nomChamp' : '".$data['NOM_DATA']."', 'null': 'true'}";
            } elseif ($data['TYPE_DATA'] == 'H') {
                $data['pathValidator'] = $this->router->generateUri('Ajax.validator.isHours');
                $data['paramValidator'] = "{'nomChamp' : '".$data['NOM_DATA']."'}";
            } elseif ($data['TYPE_DATA'] == 'F') {
                $doc = $docAttRepo->docAttAvecMemos(str_pad($data['ID_OBJET'], 9, '0', STR_PAD_LEFT), ($data['VALEUR']??''), 'DOA');
                $data['VALEUR_DOC'] = ($doc['NOM_ORI']??'');
            } elseif ($data['TYPE_DATA'] == 'C') {
                if (stripos($data['EXP_CALCUL'], '[CS') !== false) {
                    $data['VALEUR'] = $actionService->calculedData($typeObjet, $idObjet, $idDonnee, $idRecord, $data['EXP_CALCUL']);
                }
                $data['VALEUR'] = number_format((float) $data['VALEUR'], 2, '.', ' ');

                $fieldsCalculated = true;
            } elseif ($data['TYPE_DATA'] == '' && (Sql::boolSql($data['LIE_A_OBJET']) == true || Sql::boolSql($data['DATA_LIE_A_OBJ']) == true)) {
                if ((Sql::boolSql($data['FLAG_ID_OBJET']) && Sql::boolSql($data['LIE_A_OBJET'])) || (Sql::boolSql($data['DATA_LIE_A_OBJ']) && Sql::boolSql($data['ID_OBJET_DATA']))) {
                    $data['TYPE'] = 'ZOOM';

                    if ($data['OBJET_DATA']) {
                        $objetData = $data['OBJET_DATA'];
                    } else {
                        $objetData = $infoData['OBJET'];
                    }

                    if (strpos($data['OBJET'], '|') !== false || strpos($data['CHAMP_OBJET_DATA'], '|') !== false) {
                        if ($objetData == 'SECTIMPU' || $objetData == 'DIRECTIO') {
                            $data['SECTORISE'] = \Helpers\Outil\Roles::droit($this->pdo, 'SISECTOR', 'PARAMSTE');
                        } elseif ($objetData == 'CODECOMP') {
                            $data['SECTORISE'] = \Helpers\Outil\Roles::droit($this->pdo, 'CDCSECTO', 'PARAMSTE');
                        } elseif ($objetData == 'SSCPTANA') {
                            $data['SECTORISE'] = \Helpers\Outil\Roles::droit($this->pdo, 'SCASECTO', 'PARAMSTE');
                        } elseif ($champSupp->tsDonExist($objetData)) {
                            $data['SECTORISE'] = true;
                        }

                        if ($data['VALEUR']) {
                            $splitValue = explode('|', $data['VALEUR']);
                            $data['SECTO_CODE_STE'] = $splitValue[0];
                            $data['VALEUR'] = $splitValue[1];
                        }
                    }

                    $inputGenerate = $champSupp->generateImputProjetAchat(
                        $this->router,
                        $this->getTranslationService(),
                        $objetData,
                        $data['SECTORISE'],
                        $data['ID_DATA']
                    );

                    if ($inputGenerate['Entity'] == 'AoEntet' && $droit['HA_AO_LIS'] == false) {
                        $inputGenerate['MODIFIABLE'] = 'F';
                    }
                    $data = array_merge($data, $inputGenerate);
                } else {
                    $data['TYPE'] = 'TEXT';
                    $data['pathValidator'] = $this->router->generateUri('Ajax.validator.isStringAvecEspace');
                    $data['paramValidator'] = "{'sizeMin' : '0', 'sizeMax' : '3000'}";
                    $data['MODIFIABLE'] = 'F';
                }
            }
        }

        $idRecord = ((int) $actionRepo->getMaxRecord($idObjet, $idDonnee)['maxID_RECORD'] +1);

        return $this->renderer->render(
            '@projetAchat/gestion/duplicate',
            [
                'datas' => $datas,
                'listeData' => $listeData,
                'typeObjet' => $typeObjet,
                'idObjet' => $idObjet,
                'idAction' => $idAction,
                'idDonnee' => $idDonnee,
                'idRecord' => $idRecord,
                'idProjet' => $idProjet,
                'ligne' => $ligne,
            ]
        );
    }

    /**
     * @return Response|string
     */
    public function ajourneAction()
    {
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');
        $trad = $this->getTranslationService();
        $post = $this->request->getParsedBody();

        $doa = new Doa($this->pdo);
        $pa = $doa->find($idProjetAchat);

        if ($post) {
            $validator = $this->createValidator();
            $validator->isStringAvecEspace($trad->t('Commentaire'), $post['COMMENTAIRE'], 1, 3000);

            if ($validator->isValid()) {
                $doaEvent = new DoaEvent($this->pdo);
                $doaEvent->rqInsertEventDOA($idProjetAchat, 'AJO', $post['COMMENTAIRE']);

                $projetAchatRepo = new ProjetAchat($this->pdo);
                $projetAchatRepo->ajourneProjet($idProjetAchat);

                $retour = [
                    'statut' => 'O',
                    'path' => $this->router->generateUri('ProjetAchat.GestionProjetAchat.index'),
                ];

                return new Response(200, [

                ], (string) \json_encode($retour));
            } else {
                $params = [
                    'alerte' => $validator->getError(),
                    'avertissement' => '',
                    'titrePopup' => $trad->t('Erreur sur l\'ajournement du projet')
                ];

                return new Response(200, [

                ], (string) \json_encode($params));
            }
        } else {
            return $this->renderer->render('@projetAchat/gestion/ajournePopup', [
                'idProjetAchat' => $idProjetAchat,
                'pa' => $pa,
                'post' => $post,
            ]);
        }
    }

    /**
     * @return Response
     */
    public function reprendreAction(): Response
    {
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');

        $projet = new Doa($this->pdo);
        $projet = $projet->find($idProjetAchat);

        $doaEvent = new DoaEvent($this->pdo);
        $doaEvent->rqInsertEventDOA($idProjetAchat, 'DJO');
        $projetAchatRepo = new ProjetAchat($this->pdo);
        $projetAchatRepo->reprendreProjet($idProjetAchat);

        return new Response(200);
    }
    
    public function listeModeleImportAction() : string
    {
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');
        $post = $this->request->getParsedBody();
        
        $doaEntity = new Doa($this->pdo);
        $doa = $doaEntity->find($idProjetAchat);

        $trad = $this->getTranslationService();
        
        if (!$post) {
            $post['tri_REF'] = 'desc';
        }
 
        $droit = [
            'DOA_MOD_CM' => Roles::droitsUtilisateur($this->pdo, 'DOA_MOD_CM', $_SESSION["Session_Login"]),
            'DOA_MOD_TT' => Roles::droitsUtilisateur($this->pdo, 'DOA_MOD_TT', $_SESSION["Session_Login"]),
            'DOA_DOA_CM' => roles::droitsUtilisateur($this->pdo, 'DOA_DOA_CM'),
        ];
        
        $ModeleProjetAchat  = new Modele($this->pdo);
        $liste              = $ModeleProjetAchat->listeModelesProjetAchat($post, $droit);
        
        Ariane::generate(2, $trad->t('Appliquer un modèle'), $post);
        
        $paginator                      = new \Helpers\Pagination\Paginator();
        $infopagination                 = $paginator->generate($liste, 0, $post, $this->renderer);
        
        return $this->renderer->render('@projetAchat/gestion/listeModele', [
            'menuActive'     => 'ProjetAchat',
            'liste'          => $liste,
            'infoPagination' => $infopagination,
            'idProjetAchat'  => $idProjetAchat,
            'doa'            => $doa,
            'post'           => $post,
        ]);
    }
    
    public function modeleImportAction()
    {
        $idProjetAchat = $this->request->getAttribute('idProjetAchat');
        $idModele = $this->request->getAttribute('idModele');
        
        $projetWSDL = new Projet();
        $xmlResult = $projetWSDL->importModele($idProjetAchat, $idModele);
        
        $reponse = new \SimpleXMLElement($xmlResult->responseData);
        if ($reponse->Statut == "O") {
            $modeleProjetService = new ModeleProjetService($this->pdo);
            $modeleProjetService->recalculePlanning($idProjetAchat, 'D');
            
            return new Response(200, [
                
            ], (string) \json_encode([
                'statut' => 'O',
                'path' => $this->router->generateUri('ProjetAchat.ModeleProjet.details', ['typeObjet' => 'D', 'idObjet' => $idProjetAchat]),
                'post' => []
            ]));
        } else {
            return new Response(443, [], $this->renderer->render('@popup-erreur/ErreurXml', [
                'ErreurValid'    => $reponse,
            ]));
        }
    }
    
    public function popupExportAction() : string
    {
        $post['multiSelectexportRFOBLI1'] = 'DOA.ID';
        
        return $this->renderer->render('@GlobalApplication/Popup/popupExport', [
            'pathExport' => $this->router->generateUri('ProjetAchat.GestionProjetAchat.export'),
            'formFilter' => 'filtre_projetAchat',
            'coloneExport' => $this->_exportGetTab(),
            'tabObli' => ['DOA.ID'],
            'post' => $post,
        ]);
    }
    
    public function exportAction() : string
    {
        $post = $this->request->getParsedBody();
        
        
        $trad = $this->getTranslationService();
        
        $arrayMultiSelect = array_filter($post, function ($k) {
            return stristr($k, 'multiSelect');
        }, ARRAY_FILTER_USE_KEY);

        // Filter any unauthorized fields
        $arrayMultiSelect = array_intersect(
            $arrayMultiSelect,
            array_keys($this->_exportGetTab())
        );
            
        $listeCS = [];
        foreach ($arrayMultiSelect as $key => &$multiSelect) {
            if (substr($multiSelect, 0, 12) == 'CS_EXTENSION') {
                $listeCS[] = substr($multiSelect, 12);
                unset($arrayMultiSelect[$key]);
            }
        }
            
        $listeSelect = implode(',', $arrayMultiSelect);
            
        if (empty($post['okFilter'])) {
            $post= [];
        }
                    
        $gestionProjet = new ProjetAchat($this->pdo);
        $listeProjet = $gestionProjet->listeProjetAchatExport($post, $listeSelect);
        
        $doa = new Doa($this->pdo);
        $listeChps = $doa->getArchitecture($this->getTranslationService());
        
        $champSupp = new ChampSupp($this->pdo);
        
        //On récupère la liste des champs DATE & BOOL afin de les traités après
        $listeChpsDate = [];
        $listeChpsBool = [];
        $listeChpsMemo = [];
        $keyValue = [];
        foreach ($listeChps as $key => $value) {
            $keyValue['DOA.'.$key] = $value['nomChamp'];
            
            if (isset($value['type'])) {
                if ($value['type']=='DATE') {
                    $listeChpsDate[] = $key;
                }
                if ($value['type']=='RADIO') {
                    $listeChpsBool[] = $key;
                }
                if ($value['type']=='MEMO') {
                    $listeChpsMemo[] = $key;
                }
            }
        }
        
        $tab = [];
        //On génère l'entete du fichier d'export
        foreach ($arrayMultiSelect as $value) {
            $tab[$value] = $keyValue[$value];
        }
        
        $repoChampSup = new ChampSupp($this->pdo);
        foreach ($listeCS as &$cs) {
            $cs = $repoChampSup->getinfoOneCs('DOA', $cs);
            $tab['CS_EXTENSION'.$cs['NUM_FIX']] = $cs['NOM'];
        }

        $oui = $trad->t('Oui');
        $non = $trad->t('Non');
        foreach ($listeProjet as &$ligne) {
            foreach ($listeCS as $csRFx) {
                $value = null;
                $idCS = $champSupp->autoCompletCodeEnr($ligne['ID'], '', 'DOA');
                /** @phpstan-ignore-next-line */
                $value = $champSupp->generateChampSupp('DOA', $idCS, $csRFx['NUM_FIX']);
                $value = $value[0]['VALUECHAMPSUPP'];
                
                /** @phpstan-ignore-next-line */
                if ($csRFx['TYPE']=='LOGIQUE') {
                    $value = $value=='O'? $oui : $non;
                /** @phpstan-ignore-next-line */
                } elseif ($csRFx['TYPE']=='DATE') {
                    $value = Date::dateConverte($value);
                }
                
                /** @phpstan-ignore-next-line */
                $ligne['CS_EXTENSION'.$csRFx['NUM_FIX']] = $value;
            }
            
            foreach ($listeChpsDate as $chps) {
                if (isset($ligne[$chps])) {
                    $ligne[$chps] = Date::dateConverte($ligne[$chps]);
                }
            }
            
            foreach ($listeChpsBool as $chps) {
                if (isset($ligne[$chps])) {
                    $ligne[$chps] = Sql::toBool($ligne[$chps]) ? $oui : $non;
                }
            }
            
            foreach ($listeChpsMemo as $chps) {
                if (isset($ligne[$chps])) {
                    $ligne[$chps] = Sql::getMemo($this->pdo, $ligne[$chps]);
                }
            }
        }
        
        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            'export_Projet_'.date('Ymd'),
            $listeProjet,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService(),
            $tab
        );
        
        return 'ok';
    }

    /**
     *
     * @return string[] label indexed by export key
     */
    private function _exportGetTab() :array
    {
        $tab = [];

        $listeChps = (new Doa($this->pdo))->getArchitecture($this->getTranslationService());
        foreach ($listeChps as $key => $value) {
            $tab['DOA.'.$key] = $value['nomChamp'];
        }
        
        $listeTmpCS = (new ChampSupp($this->pdo))->getInfoCS('DOA');
        
        foreach ($listeTmpCS as $cs) {
            $tab['CS_EXTENSION'.$cs['NUM_FIX']] = 'CS - '.$cs['NOM'];
        }
        return $tab;
    }
}
