<?php
try {

    include dirname(__FILE__)."/../../concha.php";

} catch(Exception $e) {

    echo '{
        "mensaje": "Archivo de configuración no encontrado",
        "error": '. json_encode($e) .'
    }';

}

function sql_command($sql_command) {
    global $host, $basedatos, $usuario, $contra;
    try {
        $mbd = new PDO("mysql:host=$host;dbname=$basedatos", $usuario, $contra);
        $statement = $mbd->prepare($sql_command);
        $statement->execute();
        return $statement;

    } catch (PDOException $e) {
        return "¡Error!: " . $e->getMessage();
    }
}

function query($sql_query) {
    $statement = sql_command($sql_query);
    return $statement->fetchAll(PDO::FETCH_ASSOC);
}

function format_columns($columas_list) {
    $selector = '';
    foreach($columas_list as $columna=>$nombre)
    {
        if (!$nombre) {
            $nombre = $columna;
        }
        $selector .= ", $columna AS $nombre";
    }
    return substr($selector,2);
}

function build_query($columas_list, $tabla, $condition='') {
    $selector = format_columns($columas_list);
    if ($condition) {
        $condition .= "WHERE $condition";
    }
    return query("SELECT $selector from $tabla $condition;");
}

function insert($colum_value, $tabla) {
    global $host, $basedatos, $usuario, $contra;
    $colums = '';
    $values = '';
    foreach ($colum_value as $columna=>$valor) {
        $colums .= ", $columna";
        $valor = str_replace("'", "''", $valor);
        $values .= ", '$valor'";
    }
    $colums = substr($colums,2);
    $values = substr($values,2);
//    return ("INSERT INTO $tabla ($colums) VALUES ($values)");
    try {
        $mbd = new PDO("mysql:host=$host;dbname=$basedatos", $usuario, $contra);
        $statement = $mbd->prepare("INSERT INTO $tabla ($colums) VALUES ($values)");
        $statement->execute();
        return $statement->fetchAll(PDO::FETCH_ASSOC);

    } catch (PDOException $e) {
        return "¡Error!: " . $e->getMessage();
    }
}