<?php
include_once '../classes/pagina.php';
include_once '../classes/sessao.php';

class Script extends Pagina {

    public function __construct() {
        parent::checarPermissao(array('administrador'));
        parent::__construct();
    }
    
    public function corpo() {
        if(empty($_REQUEST[acao]) AND empty($_REQUEST[executarAcao])) echo "<div><a href='home.php' class='voltar'>Voltar para a tela inicial</a></div><br/>";
        $this->campoConsulta();
        if(!empty($_REQUEST[executar])) $this->executar();
    }
    
    public function campoConsulta() {
        echo "<form action='executaconsultasql.php' method='POST'>";
        echo "<input type='hidden' name='executar' value='sim' />";
        echo "<fieldset><legend>Consulta</legend>";
        echo "<textarea name='sql' cols='80' rows='5'>$_POST[sql]</textarea><br/>";
        echo "<div align='center'><input type='submit' value='Executar' /></div>";
        echo "</fieldset>";
        echo "</form>";
    }
    
    public function executar() {
        $bd = new BD();
        
        $sql = explode(';', $_POST[sql]);
        $sql = parent::acertarString($sql[0]);
        
        if(!empty($sql) AND stripos($sql, 'SELECT') === 0){
            echo "<p>inicio:  ".date('d/m/Y H:i:s')."</p>";
            
            $bd->executarSQL(str_replace('`', "'", $sql));
            $objs = $bd->getObjetos();
            $i = 0;
            $colunas = null;
            foreach($objs as $obj){
                $arrayobj = get_object_vars($obj);
                if($i == 0){
                    echo "<table class='tabelaDados'>";
                    echo "<tr>";
                    foreach($arrayobj as $coluna=>$valor){
                        $colunas[] = $coluna;
                        echo "<th>$coluna</th>";
                    }
                    echo "</tr>";
                }
                
                echo "<tr>";
                foreach($arrayobj as $coluna=>$valor){
                    echo "<td>$valor</td>";
                }
                echo "</tr>";
                
                $i++;
            }
            if(!empty($i)){
                echo "</table>";
                echo "<div>Total de registros: $i</div>";
            }
            
            echo "<p>fim:  ".date('d/m/Y H:i:s')."</p>";
        }else{
            echo "A consulta deve iniciar com SELECT.";
        }
        
        
    }
}

$pagina = new Script();
$pagina->montar();
