<?php
namespace Modules\Fournisseur\Controller;

use Modules\Fournisseur\MenuContextuel\BddMenuContextuel;
use Skeleton\Controller\Controller;
use Entity\Model\Paravrac;
use Entity\Model\Langues;
use Entity\Model\ParamDico;
use Helpers\Outil\Sql;
use Helpers\Session\Session;
use Modules\Fournisseur\WebService\Fournisseur;
use Modules\GlobalApplication\Repository\Bdd;
use Helpers\Trad\Trad;
use Helpers\Session\ParseBase1;

class BddController extends Controller
{

   
    /* ecran bdd creation / modification fournisseur */
    
    // phpcs:ignore
    public function CreationListeBddAction() : string
    {
        $post       = $this->request->getParsedBody();
        
        $session    = new Session('Fournisseur');
        $BddSession = $session->getSessionArray('Bdd');
        
        $paramDico  = new ParamDico($this->pdo);
        $paramDico  = $paramDico->findAll(['TYPEDICO' => 'PARAMBDDFOU']);
        
        foreach ($paramDico as $parm) { // On verifie si fournisseur a NO_PAGE BDD du parametrage
            $paramBDD = explode('|', $parm['LIBELLE']);
            
            $estPresent=false;
            foreach ($BddSession as $BDD) {
                if ($BDD['NO_PAGE']==$parm['ID1']) {
                    $estPresent=true;
                    break;
                }
            }
            
            if (!$estPresent) {
                if ($paramBDD[3]==' ') {
                    $paramBDD[3] = SQL::boolSql(false);
                }
                
                if (str_replace(' ', '', (string)$paramBDD[4])=='O') {
                    $paramBDD[4] = SQL::boolSql(true);
                } else {
                    $paramBDD[4] = SQL::boolSql(false);
                }
                
                array_push($BddSession, [
                    'ETAT'          => 'A',
                    'NO_PAGE'       => $parm['ID1'],
                    'NUMORDRE'      => $paramBDD[0],
                    'TITRE'         => $paramBDD[2],
                    'TEXTEBDD'      => '',
                    'VEPROC'        => $paramBDD[4],
                    'ONGLET'        => $paramBDD[5],
                    'LANGUE'        => $paramBDD[1],
                    'EXIST_PARAM'   => 1,
                    'EXIST_SURGRP'  => 0,
                    'LIEPARAM'      => 1,
                    'HERITAGE'      => 0,
                ]);
            }
        }

        sort($BddSession);
        
        $session->setSession('Bdd', $BddSession);
        
        $trad = $this->getTranslationService();
        $OuiNonTrad = [
            'Oui' => $trad->t('Oui'),
            'Non' => $trad->t('Non'),
        ];
        
        $paginator = new \Helpers\Pagination\Paginator();
        $infopagination = $paginator->generate($BddSession, 0, $post, $this->renderer);

        $menuContextuel = new BddMenuContextuel($this->pdo, $this->router, $this->getTranslationService());
        foreach ($BddSession as &$bdd) {
            $bdd['menuContextuel'] = $menuContextuel->generate($bdd['NO_PAGE'], $bdd['TITRE'], '');
        }
        
        return $this->renderer->render('@Fournisseur/Bdd/bddCreation', [
            'modeFournisseur'   => $session->getMode(),
            'Bdd'               => true,
            'menuActive'        => 'Fournisseur',
            'menuLeft'          => 'GestionFournisseur',
            'gestion'           => true,
            'listeBdd'          => $BddSession,
            'infoPagination'    => $infopagination,
            'OuiNonTrad'        => $OuiNonTrad,
        ]);
    }
    
    // phpcs:ignore
    public function ModificationListeBddAction() : string
    {
        $post = $this->request->getParsedBody();
        $codeFrs = $this->request->getAttribute('id');
        
        $session = new Session('Fournisseur');
        $BddSession = $session->getSessionArray('Bdd');
        $mode = $session->getSession('etatFournisseur');
        
        if ($session->getSession('OXALINK')) {
            $codeDemande = $codeFrs;
        } else {
            $code = $codeFrs;
        }
        
        $value=[
            "Langue" => $_SESSION['Session_Langue'],
            "Login" => $_SESSION['Session_Login'],
            "no_ao" => $_SESSION["Session_SocUsr"],
            "codeFrs" => $code??'',
            'codeDemande' => $codeDemande??'',
            'affDemande' => 'TRUE',
            'mode' => $mode,
            'signa' => $session->getSession('signa'),
        ];
        
        $lockModif = false;
        if ($mode=='M' || $session->getSession('ModifSigner')) {
            $lockModif = $session->getSessionArray('droitInteraction')['BDD']=='0'? true:false;
        }
        
        if (!$BddSession) {
            $xmlFile = $session->getSession('file_save_frs');
            
            if ($xmlFile) {
                $fileTMP = (new ParseBase1())->getRep()->tmp.$xmlFile;
                
                $fileContentXML = file_get_contents($fileTMP);
                $ficheFourniss = new \SimpleXMLElement($fileContentXML);
            } else {
                $ficheFourniss = new Fournisseur();
                $ficheFourniss = $ficheFourniss->ficheFournisseur($value);
                $ficheFourniss = new \SimpleXMLElement($ficheFourniss->responseData);
            }

            if ($ficheFourniss->Fournisseur->ListBDD) {
                foreach ($ficheFourniss->Fournisseur->ListBDD->BDD as $value) {
                    array_push($BddSession, [
                        'ETAT'          => strval($value->attributes()->Etat),
                        'NO_PAGE'       => strval($value->NO_PAGE),
                        'NUMORDRE'      => strval($value->NUMORDRE),
                        'TITRE'         => strval($value->TITRE),
                        'TEXTEBDD'      => strval($value->TEXTEBDD),
                        'VEPROC'        => strval($value->VEPROC),
                        'ONGLET'        => strval($value->ONGLET),
                        'LANGUE'        => strval($value->LANGUE),
                        'EXIST_PARAM'   => strval($value->EXIST_PARAM),
                        'EXIST_SURGRP'  => strval($value->EXIST_SURGRP),
                        'LIEPARAM'      => strval($value->LIEPARAM),
                        'HERITAGE'      => strval($value->HERITAGE),
                    ]);
                }
            }
            $session->setSession('Bdd', $BddSession);
        }

        $paramDico = new ParamDico($this->pdo);
        $paramDico = $paramDico->findAll(['TYPEDICO' => 'PARAMBDDFOU']);
        
        foreach ($paramDico as $parm) { // On verifie si fournisseur a NO_PAGE BDD du parametrage
            $paramBDD = explode('|', $parm['LIBELLE']);
            
            $estPresent=false;
            foreach ($BddSession as $BDD) {
                if ($BDD['NO_PAGE']==$parm['ID1']) {
                    $estPresent=true;
                    break;
                }
            }
            
            if (!$estPresent) {
                if ($paramBDD[3]==' ') {
                    $paramBDD[3] = SQL::boolSql(false);
                }
                    
                if (str_replace(' ', '', $paramBDD[4])=='O') {
                    $paramBDD[4] = SQL::boolSql(true);
                } else {
                    $paramBDD[4] = SQL::boolSql(false);
                }
                            
                array_push($BddSession, [
                    'ETAT'          => 'A',
                    'NO_PAGE'       => $parm['ID1'],
                    'NUMORDRE'      => $paramBDD[0],
                    'TITRE'         => $paramBDD[2],
                    'TEXTEBDD'      => '',
                    'VEPROC'        => $paramBDD[4],
                    'ONGLET'        => $paramBDD[5],
                    'LANGUE'        => $paramBDD[1],
                    'EXIST_PARAM'   => 1,
                    'EXIST_SURGRP'  => 0,
                    'LIEPARAM'      => 1,
                    'HERITAGE'      => 0,
                ]);
            }
        }
        
        sort($BddSession);
        
        $session->setSession('Bdd', $BddSession);
        
        $paginator = new \Helpers\Pagination\Paginator();
        $infopagination = $paginator->generate($BddSession, 0, $post, $this->renderer);
        $menuContextuel = new BddMenuContextuel($this->pdo, $this->router, $this->getTranslationService());
        foreach ($BddSession as &$bdd) {
            $bdd['menuContextuel'] = $menuContextuel->generate($bdd['NO_PAGE'], $bdd['TITRE'], '');
        }

        return $this->renderer->render('@Fournisseur/Bdd/bddCreation', [
            'modeFournisseur'   => $session->getMode(),
            'Bdd'               => true,
            'menuActive'        => 'Fournisseur',
            'menuLeft'          => 'GestionFournisseur',
            'gestion'           => true,
            "listeBdd"          => $BddSession,
            "infoPagination"    => $infopagination,
            'id'                => $session->getSession('CODE'),
            'lockModif'         => $lockModif,
        ]);
    }
    
    public function ajaxSuppresionoBddAction() : mixed
    {
        $post = $this->request->getParsedBody();
        $div = $this->request->getAttribute('div');
        $type = $this->request->getAttribute('type');
        
        if ($type) {
            $session = new Session($type);
        } else {
            $session = new Session('Fournisseur');
        }
        
        $BddSession = $session->getSessionArray('Bdd');

        for ($i=0; $i<count($BddSession); $i++) {
            if ($BddSession[$i]['NO_PAGE']==$post['entity']) {
                $BddSession[$i]['ETAT']='S';
            }
        }
        
        $session->setSession('Bdd', $BddSession);
        if ($type) {
            return (string)json_encode(
                [
                    'path' => $this->router->generateUri('Fournisseur.Bdd.ajaxBDDTableau', ['type'=>$type]),
                    'pathOnlyRedirect' => false
                
                ]
            );
        }
        return "ok";
    }
    
    
    public function ajaxCadenasBddAction() : string
    {
        $id = $this->request->getAttribute('id');
        
        $session = new Session('Fournisseur');
        $BddSession = $session->getSessionArray('Bdd');

        //on recherche ensuite la page dans le parametrage
        $paramDico = new ParamDico($this->pdo);
        $paramDico = $paramDico->findAll(['TYPEDICO' => 'PARAMBDDFOU']);
       
        
        foreach ($BddSession as &$searshBdd) {
            if ($searshBdd['NO_PAGE']==$id) {
                if (!$searshBdd['LIEPARAM'] && $searshBdd['EXIST_PARAM']) {
                    foreach ($paramDico as $parm) {
                        $paramBDD = explode('|', $parm['LIBELLE']);
                        if (trim($paramBDD[0]) == $id) {
                            $searshBdd['NUMORDRE']  = $paramBDD['0'];
                            $searshBdd['TITRE']     = $paramBDD['2'];
                            $searshBdd['VEPROC']    = SQL::boolSql($paramBDD['4']);
                            $searshBdd['ONGLET']    = $paramBDD['5'];
                            $searshBdd['LANGUE']    = $paramBDD['1'];
                            $searshBdd['LIEPARAM']  = 1;
                            $session->setSession('Bdd', $BddSession);
                            $bdd = $searshBdd;
                        }
                    }
                } elseif ($searshBdd['EXIST_SURGRP'] && $searshBdd['HERITAGE'] && !$searshBdd['EXIST_PARAM']) {
                    $searshBdd['HERITAGE']=0;
                    $session->setSession('Bdd', $BddSession);
                    $bdd = $searshBdd;
                    // détacher groupement
                } elseif ($searshBdd['EXIST_SURGRP'] && !$searshBdd['HERITAGE'] && !$searshBdd['EXIST_PARAM']) {
                    // attacher groupement
                    $groupement = $_SESSION['Fournisseur']['Fournisseur']['FOUPPAL'];
                    $bddGroup = new Bdd($this->pdo);
                    $bddGroup = $bddGroup->bddGroupement($groupement, $id);
                    
                    $searshBdd['NUMORDRE']  = $bddGroup['NUMORDRE'];
                    $searshBdd['TITRE']     = $bddGroup['TITRE'];
                    $searshBdd['VEPROC']    = $bddGroup['VEPROC'];
                    $searshBdd['ONGLET']    = $bddGroup['ONGLET'];
                    $searshBdd['LANGUE']    = $bddGroup['LANGUE'];
                    $searshBdd['LIEPARAM']  = $searshBdd['LIEPARAM'];
                    $searshBdd['HERITAGE']  = 1;
                    $session->setSession('Bdd', $BddSession);
                    $bdd = $searshBdd;
                }
                break;
            }
        }
        
        $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 = array_column(
                (new Langues($this->pdo))->fetchAll(),
                'LIBELLE',
                'COD_LNG'
            );
        }
                
        return $this->renderer->render('@Fournisseur/Ajax-Bdd/formUpdateBdd', [
            'minValNum'         => $numMinValue,
            'listeLangue'       => $langues ?? [],
            'modeFournisseur'   => $session->getMode(),
            'NouveauBdd'        => true,
            'gestion'           => true,
            'bdd'               => $bdd??[],
            'Modifbdd'          => true,
            'post'              => $post,
            'id'                => $session->getSession('CODE'),
        ]);
    }

    public function ajaxBDDTableauAction() : string
    {
        
        $type = $this->request->getAttribute('type');
        if ($type) {
            $sessionFournisseur = new Session($type);
        } else {
            $sessionFournisseur = new Session('FournisseurSimplie');
        }
        
        $BddSession = $sessionFournisseur->getSessionArray('Bdd');
        
        $trad = $this->getTranslationService();


        
        $paramDico  = new ParamDico($this->pdo);
        $paramDico  = $paramDico->findAll(['TYPEDICO' => 'PARAMBDDFOU']);
        
        foreach ($paramDico as $parm) { // On verifie si fournisseur a NO_PAGE BDD du parametrage
            $paramBDD = explode('|', $parm['LIBELLE']);
            
            $estPresent=false;
            foreach ($BddSession as $BDD) {
                if ($BDD['NO_PAGE']==$parm['ID1']) {
                    $estPresent=true;
                    break;
                }
            }
            
            if (!$estPresent) {
                if ($paramBDD[3]==' ') {
                    $paramBDD[3] = SQL::boolSql(false);
                }
                
                if (str_replace(' ', '', (string)$paramBDD[4])=='O') {
                    $paramBDD[4] = SQL::boolSql(true);
                } else {
                    $paramBDD[4] = SQL::boolSql(false);
                }
                
                array_push($BddSession, [
                    'ETAT'          => 'A',
                    'NO_PAGE'       => $parm['ID1'],
                    'NUMORDRE'      => $paramBDD[0],
                    'TITRE'         => $paramBDD[2],
                    'TEXTEBDD'      => '',
                    'VEPROC'        => $paramBDD[4],
                    'ONGLET'        => $paramBDD[5],
                    'LANGUE'        => $paramBDD[1],
                    'EXIST_PARAM'   => 1,
                    'EXIST_SURGRP'  => 0,
                    'LIEPARAM'      => 1,
                    'HERITAGE'      => 0,
                ]);
            }
        }

        sort($BddSession);
        
        $sessionFournisseur->setSession('Bdd', $BddSession);
        
        $OuiNonTrad = [
            'Oui' => $trad->t('Oui'),
            'Non' => $trad->t('Non'),
        ];

        $menuContextuel = new BddMenuContextuel($this->pdo, $this->router, $this->getTranslationService());
        foreach ($BddSession as &$bdd) {
            $bdd['menuContextuel'] = $menuContextuel->generate($bdd['NO_PAGE'], $bdd['TITRE'], $type);
        }

        $paginator = new \Helpers\Pagination\Paginator();
        $infopaginationBdd = $paginator->generate($BddSession, 0, [], $this->renderer);
        return $this->renderer->render('@Fournisseur/Ajax-Bdd/ajax-tableau', [
            'listeBdd'            => $BddSession ?? '',
            'infopaginationBdd'   => $infopaginationBdd ?? '',
            'OuiNonTrad'          => $OuiNonTrad,
            'type'                => $type
        ]);
    }
}
