<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '512M');
date_default_timezone_set('Europe/Madrid');

header('Content-Type: application/json');
if(isset($_REQUEST["json"])) 
	$json=json_decode($_REQUEST["json"], true); 
else{
	echo json_encode(["result"=>-10, "text"=>"Faltan parametros en la llamada a Navision"]);
	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 ){
	 echo json_encode(["result"=>-11 , "text"=>"No se pudo conectar con Navision"]);
	 die;
}
	$sql = "SELECT * FROM dbo.[Item Cross Reference] WHERE [Cross-Reference No.] = '".$json["barcode"]."'";
	$params = array();
	$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
	$stmt = sqlsrv_query( $connNavision, $sql, $params, $options);
	if($stmt===FALSE) {echo json_encode(["result"=>-1, "text"=>"El código de barras ya existe en Navision"]); die;}
	if(sqlsrv_num_rows($stmt)>0) {echo json_encode(["result"=>-1, "text"=>"El código de barras ya existe en Navision"]); die;}
	$sql = "INSERT INTO dbo.[Item Cross Reference] (
														[Item No.],
														[Variant Code],
														[Unit of Measure],
														[Cross-Reference Type],
														[Cross-Reference Type No.],
														[Cross-Reference No.],
														[Description],
														[Discontinue Bar Code],
														[Compra precio neto],
														[Descripcion articulo],
														[Familia articulo],
														[Subfamilia articulo],
														[Marca articulo],
														[Codigo de barras],
														[Descripcion larga],
														[Our reference no.],
														[Cod Barras INAER],
														[idaxiom]			
													) VALUES (
														'".$json["product_code"]."',
														' ',
														'UD',
														3,
														'".(isset($json["supplier_code"])?$json["supplier_code"]:'')."',
														'".$json["barcode"]."',
														' ',
														0,
														0,
														' ',
														' ',
														' ',
														' ',
														' ',
														' ',
														0,
														0,
														'".$json["axiom_id"]."'
													);";
	$stmt = sqlsrv_query( $connNavision, $sql );
	if(sqlsrv_errors(SQLSRV_ERR_ERRORS)===NULL) echo json_encode(["result"=>1]); else echo json_encode(["result"=>-12, "text"=>"Ocurrio un error en la consulta SQL de Navision"]);
?>
