<?php
include APPLICATION_PATH . '/DAO/UtilisateurDAO.php';
include APPLICATION_PATH . '/DAO/AuthorisationDAO.php';
include APPLICATION_PATH . '/DAO/LaboDAO.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 ModuleLabo
{
    
     
    public function addLabo(){
        
        if (!empty($_POST)) {
            $nom = $_POST["nom"];
            $phone = $_POST["phone"];
            $email = $_POST["email"];
            $codeParent = $_POST["inputParent_id"];
            $codeParent=trim($codeParent,'"');
            $description = $_POST["description"];
            $result = array();
            //exit();
          
            $errormsg="";
             $laboDao = new LaboDAO();
             
            // Enregistrement dans la table Profil
             if($laboDao->existLaboName($nom)==true){
                    $errormsg.="The site:".$nom." already exits!";
                     echo json_encode(array("type" => "error",'msg' => $errormsg,"result"=>$result));
           
                     exit();
                }
                if($codeParent==""){
                    $errormsg.="Define the parent of laboratory ".$nom;
                     echo json_encode(array("type" => "error",'msg' => $errormsg,"result"=>$result));
           
                     exit();
                }
           
           try {
              
                $laboDao->_em->beginTransaction();
            $labo = new \Application\Models\Laboratoire();
               
                
                $labo->setNom($nom);
                $labo->setDescription($description);
                $labo->setPhone($phone);
                $labo->setEmail($email);
                $labo->setState(1);
                $labo->setCode(str_replace(' ', '', microtime()));
                 if($codeParent!=""){
               $parent = $laboDao->getLaboByCode($codeParent);
               if(is_object($parent) && !is_null($parent))$labo->setParent($parent);
           }
                
                
                $laboDao->save($labo);
                
                
                $utilisateurDao = new UtilisateurDAO();
            $user = $utilisateurDao->getUtilisateurByCode($_SESSION["codeUser"]);
                   $f = new Fonction();
               
                $descr = "Save of laboratory " . $nom . ", with description: " . $description . " ";
                $descr .= "by user " . $user->getName() ;
                $f->EnregistrerLog($descr, $user);
                $laboDao->_em->commit();
            } catch (Exception $ex) {
                $laboDao->_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 editLabo(){
        
         $laboDao = new LaboDAO();
        $result = array();
        if (!empty($_POST)) {
             $nom = $_POST["name"];
             $code = $_POST["code"];
            $email = $_POST["email"];
            $phone = $_POST["phone"];
            $codeParent = $_POST["inputParent_id"];
            $codeParent=trim($codeParent,'"');
            $description = $_POST["description"];
            $result = array();
            
            $labo = $laboDao->getLaboByCode($code);
            if($codeParent=="" && $labo->setParent()==NULL){
                    $errormsg.="Select the parent of laboratory ".$nom;
                     echo json_encode(array("type" => "error",'msg' => $errormsg,"result"=>$result));
           
                     exit();
                }
            // MAJ dans la table role
            try {
                // ici on fait les mis à jour......
                if($nom!=null && $nom!=""){
                    $labo->setNom(trim($nom));
                 }
                 if($description!=null && $description!=""){
                    $labo->setDescription(trim($description));
                 }
                 if($email!=null && $email!=""){
                    $labo->setEmail(trim($email));
                 }
                 if($phone!=null && $phone!=""){
                    $labo->setPhone(trim($phone));
                 }
                if($codeParent!=""){
               $parent = $laboDao->getLaboByCode($codeParent);
               if(is_object($parent) && !is_null($parent))$labo->setParent($parent);
                    }
                 $laboDao->_em->beginTransaction();
               
                $laboDao->edit($labo);
               
                     $utilisateurDao = new UtilisateurDAO();
                    $user = $utilisateurDao->getUtilisateurByCode($_SESSION["codeUser"]);
                   $f = new Fonction();
               
                $descr = "Edition of laboratory " . $nom. ", with description " . $description . " ";
                $descr .= "by user " . $user->getName() ;
                $f->EnregistrerLog($descr, $user);
                 $laboDao->_em->commit();
                } catch (Exception $e) {
                     $laboDao->_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 listLabo()
    {
       $table = 'labos';

        $primaryKey = 'code';
        $columns = array(
            array('db' => 'code', 'dt' => 0),
            array('db' => 'nom', 'dt' => 1),
            array('db' => 'phone' , 'dt' => 2),
            array('db' => 'description' , 'dt' => 3),
            array('db' => 'email' , 'dt' => 4),
             array('db' => 'parent' , 'dt' => 5)
        );

        $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 findLabo()
    {
         
        try{
           $nom = trim($_POST["parent"]) ;
          $laboDao = new LaboDAO();
           $liste= $laboDao->findByName($nom);
           $resultat = array();
           foreach ( $liste as $labo){
               $resultat[]=["id"=>$labo->getCode(),"value"=>$labo->getNom()];
              
           }
           echo json_encode(array('data'=>$resultat,'nb'=>count($resultat)));
        } catch (Exception $ex) {
            
           echo json_encode(array("type" => "error","msg"=>$ex->getMessage()));
        }
        
        exit();
        
        
    }

}



