<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);
error_reporting(E_ALL & ~ E_NOTICE & ~ E_WARNING);

include_once ("utiles.php");

if (! $connection = connectDb()) {
    die("err db");
} else {
    mysqli_query($connection,"SET NAMES 'utf8';");
}

date_default_timezone_set("America/Panama");

session_start();
$_SESSION['database'] = $_POST['database'];
$_SESSION['sql'] = $_POST['sql'];
$_SESSION['key'] = $_POST['key'];
$_SESSION['all_rows'] = $_POST['all_rows'];
$_SESSION['fieldname'] = $_POST['fieldname'];

$CatNam = $_SESSION['database'];
$sqlcmd = $_SESSION['sql'];
$KeySeg = $_SESSION['key'];
$AllRws = $_SESSION['all_rows'];
$FieldN = $_SESSION['fieldname'];

/*
$CatNam = '699_bayshoreaptos';
$sqlcmd = 'SELECT 699_bayshoreaptos.Get_AllFields_ExeptV3("operacion_cxc","id_reg") AS StrLine';
$KeySeg = '1';
$AllRws = '0';
$FieldN = 'StrLine';
*/
$sqlcmd = str_replace("$$", "%", $sqlcmd);

mysqli_query($connection,'SET CHARACTER SET utf8');
mysqli_query($connection,'USE ' . $CatNam);

if (Valida_Sql_Cmds($sqlcmd) == 'true') {
    
    IF ($AllRws == '1') {
        $records = getRowAll($connection, $sqlcmd, $recount, true);
        if ($AllRws == '1') {
            echo $records;
        } else {
            if ($FieldN == '') {
                echo $records;
            } else {
                echo $records[$FieldN];
            }
        }
        ;
    } else {
        $records = getRow($connection, $sqlcmd,$recount);
        echo $records[0];
    }
    ;
    header('content-type: application/json');
}
;

function Valida_Sql_Cmds($cadena_de_texto)
{
    $cadena_de_texto = strtolower($cadena_de_texto);
    $pos1 = strpos($cadena_de_texto, 'create');
    $pos2 = strpos($cadena_de_texto, 'update');
    $pos3 = strpos($cadena_de_texto, 'truncate');
    $pos4 = strpos($cadena_de_texto, 'drop');
    $pos5 = strpos($cadena_de_texto, 'alter');
    $pos6 = strpos($cadena_de_texto, 'delete');
    $pos7 = strpos($cadena_de_texto, 'insert');
    
    $valor_devuelto = 'false';
    if ($pos1 === false && $pos2 === false && $pos3 === false && $pos4 === false && $pos5 === false && $pos6 === false && $pos7 === false) {
        $valor_devuelto = 'true';
        return $valor_devuelto;
    } else {
        echo ' No se puede ejecutar el sql';
        $valor_devuelto = 'false';
        return $valor_devuelto;
    }
    return $valor_devuelto;
}
;

@mysqli_close($connection);
?>
