<?php
namespace Modules\Index\Controller;

use Entity\Model\OxaUserPanier;
use Entity\Model\Paravrac;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
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;

class IndexController extends Controller
{
    public $droitAcces = true;


    // @phpstan-ignore-next-line
    private function testODBC() :string
    {
        // https://www.sitepoint.com/community/t/pdo-weirdness/66956

        // (new Paravrac($this->pdo))->find([
        //     'TYPEPARV' => 'LONG LONG LONG LONG', // Erreur de s�quence de la fonction
        // ]);


        $stmt = $this->pdo->prepare(
            'UPDATE DA_ENTET 
            SET NO_DEM = :NO_DEM 
            WHERE NO_DA = 1
        '
        );
        $stmt->execute(['NO_DEM' => 'éà@&']);// Require utf8_decode

        (new OxaUserPanier($this->pdo))->update(
            array (
                'id_user' => '38',
                'id_panier' => 0,
                'IS_INITIALIZED' => '1',

                //'CODE_STE' => 'éà@&', // Require utf8_decode
                // 'CODE_STE' => 'dqsdqsd qsd qsd qsd qsd qs dqs dqsdq qsd qsdqsdqsd', // Erreur de s�quence de la fonction

                'CDE_COMPTOIR' => 0x54, // Require statement literal replace
                //'CDE_COMPTOIR' => true, // Work using convert T/F inside update()
                
                'TOTAL_DA' => '', // Require statement literal replace
            ),
            array (
            'id_user' => '38',
            'id_panier' => 0,
            )
        );

        $stmt = $this->pdo->prepare(
            'SELECT * FROM DA_ENTET 
            WHERE NO_DA = :NO_DA 
            AND NO_DEM = :NO_DEM 
            AND DTE_LIV = :DTE_LIV
            AND TOTAL_DA = :TOTAL_DA
            AND VALIDITE = :VALIDITE
        '
        );
        $stmt->bindValue(':NO_DA', '0');
        $stmt->bindValue(':NO_DEM', '');
        $stmt->bindValue(':DTE_LIV', '0');
        $stmt->bindValue(':TOTAL_DA', '0');
        // $stmt->bindValue(':VALIDITE', 70); // DOES NOT WORK
        // $stmt->bindValue(':VALIDITE', 70, \PDO::PARAM_INT); // DOES NOT WORK
        $stmt->bindValue(':VALIDITE', 'T'); // WORK
        $stmt->execute();

        //______________________________________
        // Driver{SQL Server} only; Les types de donn�es varchar et text sont incompatibles dans l\'op�rateur equal to

        $stmt = $this->pdo->prepare(
            'SELECT * FROM CA_ENTET 
            WHERE  (
                select UTIL from CA_EVENT with (nolock) 
                where CA_EVENT.NO_CDE=CA_ENTET.NO_CDE 
                and CA_EVENT.NUM_ORD = CA_ENTET.EVE_VAL
            ) = :demandeur2
        '
        );
        //$stmt->bindValue(':demandeur2', 'ADMINCENTRAL');
        $stmt->bindValue(':demandeur2', 'ADMINCENTRAL', \PDO::PARAM_STR);
        $stmt->execute();

        return 'FIN';
    }
    
    public function indexAction() : string
    {
        //return $this->testODBC();

        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;

        $xml=simplexml_load_string($_SESSION['OXAPRC_LOGUSR_XML']);

       

        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;
        }

        // Si licence EASYDEMAT, accès uniquement au P2P
        if (($_SESSION['EasyDemat']??'') == 1) {
            $S2SActive = 0;
            $PAActive = 0;
            $RFActive = 0;
        }

        $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 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;
        
        $param = '?uniq=' . Sql::guidGenerate();
        $param .= '&token=' . password_hash($_SESSION['Session_Login'].session_id(), PASSWORD_DEFAULT);
        $lien = $this->base. 'charge_document.php'.$param.'&EmplacementFichier=tmp&UrlFichier='.$url;
        
        return $this->renderer->render('@ajaxTableauDeBord/tableauDeBord', [
            'tab_bord' => $lien,
        ]);
    }
    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
    {
        $v1 = $this->request->getAttribute('v1');
        
        $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'),
            'pathRedirect' => $v1?$this->contenaire->get('base').'session_ipad.php':''
        ]);
    }

    public function cspRapportAction(): bool
    {
        $HTTP_RAW_POST_DATA = file_get_contents("php://input");
        file_put_contents($_SESSION['dir_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_destroy();

        // TODO : why use session after destroying it ?
        if (isset($_SESSION['ADFS_URL_DECONNEXION']) && $_SESSION['ADFS_URL_DECONNEXION'] != '') {
            $redirect = $_SESSION['ADFS_URL_DECONNEXION'];
        } elseif ($_SESSION['SAML2_CONNECT']??false) {
            $redirect = $this->router->generateUri('Index.ADFS.ADFS', ['logout' => 'logout']);
        } else {
            $redirect = $this->router->generateUri('Index.Connexion.connexion');
        }

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