<?php

/*
 * Model's functions of Site Entity
 */

/**
 * @author Messanga Landry <messangalandry@gmail.com>
 */

include APPLICATION_PATH . '/Models/Site.php';

class SiteDAO {
    //put your code here
    public $_em;
    function SiteDAO(){
        $registry = Zend_Registry::getInstance();
        $this->_em = $registry->entitymanager;
    }
    
    /**
     * 
     * @param Application\Models\Site $site
     */
    public function save($site){
        $this->_em->persist($site);
        $this->_em->flush();
        
    }
    
    /**
     * 
     * @param Application\Models\Site $site
     */
    public function edit($site){
        $this->_em->merge($site);
        $this->_em->flush();
    }
    //Delete un site
    public function delete($site) {

        $this->_em->merge($site);
        $this->_em->flush();
    }
    
    // /**
    //  * 
    //  * @param Application\Models\Role $fiche
    //  */
    // public function disable($fiche){
    //     $this->_em->remove($fiche);
    //     $this->_em->flush();
    // }
    
    /**
    
     * @return Application\Models\Site
     */
    public function listAll(){
           $liste =  $this->_em->getRepository("\Application\Models\Site")->findBy(array("state" => 1));
          
           return $liste;
    }
     /**
     * 
     * @param string $code
     * @return Application\Models\Site
     */
    public function getSiteByCode($code){
        $site = $this->_em->getRepository('\Application\Models\Site')->findOneBy(array("code" => $code,"state"=>1));
        return $site;
    }
    
    public function existSiteName($name,$parent){

           try{
            
            $liste = $this->_em->getRepository("\Application\Models\Site")->createQueryBuilder("a")
                             ->where("UPPER(a.name) like :name")
                             ->setParameter("name" , '%'.strtoupper($name) . '%')
                             ->andWhere("a.state=1")
                             ->andWhere("a.parent=:parent")
                             ->setParameter("parent" , $parent)
                             ->getQuery()
                             ->getResult();
            
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
         
        
        if(count($liste)>0 && is_array($liste) )return true;
        else return false;
    }
      public function findByName($name){
        $liste = $this->_em->createQueryBuilder()
                ->select('c')
                ->from("\Application\Models\Site","c")
                ->where('c.state = 1')
                ->andWhere('c.name like :name ')
                ->setParameter('name',"%".$name."%")
                ->getQuery()
                ->getResult();
       
        return $liste;
    }
  

}
