<?php

namespace Modules\Contrat\Controller;

use Skeleton\Controller\Controller;
use Helpers\Pagination\Paginator;
use Helpers\Fichier\Fichier;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\ArianeSub;
use Helpers\Trad\Trad;

class CentreAutoriseController extends Controller
{
    /**
     * @return Response|string
     * @throws \Exception
     */
    public function centreEmetteurAction()
    {
        $post = $this->request->getParsedBody();
        $accListes = new \Modules\Contrat\Repository\CentreAutorise($this->pdo);

        
        $id = $this->request->getAttribute('idacc');
        $type = $post['type'] = $this->request->getAttribute('type');
        $idType = $post['idType'] = $this->request->getAttribute('idType');
        
        $accTr = new \Entity\Model\CentreEmetteur($this->pdo);
        $accadreEntity = new \Entity\Model\Acccadre($this->pdo);

        $fetchAccadre = $accadreEntity->find($id);
        if (!$fetchAccadre) {
            return $this->redirect('Index.Index.error');
        }
        $fetchAcctr   = $accTr->fetchAll([], $post);
        $trad = $this->getTranslationService();
        if ($type=='fournisseur') {
            ArianeSub::generate(2, 0, $trad->t('Centres Autorisés'), $_SERVER['REQUEST_URI'], 1);
            
            $titre = $trad->t('Fournisseurs');
            $menuActive = 'Fournisseur';
            $menuLeft = 'GestionFournisseur';
        } elseif ($type=='groupement') {
            ArianeSub::generate(2, 0, $trad->t('Centres Autorisés'), $_SERVER['REQUEST_URI'], 1);
            
            $titre = $trad->t('Groupement');
            $menuActive = 'Fournisseur';
            $menuLeft = 'GestionGroupement';
        } elseif ($type=='marches') {
            \Helpers\Ariane\Ariane::generate(3, $trad->t('Centres Autorisés'), $post);
            
            $titre = $trad->t('Marchés');
            $menuActive = 'Contrats';
            $menuLeft = 'Contrat.marche.index';
        } else {
            \Helpers\Ariane\Ariane::generate(2, $trad->t('Centres Autorisés'), $post);

            $titre = $trad->t('Accords-cadres');
            $menuActive = 'Contrats';
            $menuLeft = 'Contrat.accord-cadre.index';
        }
        $accListe = $accListes->listCentreEmeteur($post, $id);
        
        $listeAutorise = array(
            "Oui" => $trad->t('Oui'),
            "Non" => $trad->t('Non'),
        );
        $paginator = new Paginator();
        $infoPagination = $paginator->generate($accListe, 0, $post);
        $trad = $this->getTranslationService();

        return $this->renderer->render('@Contrat/centre-autorise/centre-autorise-index', [
            'id' => $id,
            'listeAutorise' => $listeAutorise,
            'titleacc' => $fetchAccadre,
            'acctr' => $fetchAcctr,
            'centreListes' => $accListe,
            'menuActive' => $menuActive,
            'menuLeft' => $menuLeft,
            'infoPagination' => $infoPagination,
            'post' => $post,
            
            'type' => $type,
            'idType' => $idType,
            'TITRE' => $titre,
            'SOUSTITRE' => $id!='' ?
                Trad::strBuild(
                    $trad->t("Centres autorisés sur l'accord-cadre @1@ (@2@)"),
                    $fetchAccadre['LIBELLE'],
                    $id
                ) :
                Trad::strBuild(
                    $trad->t("Centres autorisés sur l'accord-cadre @1@"),
                    $fetchAccadre['LIBELLE']
                )
        ]);
    }
    public function centreLivraisonAction() : string
    {
        $post = $this->request->getParsedBody();
        $accListes = new \Modules\Contrat\Repository\CentreAutorise($this->pdo);
        
        $id = $this->request->getAttribute('idacc');
        $type = $post['type'] = $this->request->getAttribute('type');
        $idType = $post['idType'] = $this->request->getAttribute('idType');
    
        $accTrLiv = new \Entity\Model\CentreLivraison($this->pdo);
        $accadreEntity = new \Entity\Model\CentreLivraison($this->pdo);

        $fetchAccadre = $accadreEntity->find($id);
        $fetchAcctLiv = $accTrLiv->fetchAll([], $post);
        $trad = $this->getTranslationService();
        
        if ($type=='fournisseur') {
            ArianeSub::generate(2, 0, $trad->t('Centres Autorisés'), $_SERVER['REQUEST_URI'], 1);

            $titre = $trad->t('Fournisseurs');
            $menuActive = 'Fournisseur';
            $menuLeft = 'GestionFournisseur';
        } elseif ($type=='groupement') {
            ArianeSub::generate(2, 0, $trad->t('Centres Autorisés'), $_SERVER['REQUEST_URI'], 1);
            
            $titre = $trad->t('Groupement');
            $menuActive = 'Fournisseur';
            $menuLeft = 'GestionGroupement';
        } elseif ($type=='marches') {
            \Helpers\Ariane\Ariane::generate(3, $trad->t('Centres Autorisés'), $post);
            
            $titre = $trad->t('Marchés');
            $menuActive = 'Contrats';
            $menuLeft = 'Contrat.marche.index';
        } else {
            \Helpers\Ariane\Ariane::generate(2, $trad->t('Centres Autorisés'), $post);

            $titre = $trad->t('Accords-cadres');
            $menuActive = 'Contrats';
            $menuLeft = 'Contrat.accord-cadre.index';
        }

        $accListe = $accListes->listSocieteCentreLiv($post, $id);
                
        $listeAutorise = array(
            "Oui" => $trad->t("Oui"),
            "Non" => $trad->t("Non"),
        );
        $paginator = new Paginator();
        $infoPagination = $paginator->generate($accListe, 0, $post);

        return $this->renderer->render('@Contrat/centre-autorise/centre-de-livraison', [
            'id'             => $id,
            'listeAutorise'  => $listeAutorise,
            'titleacc'       => $fetchAccadre,
            'acctrliv'       => $fetchAcctLiv,
            'centreListes'   => $accListe,
            'menuActive'     => $menuActive,
            'menuLeft'       => $menuLeft,
            'infoPagination' => $infoPagination,
            'post'           => $post,
            'type'           => $type,
            'idType'         => $idType,
            'TITRE'          => $titre,
            'SOUSTITRE'      => $id!='' ?
                Trad::strBuild(
                    $trad->t("Centres autorisés sur l'accord-cadre @1@ (@2@)"),
                    $fetchAccadre['LIBELLE'],
                    $id
                ) :
                Trad::strBuild(
                    $trad->t("Centres autorisés sur l'accord-cadre @1@"),
                    $fetchAccadre['LIBELLE']
                )
            
        ]);
    }
    // CENTRE EMETTEUR
    public function modifierCentreAction()
    {
      
        $post = $this->request->getParsedBody();
        $codeacd = $this->request->getAttribute('idacc');
        $codecentre = $this->request->getAttribute('idcentre');
        $type = $this->request->getAttribute('type');
        $idType = $this->request->getAttribute('idType');


        $accTr = new \Entity\Model\CentreEmetteur($this->pdo);
        $fetchAcctr = $accTr->fetchAll([], $post);
        $accTrLiv = new \Entity\Model\CentreLivraison($this->pdo);
        $fetchAcctLiv = $accTrLiv->fetchAll([], $post);
    
        
        $accListes = new \Modules\Contrat\Repository\CentreAutorise($this->pdo);
        $accListe = $accListes->listByCodeAcd($codeacd, $codecentre);
        

        
        if (isset($post['autorise'])) {
            // tableau pour effectuer une suppression cibler lorsque valider le formulaire avec comme parametre 'non autorise' de la popup
 

            $isExist   =   $accTr ->find(['CODE_ACD' => $codeacd, 'CODE_CTR' => $codecentre]);
     
            if ($post['autorise'] == 0) {
                $accTr->delete(['CODE_ACD' => $codeacd, 'CODE_CTR' => $codecentre]);
            }
            if ($post['autorise'] == 1) {
                if ($isExist) {
                    return new Response(200, [
                        
                    ], 'Existe déjà');
                } else {
                    $insert =
                    [
                        'CODE_ACD'   => $codeacd,
                        'CODE_CTR'   => $codecentre
            
                    ];
                    
                    $accTr->insert($insert);
                }
            }
        }
        
        return $this->renderer->render('@Contrat/centre-autorise/popup-centre-autorise', [
            'idacc' => $codeacd,
            
            'idcentre' => $codecentre,
            'acctr' => $fetchAcctr,
            'accliste' => $accListe,
            'acctrliv' => $fetchAcctLiv,
            'post'   => $post,
            'type' => $type,
            'idType' => $idType,
        ]);
    }
    public function modifierCentreLivraisonAction()
    {
        
        $post = $this->request->getParsedBody();
        $codeacd = $this->request->getAttribute('idacc');
        $codecentre = $this->request->getAttribute('idcentre');
        $type = $this->request->getAttribute('type');
        $idType = $this->request->getAttribute('idType');
        
        
        $accTr = new \Entity\Model\CentreEmetteur($this->pdo);
        $fetchAcctr = $accTr->fetchAll([], $post);
        $accTrLiv = new \Entity\Model\CentreLivraison($this->pdo);
        $fetchAcctLiv = $accTrLiv->fetchAll([], $post);
        
        
        $accListes = new \Modules\Contrat\Repository\CentreAutorise($this->pdo);
        $accListe = $accListes->listByCodeAcdCentreLivraison($codeacd, $codecentre);

        
        if (isset($post['autorise'])) {
            $isExist   =   $accTrLiv ->find(['CODE_ACD' => $codeacd, 'CODE_CTR' => $codecentre]);
            
            if ($post['autorise'] == 0) {
                $accTrLiv->delete(['CODE_ACD' => $codeacd, 'CODE_CTR' => $codecentre]);
            }
            
            if ($post['autorise'] == 1) {
                if ($isExist) {
                    return new Response(200, [
                        
                    ], 'Existe déjà');
                } else {
                    $insert =
                    [
                        'CODE_ACD'   => $codeacd,
                        'CODE_CTR'   => $codecentre
                        
                    ];
                    
                    $accTrLiv->insert($insert);
                    
                    return new Response(200, [
                        
                    ], '');
                }
            }
        }
        
        return $this->renderer->render('@Contrat/centre-autorise/popup-centre-livraison', [
            'idacc'    => $codeacd,
            'idcentre' => $codecentre,
            
            'acctr'    => $fetchAcctr,
            'accliste' => $accListe,
            'acctrliv' => $fetchAcctLiv,
            'post'     => $post,
            'type'     => $type,
            'idType'   => $idType,
        ]);
    }
    
    public function exportCentreAutoriseAction() : string
    {
        $id = $this->request->getAttribute('idacc');
        $acc =new \Modules\Contrat\Repository\AccordCadre($this->pdo);

        $accListe = $acc->listExport($id);
        
        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            'export_acccadre_',
            $accListe,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService()
        );

        return 'ok';
    }
    
    public function gestionAutorisationCentreEmetteurAction()
    {
        $post = $this->request->getParsedBody();
        $type = $this->request->getAttribute('type');
        $idType = $this->request->getAttribute('idType');
        if (isset($post['valider'])) {
            $accTr = new \Entity\Model\CentreEmetteur($this->pdo);

            foreach ($post as $key => $value) {
                if (strpos($key, 'centre_') === 0) {
                    $idCentre = substr($key, 7);
                    $isExist = $accTr ->find(['CODE_ACD' => $post['idacc'], 'CODE_CTR' => $idCentre]);
                    if ($value=="1") {
                        if (!$isExist) {
                            $insert =
                            [
                                'CODE_ACD'   => $post['idacc'],
                                'CODE_CTR'   => $idCentre
                            ];
                            
                            $accTr->insert($insert);
                        }
                    } else {
                        if ($isExist) {
                            $accTr->delete(['CODE_ACD' => $post['idacc'], 'CODE_CTR' => $idCentre]);
                        }
                    }
                }
            }
            return new Response(200, [
                        
            ], '');
        }

        if ($type=='fournisseur') {
            $post = array_merge($post, $_SESSION['arianeSub'][2][0]['post']);
        } elseif ($type=='groupement') {
            $post = array_merge($post, $_SESSION['arianeSub'][2][0]['post']);
        } elseif ($type=='marches') {
            $post = array_merge($post, $_SESSION['ariane'][3]['post']);
        } else {
            $post = array_merge($post, $_SESSION['ariane'][2]['post']);
        }

        $id = $this->request->getAttribute('idacc');

        $accListes = new \Modules\Contrat\Repository\CentreAutorise($this->pdo);
        $accListe = $accListes->listCentreEmeteur($post, $id);

        return $this->renderer->render('@Contrat/centre-autorise/popup-gestion-autorisation', [
            'idacc'          => $id,
            'post'           => $post,
            
            'centreListes'   => $accListe,
            'pathValidation' => $this->router->generateUri('Contrat.centre-autorise.gestionAutorisationCentreEmetteur', ['idacc' => $id, 'type' => $type, 'idType' => $idType]),
            'pathRefresh'    => $this->router->generateUri('Contrat.centre-autorise.centreEmetteur', ['idacc' => $id, 'type' => $type, 'idType' => $idType]),
            'idRefresh'      => 'centre_emetteur',
            'formRefresh'    => 'filtre_societe',
        ]);
    }
    
    public function gestionAutorisationCentreLivraisonAction()
    {
        $post = $this->request->getParsedBody();
        $type = $this->request->getAttribute('type');
        $idType = $this->request->getAttribute('idType');

        if (isset($post['valider'])) {
            $accTrLiv = new \Entity\Model\CentreLivraison($this->pdo);

            foreach ($post as $key => $value) {
                if (strpos($key, 'centre_') === 0) {
                    $idCentre = substr($key, 7);
                    $isExist = $accTrLiv ->find(['CODE_ACD' => $post['idacc'], 'CODE_CTR' => $idCentre]);
                    if ($value=="1") {
                        if (!$isExist) {
                            $insert =
                            [
                                'CODE_ACD'   => $post['idacc'],
                                'CODE_CTR'   => $idCentre
                            ];
                            
                            $accTrLiv->insert($insert);
                        }
                    } else {
                        if ($isExist) {
                            $accTrLiv->delete(['CODE_ACD' => $post['idacc'], 'CODE_CTR' => $idCentre]);
                        }
                    }
                }
            }
            return new Response(200, [
                        
            ], '');
        }

        if ($type=='fournisseur') {
            $post = array_merge($post, $_SESSION['arianeSub'][2][0]['post']);
        } elseif ($type=='groupement') {
            $post = array_merge($post, $_SESSION['arianeSub'][2][0]['post']);
        } elseif ($type=='marches') {
            $post = array_merge($post, $_SESSION['ariane'][3]['post']);
        } else {
            $post = array_merge($post, $_SESSION['ariane'][2]['post']);
        }

        $id = $this->request->getAttribute('idacc');

        $accListes = new \Modules\Contrat\Repository\CentreAutorise($this->pdo);
        $accListe = $accListes->listSocieteCentreLiv($post, $id);


        return $this->renderer->render('@Contrat/centre-autorise/popup-gestion-autorisation', [
            'idacc'          => $id,
            
            'post'           => $post ,
            'centreListes'   => $accListe,
            'pathValidation' => $this->router->generateUri('Contrat.centre-autorise.gestionAutorisationCentreLivraison', ['idacc' => $id, 'type' => $type, 'idType' => $idType]),
            'pathRefresh'    => $this->router->generateUri('Contrat.centre-autorise.centreLivraison', ['idacc' => $id, 'type' => $type, 'idType' => $idType]),
            'idRefresh'      => 'centre_livraison',
            'formRefresh'    => 'filtre_societe',
        ]);
    }
}
