<?php
namespace Modules\Administration\Controller;

use Entity\Model\DroitGrp;
use Entity\Model\Droits;
use Entity\Model\DroitUsr;
use Entity\Model\GrpDroit;
use Entity\Model\GrpUsr;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Ariane\ArianeSub;
use Helpers\Pagination\PaginatorGestion;
use Modules\Administration\MenuContextuel\GestionDroitMenuContextuel;
use Modules\Administration\Repository\Droit;
use Skeleton\Controller\Controller;

class GestionDroitUtilisateurController extends Controller
{
    /**
     * @return string
     */
    public function listeUserAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        if (!$post) {
            $post['tri_CODE'] = 'asc';
            $post['tri_NOM'] = 'asc';
        }

        (new PaginatorGestion())->generate(0, 'HASTUTIL.CODE');
        $listeUser = (new Droit($this->pdo))->listeUser($post);

        $menuContextuel = (new GestionDroitMenuContextuel($this->pdo, $this->router, $trad));
        foreach ($listeUser as &$user) {
            $user['menuContextuel'] = $menuContextuel->droitUserMenu($user['CODE']);
        }

        $nombreUser  = PaginatorGestion::getNbrArticle();
        $infopagination = PaginatorGestion::getInfoPagination();

        Ariane::generate(0, $trad->t('Gestion des droits utilisateurs'), [], null, null);

        return $this->renderer->render('@Administration/GestionDroitUtilisateur/listeUser', [
            'menuActive' => 'Administration',
            'listeUser' => $listeUser,
            'post' => $post,
            'infoPagination' => $infopagination,
            'nombreUser' => $nombreUser,
            'nombreGroup' => 0,
        ]);
    }

    /**
     * @return string
     */
    public function popupDroitUserAction()
    {
        $codeUser = $this->request->getAttribute('idUser');
        $mode = $this->request->getAttribute('mode');

        $post = [];

        if ($mode == 'droit') {
            $listeDroit = (new Droits($this->pdo))->getListeDroit();
            $listeDroitUser = (new DroitUsr($this->pdo))->findAll(['COD_USR' => $codeUser]);
            
            $tab = [];
            foreach ($listeDroit as $droit) {
                $tab[$droit['COD_DR']] = $droit['LIB_DR'].' - '.$droit['COD_DR'];
            }

            $i=1;
            foreach ($listeDroitUser as $droitUser) {
                $post['multiSelectDroit'.$i] = $droitUser['COD_DR'];
                $i++;
            }
        } else {
            $listeDroit = (new GrpDroit($this->pdo))->fetchAll();
            $listeDroitUser = (new GrpUsr($this->pdo))->findAll(['COD_USR' => $codeUser]);

            $tab = [];
            foreach ($listeDroit as $droit) {
                $tab[$droit['COD_GRP']] = $droit['LIB_GRP'].' - '.$droit['COD_GRP'];
            }

            $i=1;
            foreach ($listeDroitUser as $droitUser) {
                $post['multiSelectDroit'.$i] = $droitUser['COD_GRP'];
                $i++;
            }
        }

        return $this->renderer->render('@Administration/GestionDroitUtilisateur/popupDroitUser', [
            'listeDroit' => $tab,
            'post' => $post,
            'path' => $this->router->generateUri('Administration.GestionDroitUtilisateur.validateDroitUser', ['idUser' => $codeUser, 'mode' => $mode]),
        ]);
    }

    /**
     * @return Response
     */
    public function validateDroitUserAction()
    {
        $codeUser = $this->request->getAttribute('idUser');
        $mode = $this->request->getAttribute('mode');
        $post = $this->request->getParsedBody();
        $listeDroit = [];

        foreach ($post as $key => $val) {
            if (str_starts_with($key, 'multiSelectDroit')) {
                $listeDroit[] = $val;
            }
        }

        if ($mode == 'droit') {
            (new DroitUsr($this->pdo))->delete(['COD_USR' => $codeUser]);

            foreach ($listeDroit as $droit) {
                (new DroitUsr($this->pdo))->insert([
                    'COD_USR' => $codeUser,
                    'COD_DR' => $droit,
                ]);
            }
        } else {
            (new GrpUsr($this->pdo))->delete(['COD_USR' => $codeUser]);

            foreach ($listeDroit as $droit) {
                (new GrpUsr($this->pdo))->insert([
                    'COD_USR' => $codeUser,
                    'COD_GRP' => $droit,
                ]);
            }
        }

        return new Response(400, [], (string) json_encode([
            'action' => 'close'
        ]));
    }

    /**
     * @return string
     */
    public function listeDroitAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        if (!$post) {
            $post['tri_COD_GRP'] = 'asc';
            $post['tri_LIB_GRP'] = 'asc';
        }

        (new PaginatorGestion())->generate(0, 'COD_GRP');
        $listeGroupeDroit = (new Droit($this->pdo))->listeGroupeDroit($post);

        $menuContextuel = (new GestionDroitMenuContextuel($this->pdo, $this->router, $trad));
        foreach ($listeGroupeDroit as &$grpDroit) {
            $grpDroit['menuContextuel'] = $menuContextuel->grpDroitMenu($grpDroit['COD_GRP']);
        }

        $nombreGroupDroit  = PaginatorGestion::getNbrArticle();
        $infopagination = PaginatorGestion::getInfoPagination();

        Ariane::generate(0, $trad->t('Gestion des groupes de droits'), [], null, null);

        return $this->renderer->render('@Administration/GestionDroitUtilisateur/listeDroit', [
            'menuActive' => 'Administration',
            'onglet'    => 'groupeDroit',
            'listeGroupeDroit' => $listeGroupeDroit,
            'post' => $post,
            'infoPagination' => $infopagination,
            'nombreUser' => 0,
            'nombreGroup' => $nombreGroupDroit,
        ]);
    }

    /**
     * @return string
     */
    public function createGrpDroitAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        Ariane::generate(1, $trad->t('Ajouter un groupe de droit'), [], null, null);

        $listeDroit = (new Droits($this->pdo))->getListeDroit();
        $tab = [];

        foreach ($listeDroit as $droit) {
            $tab[$droit['COD_DR']] = $droit['LIB_DR'].' - '.$droit['COD_DR'];
        }

        return $this->renderer->render('@Administration/GestionDroitUtilisateur/createGrpDroit', [
            'menuActive' => 'Administration',
            'onglet'    => 'groupeDroit',
            'listeDroit' => $tab,
        ]);
    }

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

        $validator->isStringAvecEspace($trad->t('Code groupe de droit'), $post['COD_GRP'], 1, 10);
        $validator->isStringAvecEspace($trad->t('Libellé groupe de droits'), $post['LIB_GRP'], 1, 10);

        if ($validator->isValid()) {
            (new GrpDroit($this->pdo))->insert([
                'COD_GRP' => $post['COD_GRP'],
                'LIB_GRP' => $post['LIB_GRP'],
            ]);

            foreach ($post as $key => $val) {
                if (str_starts_with($key, 'multiSelectDroit')) {
                    (new DroitGrp($this->pdo))->insert([
                        'COD_GRP' =>  $post['COD_GRP'],
                        'COD_DR' => $val,
                    ]);
                }
            }

            $backPath = Ariane::getBackPath();
            $backPost = Ariane::getBackPost();

            return new Response(443, [], (string) json_encode(['path' => $backPath, 'post' => $backPost]));
        } else {
            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]));
        }
    }

    /**
     * @return string
     */
    public function popupGrpDroitAction()
    {
        $idGrp = $this->request->getAttribute('idGrp');

        $post = [];

        $listeDroit = (new Droits($this->pdo))->getListeDroit();
        $listeDroitGrp = (new DroitGrp($this->pdo))->findAll(['COD_GRP' => $idGrp]);
        
        $tab = [];
        foreach ($listeDroit as $droit) {
            $tab[$droit['COD_DR']] = $droit['LIB_DR'].' - '.$droit['COD_DR'];
        }

        $i=1;
        foreach ($listeDroitGrp as $droitUser) {
            $post['multiSelectDroit'.$i] = $droitUser['COD_DR'];
            $i++;
        }

        return $this->renderer->render('@Administration/GestionDroitUtilisateur/popupDroitUser', [
            'listeDroit' => $tab,
            'post' => $post,
            'path' => $this->router->generateUri('Administration.GestionDroitUtilisateur.validatePopupGrpDroit', ['idGrp' => $idGrp]),
        ]);
    }

    /**
     * @return Response
     */
    public function validatePopupGrpDroitAction()
    {
        $idGrp = $this->request->getAttribute('idGrp');

        $post = $this->request->getParsedBody();
        (new DroitGrp($this->pdo))->delete(['COD_GRP' => $idGrp]);

        foreach ($post as $key => $val) {
            if (str_starts_with($key, 'multiSelectDroit')) {
                (new DroitGrp($this->pdo))->insert([
                    'COD_GRP' => $idGrp,
                    'COD_DR' => $val,
                ]);
            }
        }

        return new Response(400, [], (string) json_encode([
            'action' => 'close'
        ]));
    }

    /**
     * @return string
     */
    public function userInGrpDroitAction()
    {
        $post = $this->request->getParsedBody();

        $idGrp = $this->request->getAttribute('idGrp');
        $trad = $this->getTranslationService();

        if (!$post) {
            $post['tri_CODE'] = 'asc';
            $post['tri_NOM'] = 'asc';
        }

        (new PaginatorGestion())->generate(500, 'HASTUTIL.CODE');
        $listeUser = (new Droit($this->pdo))->listeUser($post);
        foreach ($listeUser as &$user) {
            $user['CODE'] = str_replace('.', 'oxaPoint', $user['CODE']);
        }

        $listeUsrSelected = (new GrpUsr($this->pdo))->findAll(['COD_GRP' => $idGrp]);
        foreach ($listeUsrSelected as &$user) {
            $user['COD_USR'] = str_replace('.', 'oxaPoint', $user['COD_USR']);
        }

        $nombreUser  = PaginatorGestion::getNbrArticle();
        $infopagination = PaginatorGestion::getInfoPagination();

        Ariane::generate(1, $trad->t('Gestion des utilisateurs'), [], null, null);

        return $this->renderer->render('@Administration/GestionDroitUtilisateur/listeUserInGrp', [
            'listeUser' => $listeUser,
            'idGrp' => $idGrp,
            'post' => $post,
            'infoPagination' => $infopagination,
            'nombreUser' => $nombreUser,
            'listeUsrSelected' => $listeUsrSelected
        ]);
    }

    /**
     * @return Response
     */
    public function updateUserInGrpDroitAction()
    {
        $post = $this->request->getParsedBody();

        $idGrp = $this->request->getAttribute('idGrp');

        (new GrpUsr($this->pdo))->delete(['COD_GRP' => $idGrp]);

        foreach ($post['UserSelected'] as $user) {
            (new GrpUsr($this->pdo))->insert([
                'COD_GRP' => $idGrp,
                'COD_USR' => $user,
            ]);
        }

        $backPath = Ariane::getBackPath();
        $backPost = Ariane::getBackPost();

        return new Response(443, [], (string) json_encode(['path' => $backPath, 'post' => $backPost]));
    }
}
