<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '512M');
date_default_timezone_set('Europe/Madrid');
//include("conexion.php");
header('Content-Type: application/json; charset=utf-8');
if(isset($_REQUEST["code"])) 
	$code=$_REQUEST["code"]; 
else{
	echo json_encode(["result"=>-1 , "text"=>"Se debe proporcionar un codigo de producto"]);
	die;
}

if(isset($_REQUEST["supplier"])) 
	$supplier=$_REQUEST["supplier"]; 
else{
	echo json_encode(["result"=>-2 , "text"=>"Se debe proporcionar un codigo de proveedor"]);
	die;
}

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 ) {

}else{
	 echo json_encode(["result"=>-11 , "text"=>"No se pudo conectar con Navision"]);
	 die;
}
$sql='SELECT TOP 1 [Cross-Reference No.] FROM [Item Cross Reference] 
	  WHERE [Cross-Reference Type]=2 and [Item No.]=\''.$code.'\' and [Cross-Reference Type No.]=\''.$supplier.'\'';

$stmt = sqlsrv_query( $connNavision, $sql );
if(sqlsrv_errors(SQLSRV_ERR_ERRORS)!==NULL) {
	echo json_encode(["result"=>-3, "text"=>"1 Ocurrio un error en la consulta SQL de Navision"]);
	die;
}
if( $stmt !== false) {
	if($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
		$reference=utf8_encode($row["Cross-Reference No."]);
		echo json_encode(["result"=>1, "data"=>["reference"=>$reference]]);
		die;
	}else{
		echo json_encode(["result"=>-4, "text"=>"El producto no tiene referencia cruzada con el proveedor"]);
		die;
	}
}
echo json_encode(["result"=>-5, "text"=>"Error al ejecutar la consulta"]);
die;

?>

