<?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["from"])) 
	$from=$_REQUEST["from"]; 
else $from=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));
	}

	$maxEntry=0;
	$sql = 'SELECT MAX(itl.[Document No.]) maxEntry FROM dbo.[Item Ledger Entry] itl';
		$stmt = sqlsrv_query( $connNavision, $sql );
		if( $stmt !== false) {
			if($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
				$maxEntry=$row['maxEntry'];
			}
		}

	$sql='SELECT 
	tr.[Entry No.], 
	tr.[Document No.], 
	tr.[Item No.], 
	tr.[Location Code], 
	tr.[Quantity], 
	trd.[Transfer-to Code] destino
	FROM dbo.[Item Ledger Entry] AS tr, dbo.[Ind. Campollano Ferreterķa S.L$Transfer Shipment Header] AS trd
	WHERE tr.[Entry Type]=4 
	AND tr.[Document No.] LIKE \'%TRE%\'  
	AND tr.[Location Code]!=\'TRANSITO\' 
	AND (tr.[Location Code]=\'ALM01\' OR tr.[Location Code]=\'ALM02\' OR tr.[Location Code]=\'EXPEND ALM\')
	AND (trd.[Transfer-to Code]=\'INAEGESALB\' OR trd.[Transfer-to Code]=\'SALAMGESTO\' OR trd.[Transfer-to Code]=\'GESTOR ALI\'  
			OR trd.[Transfer-to Code]=\'EXPEALICAN\' OR trd.[Transfer-to Code]=\'LISBOAEXPE\' OR trd.[Transfer-to Code]=\'SALAMAEXPE\') 
	AND trd.[No.]=tr.[Document No.]
	AND  tr.[Transfer Order No.]>\''.$from.'\'
	ORDER BY tr.[Entry No.] Desc';
	
	//	AND  and tr.[Document No.]>\'21TRE02609\'\''.$from.'\'

	//echo($sql);
	$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["maxEntry"]=$maxEntry;
	$prueba["class"]=$quantitys;
	$result[]=$prueba;
echo json_encode($result, JSON_PRETTY_PRINT);
?>

