<?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["product"])) //Formato linux timestamp
	$product=$_REQUEST["product"]; else $product=0;
if(isset($_REQUEST["supplier"])) //Formato linux timestamp
	$supplier=$_REQUEST["supplier"]; else $supplier=0;
//$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", "ConnectionPooling" => "1", "MultipleActiveResultSets"=>'1');

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

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

		//GET MAX TIMESTAMP
		$maxtimestamp=0;
		$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'];
			}
		}	

	$sql='SELECT i.[Precio Neto Compra UM Precio] AS price, 
				d.[Sales Code] AS GroupCustomer, 
				d.[Line Discount %] AS discount, 
				(case when i.[Unidad medida precio]=\'C\' then i.[Unit Price]*100  when i.[Unidad medida precio]=\'M\' then i.[Unit Price]*1000 else i.[Unit Price] end) as pvpr, 
				i.[Precio venta UM Precio] as pvp, 
				i.[Vendor No.] as vendor FROM dbo.[Item] i
			LEFT JOIN [Ind. Campollano Ferreterķa S.L$Sales Line Discount] d ON d.[Code]=i.[Item Disc. Group]
			WHERE i.[No.]=\''.$product.'\' and i.[Blocked]=0 and i.[Discontinuado]=0 and i.[Vendor No.]=\''.$supplier.'\'';
			
	$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;		
			}
			$objects[]=$temp_object;
		}
	}
	$prueba["maxtimestamp"]=$maxtimestamp;
	$prueba["class"]=$objects;
	$result[]=$prueba;
echo json_encode($result, JSON_PRETTY_PRINT);
?>