<?php
namespace Modules\Administration\Controller;

use Skeleton\Controller\Controller;
use Modules\Administration\Repository\GestionUtilisateurOxalink;
use Helpers\Ariane\Ariane;
use Helpers\Trad\Trad;
use Modules\Administration\WebService\GestionUserOxalink;
use Helpers\Validator\Validator;
use GuzzleHttp\Psr7\Response;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Sql;
use Helpers\Pagination\PaginatorGestion;
use Modules\Administration\MenuContextuel\UserOxalinkMenuContextuel;
use Modules\Administration\Service\GestionUtilisateurOxalinkService;

class GestionUtilisateurOxalinkController extends Controller
{
    private \Modules\Administration\Repository\GestionUtilisateurOxalink $repository;
    private \Modules\Administration\Service\GestionUtilisateurOxalinkService $service;

    /**
     * init
     *
     * @return void
     */
    public function init(): void
    {
        $this->repository = new GestionUtilisateurOxalink($this->pdo);
        $this->service = new GestionUtilisateurOxalinkService($this->pdo, $this->getTranslationService());
    }
    
    public function indexAction() : string
    {
        $post = $this->request->getParsedBody();
        
        (new PaginatorGestion())->generate();
        $gestionUser = new GestionUtilisateurOxalink($this->pdo);
        $listeUser = $gestionUser->listeCompte($post);

        $menuContextuel = new UserOxalinkMenuContextuel($this->pdo, $this->router, $this->getTranslationService(), []);

        foreach ($listeUser as &$user) {
            $user['menuContextuel'] = $menuContextuel->generate($user);
        }
        $trad = $this->getTranslationService();
        
        Ariane::generate(0, $trad->t('Gestion des utilisateurs OXA.LINK'), $post, null, null);

        $trad = $this->getTranslationService();

        $tableauStatut = [
            'C' => $trad->t('En création'),
            'A' => $trad->t('Actif'),
            'B' => $trad->t('Bloqué'),
            'F' => $trad->t('Fermé'),
            'V' => $trad->t('En attente de validation'),
        ];

        return $this->renderer->render('@Administration/gestionUserOxalink/listeUserOxalink', [
            'menuActive' => 'Administration',
            'post' => $post,
            'listeUser' => $listeUser,
            'infoPagination' => PaginatorGestion::getInfoPagination(),
            'tableauStatut' => $tableauStatut,
            'OXAUSER' => $_SESSION['Session_Login'] === 'OXAUSER',
            'NonProd' => Sql::paravrac($this->pdo, 'PARAMGEN', 'TypeEnvironnement') === "NP",
        ]);
    }
    
    public function ajaxDetailUserAction() : string
    {
        $idUser = $this->request->getAttribute('idUser');
        
        $gestionUser = new GestionUtilisateurOxalink($this->pdo);
        $detailUser = $gestionUser->detailUser($idUser);
        
        $listeFrs = $gestionUser->detlisteFrsUser($idUser);
        
        return $this->renderer->render('@Administration/gestionUserOxalink/detailUserOxalink', [
            'detailUser' => $detailUser,
            'listeFrs' => $listeFrs,
        ]);
    }
    
    /**
     * @return Response|string
     */
    public function modificationUserAction()
    {
        $post = $this->request->getParsedBody();
        $idUser = $this->request->getAttribute('idUser');
        $oxalink_repo = new GestionUtilisateurOxalink($this->pdo);
        
        $trad = $this->getTranslationService();
        
        $user = $oxalink_repo->getInfoUser($idUser);

        if (!$user) {
            return $this->redirect('Index.Index.error');
        }
        
        if ($post) {
            $validator = $this->createValidator();
            $validator->isStringAvecEspace($trad->t('Nom'), $post['NOM'], 1, 100);
            $validator->isStringAvecEspace($trad->t('Fonction'), $post['FONCTION'], 0, 40);// TODO : should be zoom sometime ?
            $validator->isStringAvecEspace($trad->t('Tél. fixe'), $post['TEL'], 0, 16);
            $validator->isStringAvecEspace($trad->t('Tél. portable'), $post['TELPORT'], 0, 16);
            
            if (! $validator->isValid()) {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                ]);
            }
            $oxalink_repo->updateUser($idUser, $user['EMAIL'], $post);
            return new Response(443, [], (string) \json_encode([
                'statut' => 'O',
                'path' => $this->router->generateUri('Administration.GestionUtilisateur.index'),
            ]));
        } else {
            $post = $user;
        }
        
        Ariane::generate(1, $trad->t('Modification utilisateurs'), $post);
        
        return $this->renderer->render('@Administration/gestionUserOxalink/modificationUser', [
            'menuActive' => 'Administration',
            'post' => $post,
        ]);
    }
    
    public function popupDebloquerUserAction() : string
    {
        $idUser = $this->request->getAttribute('idUser');

        $trad = $this->getTranslationService();

        
        $gestionOxalink = new GestionUtilisateurOxalink($this->pdo);
        $user = $gestionOxalink->getInfoUser($idUser);
        
        $message = trad::strBuild($trad->t("Etes-vous sûr de vouloir débloquer l'utilisateur @1@ ?"), $user['NOM']);
        
        return $this->renderer->render('@Administration/gestionUserOxalink/popupDebloquer', [
            'message' => $message,
            'idUser' => $idUser,
        ]);
    }
    
    public function ajaxDebloquerUserAction() : string
    {
        $idUser = $this->request->getAttribute('idUser');
        
        
        $wsdl = new GestionUserOxalink();
        $xmlResult = $wsdl->debloquerUser($idUser);
        
        $reponse = new \SimpleXMLElement($xmlResult->responseData);
        
        if ($reponse->Statut=="O") {
            $trad = $this->getTranslationService();
            return $this->renderer->render('@popup-erreur/confirmationGestion', [
                'message' => $trad->t('Le compte a été débloqué.'),
                'refresh' => true,
                'iconePopup' => 'information',
                'div_refresh' => 'tabPAGE',
                'form_refresh' => 'filtre_user'
            ]);
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $reponse->Erreur,
            ]);
        }
    }
    
    public function ajaxSuppresionUserAction() : string
    {
        $idUser = $this->request->getAttribute('idUser');
        
        $gestionOxalink = new GestionUtilisateurOxalink($this->pdo);
        $gestionOxalink->suppresionUser($idUser);
        
        return '';
    }
    
    public function popupModifPasswordAction() : string
    {
        $post = $this->request->getParsedBody();
        $idUser = $this->request->getAttribute('idUser');
        $trad = $this->getTranslationService();
        
        if (isset($post['newMdp'])) {
            $validator = $this->createValidator();
            $validator->isPassword($post['newMdp'], $this->pdo);
            
            if ($post['newMdp']!=$post['confirmMdp']) {
                $validator->setError($trad->t('Le mot de passe et sa confirmation doivent être identiques.'));
                $erreur = $validator->getError();
            }
            
            if ($validator->isValid()) {
                $xmlResult = GestionUserOxalink::modificationMDP(['userId' => $idUser, 'mdp' => $post['newMdp']]);
                $reponse = new \SimpleXMLElement($xmlResult->responseData);
                
                if ($reponse->Statut=="O") {
                    return $this->renderer->render('@popup-erreur/information', [
                        'message' => $trad->t('Le mot de passe a bien été modifié.'),
                    ]);
                } else {
                    $erreur =  $reponse->MsgErreur;
                }
            }
        }
        
        $trad = $this->getTranslationService();
        
        return $this->renderer->render('@Administration/gestionUserOxalink/popupModifPassword', [
            'url' => $this->router->generateUri('Administration.GestionUtilisateur.popupModifPassword', ['idUser' => $idUser]),
            'idUser' => $idUser,
            'erreur' => $erreur??'',
        ]);
    }
    
    public function popupModifAllPasswordsAction() : string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        if (isset($post['newMdp'])) {
            $validator = $this->createValidator();
            $validator->isPassword($post['newMdp'], $this->pdo);
            $error = '';
            
            if ($post['newMdp'] != $post['confirmMdp']) {
                $validator->setError($trad->t('Le mot de passe et sa confirmation doivent être identiques.'));
                $error = $validator->getError();
            }

            if ($validator->isValid()) {
                $xmlResult = GestionUserOxalink::modificationAllMDP(['mdp' => $post['newMdp']]);
                $reponse = new \SimpleXMLElement($xmlResult->responseData);
                if ($reponse->Statut != "O") {
                    $error .= $reponse->MsgErreur;
                }

                if ($error === '') {
                    return $this->renderer->render('@popup-erreur/information', [
                        'message' => $trad->t('Le mot de passe a bien été modifié pour l\'ensemble des utilisateurs.'),
                    ]);
                }
            }
        }
        
        $trad = $this->getTranslationService();
        
        return $this->renderer->render('@Administration/gestionUserOxalink/popupModifPassword', [
            'url' => $this->router->generateUri('Administration.GestionUtilisateur.popupModifAllPasswords'),
            'erreur' => $error ?? '',
        ]);
    }
    
    public function ajaxValiderUserAction() : string
    {
        $idUser = $this->request->getAttribute('idUser');
        
        $gestionOxalink = new GestionUtilisateurOxalink($this->pdo);
        $gestionOxalink->setActifUser($idUser);
        
        $user = $gestionOxalink->getInfoUser($idUser);
        
        $gestionOxalink->updateContFour($idUser, $user['EMAIL']);
        
        return '';
    }

    public function exportAction() : string
    {
        $post = $this->request->getParsedBody();
        $type = $this->request->getAttribute('type') ?? '';
        $idUser = $this->request->getAttribute('idUser') ?? '';
        
        $trad = $this->getTranslationService();
        $repo = new GestionUtilisateurOxalink($this->pdo);

        if ($type == 'event') {
            $this->getEmailCsvService()->sendCsv(
                'export_USER_'.date('Ymd').'_event',
                $repo->getEventsUserOxalink($idUser),
                null,
                [
                    $trad->t('Utilisateur'),
                    $trad->t('Date'),
                    $trad->t('Heure'),
                    $trad->t('Auteur'),
                    $trad->t('Commentaire'),
                    $trad->t('Libellé'),
                ]
            );
            return 'ok';
        }

        $mapStatut = [
            'C' => $trad->t('En création'),
            'A' => $trad->t('Actif'),
            'B' => $trad->t('Bloqué'),
            'F' => $trad->t('Fermé'),
            'V' => $trad->t('En attente de validation'),
        ];

        $this->getEmailCsvService()->sendCsv(
            'export_USER_'.date('Ymd'),
            $repo->listeCompte($post),
            function (array $row) use ($mapStatut, $repo) {
                return [
                    'NOM'           => $row['NOM'],
                    'EMAIL'         => $row['EMAIL'],
                    'STATUT'        => $mapStatut[$row['STATUT']],
                    'FOURNISSEUR'   => implode(
                        '|',
                        array_map(function ($frs) {
                            return $frs['RS'].' ('.$frs['CODE'].')';
                        }, $repo->detlisteFrsUser($row['USER_ID']))
                    ),
                ];
            },
            [
                $trad->t('Nom'),
                $trad->t('Email'),
                $trad->t('Statut'),
                $trad->t('Fournisseur'),
            ]
        );

        return 'ok';
    }

    /**
     * suiviAction
     *
     * @return string
     */
    public function suiviAction(): string
    {
        $post = $this->request->getParsedBody();
        $userId = $this->request->getAttribute('idUser') ?? '';
        $trad = $this->getTranslationService();

        (new PaginatorGestion())->generate();
        $listEvent = $this->repository->getEventsUserOxalink($userId, $post);
        Ariane::generate(0, $trad->t('Suivi des évènements'), $post, null, null);

        $title = $trad->t('Suivi des évènements utilisateurs Portail Fournisseur');
        if ($userId != '') {
            $title = Trad::strBuild($trad->t('Suivi des évènements de l\'utilisateur @1@'), $listEvent[0]['NOM_UTILISATEUR'] ?? '');
        }
        
        return $this->renderer->render('@Administration/gestionUserOxalink/reporting', [
            'menuActive'        => 'Administration',
            'onglet'            => 'suiviEvent',
            'menuLeft'          => $this->router->getNameRoute(),
            'post'              => $post,
            'reporting'         => $listEvent,
            'infoPagination'    => PaginatorGestion::getInfoPagination(),
            'title'             => $title,
        ]);
    }
    
    /**
     * ajaxRelanceUserAction
     *
     * @return Response
     */
    public function ajaxRelanceUserAction(): Response
    {
        $userId = $this->request->getAttribute('idUser');
        $trad = $this->getTranslationService();

        $relance = $this->service->resumeUser($userId);
        
        $info = '';
        $alert = '';
        if ($relance) {
            $info  = $trad->t('L\'utilisateur a été relancé.');
        } else {
            $alert = $trad->t('Sans adresse mail enregistrée pour cet utilisateur, l\'action n\'a pas pu aboutir.');
        }

        return new Response(200, [], $this->renderer->render('@Evaluation/Popup/erreurAlerteEtAvertissement', [
            'params' => [
                'info'            => $info,
                'avertissement'   => $alert,
                'titrePopup'      => $trad->t('Relance utilisateur'),
                'typePopup'       => $alert == '' ? 'ok' : ''
            ],
        ]));
    }
}
