 <?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['suc_id'] = $_GET['suc_id'];

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

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

//$sql= "select  m.puesto, count(o.po_id) as po_id, m.op_id as op_id_puesto from ".$_GET['database'].".mesaspuesto m left outer join ".$_GET['database'].".tmp_producto_op o on m.sala = o.sala and m.mesa = o.mesa and m.puesto = o.ubicacion and m.suc_id = o.suc_id where m.suc_id = "
//                                        .$_SESSION['suc_id']." and m.mesa = ".$_SESSION['mesa']." and m.sala = ".$_SESSION['sala']." group by m.puesto";

$sql = "select
      m.puesto,
	  po_op_id as op_id,
	  m.op_id as op_id_puesto,
      co.op_id_cliente,
	  c.id_contribuyente
	  from " . $_GET['database'] . ".mesaspuesto m
      left outer join " . $_GET['database'] . ".tmp_producto_op o on m.sala = o.sala and
																   m.op_id = o.po_op_id and
																   m.mesa = o.mesa and
																   m.puesto = o.ubicacion and
																   m.suc_id = o.suc_id
	  left outer join " . $_GET['database'] . ".tmp_operacion co on o.po_op_id = co.op_id
	  left outer join " . $_GET['database'] . ".clientes c on co.op_id_cliente = c.c_id
	  where m.suc_id = " . $_SESSION['suc_id'] .
    " and m.mesa = " . $_SESSION['mesa'] . " and m.sala = " . $_SESSION['sala'] . " group by m.puesto, op_id";

//echo "aqui".$sql;

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

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

    $json->datos = "false";

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

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

        $autoinc = $r['op_id'];

        if (intval($autoinc) > 0 && intval($r['op_id_puesto']) > 0) {
            if (intval($autoinc) != intval($r['op_id_puesto'])) {
                //$autoinc = null;
            }

        }
        if ($r['id_contribuyente'] == null) {
            $r['id_contribuyente'] = 1;
        }

        $jsonTempData = array();
        $jsonTempData['puesto'] = $r['puesto'];
        $jsonTempData['autoinc'] = $autoinc;
        $jsonTempData['op_id_puesto'] = $r['op_id_puesto'];
        $jsonTempData['id_contribuyente'] = $r['id_contribuyente'];
        $jsonData[] = $jsonTempData;
    }

}

$json->jsonpuestos = $jsonData;
print_r(json_encode($json));

@mysqli_close($connection);
?>