<?php
include APPLICATION_PATH . '/DAO/UtilisateurDAO.php';
include APPLICATION_PATH . '/DAO/AuthorisationDAO.php';
include APPLICATION_PATH . '/DAO/TypeInformationMaladieDAO.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 ModuleTypeInformationMaladie
{
    public $user;
     
    public function addTypeInformationMaladie(){
        
        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,$codeParent)==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 editTypeInformationMaladie(){
        
         $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 listTypeInformationMaladie()
    {
       $table = 'type_information_maladies';

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

        $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 findsiteuser()
    {
        try{
          
           $siteDao = new SiteDAO();
           $liste= $siteDao->listAll();
           
           $resultat = array();
           foreach ( $liste as $site ){
               $resultat[]=["value"=>$site->getCode(),"item"=>$site->getName()];
              
           }
           
           echo json_encode($resultat);
        } catch (Exception $ex) {
           echo json_encode(array("type" => "error","msg"=>$ex->getMessage()));
        }
        
        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();
        
        
    }
  
     public function toObjet($carry, $item)
    {
        $object = new stdClass();
        $object->id = $item->getCode();
        $object->text = $item->getName();
        $object->parent = NULL;
        $object->children = NULL;
        if($item->getParent()!=NULL)$object->parent = $item->getParent()->getCode();
        $carry[] = $object;
        return $carry;
    }
     public function toObjetChildren($carry, $item)
    {
        $item->children = $this->makeTree($carry, $item->id);
        return $item;
    }
      public function getSites(){
         $siteDao = new SiteDAO();
         $liste= $siteDao->listAll();
         $result = array();
         $final = array();
        $result=array_reduce($liste, array($this,"toObjet"));
      $final[]=$this->makeTree($result);
         echo json_encode(array("type" => "success",'msg' => "Connexion reussie","result"=>$final));
          exit();
      
    }
    public function makeTree($nodes){
       
       
            array_reduce($nodes, function($carry,$item) use($nodes) {
                
                $resultInter = array_filter($nodes, function($node) use ($item) {
                            return $node->parent==$item->id;
                    });
                     
                      foreach ($resultInter as $elem){
                          $item->children[] =$elem;
                          
                      }
                    
            });
            $result= new stdClass();
            foreach ($nodes as $elem){
                if($elem->parent==NULL){
                    unset($elem->parent);
                   $result =  $elem;
                }
            }
            foreach ($result->children as $elem){
                unset($elem->parent);
            }
            return $result;
    }

}



