<?php

include APPLICATION_PATH . '/DAO/UtilisateurDAO.php';
include APPLICATION_PATH . '/DAO/AuthorisationDAO.php';
include APPLICATION_PATH . '/DAO/ConsommableDAO.php';
include APPLICATION_PATH . '/DAO/FournitureDAO.php';
include APPLICATION_PATH . '/DAO/EmplacementDAO.php';
include APPLICATION_PATH . '/DAO/EntreeConsommableDAO.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 FournitureController 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(), "Fourniture")){
                    $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 fournitures; CREATE  TABLE IF NOT EXISTS fournitures(PRIMARY KEY (id)) select f.id as id,f.nom as nom,f.datefourniture as datefourniture,e.nom as emplacement "
                . " from fourniture f join emplacement e on f.emplacement=e.id where f.state=1";
        $requete = $connexion->prepare($sql);
        $requete->execute();
         $table = 'fournitures';

        $primaryKey = 'id';
        $columns = array(
            array('db' => 'id', 'dt' => 0),
            array('db' => 'nom', 'dt' => 1),
            array('db' => 'datefourniture' , '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();
           $entreeConsoDao = new EntreeConsommableDAO();
           $utilisateurDao = new UtilisateurDAO();
           $user = $utilisateurDao->getUtilisateurByCode($_SESSION["codeUser"]);
           //Recuperation de l'emplacement
           $empDao = new EmplacementDAO();
           
            $emp= $empDao->getEmpById((int)ltrim($_POST["idemplacement"],'"'));
           
           $consoDao->_em->beginTransaction();
           $fournitureDao = new FournitureDAO();
           $fourniture = new \Application\Models\Fourniture();
           $fourniture->setDatefourniture(new \DateTime());
           $fourniture->setNom($user->getName());
            $fourniture->setReceptioniste($user);
           $fourniture->setState(1);
           $fourniture->setEmplacement($emp);
           
          $fourniture= $fournitureDao->save($fourniture);
          
           try {
                foreach ($_POST['details'] as $entree){
                   
                    $conso  = $consoDao->getConsoById((int)ltrim($entree['id'],'"'));
                   
                    $entreeConso = new Application\Models\EntreeConsommable();

                    $entreeConso->setConsommable($conso);
                    $entreeConso->setDateentree(new \DateTime());
                    $entreeConso->setQuantite($entree['quantite']);
                    
                    $entreeConso->setFourniture($fourniture);
                    $entreeConso->setState(1);
                    $entreeConsoDao->save($entreeConso);
               
                    }
           
                   $f = new Fonction();
               
                $descr = "Enregistrement de la fourniture " . $fourniture->getId() . ", du " . date_format($fourniture->getDatedatefourniture(), '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()
    {
         $fournitureDao = new FournitureDAO();
         $entreeDao = new EntreeConsommableDAO();
         $resutltat = [];
          if (!empty($_POST)) {
               $fourniture  = $fournitureDao->getFournitureById((int)$_POST['fourniture']);
               if(is_object($fourniture)){
                   $liste = $entreeDao->getEntreeByFourniture($fourniture);
                   
                   foreach ($liste as $itemF){
                       $object = new stdClass();
                        //$object->id = $elemF->getId();
                        $object->date = date_format($itemF->getDateentree(), 'D-M-Y H:i:s');
                        $object->quantite =$itemF->getQuantite();
                        $object->consommable =$itemF->getConsommable()->getLibelle();
                        $resutltat[]=$object;
                   }
                     echo json_encode([ 'data' => $resutltat,'emplacement'=>$fourniture->getEmplacement()->getNom(), '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();
    }
    
}

