<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
date_default_timezone_set('Europe/Madrid');
$product='';
$variant='';
$supplier=null;
if(isset($_REQUEST["product"])){
	$product=$_REQUEST["product"];
}else{
	 echo json_encode(["result"=>-2 , "text"=>"Se debe proporcionar un codigo de producto"]);
	 die;
}
if(isset($_REQUEST["variant"]) && $_REQUEST["variant"]!=''){
	$variant=$_REQUEST["variant"];
}
if(isset($_REQUEST["supplier"]) && $_REQUEST["supplier"]!=''){
	$supplier=$_REQUEST["supplier"];
}

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



// Conexión con Navision
$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 json_encode(["result"=>-1 , "text"=>"No se pudo conectar con Navision"]);
	  die;
}

// Fecha último registro
$purchaseorder='';
$supplierorder='';
$sql = 'SELECT [Document No.] purchaseorder, [Buy-from Vendor No.] supplier FROM dbo.[Ind. Campollano Ferretería S.L$Purchase Line] WHERE [No.]=\''.$product.'\' AND [Variant Code]=\''.$variant.'\'';
$sql.=($supplier?' AND [Buy-from Vendor No.]=\''.$supplier.'\'':''); 
$sql.=' ORDER BY [Order Date] DESC';
$stmt = sqlsrv_query( $connNavision, $sql );
if( $stmt !== false) {
	if($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
		$purchaseorder=$row['purchaseorder'];
		$supplierorder=$row['supplier'];
	}
}
$results =[];
if($purchaseorder!=''){
	$results['result'] = 1;
	$results['purchaseorder'] = $purchaseorder;
	$results['supplierorder'] = $supplierorder;
}else{
	$results['result'] = -3;
	$results['text'] = "No se ha podido encontrar el pedido de compra";
}
header('Content-Type: application/json');
echo json_encode($results, JSON_UNESCAPED_UNICODE);
?>
