<?php
class UtilObjeto {

    private $tabelaNome;
    private $tabelaId;
    private $arrCampos;

    ##################################
    # METODOS MAGICOS
    ##################################
    private $attr = array();
    public function __set($atributo, $valor) {
        // echo "Setando $atributo para $valor";
        $this->attr[$atributo] = trim($valor);
    }
    public function __get($atributo) {
        // echo "Obtendo $atributo";
        if (array_key_exists($atributo, $this->attr)) {
            return $this->attr[$atributo];
        }
        trigger_error("Propriedade $atributo não existe");
        return null;
    }

    ##################################
    # CONSTRUTOR
    ##################################
    public function __construct($objeto, $params) {
        # inclui array de configuracoes da classe
        global ${'arrinforz2' . $objeto};
        $arrInfo = ${'arrinforz2' . $objeto};
        $this->tabelaNome = $arrInfo[INFOTABELA]['tabelanome'];
        $this->tabelaId = $arrInfo[INFOTABELA]['tabelaid'];
        $this->arrCampos = $arrInfo[INFOCAMPOS];

        # seta atributos
        $verArray = (is_array($params)) ? true : false;
        foreach ($this->arrCampos as $campo => $variavel) {
            if ($verArray && isset($params[$variavel])) {
                $this->{$variavel} = $params[$variavel];
            } else {
                $this->{$variavel} = "";
            }
        }
    }

    ##################################
    # CARGA DE DADOS
    ##################################
    public function carga($params) {
        # seta atributos
        $verArray = (is_array($params)) ? true : false;
        foreach ($this->arrCampos as $campo => $variavel) {
            if ($verArray && isset($params[$variavel])) {
                $this->{$variavel} = $params[$variavel];
            }
        }
    }

    ##################################
    # CARREGAR (select)
    ##################################
    public function carregar() {
        global $db;
        //echoArray($this); exit;
        $sql = "SELECT *
                FROM   " . $this->tabelaNome . "
                WHERE  " . $this->tabelaId . " = " . $this->{$this->arrCampos[$this->tabelaId]};
        // exit($sql);
        $rs = executaSql($sql);
        if ($rg = $rs->fetchRow()) {
            foreach ($this->arrCampos as $campo => $variavel) {
                $this->{$variavel} = $rg[$campo];
            }
        } else {
            return false;
        }
        return true;
    }

    ##################################
    # INSERIR (insert)
    ##################################
    public function inserir() {
        global $db;
        $sql = "INSERT INTO " . $this->tabelaNome . " ";
        $campos = "";
        $valores = "";
        foreach ($this->arrCampos as $campo => $variavel) {
            $campos .= $campo . ", ";
            switch ($campo) {
                case $this->tabelaId:
                    $valores .= "'', ";
                    break;
                case 'dt_cadastro':
                    $valores .= "'" . DATAHORAMYSQL . "', ";
                    break;
                default:
                    $valores .= "'" . $this->{$variavel} . "', ";
            }
        }
        $sql .= "(" . substr(trim($campos), 0, -1) . ") ";
        $sql .= "VALUES (" . substr(trim($valores), 0, -1) . ")";
        //exit($sql);
        $rs = executaSql($sql);
        // atualiza campo id
        $this->atualizaId();
        return true;
    }

    ##################################
    # ALTERAR (update)
    ##################################
    public function alterar() {
        global $db;
        $sql = "UPDATE " . $this->tabelaNome . " ";
        $sql .= "SET ";
        $set = "";
        foreach ($this->arrCampos as $campo => $variavel) {
            switch ($campo) {
                case $this->tabelaId:
                    $set .= "";
                    break;
                default:
                    $set .= $campo . "='" . $this->{$variavel} . "', ";
            }
        }
        $sql .= substr(trim($set), 0, -1) . " ";
        $sql .= "WHERE  " . $this->tabelaId . " = " . $this->{$this->arrCampos[$this->tabelaId]};
        // exit($sql);
        $rs = executaSql($sql);
        return true;
    }

    ##################################
    # EXCLUIR (delete)
    ##################################
    public function excluir() {
        global $db;
        $sql = "DELETE FROM   " . $this->tabelaNome . " WHERE  " . $this->tabelaId . " = " . $this->{$this->arrCampos[$this->tabelaId]};
        //exit($sql);
        $rs = executaSql($sql);
        return true;
    }

    ##################################
    # LISTAR (select)
    ##################################
    public static function listar($objeto, $filtro = "") {
        global $db;
        # inclui array de configuracoes da classe
        global ${'arrinforz2' . strtolower($objeto)};
        $arrInfo = ${'arrinforz2' . strtolower($objeto)};
        $tabelaNome = $arrInfo[INFOTABELA]['tabelanome'];
        $tabelaId = $arrInfo[INFOTABELA]['tabelaid'];
        $sql = "SELECT * FROM   " . $tabelaNome . " " . $filtro;
        //exit($sql);
        //echo $sql;
        $rs = executaSql($sql);
        $arrLista = array();
        while ($rg = $rs->fetchRow()) {
            foreach ($rg as $campo => $valor) {
                $arrLista[$rg[$tabelaId]][$campo] = $valor;
            }
        }
        return (count($arrLista) > 0) ? $arrLista : false;
    }

    ##################################
    # LIMPAR (delete)
    ##################################
    public static function limpar($objeto, $filtro = "") {
        global $db;
        # inclui array de configuracoes da classe
        global ${'arrinforz2' . strtolower($objeto)};
        $arrInfo = ${'arrinforz2' . strtolower($objeto)};
        $tabelaNome = $arrInfo[INFOTABELA]['tabelanome'];
        $tabelaId = $arrInfo[INFOTABELA]['tabelaid'];
        $sql = "DELETE FROM   " . $tabelaNome . " " . $filtro;
        //exit($sql);
        $rs = executaSql($sql);
        return true;
    }

    ##################################
    # ATUALIZA ID DO OBJETO
    ##################################
    public function atualizaId() {
        global $db;
        $sql = "SELECT MAX(" . $this->tabelaId . ") ultimo FROM " . $this->tabelaNome;
        $rs = executaSql($sql);
        $rg = $rs->fetchRow();
        $this->{$this->arrCampos[$this->tabelaId]} = $rg['ultimo'];
        //return $rg['ultimo'];
    }

    ##################################
    # TRATA NOME PARA URL
    ##################################
    public static function trataNomeUrl($nome) {
        // aplica trim
        $novoNome = trim($nome);
        // retira acentos
        $search = array('ç', 'á', 'é', 'í', 'ó', 'ú', 'ã', 'õ', 'â', 'ê', 'î', 'ô', 'û', 'ö', 'ü', 'à', 'è', 'ì', 'ò', 'ù',
            'Ç', 'Á', 'É', 'Í', 'Ó', 'Ú', 'Ã', 'Õ', 'Â', 'Ê', 'Î', 'Ô', 'Û', 'Ö', 'Ü', 'À', 'È', 'Ì', 'Ò', 'Ù',
            ' ', '?', '&', '(', ')', '{', '}', '[', ']', '/', '.', '?', '=', '#', '~');
        $replace = array('c', 'a', 'e', 'i', 'o', 'u', 'a', 'o', 'a', 'e', 'i', 'o', 'u', 'o', 'u', 'a', 'e', 'i', 'o', 'u',
            'C', 'A', 'E', 'I', 'O', 'U', 'A', 'O', 'A', 'E', 'I', 'O', 'U', 'O', 'U', 'A', 'E', 'I', 'O', 'U',
            '-', '-', '-', '', '', '', '', '', '', '', '', '', '', '', '');
        $novoNome = str_replace($search, $replace, $novoNome);
        //echo '1) '.$novoNome.'<br />';
        // retira hifens duplos / triplos / quadruplos
        $novoNome = str_replace("----", "-", $novoNome);
        $novoNome = str_replace("---", "-", $novoNome);
        $novoNome = str_replace("--", "-", $novoNome);
        //echo '2) '.$novoNome.'<br />';
        return $novoNome;
    }

    ##################################
    # PEGA EXTENSAO DO ARQUIVO
    ##################################
    public static function getExtensao($nomeArquivo) {
        $arr = explode(".", $nomeArquivo);
        $extensao = end($arr);
        return $extensao;
    }

    ##################################
    # DEBUG
    ##################################
    public function debug() {
        echoArray($this);
    }
    
    ##################################
    # PEGA NOME DA PAGINA
    ##################################
    public static function getNomePagina() {
        $arrPhpSelf = explode('/', $_SERVER['PHP_SELF']);
        $scriptName = trim(strtolower(end($arrPhpSelf)));
        $auxName = explode('.', $scriptName);
        $nomeDaPagina = $auxName[0];
        return $nomeDaPagina;
    }

}

?>