<?php
include APPLICATION_PATH . '/DAO/UtilisateurDAO.php';
include APPLICATION_PATH . '/DAO/AuthorisationDAO.php';
include APPLICATION_PATH . '/DAO/RoleDAO.php';
include APPLICATION_PATH . '/DAO/RoleAuthorisationDAO.php';
include APPLICATION_PATH . '/DAO/LogDAO.php';
include PUBLIC_PATH.'/Fonctions/Fonction.php';
#include PUBLIC_PATH . '/files_to_include/Constantes.php';

class ModuleRole
{
    public $user;
     
    public function addRole(){
        
        if (!empty($_POST)) {
            $label = $_POST["label"];
            $description = $_POST["description"];
            $listAuth = $_POST["listAuth"];
            $result = array();
            //exit();
           
            $errormsg="";
             $roleDao = new RoleDAO();
            // Enregistrement dans la table Profil
            
             if($roleDao->existProfilName($label)==true){
                    $errormsg.="The role:".$label." already exist!";
                     echo json_encode(array("type" => "error",'msg' => $errormsg,"result"=>$result));
           
                     exit();
                }
           
           try {
              
                $roleDao->_em->beginTransaction();
            $role = new \Application\Models\Role();
               
                // ici on fait les enregistrements......
                $role->setLabel($label);
                $role->setDescription($description);
                $role->setState(1);
                $role->setCode(str_replace(' ', '', microtime()));
                
                $roleDao->save($role);
                
                $roleAuthDao = new RoleAuthorisationDAO();
                $authDao = new AuthorisationDAO();
                
                foreach ($listAuth as $elem)
                {
                         $codeAuth=$elem->value;
                        $auth = $authDao->getAuthorisationByCode($codeAuth);
                        
                        $roleAuth= new \Application\Models\RoleAuthorisation();
                        $roleAuth->setRole($role);
                        $roleAuth->setAuthorisation($auth);
                        $roleAuth->setState(1);
                        $roleAuth->setCode(str_replace(' ', '', microtime()));
                        //enregistrement
                        $roleAuthDao->save($roleAuth);
                } 
                $utilisateurDao = new UtilisateurDAO();
            $this->user = $utilisateurDao->getUtilisateurByCode($_SESSION["codeUser"]);
                   $f = new Fonction();
               
                $descr = "Enregistrement du role " . $label . ", dont la description est " . $description . "";
                
                $f->EnregistrerLog($descr, $this->user);
                $roleDao->_em->commit();
            } catch (Exception $ex) {
                $roleDao->_em->rollBack();

                    //$this->view->errormsg=$e->getMessage();
                    $errormsg = $ex->getMessage(); //"Echec d'enregistrement";
                    $rep = array('type' => "error", 'msg' => $ex->getMessage(),"result"=>$result);
                echo json_encode($rep);
                 exit(); 

            }
           
            $rep = array('type' => "success", 'msg' => "enregistrement effectué avec succes","result"=>$result);
            echo json_encode($rep);
            //echo json_encode($list);
           exit(); 
        }
    }
   
   public function listAuthorisation(){
        $authDao = new AuthorisationDAO();
            $listeParent = $authDao->listAuthParent();
            
            
            $result = [];
            
            foreach($listeParent as $parent){
                $result[$parent->getCode()][] = array("code"=>$parent->getCode(),"label"=>$parent->getLabel(),"action"=>$parent->getAction(),"parent"=>NULL);
                $list=$authDao->listerSousAuths($parent);
                foreach($list as $elem){
                    if ($parent == $elem->getParent()){
                        $result[$parent->getCode()][] = array("code"=>$elem->getCode(),"label"=>$elem->getLabel(),"action"=>$elem->getAction(),"parent"=>$parent->getCode());
                    }
                }
                
            }
            
           echo json_encode(array("type" => "success",'msg' => "Connexion reussie","result"=>$result));
            exit();
   }
   
    public function editRole(){
        
         $authDao = new AuthorisationDAO();
        $roleAuthDao = new RoleAuthorisationDAO();
        $roleDao = new RoleDAO();
        $result = array();
        if (!empty($_POST)) {
             $label = $_POST["label"];
            $description = $_POST["description"];
            $codeRole=$_POST["codeRole"];
            
            $role = $roleDao->getRoleByCode($codeRole);
            $listAuth = $_POST["listAuth"];
            // MAJ dans la table role
            try {
                // ici on fait les mis à jour......
                if($label!=null && $label!=""){
                    $role->setLabel(trim($label));
                 }
                 if($description!=null && $description!=""){
                    $role->setDescription(trim($description));
                 }
                 $roleDao->_em->beginTransaction();
                $role->setState(1);
                $roleDao->edit($role);
                $listRoleAuth=$roleAuthDao->getRoleAuthorisationByRole($role);
                //var_dump($lignes); die;
                
                if(is_array($listRoleAuth)) foreach ($listRoleAuth as $roleAuth) $roleAuthDao->delete($roleAuth);
                 foreach ($listAuth as $elem)
                {
                     
                         $codeAuth=$elem["value"];
                        $auth = $authDao->getAuthorisationByCode($codeAuth);
                        
                        $roleAuth= new \Application\Models\RoleAuthorisation();
                        $roleAuth->setRole($role);
                        $roleAuth->setAuthorisation($auth);
                        $roleAuth->setState(1);
                        $roleAuth->setCode(str_replace(' ', '', microtime()));
                        //enregistrement
                        $roleAuthDao->save($roleAuth);
                }
                     $utilisateurDao = new UtilisateurDAO();
                    $this->user = $utilisateurDao->getUtilisateurByCode($_SESSION["codeUser"]);
                   $f = new Fonction();
               
                $descr = "Edition du role " . $label . ", dont la description est " . $description . "";
                
                $f->EnregistrerLog($descr, $this->user);
                $roleDao->_em->commit();
                } catch (Exception $e) {
                     $roleDao->_em->rollBack();
                    $errormsg = $ex->getMessage(); //"Echec d'enregistrement";
                    $rep = array('type' => "error", 'msg' => $ex->getMessage(),"result"=>$result);
                    echo json_encode($rep);
                    exit(); 
                }

            
            $rep = array('type' => "success", 'msg' => "enregistrement effectué avec succes","result"=>$result);
            echo json_encode($rep);
            //echo json_encode($list);
           exit(); 
        }
    }
    
   
   
     public function listRole()
    {
       $table = 'roles';

        $primaryKey = 'code';
        $columns = array(
            array('db' => 'code', 'dt' => 0),
            array('db' => 'label', 'dt' => 1),
            array('db' => 'description' , 'dt' => 2)
        );

        $sql_details = array(
            'user' => DB_USER,
            'pass' => DB_PASSWORD,
            'db' => DB_NAME,
            'host' => HOSTNAME
        );

         
        require(PUBLIC_PATH . '/files_to_include/ssp.class.php');

        $resultatDataTable = SSP::simple($_POST, $sql_details, $table, $primaryKey, $columns);
        
       
        echo json_encode($resultatDataTable);
        exit();
    }
    public function viewRole()
    {
        $id = $this->getRequest()->getParam('id');
        $objuti = new UtilisateurDAO();
        $utilisateur = $objuti->getUtilisateurById($id);
        $profilDAO = new ProfilDAO();
        $profils = $profilDAO->lister();
        $this->view->profils = $profils;

        $this->view->utilisateur = $utilisateur;
         
    }

    public function deleteRole()
    {
       if (!empty($_POST)) {

            $code = $_POST["code"];
            $roleDao = new RoleDAO();
            $roleAuthDao = new RoleAuthorisationDAO();
             $result = array();
            $role = $roleDao->getRoleByCode($code);
            if(is_object($role)){
                
           
             try {      
                        $roleDao->_em->beginTransaction();
                        $listRoleAuth=$roleAuthDao->getRoleAuthorisationByRole($role);
                        if(is_array($listRoleAuth)) foreach ($listRoleAuth as $roleAuth) $roleAuthDao->delete($roleAuth);
                        $role->setState(0);
                        $roleDao->edit($role);
                        $f = new Fonction();
                        $utilisateurDao = new UtilisateurDAO();
                        $user = $utilisateurDao->getUtilisateurByCode($_SESSION["codeUser"]);
                        $descr = "Suppression du role No ".$code." de label:".$role->getLabel();
                        $descr .= " par l'utilisateur ".utf8_encode($user->getName())." ";
                        $f->EnregistrerLog($descr, $user);
                      $roleDao->_em->commit();  
                    } catch (Exception $ex) {
                        $errormsg = $ex->getMessage(); //"Echec d'enregistrement";
                         $rep = array('type' => "error", 'msg' => $ex->getMessage(),"result"=>$result);
                          echo json_encode($rep);
                         exit();
                    }
                    $rep = array('type' => "success", 'msg' => "enregistrement effectué avec succes","result"=>$result);
                    echo json_encode($rep);
                    //echo json_encode($list);
                    exit(); 
           }
        }
    }

   
      public function findauth()
    {
        try{
          
           $authDao = new AuthorisationDAO();
           $liste= $authDao->listAll();
           
           $resultat = array();
           foreach ( $liste as $auth ){
               $resultat[]=["value"=>$auth->getCode(),"item"=>$auth->getLabel()];
              
           }
           
           echo json_encode($resultat);
        } catch (Exception $ex) {
           echo json_encode(array("type" => "error","msg"=>$ex->getMessage()));
        }
        
        exit();
        
        
    }
    
      public function allrole()
    {
        try{
          
           $roleDao = new RoleDAO();
           $liste= $roleDao->listAll();
           
           $resultat = array();
           foreach ( $liste as $role ){
               
                $resultat[]=["id"=>$role->getCode(),"value"=>$role->getLabel()];
              
           }
           
            echo json_encode(array('data'=>$resultat,'nb'=>count($resultat)));
        } catch (Exception $ex) {
           echo json_encode(array("type" => "error","msg"=>$ex->getMessage()));
        }
        
        exit();
        
        
    }
       public function findchoice()
    {
           
           if (!empty($_POST)) {
        try{
            $roleDao = new RoleDAO();
            $code = $_POST['code'];
            $leRole = $roleDao->getRoleByCode($code);
            $roleAuthDao = new RoleAuthorisationDAO();
            $listAuth= $roleAuthDao->listRoleAuthorisationByRole($leRole);
            
             $authDao = new AuthorisationDAO();
           $liste= $authDao->listAll();
           $resultat = array();
            $all = array();
            $own = array();
           foreach ( $liste as $auth ){
               $all[]=["value"=>$auth->getCode(),"item"=>$auth->getLabel()];
           }
           foreach ($listAuth as $roleAuth ){
               $own[]=["value"=>$roleAuth->getAuthorisation()->getCode(),"item"=>$roleAuth->getAuthorisation()->getLabel()];
           }
           $diff = array_udiff($all, $own,function ($obj_a, $obj_b) {
                 return strcmp($obj_a["value"], $obj_b["value"]);
                });
            foreach ($own as $elem ){
               $resultat[]=["value"=>$elem["value"],"item"=>$elem["item"],"selected"=>true];
           }
           foreach ($diff as $elem ){
               $resultat[]=["value"=>$elem["value"],"item"=>$elem["item"]];
           }
          echo json_encode($resultat);
        } catch (Exception $ex) {
           echo json_encode(array("type" => "error","msg"=>$ex->getMessage()));
        }
        
        exit();
        
          }
    }
   
     public function findRole()
    {
         
        try{
           $nom = trim($_POST["nom"]) ;
          $personneDao = new PersonneDAO();
           $liste= $personneDao->chercherClient($nom);
           $resultat = array();
           foreach ( $liste as $personne ){
               $resultat[]=["id"=>$personne->getIdpersonne(),"value"=>$personne->getNom()." ".$personne->getPrenom()];
              
           }
           echo json_encode(array('data'=>$resultat,'nb'=>count($resultat)));
        } catch (Exception $ex) {
           echo json_encode(array("type" => "error"));
        }
        
        exit();
        
        
    }

}



