<?php
namespace Modules\Parametrage\Oxalink\Controller;

use Entity\Model\LstDocs;
use Skeleton\Controller\Controller;
use Helpers\Ariane\Ariane;
use Helpers\Trad\Trad;
use Helpers\Outil\Sql;
use Helpers\Validator\Validator;
use Entity\Model\Paravrac;
use Helpers\Ariane\ArianeSub;
use Helpers\Fichier\Gestion_Fic_PJ;
use Modules\Parametrage\Oxalink\Repository\ParametrageOxalink;
use Helpers\Fichier\Fichier;
use Entity\Model\ParamDico;
use GuzzleHttp\Psr7\Response;
use Helpers\Securite\Securite;
use Tamtamchik\SimpleFlash\Flash;
use Helpers\Session\ParseBase1;

class ParametrageOxalinkController extends Controller
{

    /**
     * @return Response|string
     */
    public function indexAction()
    {
        $post = $this->request->getParsedBody();
        
        $trad = $this->getTranslationService();
        
        if ($post) {
            $validator = $this->createValidator();
            

            $validator->isCheck($post['FACT_SUIVIREG']);

            if (isset($post['MAIL_DEFAUT']) && $post['MAIL_DEFAUT']) {
                $validator->adresseMail($trad->t('Adresse mail par défaut'), $post['MAIL_DEFAUT'], 0, 100, true);
            }
            
            $validator->isStringAvecEspace($trad->t('Nom de l\'onglet navigateur'), $post['ONGLET_NAV'], 0, 100);
            
            $file = $this->request->getUploadedFiles();

            $file_Bandeau = null;
            $file_Accueil = null;
            if ($file) {
                if (isset($file['importBANDEAU_OXALINK'])) {
                    $file_Bandeau = $file['importBANDEAU_OXALINK']->getClientFilename();
                    $fileSizeBandeau = $file['importBANDEAU_OXALINK']->getSize();
                }
                
                if (isset($file['importBG_ACCUEIL_OXALINK'])) {
                    $file_Accueil = $file['importBG_ACCUEIL_OXALINK']->getClientFilename();
                    $fileSizeAccueil= $file['importBG_ACCUEIL_OXALINK']->getSize();
                }
            }
            
            if ($file_Bandeau) {
                $validator->fileCheck($trad->t('Bandeau OXA.LINK'), $file_Bandeau, ['png', 'jpg', 'svg', 'html', 'htm'], '', $fileSizeBandeau ?? 0);
            }
            if ($file_Accueil) {
                $validator->fileCheck($trad->t('Image d\'accueil OXA.LINK'), $file_Accueil, ['png', 'jpg', 'svg'], '', $fileSizeAccueil ?? 0);
            }
            
            if ($validator->isValid()) {
                $paravrac = new Paravrac($this->pdo);
                $paramdico = new ParamDico($this->pdo);
                
                $getAllParavrac = $paravrac->findAll(['TYPEPARV' => 'PF_OXALINK']);
                
                $arrayParavrac = [];
                foreach ($getAllParavrac as $param) {
                    $arrayParavrac[$param['CODEPARV']] = $param['LIB01PARV'];
                }
                
                /** PAGE_ACCUEIL **/
                if (isset($arrayParavrac['PAGE_ACCUEIL'])) {
                    $paravrac->update(['LIB01PARV' => $post['PAGE_ACCUEIL']], ['TYPEPARV' => 'PF_OXALINK', 'CODEPARV' => 'PAGE_ACCUEIL']);
                } else {
                    $paravrac->insert(['TYPEPARV' => 'PF_OXALINK', 'CODEPARV' => 'PAGE_ACCUEIL', 'LIB01PARV' => $post['PAGE_ACCUEIL']]);
                }
                
                /** PAGE_REFERENCEMENT **/
                if (isset($arrayParavrac['PAGE_REFERENCEMENT'])) {
                    $paravrac->update(['LIB01PARV' => $post['PAGE_REFERENCEMENT']], ['TYPEPARV' => 'PF_OXALINK', 'CODEPARV' => 'PAGE_REFERENCEMENT']);
                } else {
                    $paravrac->insert(['TYPEPARV' => 'PF_OXALINK', 'CODEPARV' => 'PAGE_REFERENCEMENT', 'LIB01PARV' => $post['PAGE_REFERENCEMENT']]);
                }

                /** FACT_SUIVIREG : Filtres d'affichage des factures "En traitement" **/
                // TODO A vérifier : enregistrement en O ou N
                if (isset($arrayParavrac['FACT_SUIVIREG'])) {
                    $paravrac->update(['LIB01PARV' => ($post['FACT_SUIVIREG']? 'O':'N')], ['TYPEPARV' => 'PF_OXALINK', 'CODEPARV' => 'FACT_SUIVIREG']);
                } else {
                    $paravrac->insert(['TYPEPARV' => 'PF_OXALINK', 'CODEPARV' => 'FACT_SUIVIREG', 'LIB01PARV' => ($post['FACT_SUIVIREG']? 'O':'N')]);
                }

                /** FACT_STATUT : affichage des statut dans le suivi des factures */
                if (isset($arrayParavrac['FACT_STATUT'])) {
                    $paravrac->update(['LIB01PARV' => ($post['FACT_STATUT']? 'O':'N')], ['TYPEPARV' => 'PF_OXALINK', 'CODEPARV' => 'FACT_STATUT']);
                } else {
                    $paravrac->insert(['TYPEPARV' => 'PF_OXALINK', 'CODEPARV' => 'FACT_STATUT', 'LIB01PARV' => ($post['FACT_STATUT']? 'O':'N')]);
                }

                /** FACT_DATE_ENREG : affichage de la date d'enregistrement dans le suivi des factures */
                if (isset($arrayParavrac['FACT_DATE_ENREG'])) {
                    $paravrac->update(['LIB01PARV' => ($post['FACT_DATE_ENREG']? 'O':'N')], ['TYPEPARV' => 'PF_OXALINK', 'CODEPARV' => 'FACT_DATE_ENREG']);
                } else {
                    $paravrac->insert(['TYPEPARV' => 'PF_OXALINK', 'CODEPARV' => 'FACT_DATE_ENREG', 'LIB01PARV' => ($post['FACT_DATE_ENREG']? 'O':'N')]);
                }
                
                /** Adresse mail LAD **/
                if ($paramdico->find(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'MAIL_FACTURATION', 'ID2' => 'MAIL_DEFAUT'])) {
                    $paramdico->update(['LIBELLE' => $post['MAIL_DEFAUT']], ['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'MAIL_FACTURATION', 'ID2' => 'MAIL_DEFAUT']);
                } else {
                    $paramdico->insert(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'MAIL_FACTURATION', 'ID2' => 'MAIL_DEFAUT', 'LIBELLE' => $post['MAIL_DEFAUT']]);
                }
                
                /** Nom de l'onglet navigateur OXA.LINK **/
                if (isset($arrayParavrac['ONGLET_NAV'])) {
                    $paravrac->update(['LIB01PARV' => $post['ONGLET_NAV']], ['TYPEPARV' => 'PF_OXALINK', 'CODEPARV' => 'ONGLET_NAV']);
                } else {
                    $paravrac->insert(['TYPEPARV' => 'PF_OXALINK', 'CODEPARV' => 'ONGLET_NAV', 'LIB01PARV' => $post['ONGLET_NAV']]);
                }

                $gestionFic = new Gestion_Fic_PJ($this->pdo, true);
                //Bandeau OXA.LINK
                if ($file_Bandeau) {
                    $newPath = Fichier::UploadDocAtt($file_Bandeau);

                    $nameFile = pathinfo($file_Bandeau);

                    $nameFile = $nameFile['filename'];
                    
                    $file['importBANDEAU_OXALINK']->moveTo($newPath["racine"].$newPath["new_name"]);

                    $fileSave = $gestionFic->updateFicher(sql::paramDico($this->pdo, 'PF_OXALINK', 'BANDEAU_OXALINK', 'LIBELLE'), $newPath['new_name']);

                    if ($paramdico->find(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'BANDEAU_OXALINK'])) {
                        $paramdico->update(['LIBELLE' => $fileSave, 'ALPHA1' => $nameFile], ['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'BANDEAU_OXALINK']);
                    } else {
                        $paramdico->insert(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'BANDEAU_OXALINK', 'LIBELLE' => $fileSave, 'ALPHA1' => $nameFile]);
                    }
                    
                    $post['BANDEAU_OXALINK'] = $newPath["new_name"];
                } elseif ($post['file_nameBANDEAU_OXALINK']=='') {
                    $gestionFic->deleteFichier(sql::paramDico($this->pdo, 'PF_OXALINK', 'BANDEAU_OXALINK', 'LIBELLE'));
                    
                    if ($paramdico->find(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'BANDEAU_OXALINK'])) {
                        $paramdico->update(['LIBELLE' => '', 'ALPHA1' => ''], ['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'BANDEAU_OXALINK']);
                    } else {
                        $paramdico->insert(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'BANDEAU_OXALINK', 'LIBELLE' => '', 'ALPHA1' => '']);
                    }
                }
                //Page OXA.LINK
                if ($file_Accueil) {
                    $newPath = Fichier::UploadDocAtt($file_Accueil);

                    $nameFile = pathinfo($file_Accueil);

                    $nameFile = $nameFile['filename'];

                    $file['importBG_ACCUEIL_OXALINK']->moveTo($newPath["racine"].$newPath["new_name"]);

                    $fileSave = $gestionFic->updateFicher(sql::paramDico($this->pdo, 'PF_OXALINK', 'BG_ACCUEIL_OXALINK', 'LIBELLE'), $newPath['new_name']);
                    
                    if ($paramdico->find(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'BG_ACCUEIL_OXALINK'])) {
                        $paramdico->update(['LIBELLE' => $fileSave, 'ALPHA1' => $nameFile], ['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'BG_ACCUEIL_OXALINK']);
                    } else {
                        $paramdico->insert(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'BG_ACCUEIL_OXALINK', 'LIBELLE' => $fileSave, 'ALPHA1' => $nameFile]);
                    }
                    
                    $post['BG_ACCUEIL_OXALINK'] = $newPath["new_name"];
                } elseif ($post['file_nameBG_ACCUEIL_OXALINK']=='') {
                    $gestionFic->deleteFichier(sql::paramDico($this->pdo, 'PF_OXALINK', 'BG_ACCUEIL_OXALINK', 'LIBELLE'));
                    
                    if ($paramdico->find(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'BG_ACCUEIL_OXALINK'])) {
                        $paramdico->update(['LIBELLE' => '', 'ALPHA1' => ''], ['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'BG_ACCUEIL_OXALINK']);
                    } else {
                        $paramdico->insert(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'BG_ACCUEIL_OXALINK', 'LIBELLE' => '', 'ALPHA1' => '']);
                    }
                }

                //$image['BANDEAU_OXALINK'] = sql::paramDico($this->pdo, 'PF_OXALINK', 'BANDEAU_OXALINK', 'LIBELLE');
                $BANDEAU_OXALINK            = sql::paramDico($this->pdo, 'PF_OXALINK', 'BANDEAU_OXALINK', 'LIBELLE');
                $bandeau_relative_path      = (new ParseBase1())->getRep()->images;
                    // Absolute path to file image
                $image['BANDEAU_OXALINK']   = realpath($bandeau_relative_path . '\\' . $BANDEAU_OXALINK);

                //$image['BG_ACCUEIL_OXALINK']    = sql::paramDico($this->pdo, 'PF_OXALINK', 'BG_ACCUEIL_OXALINK', 'LIBELLE');
                $BG_ACCUEIL_OXALINK             = sql::paramDico($this->pdo, 'PF_OXALINK', 'BANDEAU_OXALINK', 'LIBELLE');
                $bg_relative_path               = (new ParseBase1())->getRep()->images;
                    // Absolute path to file image
                $image['BG_ACCUEIL_OXALINK']    = realpath($bg_relative_path . '\\' . $BG_ACCUEIL_OXALINK);
            } else {
                return new Response(443, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                ]));
            }
        } else {
            //$post['URLACCESOXALINK']    = Sql::paravrac($this->pdo, 'PF_OXALINK', 'URLACCESOXALINK');
            $post['PAGE_ACCUEIL']       = sql::paravrac($this->pdo, 'PF_OXALINK', 'PAGE_ACCUEIL');
            $post['PAGE_REFERENCEMENT'] = sql::paravrac($this->pdo, 'PF_OXALINK', 'PAGE_REFERENCEMENT');
            $post['BANDEAU_OXALINK']    = sql::paramDico($this->pdo, 'PF_OXALINK', 'BANDEAU_OXALINK', 'ALPHA1');
            $post['BG_ACCUEIL_OXALINK'] = sql::paramDico($this->pdo, 'PF_OXALINK', 'BG_ACCUEIL_OXALINK', 'ALPHA1');
            $post['ONGLET_NAV']         = sql::paravrac($this->pdo, 'PF_OXALINK', 'ONGLET_NAV');
            $post['FACT_SUIVIREG']      = sql::paravrac($this->pdo, 'PF_OXALINK', 'FACT_SUIVIREG');
            $post['FACT_STATUT']        = sql::paravrac($this->pdo, 'PF_OXALINK', 'FACT_STATUT') == 'N'? false:true;
            $post['FACT_DATE_ENREG']    = sql::paravrac($this->pdo, 'PF_OXALINK', 'FACT_DATE_ENREG') == 'N'? false:true;

            //$image['BANDEAU_OXALINK'] = sql::paramDico($this->pdo, 'PF_OXALINK', 'BANDEAU_OXALINK', 'LIBELLE');
            $BANDEAU_OXALINK            = sql::paramDico($this->pdo, 'PF_OXALINK', 'BANDEAU_OXALINK', 'LIBELLE');
            $bandeau_relative_path      = (new ParseBase1())->getRep()->images;
                // Absolute path to file image
            $image['BANDEAU_OXALINK']   = realpath($bandeau_relative_path . '\\' . $BANDEAU_OXALINK);

             //$image['BG_ACCUEIL_OXALINK']    = sql::paramDico($this->pdo, 'PF_OXALINK', 'BG_ACCUEIL_OXALINK', 'LIBELLE');
             $BG_ACCUEIL_OXALINK             = sql::paramDico($this->pdo, 'PF_OXALINK', 'BG_ACCUEIL_OXALINK', 'LIBELLE');
             $bg_relative_path               = (new ParseBase1())->getRep()->images;
                 // Absolute path to file image
             $image['BG_ACCUEIL_OXALINK']    = realpath((string) $bg_relative_path . '\\' . (string)$BG_ACCUEIL_OXALINK);
        }
        $PAR_DEFAUT = sql::paramDico($this->pdo, 'PF_OXALINK', 'MAIL_FACTURATION', 'LIBELLE', 'MAIL_DEFAUT');
        
        $liste_PROSPECT_REFERENCE = [
            'R'=> $trad->t('Référencé'),
            'P' => $trad->t('Prospect'),
        ];

        $paramOxalink = new ParametrageOxalink($this->pdo);
        $liste = $paramOxalink->listePageClientPublic();
        
        foreach ($liste as $value) {
            $listePage[$value['CODE']] = $value['TITRE'];
        }
   


        if (($_SESSION['ariane'][0]['path']??null) == $this->router->generateUri('Parametrage.Parametrage.index')) {
            $indexAriane = 1;
            $menuActive = 'Parametrage';
            $menuLeft = 'Parametrage';
        } else {
            $indexAriane = 0;
            $menuActive = 'Fournisseur';
            $menuLeft = 'Parametrage';
        }

        Ariane::generate($indexAriane, $trad->t('Gestion des paramètres'), $post);
        
        ArianeSub::init();
        ArianeSub::generate(0, 0, $trad->t('Paramétrage'), $this->router->generateUri('Parametrage.ParametrageOxalink.index'), 1);
        ArianeSub::generate(0, 1, $trad->t('Demande référencement'), $this->router->generateUri('Parametrage.ParametrageOxalink.fournisseur'));
        ArianeSub::generate(0, 2, $trad->t('Pages OXA.LINK'), $this->router->generateUri('Parametrage.ParametrageOxalink.page'));
        ArianeSub::generate(0, 3, $trad->t('Accès'), $this->router->generateUri('Parametrage.ParametrageAcces.acces'));
        ArianeSub::generate(
            0,
            4,
            $trad->t('Destinataires à notifier'),
            $this->router->generateUri('Parametrage.ParametrageOxalink.notifierDestinataire')
        );
        
        return $this->renderer->render('@ParamOxalink/oxalink', [
            'menuActive' => $menuActive,
            'menuLeft' => $menuLeft,
            'post' => $post,
            'liste_PROSPECT_REFERENCE' => $liste_PROSPECT_REFERENCE,
            'image' => $image,
            'PAR_DEFAUT' => $PAR_DEFAUT,
            'liste_PAGE' => $listePage ?? [],
            ]);
    }
    
    public function paramMailAction() : string
    {
        $post = $this->request->getParsedBody();
        
        $oxalinkRepo = new ParametrageOxalink($this->pdo);
        $listeMailSociete = $oxalinkRepo->listeMailSociete();
        $paramdico = new ParamDico($this->pdo);
        
        if ($post) {
            $validator = $this->createValidator();
            
            foreach ($listeMailSociete as $adresse) {
                $validator->adresseMail('Adresse mail par défaut', $post['MAIL_'.$adresse['CODE_STE']], 0, 100, true);
            }
            
            if ($validator->isValid()) {
                foreach ($listeMailSociete as $adresse) {
                    if ($paramdico->find(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'MAIL_FACTURATION', 'ID2' => $adresse['CODE_STE']])) {
                        $paramdico->update(['LIBELLE' => $post['MAIL_'.$adresse['CODE_STE']]], ['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'MAIL_FACTURATION', 'ID2' => $adresse['CODE_STE']]);
                    } else {
                        $paramdico->insert(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'MAIL_FACTURATION', 'ID2' => $adresse['CODE_STE'], 'LIBELLE' => $post['MAIL_'.$adresse['CODE_STE']]]);
                    }
                }

                $trad = $this->getTranslationService();
                
                return $this->renderer->render('@popup-erreur/information', [
                    'message' => $trad->t('Vos modifications ont prises en compte.'),
                ]);
            } else {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                ]);
            }
        }
        
        ArianeSub::generate(1, 1, 'Email LAD', $this->router->generateUri('Parametrage.ParametrageOxalink.paramMail'), 1);
        
        if (($_SESSION['ariane'][0]['path']??null) == $this->router->generateUri('Parametrage.Parametrage.index')) {
            $menuActive = 'Parametrage';
            $menuLeft = 'Parametrage';
        } else {
            $menuActive = 'Fournisseur';
            $menuLeft = 'Parametrage';
        }
        
        return $this->renderer->render('@ParamOxalink/paramMail', [
            'menuActive' => $menuActive,
            'menuLeft' => $menuLeft,
            'listeMailSociete' => $listeMailSociete,
        ]);
    }

    /**
     * @return string|Response
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \Exception
     */
    public function notifierDestinataireAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->contenaire->get(\Helpers\Trad\ITrad::class);

        $typeDico = 'MAIL_DOC_OXALINK';
        $paramDico  = new ParamDico($this->pdo);
        $paraVrac   = new Paravrac($this->pdo);
        $listDoc    = new LstDocs($this->pdo);


        $listeTypeDoc = [];
        $listeTypeDoc['DEFAUT'] = $trad->t('Défaut');
        $listeTypeDoc['KBIS'] = 'KBIS';
        $listing = $listDoc->findAll(null);

        if ($listing) {
            foreach ($listing as $doc) {
                $listeTypeDoc[$doc['CODE_DOC']] = $doc['TITRE_DOC'];
            }
        }

        $validator = new Validator($this->pdo, $trad);

        $flash = new Flash();
        if ($post && isset($post['formSend'])) {
            $_SESSION['Parametrage']['formToShow'] = $post['formSend'];

            if ($post['formSend'] === 'form_type') {
                $inputToUse = '_second';
            } else {
                $inputToUse = '';
            }

            $dataToUse = [
                'COMMENTAIRE'   => (($post['COMMENTAIRE'.$inputToUse]) ?? ''),
                'ALPHA2'        => (isset($post['ALPHA2'.$inputToUse]) ? 'on' : ''),
                'ALPHA3'        => (isset($post['ALPHA3'.$inputToUse]) ? 'on' : ''),
                'TYPE_DOC'      => (($post['TYPE_DOC'.$inputToUse]) ?? ''),
            ];

            $validator->isStringSansEspace(
                'Destinataires',
                $dataToUse['COMMENTAIRE'],
                0,
                3000
            );

            if ($validator->isValid()) {
                $result = $paramDico->createOrUpdate($dataToUse, $typeDico);

                if ($result) {
                    return new Response(
                        200,
                        [],
                        $trad->t('Vos modifications sont prises en compte.')
                    );
                } else {
                    return new Response(
                        400,
                        [],
                        $trad->t('Vos modifications n\'ont pas été prises en compte.')
                    );
                }
            } else {
                return new Response(
                    400,
                    [],
                    $validator->getError()
                );
            }
        }

        $data = $paramDico->findAll(
            [
                'TYPEDICO' => $typeDico,
            ],
            [
                'ID1', 'COMMENTAIRE', 'ALPHA2', 'ALPHA3',
            ],
        );
        
        $newData = [];
        foreach ($data as $k => $v) {
            $id1 = $v['ID1'];
            unset($v['ID1']);
            $newData[$id1] = $v;
        }

        unset($listeTypeDoc['DEFAUT']);

        ArianeSub::generate(
            0,
            4,
            $trad->t('Destinataires à notifier'),
            $this->router->generateUri('Parametrage.ParametrageOxalink.notifierDestinataire'),
            4
        );

        $formToShow = $_SESSION['Parametrage']['formToShow'] ?? 'form_default';

        return $this->renderer->render('@ParamOxalink/mail', [
            'listeTypeDoc'  => $listeTypeDoc,
            'idDoc'         => $newData,
            'post'          => $post,
            'flash'         => $flash,
            'formToShow'    => $formToShow
        ]);
    }


    /**
     * @return Response
     * @throws \Exception
     */
    public function ajaxDeleteParamDestinataireAction()
    {
        $type = $this->request->getAttribute('type');
        $trad = $this->getTranslationService();

        $paramDico = new ParamDico($this->pdo);

        if ($paramDico->delete($type)) {
            return new Response(
                200,
                [],
                $trad->t('Le paramètrage a bien été supprimé.'),
            );
        } else {
            return new Response(
                400,
                [],
                $trad->t('Le paramètrage n\'a pas été supprimé ou est inexistant.'),
            );
        }
    }
}
