<?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 [No.] FROM dbo.[Item] WHERE [No.] ='".$json["code"]."';";
	$stmt = sqlsrv_query( $connNavision, $sql );

	if(sqlsrv_num_rows($stmt)==0){
		$dateupd=new DateTime($json["dateupd"]["date"]);
		$sql = "INSERT INTO dbo.[Item] (
						[No.],
						[No. 2],
						[Description],
						[Search Description],
						[Description 2],
						[Base Unit of Measure],
						[Price Unit Conversion],
						[Inventory Posting Group],
						[Shelf_Bin No.],
						[Item Disc. Group],
						[Allow Invoice Disc.],  
						[Statistics Group],  
						[Commission Group],  
						[Unit Price],  
						[Price_Profit Calculation],  
						[Profit %],  
						[Costing Method],  
						[Unit Cost],  
						[Standard Cost],  
						[Last Direct Cost],  
						[Indirect Cost %],  
						[Cost is Adjusted],  
						[Allow Online Adjustment],  
						[Vendor No.],  
						[Vendor Item No.],  
						[Lead Time Calculation],  
						[Reorder Point],  
						[Maximum Inventory],  
						[Reorder Quantity],  
						[Alternative Item No.],  
						[Unit List Price],  
						[Duty Due %],  
						[Duty Code],  
						[Gross Weight],  
						[Net Weight],  
						[Units per Parcel],  
						[Unit Volume],  
						[Durability],  
						[Freight Type],  
						[Tariff No.],  
						[Duty Unit Conversion],  
						[Country_Region Purchased Code],  
						[Budget Quantity],  
						[Budgeted Amount],  
						[Budget Profit],  
						[Blocked],  
						[Last Date Modified],  
						[Price Includes VAT],  
						[VAT Bus. Posting Gr. (Price)],  
						[Gen. Prod. Posting Group],  
						[Picture],  
						[Country_Region of Origin Code],  
						[Automatic Ext. Texts],  
						[No. Series],  
						[Tax Group Code],  
						[VAT Prod. Posting Group],  
						[Reserve],  
						[Global Dimension 1 Code],  
						[Global Dimension 2 Code],  
						[Low-Level Code],  
						[Lot Size],  
						[Serial Nos.],  
						[Last Unit Cost Calc. Date],  
						[Rolled-up Material Cost],  
						[Rolled-up Capacity Cost],  
						[Scrap %],  
						[Inventory Value Zero],  
						[Discrete Order Quantity],  
						[Minimum Order Quantity],  
						[Maximum Order Quantity],  
						[Safety Stock Quantity],  
						[Order Multiple],  
						[Safety Lead Time],  
						[Flushing Method],  
						[Replenishment System],  
						[Rounding Precision],  
						[Sales Unit of Measure],  
						[Purch. Unit of Measure],  
						[Reorder Cycle],  
						[Reordering Policy],  
						[Include Inventory],  
						[Manufacturing Policy],  
						[Manufacturer Code],  
						[Item Category Code],  
						[Created From Nonstock Item],  
						[Product Group Code],  
						[Service Item Group],  
						[Item Tracking Code],  
						[Lot Nos.],  
						[Expiration Calculation],  
						[Special Equipment Code],
						[Put-away Template Code],
						[Put-away Unit of Measure Code],
						[Phys Invt Counting Period Code],
						[Last Counting Period Update],
						[Next Counting Period],
						[Use Cross-Docking],
						[Cost Regulation %],
						[Control margen beneficio],
						[Coste inicial sistema anterior],
						[% incremento tarifa],
						[Obliga Factura],
						[Equivalente],
						[Cod. Corporativo],
						[Cod. Marca],
						[Coste de Tarifa Compra],
						[% Descuento de compra],
						[Caducidad],
						[Unidad de embalaje de compra],
						[Unidad de embalaje de venta],
						[Cantidad mínima a vender],
						[Canon RAE],
						[Canon Medioambiental],
						[Discontinuado],
						[Cantidad a incluir],
						[Cod. Estado],
						[Unidad medida precio],
						[Precio venta UM precio],
						[Transitorio],
						[Proveedor Tarifa-Dto Compra],
						[Precio Neto Compra UM Precio],
						[Last Direct Cost UM Precio],
						[Articulo en incidencia],
						[Grupo Dto. Art. Compra],
						[Fecha historico],
						[Descripcion larga],
						[Pos Sale Restriction],
						[Generico],
						[Routing No.],
						[Production BOM No.],
						[Single-Level Material Cost],
						[Single-Level Capacity Cost],
						[Single-Level Subcontrd. Cost],
						[Single-Level Cap. Ovhd Cost],
						[Single-Level Mfg. Ovhd Cost],
						[Overhead Rate],
						[Rolled-up Subcontracted Cost],
						[Rolled-up Mfg. Ovhd Cost],
						[Rolled-up Cap. Overhead Cost],
						[Order Tracking Policy],
						[Critical],
						[Common Item No.],
						[Tipo producto],
						[Exclude inventory],
						[Classification code],
						[Net Profit %],
						[Exclude from req. filter],
						[Classification excluded],
						[Reorder order quantity],
						[Margen Compra Venta],
						[Margen Compra Venta Descuentos],
						[Aviso Txt Adicional],
						[Unit packaging control],
						[Solo en Ofertas],
						[Omitir Control Margen],
						[ProductoWEB],
						[ImagenWEB],
						[FamiliaWEB],
						[DescripcionWEB],
						[DescripcionCortaWEB],
						[MetadatosWEB],
						[MetadatosDescripcionWEB],
						[Descripcion2WEB],
						[TipoAgrupWEB],
						[precioDestacadoWEB],
						[NovedadWEB],
						[OutlerWEB],
						[DestacadoWEB],
						[PrecioWEB],
						[IncidenciaWEB],
						[AgrupacionWEB],
						[NoRotacion],
						[RevisarWEB],
						[EtiquetaAtribWEB],
						[DescripcionAtribWEB],
						[CantidadEnDecimalesWEB],
						[CantidadPedidoWEB],
						[ArticuloVoluminosoWEB],
						[ProductoWebINAER],
						[PermitirProductoSinCargo],
						[ActualizarWEB],
						[EnvaseCompletoWEB],
						[ProductoNuevo2017],
						[RevisarTarifaVentas],
						[NoControlStockNegativo]
						
					
					)VALUES(
						'".$json["code"]."',
						'',
						'".substr($json["name"],0,30)."',
						'".strtoupper (substr($json["name"],0,30))."',
						'".substr($json["name"],30,30)."',
						'UD',
						0,
						'EXISTENCIA',
						'',
						'',
						1,
						0,
						0,
						".($json["pvp"]?$json["pvp"]:0).",
						2,
						0,
						3,
						".($json["shoppingPrice"]?$json["shoppingPrice"]:0).",
						0,
						".($json["shoppingPrice"]?$json["shoppingPrice"]:0).",
						0,
						1,
						1,
						'".$json["vendor"]."',
						'".$json["vendoritem"]."',  
						'',  
						0,  
						0,  
						0,  
						'',  
						0,  
						0,  
						'',  
						0,  
						0,  
						0,  
						0,  
						'',  
						'',  
						'',  
						0,  
						'',  
						0,  
						0,  
						'0',  
						'0',  
						'".$dateupd->format("Y-m-d").'T00:00:00.000'."',  
						'0',  
						'',  
						'MERCADERIA',  
						null,  
						'',  
						0,  
						'',  
						'',  
						'IVA21',  
						'1',  
						'',  
						'',  
						0,  
						0,  
						'',  
						'1753-01-01T00:00:00.000',  
						0,  
						0,  
						0,  
						0,  
						0,  
						0,  
						0,  
						0,  
						0,  
						'',  
						0,  
						0,  
						1,  
						'UD',  
						'UD',  
						'10',  
						1,  
						1,  
						0,  
						'',  
						'',  
						0,  
						'',  
						'',  
						'',  
						'',  
						'',  
						'',
						'',
						'',
						'',
						'1753-01-01T00:00:00.000',
						'',
						1,
						0,
						0,
						".($json["shoppingPrice"]?$json["shoppingPrice"]:0).",
						0,
						0,
						'',
						'',
						'".$json["manufacturer"]."',
						".($json["shoppingPrice"]?$json["shoppingPrice"]:0).",
						0,
						0,
						1,
						1,
						0,
						0,
						0,
						0,
						0,
						'',
						'UD',
						".($json["pvp"]?$json["pvp"]:0).",
						0,
						'".$json["vendoritem"]."',
						".($json["shoppingPrice"]?$json["shoppingPrice"]:0).",
						".($json["shoppingPrice"]?$json["shoppingPrice"]:0).",
						0,
						'',
						'1753-01-01T00:00:00.000',
						'".substr($json["name"],0,30)."',
						0,
						0,
						'',
						'',
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						'',
						0,
						0,
						'',
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						".($json["checkweb"]?1:0).",
						'',
						'',
						'',
						'',
						'',
						'',
						'',
						'',
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						'',
						'',
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						0					
					
					)";
		
		$stmt = sqlsrv_query( $connNavision, $sql );
		if(sqlsrv_errors(SQLSRV_ERR_ERRORS)===NULL) echo json_encode(["code"=>$json["code"], "result"=>1]); else{
			echo json_encode(["code"=>$json["code"], "result"=>-12, "text"=>"Ocurrio un error en la consulta SQL de Navision"]);
			/*echo json_encode($json);
			    if( ($errors = sqlsrv_errors() ) != null) {
					foreach( $errors as $error ) {
						echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
						echo "code: ".$error[ 'code']."<br />";
						echo "message: ".$error[ 'message']."<br />";
					}
				}*/
		}
		//echo $sql;
		$sql = "INSERT INTO dbo.[Item Unit of Measure] (
					[Item No.],
					[Code],
					[Qty. per Unit of Measure],
					[Length],
					[Width],
					[Height],
					[Cubage],
					[Weight]		
		)VALUES(
					'".$json["code"]."',
					'UD',
					1,
					0,
					0,
					0,
					0,
					0
		)";
		$stmt = sqlsrv_query( $connNavision, $sql );
		if(sqlsrv_errors(SQLSRV_ERR_ERRORS)===NULL) echo json_encode(["code"=>$json["code"], "result"=>1]); else {
			echo json_encode(["code"=>$json["code"], "result"=>-12, "text"=>"Ocurrio un error en la consulta SQL de Navision"]);
			/*echo json_encode($json);
			    if( ($errors = sqlsrv_errors() ) != null) {
					foreach( $errors as $error ) {
						echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
						echo "code: ".$error[ 'code']."<br />";
						echo "message: ".$error[ 'message']."<br />";
					}
				}*/
		}
		die();
	}
	echo json_encode(["code"=>$json["code"], "result"=>-1]); 
	//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"]);
?>
