 <?php

if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400'); // cache for 1 day
}

error_reporting(E_ERROR | E_PARSE);

$_SESSION['database'] = $_GET['database'];
$_SESSION['sala'] = $_GET['sala'];
$_SESSION['mesa'] = $_GET['mesa'];
$_SESSION['puesto'] = $_GET['puesto'];
$_SESSION['suc_id'] = $_GET['suc_id'];
$_SESSION['no_estacion'] = $_GET['no_estacion'];
$op_id = "";

include 'conn.php';
include 'funciones.php';

$jsonData = array();
$jsonTempData = array();

$sqlval = "select null from " . $_GET['database'] . ".mesaspuesto
				 where suc_id = " . $_SESSION['suc_id'] . "
				 and sala =" . $_SESSION['sala'] . "
				 and mesa = " . $_SESSION['mesa'] . "
				 and puesto =" . $_SESSION['puesto'] . "";

$qur = $connection->query($sqlval);
$val = 0;
while ($r = mysqli_fetch_assoc($qur)) {

    $val = 1;
}

if ($val == 0) {

    $suc_est = $_SESSION['suc_id'] . $_SESSION['no_estacion'];
    $sqlOrden = "select LPAD(no_operacionespera,9,'0') as no_operacionespera from " . $_GET['database'] . ".conf_sistema  where suc_id = " . $_SESSION['suc_id'] . " and no_estacion =" . $_SESSION['no_estacion'] . "";
    $qur = $connection->query($sqlOrden);

    $estacionconfig = 0;
    while ($r = mysqli_fetch_assoc($qur)) {

        $estacionconfig = 1;
        $espera = $r['no_operacionespera'];
        $op_id = $suc_est . substr($espera, strlen($suc_est), 9);
    }

    if ($estacionconfig == 1) {
        $sql = "insert into " . $_GET['database'] . ".mesaspuesto (op_id,sala,mesa,puesto,suc_id) values ('" . $op_id . "', " . $_SESSION['sala'] . "," . $_SESSION['mesa'] . "," . $_SESSION['puesto'] . "," . $_SESSION['suc_id'] . ")";
        $qur = $connection->query($sql);

        $sqlOrden = "update  " . $_GET['database'] . ".conf_sistema set no_operacionespera = no_operacionespera + 1  where suc_id = " . $_SESSION['suc_id'] . " and no_estacion =" . $_SESSION['no_estacion'] . "";
        $qur = $connection->query($sqlOrden);
    } else {
        $op_id = "-1";
    }

}

$jsonTempData = array();
$jsonTempData['op_id'] = $op_id;
$jsonData[] = $jsonTempData;
$json->op_id = $jsonData;

if ($_SESSION['codigo'] == "99") {

    $json->datos = "false";

} else {
    $json->datos = "true";

}

print_r(json_encode($json));

@mysqli_close($connection);
?>