<?php
namespace Modules\GlobalApplication\Controller;

use Skeleton\Controller\Controller;
use Entity\Model\Fourniss;
use Modules\GlobalApplication\Repository\Bdd;
use Helpers\Fichier\Fichier;
use Entity\Model\Paravrac;
use Entity\Model\Langues;
use Helpers\Outil\Sql;
use Entity\Model\Grpfou;
use Helpers\Ariane\ArianeSub;
use Helpers\Trad\Trad;

/**
 * Fournisseur
 * Groupement Fournisseur
 * Articles
 *
 */
class BddController extends Controller
{
    // phpcs:ignore
    public function BddAction() : string
    {
        $id = $this->request->getAttribute('id');
        $module = $this->request->getAttribute('MODULE');
        //POUR LES MODULES AVEC WF
        $codeDemande=$this->request->getAttribute('codeDemande');
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();
        $bdd = new Bdd($this->pdo);

        if ($module=='Fournisseur') {
            if (empty($post['array_serialize'])) {
                $value=[
                    "Langue" => $_SESSION['Session_Langue'],
                    "Login" => $_SESSION['Session_Login'],
                    "no_ao" => $_SESSION['Session_NumClient'],
                    "codeFrs" => $id=='noId'? '':$id,
                    'codeDemande' => $codeDemande,
                    'affDemande' => '',
                    'mode' => 'V',
                ];
                
                $xmlResult = new \Modules\Fournisseur\WebService\Fournisseur();
                $xmlResult= $xmlResult->ficheFournisseur($value);
                
                $fournisseur = new \SimpleXMLElement($xmlResult->responseData);
                $XML_BDD = $fournisseur->Fournisseur->ListBDD;
                
                $listeBdd=[];
                foreach ($XML_BDD->BDD as $XMLBDD) {
                    $listeBdd[]= [
                        'ETAT' => strval($XMLBDD->attributes()->Etat),
                        'NO_PAGE' => strval($XMLBDD->NO_PAGE),
                        'NUMORDRE' => strval($XMLBDD->NUMORDRE),
                        'TITRE' => strval($XMLBDD->TITRE),
                        'TEXTEBDD' => strval($XMLBDD->TEXTEBDD),
                        'VEPROC' => strval($XMLBDD->VEPROC),
                        'ONGLET' => strval($XMLBDD->ONGLET),
                        'LANGUE' => strval($XMLBDD->LANGUE),
                        
                        'OLD_NO_PAGE' => strval($XMLBDD->NO_PAGE->attributes()->ValeurModif),
                        'OLD_NUMORDRE' => strval($XMLBDD->NUMORDRE->attributes()->ValeurModif),
                        'OLD_TITRE' => strval($XMLBDD->TITRE->attributes()->ValeurModif),
                        'OLD_TEXTEBDD' => strval($XMLBDD->TEXTEBDD->attributes()->ValeurModif),
                        'OLD_VEPROC' => strval($XMLBDD->VEPROC->attributes()->ValeurModif),
                        'OLD_ONGLET' => strval($XMLBDD->ONGLET->attributes()->ValeurModif),
                        'OLD_LANGUE' => strval($XMLBDD->LANGUE->attributes()->ValeurModif),
                    ];
                }
            } else {
                $listeBdd = unserialize($post['array_serialize'], ["allowed_classes" => false]);
            }
            $serialize = serialize($listeBdd??[]);
        } else {
            $listeBdd = $bdd->listeBdd($id, $post, false, $module);
        }

        $paginator = new \Helpers\Pagination\Paginator();
        $infopagination = $paginator->generate($listeBdd, 10, $post, $this->renderer, 'Gestion');
        
        
        if ($module=='Fournisseur') {
            $fournis = new Fourniss($this->pdo);
            $fournis = $fournis->find($id);
            
            $menuActive = 'Fournisseur';
            $menuLeft = 'GestionFournisseur';
            $libelle = $fournis["RS"]??$fournisseur->Fournisseur->Identity->RS;
            
            $titre= $trad->t('Fournisseur');
            
            if ($codeDemande) {
                ArianeSub::generate(0, 4, $trad->t('BDD'), $_SERVER['REQUEST_URI'], 1, $post);
            } else {
                ArianeSub::generate(1, 0, $trad->t('BDD'), $_SERVER['REQUEST_URI'], 1, $post);
            }
        } elseif ($module=='Groupement') {
            $menuActive = 'Fournisseur';
            $menuLeft = 'GestionGroupement';
            $titre='Groupement';
            
            $grp = new Grpfou($this->pdo);
            $grp = $grp->find($id);
            $libelle = $grp['RS'];
            
            ArianeSub::generate(1, 0, $trad->t('BDD'), $_SERVER['REQUEST_URI'], 1, $post);
        } elseif ($id=='Article') {
        } else {
            $fournis = new Fourniss($this->pdo);
            $fournis = $fournis->find($id);
            
            $menuActive = 'Fournisseur';
            $menuLeft = 'GestionFournisseur';
            $libelle = $fournis["RS"];
            $articleTrue=true;
            $titre='Fournisseurs';
            
            ArianeSub::generate(2, 0, $trad->t('BDD d\'article'), $_SERVER['REQUEST_URI'], 1);
        }
        

        
        $ONGLET = [
            'F' => 'Fournisseur',
            'D' => 'Détail panier',
        ];
        
        return $this->renderer->render('@GlobalApplication/Bdd/bdd', [
            'menuActive' => $menuActive??'',
            'menuLeft' => $menuLeft??'',
            "id" => $id,
            "libelle" => $libelle??'',
            "bddIndex" => true,
            "listeBdd" => $listeBdd,
            'infoPagination' => $infopagination,
            'MODULE' => $module,
            'articlesTRUE' => $articleTrue??false,
            'Titre' => $titre??'',
            'suiviDemande' => $codeDemande? true:false,
            'listeEtat' => ['A' => $trad->t('Nouveau') ,'S' => $trad->t('Supprimer')],
            'array_serialize' => $serialize??'',
            'listeOnglet' => $ONGLET,
        ]);
    }
    
    public function exportBddAction() : string
    {
        $code = $this->request->getAttribute('id');
        $module = $this->request->getAttribute('MODULE');
        $post = $this->request->getParsedBody();
        
        $bdd = new Bdd($this->pdo);
        $listeBdd = $bdd->listeBdd($code, $post, true, $module);
        $trad = $this->getTranslationService();
        
        foreach ($listeBdd as &$value) {
            $value['EPROC'] = (sql::boolSql($value['EPROC'])? 'Oui':'Non');
            $value['ONGLET'] = $value['ONGLET']=='F'? $trad->t('Fournisseur') : $trad->t('Détail panier');
        }
        
        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            "export_bdd_".$code,
            $listeBdd,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService()
        );

        return 'ok';
    }
    
    public function creationBddAction()
    {
        $id = $this->request->getAttribute('id');
        $module = $this->request->getAttribute('MODULE');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $PARAVRAC= new Paravrac($this->pdo);
        $numMinValue= $PARAVRAC->find(['TYPEPARV' => 'PARAMBDD',  'CODEPARV'=> 'BDD_1ERELIGNE']);
        
        if (!$numMinValue || str_replace(' ', '', $numMinValue['LIB01PARV'])=='0' || str_replace(' ', '', $numMinValue['LIB01PARV'])=='00') {
            $numMinValue='1';
        } else {
            $numMinValue=$numMinValue['LIB01PARV'];
        }
        
        if ($PARAVRAC->getFlag('PARAMOXA', 'MULTILNGACTIF')) {
            $post['MultiLangue']=true;
            $langues = (new Langues($this->pdo))->listChoice();
        }
        
        if ($this->request->getMethod() == 'POST') {
            $validator = $this->createValidator();
            $BDD = new Bdd($this->pdo);
            
            $validator->isInteger($trad->t("Numéro"), $post['NO_PAGE'], 1, 2);
            $validator->isInteger($trad->t("Numéro d'ordre"), $post['NUMORDRE']);
            $validator->isStringAvecEspace($trad->t("Sommaire"), $post['TITRE'], 1, 60);
            $validator->isCheck($post['VEPROC']);
            
            $validator->isStringAvecEspace("Commentaires", $post['TEXTEBDD'], 1, 300);
            
            $estPresent = $BDD->bddExist($id, $post['NO_PAGE'], $module);
            $validator->isTrue($estPresent, Trad::strBuild($trad->t('Le numéro @1@ existe déjà pour ce fournisseur'), $post['NO_PAGE']));
            
            if ($validator->isValid()) {
                $BDD->nouveauBdd($id, $module, $post);
                
                if ($id!='Article') {
                    return $this->redirect('GlobalApplication.Bdd.bdd', ['MODULE' => $module, 'id' => $id]);
                }
            } else {
                $erreur= $validator->getError();
            }
        }

        if ($id=='Article') {
        } else {
            $fournis = new Fourniss($this->pdo);
            $fournis = $fournis->find($id);
            
            $menuActive = 'Fournisseur';
            $menuLeft = 'GestionFournisseur';
            $libelle = $fournis["RS"];
            $layout ='@layoutFournisseur/fournisseur.twig';
            $articleTrue=true;
            
            ArianeSub::generate(3, 0, $trad->t('Ajouter BDD d\'article'), $_SERVER['REQUEST_URI'], 1);
        }
        
        return $this->renderer->render('@GlobalApplication/Bdd/nouveau', [
            'menuActive' => $menuActive??'',
            'menuLeft' => $menuLeft??'',
            "id" => $id,
            "libelle" => $libelle??'',
            "Nouveaubdd" => true,
            'layout' => $layout??'layout.twig',
            'MODULE' => $module,
            'articlesTRUE' => $articleTrue??false,
            'listeLangue' => $langues ?? '',
            'ErreurValid' => $erreur ?? false,
            'post' => $post,
        ]);
    }
    
    public function modificationBddAction()
    {
        $id = $this->request->getAttribute('id');
        $module = $this->request->getAttribute('MODULE');
        $page = $this->request->getAttribute('page');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $BDD = new Bdd($this->pdo);
        
        if (!$post) {
            $post = $BDD->bddAffichage($id, $page, $module);
        }
        
        $PARAVRAC= new Paravrac($this->pdo);
        $numMinValue= $PARAVRAC->find(['TYPEPARV' => 'PARAMBDD',  'CODEPARV'=> 'BDD_1ERELIGNE']);
        
        if (!$numMinValue || str_replace(' ', '', $numMinValue['LIB01PARV'])=='0' || str_replace(' ', '', $numMinValue['LIB01PARV'])=='00') {
            $numMinValue='1';
        } else {
            $numMinValue=$numMinValue['LIB01PARV'];
        }
            
        if ($PARAVRAC->getFlag('PARAMOXA', 'MULTILNGACTIF')) {
            $post['MultiLangue']=true;
            $langues = (new Langues($this->pdo))->listChoice();
        }
        
        if ($this->request->getMethod() == 'POST') {
            $validator = $this->createValidator();
            
            $validator->isInteger("Numéro d'ordre", $post['NUMORDRE']);
            $validator->isStringAvecEspace("Sommaire", $post['TITRE'], 1, 60);
            $validator->isCheck($post['VEPROC']);
            
            $validator->isStringAvecEspace("Commentaires", $post['TEXTEBDD'], 1, 300);

            
            if ($validator->isValid()) {
                $idmemo = $BDD->bddAffichage($id, $page, $module);
                sql::updateMemo($this->pdo, $idmemo['NODEMEMO'], $post['TEXTEBDD']);
                
                $BDD->updaetBDD($id, $module, $page, $post);
                
                if ($id!='Article') {
                    return $this->redirect('GlobalApplication.Bdd.bdd', ['MODULE' => $module, 'id' => $id]);
                }
            } else {
                $erreur= $validator->getError();
            }
        }
        
        if ($id=='Article') {
        } else {
            $fournis = new Fourniss($this->pdo);
            $fournis = $fournis->find($id);
            
            $menuActive = 'Fournisseur';
            $menuLeft = 'GestionFournisseur';
            $libelle = $fournis["RS"];
            $layout ='@layoutFournisseur/fournisseur.twig';
            $articleTrue=true;
            ArianeSub::generate(3, 0, $trad->t('Modification BDD d\'article'), $_SERVER['REQUEST_URI'], 1);
        }
        
        return $this->renderer->render('@GlobalApplication/Bdd/nouveau', [
            'menuActive' => $menuActive??'',
            'menuLeft' => $menuLeft??'',
            "id" => $id,
            "libelle" => $libelle??'',
            "Modifbdd" => true,
            'layout' => $layout??'layout.twig',
            'MODULE' => $module,
            'articlesTRUE' => $articleTrue??false,
            'listeLangue' => $langues ?? '',
            'ErreurValid' => $erreur ?? false,
            'post' => $post,
            'lock' => 'readOnly',
        ]);
    }
    
    public function suppresionBDDAction()
    {
        $id = $this->request->getAttribute('id');
        $module = $this->request->getAttribute('MODULE');
        $page = $this->request->getAttribute('page');
        
        $BDD = new bdd($this->pdo);
        $BDD->deleteBdd($id, $page, $module);
    }
}
