<?php
namespace Modules\ProjetAchat\Controller;

use Entity\Model\Hastutil;
use Helpers\Filter\FiltreAvance\GeneratorCs;
use Helpers\Trad\Trad;
use Modules\ProjetAchat\Service\ElementsConcernedService;
use Psr\Container\ContainerInterface;
use Skeleton\Controller\Controller;
use Skeleton\Renderer\RendererInterface;
use Skeleton\Router;
use Helpers\Ariane\Ariane;
use Modules\ProjetAchat\Repository\ProjetAchat;
use Modules\ProjetAchat\Service\DoublonsService;
use Modules\ProjetAchat\Service\ModeleProjetService;
use Entity\Model\DoarType;
use Entity\Model\DoarOpe;
use Entity\Model\DoarEtatAv;
use Helpers\Filter\FiltreAvance\Generator;
use GuzzleHttp\Psr7\Response;
use Helpers\Validator\Validator;
use Entity\Model\Doa;
use Modules\ProjetAchat\WebService\Projet;
use Modules\ProjetAchat\Repository\Doublons;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Parametres\Constante;
use Helpers\Outil\Roles;
use Modules\ProjetAchat\MenuContextuel\DoublonMenuContextuel;

class DoublonsController extends Controller
{
    /**
     * @var ElementsConcernedService
     */
    private $elementsConcernedService;

    private $dataService;

    /**
     * @var array|mixed
     */
    private $trads;

    public function __construct(RendererInterface $renderer, \PDO $pdo, Router $router, ContainerInterface $contenaire)
    {
        parent::__construct($renderer, $pdo, $router, $contenaire);
    }
    
    public function searchDoublonsAction() : string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        
        $doublonsService = $this->getService();

        $ProjetAchat = new ProjetAchat($this->pdo);
        $modeleProjetService = new ModeleProjetService($this->pdo);
        
        
        
        $listeSelectInput = [];
        if ($post) {
            $liste = $ProjetAchat->listeProjetAchatSearch($post);

            $menuContextuel = new DoublonMenuContextuel($this->pdo, $this->router, $this->getTranslationService());
            foreach ($liste as &$projet) {
                $projet['menuContextuel'] = $menuContextuel->generate($projet);
            }
            
            foreach ($post as $key => $value) {
                if (strpos($key, 'save_selected_projet_') === 0) {
                    $listeSelectInput[$key] = $value;
                }
            }
        } else {
            $liste = [];
        }
        
        $listeStatut = $modeleProjetService->listeStatut($trad);
        
        $DoarType = new DoarType($this->pdo);
        $listeTMP = $DoarType->fetchAll();
        
        foreach ($listeTMP as $item) {
            $listeType[$item['ID']] = $item['LIB'];
        }
        
        $DoarOpe = new DoarOpe($this->pdo);
        $listeTMP = $DoarOpe->fetchAll();
        
        foreach ($listeTMP as $item) {
            $ListeOpe[$item['CODE_OPE']] = $item['LIB'];
        }

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

        $listeIdProjet = [];
        foreach ($liste as $projet) {
            $listeIdProjet[] = "'".$projet['ID']."'";
        }
        
        $listeImplode = implode(',', $listeIdProjet);
        
        /** Build pannel **/
        $tabPannelStatut = $doublonsService->generatePannelStatut($post, $listeImplode);
        $tabPannelSociete = $doublonsService->generatePannelSociete($post, $listeImplode);
        $tabPannelGroupe = $doublonsService->generatePannelSociete($post, $listeImplode, false);
        $tabPannelTypeElem = $doublonsService->generatePannelTypeElem($post, $listeImplode);
        
        $tabPannel = array_merge($tabPannelStatut, $tabPannelSociete, $tabPannelGroupe, $tabPannelTypeElem);
        /** *********** **/
        
        /* Filtre avancées */
        $filtreAvance = new GeneratorCs($post, 'DOA', 'ID', $this->pdo, $this->getTranslationService());
        $filtreAvance->setFiltre('DATE_DEB', 'date', $trad->t('Date début'));
        $filtreAvance->setFiltre('DATE_FIN', 'date', $trad->t('Date fin'));
        $filtreAvance->setFiltre('DATE_CREAT', 'date', $trad->t('Date création'));
        $filtreAvance->setFiltre('CTR_EMETT', 'liste', $trad->t('Centre émetteur'), '', 'Ajax.liste.centreEmetteur', 'Centre');

        /* Ce n'est pas un écran de gestion */
        Ariane::generate(0, $trad->t('Recherche doublons'), $post, count($liste));
        
        $listSearch = ['CONTIENT' => $trad->t('Contient'), 'COMMENCE' => $trad->t('Commence par'), 'EXACT' => $trad->t('Exact')];
        
        $paginator = new \Helpers\Pagination\Paginator();
        $infopagination = $paginator->generate($liste, 30, $post, $this->renderer);
        
        return $this->renderer->render('@projetAchat/doublons/search', [
            'menuActive'            => 'ProjetAchat',
            'trad'                  => $trad,
            'login'                 => $_SESSION["Session_Login"],
            'user'                  => (new Hastutil($this->pdo))->find($_SESSION["Session_Login"]),
            'initFiltreAvance'      => $filtreAvance->getInit(),
            'filtreAvance'          => $filtreAvance->getFiltres(),
            'listeProjet'           => $liste,
            'tabPannel'             => $tabPannel,
            'listeStatut'           => $listeStatut,
            'listeType'             => $listeType,
            'ListeOpe'              => $ListeOpe,
            'ListeEtatAv'           => $ListeEtatAv,
            'post'                  => $post,
            'listSearch'            => $listSearch,
            'infoPagination'        => $infopagination,
            'listeSelectInput'      => $listeSelectInput,
        ]);
    }
    
    public function regroupProjetAction() : string
    {
        $postInit = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $post =  [];
        $listeSelectedInput = [];

        foreach ($postInit as $val) {
            $post[$val['name']] = $val['value']??'';
            
            if (strpos($val['name'], 'save_selected_projet_') === 0) {
                $listeSelectedInput[] = substr($val['name'], 21);
            }
        }

        $ProjetAchat = new ProjetAchat($this->pdo);
        
        /*$liste = $ProjetAchat->listeProjetAchat($post, true, true);

        foreach($liste as $val)
        {
            $listePere[$val['ID']] = $val['REF'].' - '.$val['LIB'];

            if(!Sql::boolSql($val['SUSPENDU']) && sql::boolSql($val['IS_PERE']))
            {
                $listPereNoSuspendu[$val['ID']] = $val['ID'];
            }
        }*/

        $listeImplodeFils = implode(',', $listeSelectedInput);
        $liste = $ProjetAchat->getListeProjetByListId($listeImplodeFils);
        foreach ($liste as $val) {
            $listeFils[$val['ID']] = $val['REF'].' - '.$val['LIB'];
        }

        foreach ($post as $key => $value) {
            if (strpos($key, 'save_selected_projet_') === 0) {
                $listeSelectInput[$key] = $value;
            }
        }

        krsort($listeFils);
        
        Ariane::generate(1, $trad->t('Regroupement de projets'));

        return $this->renderer->render('@projetAchat/doublons/regroupement', [
            'menuActive'            => 'ProjetAchat',
            'trad'                  => $trad,
            //'listePere'             => $listePere,
            'listeFils'             => $listeFils,
            'post'                  => $post,
            //'listPereNoSuspendu'    => $listPereNoSuspendu??[],
            'listeSelectInput'      => $listeSelectInput??[],
        ]);
    }
    
    /**
     * @return Response|string
     */
    public function ajaxRegroupProjetAction()
    {
        $post = $this->request->getParsedBody();
        $validator = $this->createValidator();
        $trad = $this->getTranslationService();
        
        $validator->isObligatoire(($post['type_regroup']??''), $trad->t('Type de regroupement'));
        if (($post['type_regroup']??'') == 'EXIST') {
            $validator->isObligatoire($post['PROJET_PERE'], $trad->t('Projet père'));
        } elseif (($post['type_regroup']??'') == 'NEW') {
            $validator->isCheck($post['ALL']);
            if ($post['ALL']) {
                $validator->isObligatoire($post['PROJET_COPIE'], $trad->t('Projet à copier'));
            }
        }
        
        if ($validator->isValid()) {
            if ($post['type_regroup'] == 'EXIST') {
                $doublonsService = $this->getService();
                
                $doublonsService->updateFamille($post['PROJET_PERE'], $post, false);
                
                $pathRedirect = $this->router->generateUri('ProjetAchat.ModeleProjet.details', ['typeObjet' => 'D', 'idObjet' => $post['PROJET_PERE']]);
                $postRedirect = [];
            } elseif ($post['type_regroup'] == 'NEW') {
                foreach ($post as $key => $value) {
                    if (strpos($key, 'save_selected_projet_') === 0) {
                        $listeSelectInput[$key] = $value;
                    }
                }
                
                if ($post['ALL']) {
                    $arrayPath = [
                        'type' => 'D',
                        'idProjet' => $post['PROJET_COPIE'],
                        'typeSource' => 'D',
                    ];
                } else {
                    $arrayPath = [
                        'type' => 'D',
                        'idProjet' => 'noId',
                    ];
                }
                
                $pathRedirect = $this->router->generateUri('ProjetAchat.ModeleProjet.createEdit', $arrayPath);
                $postRedirect['listeSelectInput'] = $listeSelectInput;
            }

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

    public function createSonAction() : string
    {
        $idProjet = $this->request->getAttribute('idProjet');
        
        $doaEntity = new Doa($this->pdo);
        $projetPere = $doaEntity->find($idProjet);
        
        $trad = $this->getTranslationService();
        
        Ariane::generate(1, $trad->t('Création projet fils'));
        
        return $this->renderer->render('@projetAchat/doublons/createSon', [
            'menuActive'    => 'ProjetAchat',
            'projetPere'    => $projetPere,
            'idProjet'      => $idProjet,
        ]);
    }
    
    /**
     * @return Response|string
     */
    public function validateSonAction()
    {
        $idProjet = $this->request->getAttribute('idProjet');
        $post = $this->request->getParsedBody();
        
        $trad = $this->getTranslationService();
        
        $doublonsRepo = new Doublons($this->pdo);
        $doaEntity = new Doa($this->pdo);
        $projetPere = $doaEntity->find($idProjet);
        
        $validator = $this->createValidator();

        $validator->isStringAvecEspace($trad->t('Libellé'), $post['LIB'], 1, 100);
        $validator->isStringAvecEspace($trad->t('Description'), $post['DESCR'], 0, 300);
        $validator->isCheck($post['RepriseDonnes']);
        $validator->isCheck($post['RepriseTachesActions']);
        
        if ($validator->isValid()) {
            $countSon = ((int) $doublonsRepo->countProjetSon($idProjet)['NB_FILS']) +1;
            
            $arrayDoa = [
                'LIB' => $post['LIB'],
                'REF' => $projetPere['REF'].'-'.$countSon,
                'DESCR' => $post['DESCR'],
                'ID_TYPE' => $projetPere['ID_TYPE'],
                'CODE_OPE' => $projetPere['CODE_OPE'],
                'PROPRIETAIRE' => $projetPere['PROPRIETAIRE'],
                'PRESCRIPTEUR' => $projetPere['PRESCRIPTEUR'],
                'CTR_EMETT' => $projetPere['CTR_EMETT'],
                'DATE_DEB' => $projetPere['DATE_DEB'],
                'DATE_FIN' => $projetPere['DATE_FIN'],
                'ID_CAL' => $projetPere['ID_CAL'],
            ];
            
            $champSupp = ChampSupp::listeCSDON('DOA', ChampSupp::autoCompletCodeEnr($idProjet), $this->pdo);
            
            foreach ($champSupp as $val) {
                $cs['CS_EXTENTION'.Constante::spliter.Constante::spliter.Constante::spliter.$val['NUM_FIX']] = $val['VALEUR'];
            }
            
            $projetWSDL = new Projet();
            $xmlResult = $projetWSDL->wsdlDuplication($idProjet, false, $arrayDoa, $cs??[], true, $post['RepriseDonnes'], $post['RepriseTachesActions']);
            
            
            $reponse = new \SimpleXMLElement($xmlResult->responseData);
            if ($reponse->Statut == "O") {
                $newID = (int)$reponse->NewID_DOA;
                $doublonsService = $this->getService();
                $doublonsService->updateFamille($idProjet, ['save_selected_projet_'.$newID => '1'], true);

                return new Response(443, [
                    
                ], (string) \json_encode([
                    'statut' => 'O',
                    'path' => $this->router->generateUri('ProjetAchat.ModeleProjet.details', ['typeObjet' => 'D', 'idObjet' => $newID]),
                    'post' => []
                ]));
            } else {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $reponse->$reponse,
                ]);
            }
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
            ]);
        }
    }

    private function getService() :DoublonsService
    {
        return new DoublonsService($this->pdo, $this->getTranslationService());
    }
}
