<?php

include APPLICATION_PATH . '/DAO/UtilisateurDAO.php';
include APPLICATION_PATH . '/DAO/AuthorisationDAO.php';
include APPLICATION_PATH . '/DAO/ConsommableDAO.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';

class ConsommableController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        session_start();
        if ( isset($_SESSION["codeUser"])){
             $_SESSION["derniereAction"] = new \DateTime();
             $utilisateurDao = new UtilisateurDAO();
             $roleAuthDao = new RoleAuthorisationDAO();
            $user = $utilisateurDao->getUtilisateurByCode($_SESSION["codeUser"]);
            if(is_object($user)){
                if(!$roleAuthDao->existController($user->getRole(), "Consommable")){
                    $this->_helper->redirector('index' , 'Index');
                }
            }else{
                $this->_helper->redirector('index' , 'Index');
            }
        }else{
            $this->_helper->redirector('index' , 'Index');
        }
    }

    public function indexAction()
    {
         
    }
     public function datatableAction()
    {
       $table = 'consommable';

        $primaryKey = 'id';
        $columns = array(
            array('db' => 'id', 'dt' => 0),
            array('db' => 'libelle', 'dt' => 1),
            array('db' => 'description' , 'dt' => 2),
            array('db' => 'min' , 'dt' => 3)
        );

        $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);
        
       
        //var_dump($resultatDataTable);
        echo utf8_encode(json_encode($resultatDataTable));
        exit();
    }
    
     public function stockAction()
    {
       $table = 'stocks';
        $userDao = new UtilisateurDAO();
        $connexion = $userDao->_em->getConnection();
        $sql = "drop table if exists stocks; CREATE  TABLE IF NOT EXISTS stocks(PRIMARY KEY (id)) select st.id as id,st.consommable,et.entree-st.sortie as quantite

from (SELECT c.id as id,c.libelle as consommable, sum(IFNULL(s.quantite,0)) as sortie  FROM consommable c 
left join sortieconsommable s on c.id=s.consommable WHERE c.state= 1 group by c.id, c.libelle) st join (SELECT c.id as id,c.libelle as consommable, sum(IFNULL(e.quantite,0)) as entree  FROM consommable c 
left join entreeconsommable e on c.id=e.consommable WHERE c.state= 1 group by c.id, c.libelle) et on st.id = et.id ";
        $requete = $connexion->prepare($sql);
        $requete->execute();

        $primaryKey = 'id';
        $columns = array(
            array('db' => 'id', 'dt' => 0),
            array('db' => 'consommable', 'dt' => 1),
            array('db' => 'quantite' , '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);
        
       
        //var_dump($resultatDataTable);
        echo utf8_encode(json_encode($resultatDataTable));
        exit();
    }

    public function enregistrerAction()
    {
       
        if (!empty($_POST)) {
           $consoDao = new ConsommableDAO();
           if($consoDao->existSiteName($_POST['libelle'])){
               echo json_encode([ 'data' => NULL, 'message' => 'The element '.$_POST['libelle'].' already exists','status' =>200]) ;
                exit();
           }
           $conso  = new Application\Models\Consommable();
           $conso->setDescription($_POST['description']);
           $conso->setLibelle($_POST['libelle']);
           $conso->setMin((int)$_POST['quantite']);
           $conso->setState(1);
           $consoDao->save($conso);
           echo json_encode([ 'data' => NULL, 'message' => 'Saved successfully','status' =>200]) ;
        } 
        exit();

    }
    public function editerAction()
    {
       $authDao = new AuthorisationDAO();
        $roleAuthDao = new RoleAuthorisationDAO();
        $roleDao = new RoleDAO();
        $siteDao = new SiteDAO();
        
        if ($this->getRequest()->getMethod() == 'POST' && !empty($_POST)) {
             $moduleSite = new ModuleSite();
             $moduleSite->editSite();
            
        }else{
            $code = $this->getRequest()->getParam('code');
            $leSite = $siteDao->getSiteByCode($code);
            $this->view->site = $siteDao->getSiteByCode($code);
           
        }
        
        
    }
    
    public function deleteAction()
    {
        if (!empty($_POST)) {

            $moduleRole = new ModuleRole();
             $moduleRole->deleteRole();
        }else{
                    $rep = array('type' => "error", 'msg' => "Requete mal formée");
                          echo json_encode($rep);
                         exit();
        }
    }
    
      public function findAction()
    {
        
        try{
           $nom = trim($_POST["consommable"]) ;
          $consoDao = new ConsommableDAO();
           $liste= $consoDao->findByName($nom);
           $resultat = array();
           foreach ( $liste as $conso){
               $resultat[]=["id"=>$conso->getId(),"value"=>$conso->getLibelle()];
              
           }
           echo json_encode(array('data'=>$resultat,'nb'=>count($resultat)));
        } catch (Exception $ex) {
           echo json_encode(array("type" => "error"));
        }
        
        exit();
        
        
    }
    
}

