 <?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['operacion'] = $_GET['operacion'];
$_SESSION['valor'] = $_GET['valor'];
$_SESSION['sala'] = $_GET['sala'];
$_SESSION['estacion'] = $_GET['estacion'];
$_SESSION['cant'] = $_GET['cant'];
$_SESSION['suc_id'] = $_GET['suc_id'];
$_SESSION['op_tipo'] = $_GET['op_tipo'];

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

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

//CONSULTAR

$valoroperacion = $_SESSION['valor'];

switch ($_SESSION['operacion']) {
    case 0:
        $operacion = "op_id like '%" . $valoroperacion . "%'";
        break;
    case 1:
        $operacion = "op_fecha >= '" . $valoroperacion . "'";
        break;
    case 2:
        $operacion = "op_nombre like '%" . $valoroperacion . "%'";
        break;
    case 3:
        $operacion = "mesa = " . $valoroperacion;
        break;
    case 4:
        $operacion = "op_total = " . $valoroperacion;
        break;

}

$sql = "select distinct(op_id) op_id, op_num_nco, op_num_ncf, op_fecha, op_total,op_nombre, mesa,ubicacion ,nombre_tipo " .
    "from " . $_GET['database'] . ".operacion o" .
    " left outer join " . $_GET['database'] . ".producto_op p on o.op_id = p.po_op_id " .
    " left outer join " . $_GET['database'] . ".tipo_op t on o.op_tipo = t.id_tipo " .
    " where " . $operacion . " and " .
    " p.suc_id = " . $_SESSION['suc_id'] . " and " .
    " p.e_id = " . $_SESSION['estacion'] . " and op_tipo = " .
    $_SESSION['op_tipo'] . " order by op_fecha desc limit " .
    $_SESSION['cant'];

//print_r($sql);

$qur = $connection->query($sql);

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

    $json->datos = "false";

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

    while ($r = mysqli_fetch_assoc($qur)) {

        $jsonTempData = array();
        $jsonTempData['operacion'] = $r['op_id'];
        $jsonTempData['fecha'] = $r['op_fecha'];
        $jsonTempData['total'] = number_format($r['op_total'], 2);
        $jsonTempData['cliente'] = utf8_encode($r['op_nombre']);
        $jsonTempData['mesa'] = $r['mesa'];
        $jsonTempData['puesto'] = $r['ubicacion'];
        $jsonTempData['op_num_nco'] = $r['op_num_nco'];
        $jsonTempData['op_num_ncf'] = $r['op_num_ncf'];
        $jsonTempData['nombre_tipo'] = substr(utf8_encode($r['nombre_tipo']), 0, 11);
        $jsonTempData['po_op_id'] = $r['op_id'];
        $jsonData[] = $jsonTempData;

    }
    $json->jsonordenes = $jsonData;
}

//print_r(json_encode($sql));

print_r(json_encode($json));

@mysqli_close($connection);
?>