<?php

include APPLICATION_PATH . '/DAO/UtilisateurDAO.php';
include APPLICATION_PATH . '/DAO/AuthorisationDAO.php';
include APPLICATION_PATH . '/DAO/ConsommableDAO.php';
include APPLICATION_PATH . '/DAO/SortieDAO.php';
include APPLICATION_PATH . '/DAO/SortieConsommableDAO.php';
include APPLICATION_PATH . '/DAO/EmplacementDAO.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 SortieController 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(), "Sortie")){
                    $this->_helper->redirector('index' , 'Index');
                }
            }else{
                $this->_helper->redirector('index' , 'Index');
            }
        }else{
            $this->_helper->redirector('index' , 'Index');
        }
    }

    public function indexAction()
    {
         
    }
     public function datatableAction()
    {
        $userDao = new UtilisateurDAO();
        $connexion = $userDao->_em->getConnection();
        $sql = "drop table if exists sorties; CREATE  TABLE IF NOT EXISTS sorties(PRIMARY KEY (id)) select f.id as id,f.nom as nom,f.datesortie as datesortie,e.nom as emplacement "
                . " from sortie f join emplacement e on f.emplacement=e.id where f.state=1";
        $requete = $connexion->prepare($sql);
        $requete->execute();
         $table = 'sorties';

        $primaryKey = 'id';
        $columns = array(
            array('db' => 'id', 'dt' => 0),
            array('db' => 'nom', 'dt' => 1),
            array('db' => 'datesortie' , 'dt' => 2),
            array('db' => 'emplacement' , '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 enregistrerAction()
    {
       
        if (!empty($_POST)) {
           $consoDao = new ConsommableDAO();
           $sortieConsoDao = new SortieConsommableDAO();
           $utilisateurDao = new UtilisateurDAO();
           $user = $utilisateurDao->getUtilisateurByCode($_SESSION["codeUser"]);
           
            $empDao = new EmplacementDAO();
           
            $emp= $empDao->getEmpById((int)ltrim($_POST["idemplacement"],'"'));
           $consoDao->_em->beginTransaction();
           $sortieDao = new SortieDAO();
           $sortie = new \Application\Models\Sortie();
           $sortie->setDatesortie(new \DateTime());
           $sortie->setNom($user->getName());
            $sortie->setReceptioniste($user);
           $sortie->setState(1);
           $sortie->setEmplacement($emp);
           
          $sortie= $sortieDao->save($sortie);
          
           try {
                foreach ($_POST['details'] as $entree){
                   
                    $conso  = $consoDao->getConsoById((int)ltrim($entree['id'],'"'));
                   
                    $sortieConso = new Application\Models\SortieConsommable();

                    $sortieConso->setConsommable($conso);
                    $sortieConso->setDatesortie(new \DateTime());
                    $sortieConso->setQuantite($entree['quantite']);
                    
                    $sortieConso->setSortie($sortie);
                    $sortieConso->setState(1);
                    $sortieConsoDao->save($sortieConso);
               
                    }
           
                   $f = new Fonction();
               
                $descr = "Enregistrement de la sortie " . $sortie->getId() . ", du " . date_format($sortie->getDatedatesortie(), 'yyyy-mm-dd') . " ";
                $descr .= "Par l'utilisateur " . $user->getName() ;
                $f->EnregistrerLog($descr, $user);
           $consoDao->_em->commit();
           echo json_encode([ 'data' => NULL, 'message' => 'Saved successfully','status' =>200]) ;
           } catch (Exception $ex) {
               var_dump($ex);
            $consoDao->_em->rollBack();
            echo json_encode([ 'data' => NULL, 'message' => $ex->getMessage(),'status' =>201]) ;
           }
           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()
    {
         $sortieDao = new SortieDAO();
         $ligneSortieDao = new SortieConsommableDAO();
         $resutltat = [];
         $data = new stdClass();
          if (!empty($_POST)) {
               $sortie  =$sortieDao->getSortieById((int)$_POST['sortie']);
               if(is_object($sortie)){
                   $liste = $ligneSortieDao->getItemBySortie($sortie);
                   
                   foreach ($liste as $itemF){
                       $object = new stdClass();
                        //$object->id = $elemF->getId();
                        $object->date = date_format($itemF->getDatesortie(), 'D-M-Y H:i:s');
                        $object->quantite =$itemF->getQuantite();
                        $object->consommable =$itemF->getConsommable()->getLibelle();
                        $resutltat[]=$object;
                   }
                   $data->receptioniste = $sortie->getNom();
                   $data->resultat = $resutltat;
                   $data->emplacement = $sortie->getEmplacement()->getNom();
                     echo json_encode([ 'data' => $data, 'message' => 'Saved successfully','status' =>200]) ;
               }else{
                   echo json_encode([ 'data' => NULL, 'message' => 'Apprivisionement non retrouve','status' =>201]) ;
               }
               exit();
        }
         
    }
      public function findsiteuserAction()
    {
         $moduleSite = new ModuleSite();
       $moduleSite->findsiteuser();
    }
       public function treeAction()
    {
         $moduleSite = new ModuleSite();
       $moduleSite->getSites();
    }
    
}

