<?php
class MenuDAO{
    private $banco;
    private $auditoria;

    static private  $tabela          = "menus";
    static private  $tabelaId        = "idMenu";
    static private  $tabelaMenuPai   = "idMenuPai"; 

    public function __construct() {
        $this->banco = new Banco();
        return;
    }
    
    public function consultaExistenciaPeloNome($nome){
         $param["Nome"] = $nome;
         
         $consulta = $this->banco->buscar(self::$tabela,self::$tabelaId, $param);
         if($consulta){
             return true;
         }else{
             return false;
         }
     }
     
     public function consultar($campos, $param = false, $retorno = "obj", $order = false, $auditoria = false){
         
         if($auditoria){
            $join .= 'LEFT JOIN auditorias ON ';
            $join .= self::$tabela.'.idAuditoria = auditorias.idAuditoria ';    
         }
         
         $busca = $this->banco->buscar(self::$tabela, $campos, $param, $join, $order);
         
         if(is_array($busca)){
             if($retorno == "obj")  $consulta = self::montarObjeto($busca);
             if($retorno == "json") $consulta = self::montarJSON($busca);
         }else{
             $consulta = false;
         }
         return $consulta;
     }
     
     
     public function inserir(Menu $objMenu){
         $dados["Nome"]               = $objMenu->getNome();
         $dados["Link"]               = $$objMenu->getLink();
         $dados["idMenuPai"]          = $$objMenu->getIdMenuPai();
         
         $this->auditoria = new AuditoriaDAO('insere', 'INSERIR MENU');
         $dados["idAuditoria"] = $this->auditoria->getUltimoId();
         
         $insere = $this->banco->insere(self::$tabela, $dados, self::$tabelaId);
         if($insere) return $insere; else return false;
     }
     
     public function getMenuUsuario($retorno = 'obj'){
        $campos = self::$tabela.'.*'; 
        
        $order  = ' ORDER BY '.self::$tabela.'.idMenuPai ASC, ';
        $order .= self::$tabela.'.Ordem ASC ';
        
        $param['menus_niveis.idNivel']   = $_SESSION['login']['Nivel']['id'];
        $param['menus_modulos.idModulo'] = $_SESSION['login']['ModuloAtual']['id'];
        
        $join  = ' INNER JOIN menus_niveis ON ';
        $join .= self::$tabela.'.'.self::$tabelaId.' = menus_niveis.'.self::$tabelaId.' ';
        $join .= ' INNER JOIN menus_modulos ON ';
        $join .= self::$tabela.'.'.self::$tabelaId.' = menus_modulos.'.self::$tabelaId.' ';
       
        
        $busca = $this->banco->buscar(self::$tabela, $campos, $param, $join, $order);
        
        if(is_array($busca)){
            if($retorno == "obj")  $consulta = self::montarObjeto($busca);
            if($retorno == "json") $consulta = self::montarJSON($busca);
            if($retorno == "h_array") $consulta = self::montarArrayHierarquico($busca);
        }else{
            $consulta = false;
        }

        return $consulta;
     }
     
     
     /* metodos nao publicos */
     
     private function montarArrayHierarquico(array $busca){
         
         foreach($busca as $ch=>$vl){
             $menu = new Menu($vl['idMenu'], $vl['Nome'], $vl['Link'], $vl['Ordem'], $vl['idMenuPai']);
             $retorno[$vl['idMenuPai']][$vl['idMenu']] = $menu;
         }
         return $retorno;
     }
     
     private function montarObjeto(array $linha){
         foreach($linha as $ch=>$menu){
            $Menu[$ch] = new Menu($menu[self::$tabelaId]);
            $Menu[$ch]->setNome($menu["Nome"]);
            $Menu[$ch]->setLink($menu["Link"]);
            $Menu[$ch]->setIdMenuPai($menu["idMenuPai"]);
        }
        return $Menu;
     }
     
     private function montarJSON(array $linha){
        // self::remontaMenu($linha);
         $total   = count($linha);
         $cc      = 1;
         $retorno = '{"total":"'.$total.'", "dados":[';
         foreach($linha as $menu){
             
             $retorno .= '{"idmenu":"'.$menu[self::$tabelaId].'", ';
             $retorno .= ' "nome":"'.$menu["Nome"].'", ';
             $retorno .= ' "link":"'.$menu["Link"].'", ';
             $retorno .= ' "idmenupai":"'.$menu["idMenuPai"].'" }';
             $cc++;
             if($cc <= $total) $retorno .= ', ';
         }
         $retorno .= ']}';
         return $retorno;
     }
     
     /*
     private function remontaMenu(array $menu){
         foreach($menu as $ch=>&$item){
             if(!is_null($item[self::$tabelaMenuPai])){
                $item = array_search($item[self::$tabelaMenuPai], self::array_column($menu, self::$tabelaId));
                unset($menu[$ch]);
             }
         }
         return;
     }
      * 
      */
     
    /* remover funcao após mudar versao do PHP*/ 
    function array_column(array $input, $columnKey, $indexKey = null) {
        $array = array();
        foreach ($input as $value) {
            if ( ! isset($value[$columnKey])) {
                trigger_error("Key \"$columnKey\" does not exist in array");
                return false;
            }
            if (is_null($indexKey)) {
                $array[] = $value[$columnKey];
            }
            else {
                if ( ! isset($value[$indexKey])) {
                    trigger_error("Key \"$indexKey\" does not exist in array");
                    return false;
                }
                if ( ! is_scalar($value[$indexKey])) {
                    trigger_error("Key \"$indexKey\" does not contain scalar value");
                    return false;
                }
                $array[$value[$indexKey]] = $value[$columnKey];
            }
        }
        return $array;
    }
     
}