<?php
namespace Modules\Index\Controller;

use Entity\Model\ParamDico;
use Skeleton\Controller\Controller;
use GuzzleHttp\Psr7\Response;
use Helpers\Validator\Validator;
use Helpers\Trad\Trad;
use Helpers\Outil\Sql;
use Modules\Index\Repository\CreationCompte;
use Modules\Index\WebService\UtilisateurWsdl as CreationCompteWs;
use Entity\Model\DomaineFonctionnel;

use function GuzzleHttp\json_decode;
use Helpers\Securite\Securite;
use Helpers\Parametres\Constante;

class CreationCompteController extends Controller
{
    public $droitAcces = true;
    
    public function init()
    {
        if (isset($_SESSION['Session_Login']) && $_SESSION['Session_Login'] !='') {
            return (new Response())->withStatus(301)->withHeader('Location', '../index.php');
        }
    }
    
    public function cordonneAction() : string
    {
        $trad = $this->getTranslationService();

        $post = $this->request->getParsedBody();

        $param['choixSupHier'] = Sql::paravrac($this->pdo, 'OXAPROC', 'CHOIX_SUPHIER')=='O'? true:false;
        $param['choixUO'] = Sql::paravrac($this->pdo, 'OXAPROC', 'CHOIX_UO')=='O'? true:false;
        $param['ssoActive'] = Sql::paravrac($this->pdo, 'PARAMGEN', 'CNX_SSO')=='O'? true:false;
        $param['activeDirectory'] = sql::paravrac($this->pdo, 'PARAMGEN', 'CNX_ACTIVE_DIRECTORY')=='O'? true:false;
        $param['passwordForSignActivated'] = sql::paravrac($this->pdo, 'PARAMGEN', 'MDP_LOG_DIF_SIG')=='O'? true:false;
        $param['passwordActive'] = sql::paravrac($this->pdo, 'PARAMGEN', 'PAS_DE_MDP_SIG')=='O'? false:true;
        $param['affichageCommandeEproc'] = sql::paravrac($this->pdo, 'OXAPROC', 'MASQUER_EPROC_DEMANDE')=='O'? false:true;
        $param['AffichageAboProfil'] = sql::paravrac($this->pdo, 'OXAPROC', 'MASQUER_ABON_PROFIL')=='O'? false:true;
        $param['MasquerSMTP'] = sql::paravrac($this->pdo, 'OXAPROC', 'PROFILUSER_MASQ_CPT_SMTP')=='O'? true:false;
        
        $creationCompte = new CreationCompte($this->pdo);
        $listeDomaine = (new ParamDico($this->pdo))->listLdapDomaine();
        $listeDomaine[''] = $trad->t('Choisir un domaine...');
        
        $DomaineFonctionnel = new DomaineFonctionnel($this->pdo);
        $DomaineFonctionnel = $DomaineFonctionnel->fetchAll();

        return $this->renderer->render('@index/creationCompte/formulaireCreation', [
            'post' => $post,
            'param' => $param,
            'listeDomaine' => $listeDomaine,
            'DomaineFonctionnel' => $DomaineFonctionnel??false,
            'passwordForSignActivated' => $param['passwordForSignActivated'],
        ]);
    }
    
    public function ajaxCoordonneesAction()
    {
        $post = $this->request->getParsedBody();
        $validator = $this->createValidator();
        
        $param['choixSupHier'] = Sql::paravrac($this->pdo, 'OXAPROC', 'CHOIX_SUPHIER')=='O'? true:false;
        $param['choixUO'] = Sql::paravrac($this->pdo, 'OXAPROC', 'CHOIX_UO')=='O'? true:false;
        $param['ssoActive'] = Sql::paravrac($this->pdo, 'PARAMGEN', 'CNX_SSO')=='O'? true:false;
        $param['activeDirectory'] = sql::paravrac($this->pdo, 'PARAMGEN', 'CNX_ACTIVE_DIRECTORY')=='O'? true:false;
        
        $ssoActive = Sql::paravrac($this->pdo, 'PARAMGEN', 'CNX_SSO')=='O'? true:false;
        $activeDirectory = sql::paravrac($this->pdo, 'PARAMGEN', 'CNX_ACTIVE_DIRECTORY')=='O'? true:false;
        $choixSupHier = Sql::paravrac($this->pdo, 'OXAPROC', 'CHOIX_SUPHIER')=='O'? true:false;
        $choixUO = Sql::paravrac($this->pdo, 'OXAPROC', 'CHOIX_UO')=='O'? true:false;
         /* trad */
         
         $trad = $this->getTranslationService();

        //Info utilisater
         $validator->isStringAvecEspace($trad->t('Nom'), $post['NOM'], 1, 30);
         $validator->isStringAvecEspace($trad->t('Prénom'), $post['PRENOM'], 1, 30);

         $controleFonction = Sql::paravrac($this->pdo, 'PARAMGEN', 'CONTROLE_FONCTION_UTILISATEUR');

        if ($controleFonction == 'O') {
            $validator->zoom('FoncUsr', $post['FONCTION'], $trad->t('Fonction'), $this->pdo, true);
        } else {
            $validator->isStringAvecEspace($trad->t('Fonction'), $post['FONCTION'], 0, 60);
        }

         $validator->isInteger($trad->t('Telephone fixe'), $post['TEL_FIX'], 0, 16);
         $validator->isInteger($trad->t('Telephone mobile'), $post['TEL_MOB'], 0, 16);
         $validator->isInteger($trad->t('Fax'), $post['FAX'], 0, 16);
         $validator->adresseMail($trad->t('Adresse mail'), $post['MAIL'], 1, 100, true);
        
         $creationCompte = new CreationCompte($this->pdo);
         $validator->isTrue($creationCompte->checkEmailDispo($post['MAIL']), '<br />'.$trad->t('Cette adresse mail existe déjà.'));
        
         $sisecto = \Helpers\Outil\Roles::droit($this->pdo, 'SISECTOR', 'PARAMSTE');
         $scaSecto = \Helpers\Outil\Roles::droit($this->pdo, 'SCASECTO', 'PARAMSTE');
         $cdcSecto = \Helpers\Outil\Roles::droit($this->pdo, 'CDCSECTO', 'PARAMSTE');

        //Axe d'imputation
         $validator->zoom('Societe', $post['SOCIETE'], $trad->t('Societe'), $this->pdo);
         $societe = $post['SOCIETE'];
         $validator->zoom('Sectimpu', $post['SI'], $trad->t('Section d\'imputation'), $this->pdo, true, ['filter_CODE_STE' => $sisecto? $societe:'']);
         $validator->zoom('Codecomp', $post['CDC'], $trad->t('Code complémentaire'), $this->pdo, true, ['filter_CODE_STE' => $cdcSecto? $societe:'']);
         $validator->zoom('Sscptana', $post['SCA'], $trad->t('Sous-compte d\'analyse'), $this->pdo, true, ['filter_CODE_STE' => $scaSecto? $societe:'']);
         $validator->zoom('Centre', $post['Emtteur'], $trad->t('Centre émetteur'), $this->pdo, false, ['filter_egal_CODE_STE' => $societe, 'filter_EMISSION' => 'T']);
         $validator->zoom('Centre', $post['LIVRAISON'], $trad->t('Centre de livraison'), $this->pdo, false, ['filter_egal_CODE_STE' => $societe, 'filter_LIVRAISON' => 'T']);
        if ($param['choixSupHier']) {
            $validator->zoom('Hastutil', $post['SUPHIERARCHIQUE'], $trad->t('Superieur Hiérarchique'), $this->pdo, false, ['filter_USRSUPHIE' => 'T']);
        }
        if ($param['choixUO']) {
            $validator->zoom('UO', $post['Uo'], $trad->t('Unité Organisationnelle'), $this->pdo, false, []);
        }
        
        //Messagerie
         $validator->isStringSansEspace($trad->t('Login messagerie'), $post['CODE_UTILISATEUR'], 0, 30);
         $validator->isStringSansEspace($trad->t('mot de passe messagerie'), $post['MessagerieMdp'], 0, 30);
        
         $domaine = $post['DOMFONCT'];
         $listeDomaine = explode('/', $domaine);
        
        //SSO
        if ($param['ssoActive']) {
            $validator->isCheck($post['SingleOne']);
        }
        
        //active directory
        if ($param['activeDirectory']) {
            if ($validator->isCheck($post['ActiveDirectory'])) {
                $validator->isFalse($post['DOMAINE'], $trad->t('Vous devez sélectionner un domaine valide.'));
            }
        }
         $validator->isCheck($post['ENV_FOURN']);
        
        if ($validator->isValid()) {
            return new Response(443, [], '');
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
               'ErreurValid' => $validator->getError(),
               'titrePopup'  => $trad->t('Erreur sur la validation'),
            ]);
        }
    }
    
    public function ajaxAbonnementsAction()
    {
        
        $post = $this->request->getParsedBody();

        $validator = $this->createValidator();
        
        $trad = $this->getTranslationService();

        if ($validator->isCheck($post['commandeEproc'])) {
            $validator->isCheck($post['LIGNE_MANUELLE']);
            $validator->isCheck($post['LIGNE_LIBRE']);
            $validator->isFloat($trad->t('Seuil commande Eproc'), $post['CDE_EPROC'], Constante::formatMontant);
        }
        
        if ($validator->isCheck($post['modeAppro'])) {
            $validator->isCheck($post['SAISIE_VALIDE']);
            $validator->isCheck($post['SIGNA_DA']);
            $validator->isCheck($post['DA_TRAIT']);
            $validator->isCheck($post['COMP_AO']);
            $validator->isCheck($post['SIG_CDE']);
        }
        
        if ($validator->isCheck($post['mdouleSaisieRecep'])) {
        }
        
        if ($validator->isCheck($post['ModuleSignature'])) {
            $validator->isCheck($post['DEMANDE_ACHAT']);
            $validator->isCheck($post['COMMANDE']);
            $validator->isCheck($post['BONAP']);
            
            $validator->isCheck($post['DA_SIG']);
            $validator->isCheck($post['CDE_SIG']);
            $validator->isCheck($post['BAP_SIG']);
        
            $file = $this->request->getUploadedFiles();
            
            if ($file) {
                $file_name = $file['importuploadImageSignature']->getClientFilename();
                $fileSize = $file['importuploadImageSignature']->getSize();
            }
            $validator->fileCheck($trad->t('Fichier image de votre signature'), $file_name??'', ['png', 'jpg', 'svg'], true, $fileSize ?? 0);
        }
        
        if ($validator->isCheck($post['ModuleSuivi'])) {
            $validator->zoom('SsItesto', $post['SITE_STK'], $trad->t('Site de stock'), $this->pdo, true);
        }
        
        if ($validator->isValid()) {
            return new Response(443, [], '');
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'titrePopup'  => $trad->t('Erreur sur la validation'),
            ]);
        }
    }
    
    public function ajaxPasswordAction() : string
    {
        $post = $this->request->getParsedBody();
        $validator = $this->createValidator();
        
        $param['passwordForSignActivated'] = sql::paravrac($this->pdo, 'PARAMGEN', 'MDP_LOG_DIF_SIG')=='O'? true:false;
        $param['passwordActive'] = sql::paravrac($this->pdo, 'PARAMGEN', 'PAS_DE_MDP_SIG')=='O'? false:true;
        
        $param['choixSupHier'] = Sql::paravrac($this->pdo, 'OXAPROC', 'CHOIX_SUPHIER')=='O'? true:false;
        $param['choixUO'] = Sql::paravrac($this->pdo, 'OXAPROC', 'CHOIX_UO')=='O'? true:false;
        $param['ssoActive'] = Sql::paravrac($this->pdo, 'PARAMGEN', 'CNX_SSO')=='O'? true:false;
        $param['activeDirectory'] = sql::paravrac($this->pdo, 'PARAMGEN', 'CNX_ACTIVE_DIRECTORY')=='O'? true:false;
        $param['passwordForSignActivated'] = sql::paravrac($this->pdo, 'PARAMGEN', 'MDP_LOG_DIF_SIG')=='O'? true:false;
        $param['passwordActive'] = sql::paravrac($this->pdo, 'PARAMGEN', 'PAS_DE_MDP_SIG')=='O'? false:true;
        $param['affichageCommandeEproc'] = sql::paravrac($this->pdo, 'OXAPROC', 'MASQUER_EPROC_DEMANDE')=='O'? false:true;
        $param['AffichageAboProfil'] = sql::paravrac($this->pdo, 'OXAPROC', 'MASQUER_ABON_PROFIL')=='O'? false:true;
        
        $trad = $this->getTranslationService();
        if (!$validator->isCheck($post['ActiveDirectory'])) {
            if ($post['MDP']!=$post['MDP_CONFIRM']) {
                $validator->setError($trad->t('Le mot de passe et sa confirmation ne peuvent être different.'));
            } else {
                $validator->isPassword($post['MDP'], $this->pdo);
            }
        }
        if ($param['passwordForSignActivated'] && $param['passwordActive']) {
            if ($post['MDP_SIGNA']!=$post['MDP_SIGNA_CONFIRM']) {
                $validator->setError($trad->t('Le mot de passe et sa confirmation ne peuvent être different.'));
            } else {
                $validator->isPassword($post['MDP_SIGNA'], $this->pdo);
            }
        }
        
        
        if ($param['ssoActive']) {
            $validator->isCheck($post['SingleOne']);
        }
        
        //active directory
        if ($param['activeDirectory']) {
            $validator->isCheck($post['ActiveDirectory']);
        }
        $validator->isCheck($post['ENV_FOURN']);
        
        if ($validator->isCheck($post['commandeEproc'])) {
            $validator->isCheck($post['LIGNE_MANUELLE']);
            $validator->isCheck($post['LIGNE_LIBRE']);
        }
        
        if ($validator->isCheck($post['modeAppro'])) {
            $validator->isCheck($post['SAISIE_VALIDE']);
            $validator->isCheck($post['SIGNA_DA']);
            $validator->isCheck($post['DA_TRAIT']);
            $validator->isCheck($post['COMP_AO']);
            $validator->isCheck($post['SIG_CDE']);
        }
        
        if ($validator->isCheck($post['mdouleSaisieRecep'])) {
        }
        
        if ($validator->isCheck($post['ModuleSignature'])) {
            $validator->isCheck($post['DEMANDE_ACHAT']);
            $validator->isCheck($post['COMMANDE']);
            $validator->isCheck($post['BONAP']);
            
            $validator->isCheck($post['DA_SIG']);
            $validator->isCheck($post['CDE_SIG']);
            $validator->isCheck($post['BAP_SIG']);
            
            $file = $this->request->getUploadedFiles();
            
            if ($file) {
                $file_name = $file['importuploadImageSignature']->getClientFilename();
            }
        }
        
        if ($validator->isCheck($post['ModuleSuivi'])) {
        }
        
        
        if ($validator->isValid()) {
            $creationCompteWSDL = new CreationCompteWs($this->contenaire);

            if ($file_name) {
                $path_info = pathinfo($file_name);
                list($void, $sec) = explode(' ', microtime());
                $sec .= $sec.rand(1, 999999);
                
                $new_name = 'file_' . $sec . '.' . $path_info['extension'];

                $file['importuploadImageSignature']->moveTo($_SESSION['_images'].$new_name);
                $file_name = '%_images%'.$new_name;
            } else {
                $file_name = '';
            }

            $xmlResult = $creationCompteWSDL->creationCompte($post, $file_name);
            $reponse = new \SimpleXMLElement($xmlResult->responseData);
            
            if ($reponse->Retour == "Workflow") {
                return $this->renderer->render('@popup-erreur/confirmationRedirection', [
                    'message' => $trad->t('Votre demande a été prise en compte.'),
                    'pathURL' => $this->router->generateUri('Index.Connexion.connexion')
                ]);
            } else {
                if ($reponse->MsgErreur=='') {
                    return $this->renderer->render('@popup-erreur/ErreurXml', [
                        'ErreurValid' => ['MsgErreur' => $trad->t('Une erreur est survenue lors de l\'appel webService.')],
                    ]);
                }
                
                return $this->renderer->render('@popup-erreur/ErreurXml', [
                    'ErreurValid' => ['MsgErreur' => $reponse->MsgErreur],
                ]);
            }
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'titrePopup'  => $trad->t('Erreur sur la validation'),
            ]);
        }
    }
    
    public function errorIntegriteAction() : string
    {
        $trad = $this->getTranslationService();
        return $this->renderer->render('@index-error/error', [
            'message' => $trad->t('OXA.PROC : l’intégrité de l’installation de l’application n’est pas respectée. Veuillez contacter votre administrateur.'),
        ]);
    }
}
