<?php
include APPLICATION_PATH . '/DAO/UtilisateurDAO.php';
include APPLICATION_PATH . '/DAO/AuthorisationDAO.php';
include APPLICATION_PATH . '/DAO/SiteDAO.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 ModuleSite
{
    public $user;
     
    public function addSite(){
        
        if (!empty($_POST)) {
            $name = $_POST["name"];
            $localisation = $_POST["localisation"];
            $codeParent = $_POST["inputParent_id"];
            $codeParent=trim($codeParent,'"');
            $description = $_POST["description"];
            $result = array();
            //exit();
          
            $errormsg="";
             $siteDao = new SiteDAO();
             
            // Enregistrement dans la table Profil
             if($siteDao->existSiteName($name)==true){
                    $errormsg.="The site:".$name." already exits!";
                     echo json_encode(array("type" => "error",'msg' => $errormsg,"result"=>$result));
           
                     exit();
                }
           if($codeParent==""){
                    $errormsg.="Select the parent of site ".$name;
                     echo json_encode(array("type" => "error",'msg' => $errormsg,"result"=>$result));
           
                     exit();
                }
           try {
              
                $siteDao->_em->beginTransaction();
            $site = new \Application\Models\Site();
               
                // ici on fait les enregistrements......
                $site->setName($name);
                $site->setDescription($description);
                $site->setLocalisation($description);
                $site->setState(1);
                $site->setCode(str_replace(' ', '', microtime()));
                 if($codeParent!=""){
               $parent = $siteDao->getSiteByCode($codeParent);
               if(is_object($parent) && !is_null($parent))$site->setParent($parent);
           }
                
                
                $siteDao->save($site);
                
                
                $utilisateurDao = new UtilisateurDAO();
            $user = $utilisateurDao->getUtilisateurByCode($_SESSION["codeUser"]);
                   $f = new Fonction();
               
                $descr = "Enregistrement du site " . $name . ", dont la description est " . $description . " ";
                $descr .= "Par l'utilisateur " . $user->getName() ;
                $f->EnregistrerLog($descr, $user);
                $siteDao->_em->commit();
            } catch (Exception $ex) {
                $siteDao->_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 editSite(){
        
         $siteDao = new SiteDAO();
        $result = array();
        if (!empty($_POST)) {
             $name = $_POST["name"];
             $code = $_POST["code"];
            $localisation = $_POST["localisation"];
            $codeParent = $_POST["inputParent_id"];
            $codeParent=trim($codeParent,'"');
            $description = $_POST["description"];
            $result = array();
            
            $site = $siteDao->getSiteByCode($code);
            if($codeParent=="" && $site->setParent()==NULL){
                    $errormsg.="Select the parent of site ".$name;
                     echo json_encode(array("type" => "error",'msg' => $errormsg,"result"=>$result));
           
                     exit();
                }
            // MAJ dans la table role
            try {
                // ici on fait les mis à jour......
                if($name!=null && $name!=""){
                    $site->setName(trim($name));
                 }
                 if($description!=null && $description!=""){
                    $site->setDescription(trim($description));
                 }
                 if($localisation!=null && $localisation!=""){
                    $site->setLocalisation(trim($localisation));
                 }
                if($codeParent!=""){
               $parent = $siteDao->getSiteByCode($codeParent);
               if(is_object($parent) && !is_null($parent))$site->setParent($parent);
                    }
                 $siteDao->_em->beginTransaction();
                $site->setState(1);
                $siteDao->edit($site);
               
                     $utilisateurDao = new UtilisateurDAO();
                    $user = $utilisateurDao->getUtilisateurByCode($_SESSION["codeUser"]);
                   $f = new Fonction();
               
                $descr = "Edition du site " . $name . ", dont la description est " . $description . " ";
                $descr .= "Par l'utilisateur " . $user->getName() ;
                $f->EnregistrerLog($descr, $user);
                 $siteDao->_em->commit();
                } catch (Exception $e) {
                     $siteDao->_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 listSite()
    {
       $table = 'sites';

        $primaryKey = 'code';
        $columns = array(
            array('db' => 'code', 'dt' => 0),
            array('db' => 'name', 'dt' => 1),
            array('db' => 'localisation' , 'dt' => 2),
            array('db' => 'description' , 'dt' => 3),
             array('db' => 'parent' , 'dt' => 4)
        );

        $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 findSite()
    {
         
        try{
           $nom = trim($_POST["parent"]) ;
          $siteDao = new SiteDAO();
           $liste= $siteDao->findByName($nom);
           $resultat = array();
           foreach ( $liste as $site){
               $resultat[]=["id"=>$site->getCode(),"value"=>$site->getName()];
              
           }
           echo json_encode(array('data'=>$resultat,'nb'=>count($resultat)));
        } catch (Exception $ex) {
           echo json_encode(array("type" => "error"));
        }
        
        exit();
        
        
    }

}



