<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '512M');
date_default_timezone_set('Europe/Madrid');
//include("conexion.php");
if(isset($_REQUEST["store"])) 
	$store=$_REQUEST["store"]; 
else $store=0;
if(isset($_REQUEST["date"])) 
	$date=$_REQUEST["date"]; 
else $date=0;
if(isset($_REQUEST["product"])) 
	$product=$_REQUEST["product"]; 
else $product=0;
$quantitys=[];

function mssql_escape($str)
{
    if(get_magic_quotes_gpc())
    {
        $str= stripslashes($str);
    }
    return str_replace("'", "''", $str);
}

$serverName = "localhost";
$connectionInfo = array( "Database"=>"ICF", "UID"=>"VAIO", "PWD"=>"VAIO");

$connNavision=false;
$retries=0;
while(!$connNavision && $retries<3){
	$connNavision = sqlsrv_connect( $serverName, $connectionInfo);
	$retries++;
}

	if( $connNavision ) {
		 //echo "Conexion establecida con Navision.\r\n";
	}else{
		 //echo "Conexion no se pudo establecer con Navision.\r\n";
		 die( print_r( sqlsrv_errors(), true));
	}
	
	if ($store=='ALI') $store='GESTOR ALI';

	if ($product!=0) $sql='SELECT 
	itl.[Quantity] stock, 
	itl.[Location Code] almacen,
	itl.[Item No.] code,
	itl.[Variant Code] variant
	FROM dbo.[Item Ledger Entry] itl
	WHERE (itl.[Location Code]=\''.$store.'\')
	AND itl.[Posting Date]>=CAST(\''.$date.'\' AS DATETIME)
	AND itl.[Entry Type]=4
	AND itl.[Item No.]=\''.$product.'\'';
	
	else $sql='SELECT 
	itl.[Quantity] stock, 
	itl.[Location Code] almacen,
	itl.[Item No.] code,
	itl.[Variant Code] variant
	FROM dbo.[Item Ledger Entry] itl
	WHERE (itl.[Location Code]=\''.$store.'\')
	AND itl.[Posting Date]>=CAST(\''.$date.'\' AS DATETIME)
	AND itl.[Entry Type]=4
	AND itl.[item No.]!=\'02TR31210BABCOCK\'';
	
	$stmt = sqlsrv_query( $connNavision, $sql );
		if( $stmt !== false) {
			while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
				$temp=[];
				foreach($row as $key=>$object){
					$temp_object[$key]=!is_object($object)?utf8_encode($object):$object;		
					
				}
				$quantitys[]=$temp_object;
			}
		}

	$prueba["class"]=$quantitys;
	$result[]=$prueba;
echo json_encode($result, JSON_PRETTY_PRINT);
?>

