<?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;
}
	foreach($json as $code){
		$sql = "SELECT * FROM dbo.[Item Cross Reference] WHERE [Cross-Reference No.] = ''".$code["barcode"]."''";
		$stmt = sqlsrv_query( $connNavision, $sql );
		if(sqlsrv_num_rows==0){
			$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 (
															'".$code["product_code"]."',
															' ',
															'UD',
															3,
															' ',
															'".$code["barcode"]."',
															' ',
															0,
															0,
															' ',
															' ',
															' ',
															' ',
															' ',
															' ',
															0,
															0,
															'".$code["axiom_id"]."'
														);";
		$stmt = sqlsrv_query( $connNavision, $sql );
		
		}
	}
	echo json_encode(["result"=>1]); 
?>
