<?php

include APPLICATION_PATH . '/api/SiteApi.php';

class SiteController 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(), "Role")){
                    $this->_helper->redirector('index' , 'Index');
                }
            }else{
                $this->_helper->redirector('index' , 'Index');
            }
        }else{
            $this->_helper->redirector('index' , 'Index');
        }
    }

    public function indexAction()
    {
         $userDao = new UtilisateurDAO();
        $connexion = $userDao->_em->getConnection();
        $sql = "drop table if exists sites; CREATE  TABLE IF NOT EXISTS sites(PRIMARY KEY (code)) SELECT s.code,p.name as parent,s.name,s.description,s.localisation  FROM site s left join site p on s.parent=p.code WHERE s.state= 1 ";
        $requete = $connexion->prepare($sql);
        $requete->execute();
    }
     public function datatableAction()
    {
       $moduleSite = new ModuleSite();
       $moduleSite->listSite();
    }

    public function enregistrerAction()
    {
       
        if (!empty($_POST)) {
           $moduleSite = new ModuleSite();
           $moduleSite->addSite();
        } else {
            $authDao = new AuthorisationDAO();
            $this->view->auths = $authDao->listAuthParent();
        }

    }
    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()
    {
         $moduleSite = new ModuleSite();
       $moduleSite->findSite();
    }

}

