<?php
namespace Modules\Index\Controller;

use Entity\Model\Hastutil;
use Entity\Model\Memos;
use Entity\Model\OxaUserPanierLigne;
use Entity\Model\Paravrac;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Outils;
use Skeleton\Controller\Controller;
use Modules\Index\WebService\TableauDeBord;
use Modules\Index\Repository\Index;
use Modules\Ajax\Repository\Favoris;
use Helpers\Outil\Roles;
use Modules\Utilisateur\Repository\etatTableauDeBord;
use Helpers\Outil\Sql;
use Helpers\Session\InitSession;
use Helpers\Trad\Trad;
use Modules\Index\Repository\Connexion;
use Helpers\Session\ParseBase1;

class IndexController extends Controller
{
    public $droitAcces = true;
    
    /**
     * @return Response
     */
    public function indexResetAction()
    {

        $get = $this->request->getQueryParams();

        $param = [];
        if (array_intersect(array_keys($get), [
            'access', 'id', 'profil', 'menu', 'refDemande'
        ])) {
            $param = [
                'redirect'      => 'NULL',
                'error'         => 'NULL',
                'access'        => $get['acces'] ?? 'NULL',
                'id'            => $get['id'] ?? 'NULL',
                'profil'        => $get['profil'] ?? 'NULL',
                'menu'          => $get['menu'] ?? 'NULL',
                'refDemande'    => $get['refDemande'] ?? 'NULL',
            ];
        }
        
        Outils::sessionDestroy();

        //connexion[/{redirect:[A-Za-z0-9]+}[/{error:[A-Za-z0-9]+}[/{access:[A-Za-z0-9]+}/{id:[A-Za-z0-9%.@_ -]+}/{profil:[A-Za-z0-9]+}/{menu:[A-Za-z0-9]+}/{refDemande:[A-Za-z0-9]+}]]]",
        return $this->redirect('Connexion.Connexion.connexion', $param);
    }

    public function indexAction() : string
    {
        if (isset($_SESSION['init_modeBackup']) && $_SESSION['init_modeBackup'] === true) {
            $initSession = new InitSession($this->pdo);
            $initSession->initSessionHeader();

            unset($_SESSION['init_modeBackup']);
        }

        Ariane::init();
        if (isset($_SESSION['redirect'])) {
            $redirect = $_SESSION['redirect'];
            unset($_SESSION['redirect']);
        }

        $post = $this->request->getParsedBody();
        if ($post) {
            $_SESSION['typeMenu'] = $post['type'] ?? $_SESSION['typeMenu'];
        }
        
        $index = new Index($this->pdo);
        $liste_favoris = $index->getFavoris();
        $actualites = $index->getActu();

        /// TODO droit

        $S2SActive = 0;
        $PAActive = 0;
        $RFActive = 0;
        $P2PActive = 0;

        if (Roles::s2cAccess($this->pdo, $this->router, $this->contenaire)) {
            $S2SActive = 1;
        }
        
        if (Roles::p2pAcces($this->pdo, $this->router, $this->contenaire)) {
            $P2PActive = 1;
        }
     
        if (Roles::rfAccess($this->pdo, $this->router, $this->contenaire)) {
            $RFActive = 1;
        }
      
        if (Roles::paAccess($this->pdo, $this->router, $this->contenaire)) {
            $PAActive = 1;
        }

        $listeAccesRapide = new Favoris($this->pdo);
        $listeAccesRapide = $listeAccesRapide->listeFavorisAccesRapide();
        $trad = $this->getTranslationService();

        foreach ($listeAccesRapide as &$value) {
            $value['PATH_PARAMS']=json_decode($value['PATH_PARAMS'], true);
            $value['TITRE_FAV']=$trad->t($value['TITRE_FAV']);
        }

        return $this->renderer->render('@index/index', [
            'menuActive' => 'Accueil',
            //'tab_bord' => $url,
            'liste_favoris' => $liste_favoris,
            'actu' => $actualites,
            'type' => $_SESSION['typeMenu']??'',
            'S2SActive' => $S2SActive,
            'PAActive' => $PAActive,
            'RFActive'=> $RFActive,
            'P2PActive' => $P2PActive,
            'listeAccesRapide' => $listeAccesRapide,
            'NouvelleConnexion' => $_SESSION['NouvelleConnexion'] ?? 0,
            'redirect' => $redirect??'',
        ]);
    }

    public function SRMIndexAction():string
    {
        $index = new Index($this->pdo);
        
        return $this->renderer->render('@index/SRMIndex', [
            'liste_favoris' => $index->getFavoris(),
            'actu' => $index->getActu(),

            'ConnexionEproc' => $_SESSION['ConnexionEproc'],
            'ConnexionOXASRM' => $_SESSION['ConnexionOXASRM'],
            
            '_haplusweb' => (new ParseBase1())->getPath()->haplusweb ?? '',
            'session_id' => session_id(), // TODO: session id should not be accessible by js
        ]);
    }
     
    public function errorAction() :Response
    {
        return $this->create404Response();
    }

    public function forbiddenAction() : string
    {
        
        $trad = $this->getTranslationService();

        return $this->renderer->render('@index-error/error', [
            'message' => $trad->t("Vous n'avez pas les permissions pour accéder à cette page.")
        ]);
    }
    
    public function errorDroitAction() : string
    {
        
        $trad = $this->getTranslationService();

        return $this->renderer->render('@index-error/error', [
            'message' => $trad->t("Vous n'avez pas les droits sur cette page")
        ]);
    }
    
    public function erreurFormulaireAction() : string
    {
        
        $trad = $this->getTranslationService();
        return $this->renderer->render('@index-error/error', [
            'message' => $trad->t('Un problème est survenu sur le formulaire')
        ]);
    }
    
    public function errorConstructAction() : string
    {
        
        $trad = $this->getTranslationService();

        return $this->renderer->render('@index-error/error', [
            'message' => $trad->t('Accès non autorisé : votre adresse IP a été bloquée pour des raisons de sécurité. Merci de contacter votre administrateur.')
        ]);
    }

    public function errorIpBanAction() : string
    {
        
        $trad = $this->getTranslationService();
        
        return $this->renderer->render('@index-error/error', [
            'message' => $trad->t('Cette page est en construction')
        ]);
    }
    
    
    public function ajaxTableauDeBordAction() : string
    {
        $graph = new TableauDeBord();
        $etatTB = new etatTableauDeBord($this->pdo);
        
        if ($etatTB->etatUserTB()) {
            $codeEtat = 'TB_USER';
        } else {
            $codeEtat = 'TB_GLOBAL';
        }
        $graph = $graph->TableauDeBord($codeEtat);
        
        $reponse = new \SimpleXMLElement($graph->responseData);
        $url = $reponse->NomFichier;
                
        return $this->renderer->render('@ajaxTableauDeBord/tableauDeBord', [
            'tab_bord' => $this->router->generateUri('GlobalApplication.ChargeDocument.chargeDocument', [
                'emplacement' => 'tmp',
                'urlFichier' => $url,
                'modeAffichage' => 0
            ]),
        ]);
    }
    public function noPdfAction() : string
    {
        return $this->renderer->render('@outil/noPdf');
    }

    public function specifiqueAction() : string
    {
        Ariane::generate(1, '');
        return $this->renderer->render('@index/specifique', [
            'menuActive'        => 'Specifique',
        ]);
    }
    
    
    public function redirectionCSRFAction() : string
    {
        $trad = $this->getTranslationService();

        return $this->renderer->render('@index-error/error', [
            'message' => $trad->t('Veuillez recharger votre page'),
            'LibelleBouton' => $trad->t('Recharger'),
            'LibelleRedirect' => $trad->t('Recharger')
        ]);
    }

    public function cspRapportAction(): bool
    {
        $HTTP_RAW_POST_DATA = file_get_contents("php://input");
        file_put_contents((new ParseBase1())->getRep()->tmp.'csp_report.txt', $HTTP_RAW_POST_DATA.PHP_EOL, FILE_APPEND);
        return true;
    }

    /**
     * @return Response
     */
    public function changeModuleAction()
    {
        $post = $this->request->getParsedBody();
        $_SESSION['typeMenu'] = $post['type'] ?? $_SESSION['typeMenu'];
        
        return new Response(200);
    }

    /**
     * @return Response
     */
    public function logoutAction()
    {
        /*if (isset($_SESSION["Session_Login"])) {
            $connexion = new Connexion($this->pdo);
            $connexion->trackConnexionOut($_SESSION["Session_Login"]);

            Sql::logAudit($this->pdo, 'LOGIN', 'SORTIE');
        }*/

        $session = $_SESSION;
        Outils::sessionDestroy();

        if ($session['user_logged']['typeConnexion'] == 'SAML2') {
            $paravrac = new Paravrac($this->pdo);
            $getUrl = $paravrac->find([
                'TYPEPARV' => 'PARAMADFS',
                'CODEPARV' => 'URLRETOURCLIENT'
                ]);

            if (is_array($getUrl) && count($getUrl)) {
                $redirect = $getUrl['LIB01PARV'];
            } else {
                $redirect = $this->router->generateUri('Connexion.Connexion.connexion', ['redirect' => 'mwSAML2logout']);
            }
        } elseif ($session['user_logged']['typeConnexion'] == 'SSOInterne') {
            $redirect = $this->router->generateUri('Connexion.Connexion.connexion');
        } else {
            $redirect = $this->router->generateUri('Connexion.Connexion.connexion');
        }

        return $this->redirect($redirect);
    }
}
