<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//ini_set('memory_limit', '2048M');
date_default_timezone_set('Europe/Madrid');
//include("conexion.php");
if(isset($_REQUEST["name"])) //Formato linux timestamp
	$name=$_REQUEST["name"]; else $name='';
//$from=date('d/m/Y', $from);

$resultProducts=[];

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));
	}

		$objects=[];
		$prueba=[];
		
		//GET MAX TIMESTAMP
		$maxtimestamp=0;
		
		
		if ($name=='products'){
		$sql = 'SELECT CAST(MAX(TIMESTAMP) AS BIGINT) timestamp FROM [Item]';
		$stmt = sqlsrv_query( $connNavision, $sql );
		if( $stmt !== false) {
			if($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
				$maxtimestamp=$row['timestamp'];
			}
		}
		}
		
		else if ($name=='References'){
		$sql = 'SELECT CAST(MAX(TIMESTAMP) AS BIGINT) timestamp FROM [Item Cross Reference] where "Cross-Reference Type"!=3';
		$stmt = sqlsrv_query( $connNavision, $sql );
		if( $stmt !== false) {
			if($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
				$maxtimestamp=$row['timestamp'];
			}
		}
		}
		
		else if ($name=='EAN13'){
		$sql = 'SELECT CAST(MAX(TIMESTAMP) AS BIGINT) timestamp FROM [Item Cross Reference] where "Cross-Reference Type"=3';
		$stmt = sqlsrv_query( $connNavision, $sql );
		if( $stmt !== false) {
			if($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
				$maxtimestamp=$row['timestamp'];
			}
		}
		}
		
		
		//var_dump($objects);
		$prueba["maxtimestamp"]=$maxtimestamp;
		$result[]=$prueba;
header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT);

?>
