<?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');


function utf8_converter($array)
{
    array_walk_recursive($array, function(&$item, $key){
        if(mb_detect_encoding($item, 'utf-8', true)){
                $item = utf8_decode($item);
				$item = str_replace("'", "''", $item );
				$item = str_replace("/", "//", $item );
        }
    });
 
    return $array;
}
/*
if(isset($_REQUEST["json"])) {
	$json=json_decode($_REQUEST["json"], true); 
	$json=utf8_converter($json);

}else{
	echo json_encode(["result"=>-10, "text"=>"Faltan parametros en la llamada a Navision"]);
	die;
}
*/



if(isset($_POST["json"])) {
	$json=json_decode($_POST["json"], true); 
	$json=utf8_converter($json);

}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", "ConnectionPooling" => "1", "MultipleActiveResultSets"=>'0');

$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;
}



$exist=false;
	$sqlExist='SELECT * FROM dbo.[Ind. Campollano Ferretería S.L$Sales Header] WHERE [No.]=\''.$json["No."].'\'';
	$smtpExist=sqlsrv_query( $connNavision, $sqlExist );
	
	echo $sqlExist;
	if($row = sqlsrv_fetch_array( $smtpExist, SQLSRV_FETCH_ASSOC)){
		$exist=true;
		
	}

	if(!$exist)
	{
	
	$sqlAgent='SELECT [User ID] from dbo.[Ind. Campollano Ferretería S.L$User Setup] where [E-Mail]=\''.$json["Assigned User ID"].'\'';
	//echo $sqlAgent."<br><br>";
	$smtpAgent=sqlsrv_query( $connNavision, $sqlAgent );
	
	
	if($row = sqlsrv_fetch_array( $smtpAgent, SQLSRV_FETCH_ASSOC)){
				$userid=$row["User ID"];
	}
	
	$sqlAgent='SELECT [Salespers._Purch. Code] from dbo.[Ind. Campollano Ferretería S.L$User Setup] where [E-Mail]=\''.$json["Agent"].'\'';
	//echo $sqlAgent."<br><br>";
	$smtpAgent=sqlsrv_query( $connNavision, $sqlAgent );
	
	
	if($row = sqlsrv_fetch_array( $smtpAgent, SQLSRV_FETCH_ASSOC)){
				$agent=$row["Salespers._Purch. Code"];
	}
	
	
	$sqlSalesPerson='SELECT [Code] from dbo.[Ind. Campollano Ferretería S.L$Salesperson_Purchaser] where [E-Mail]=\''.$json["Assigned User ID"].'\'';
	$smtpSalesPerson=sqlsrv_query( $connNavision, $sqlSalesPerson );
	
	$salesperson='';
	if($row = sqlsrv_fetch_array( $smtpSalesPerson, SQLSRV_FETCH_ASSOC)){
				$salesperson=$row["Code"];
	}
		
	
	$sqlCustomerDiscGroup='SELECT [Customer Disc. Group], [Payment Terms Code] from dbo.[Ind. Campollano Ferretería S.L$Customer] where [No.]=\''.$json["Bill-to Customer No."].'\'';
	$smtpCustomerDiscGroup=sqlsrv_query( $connNavision, $sqlCustomerDiscGroup );	
		
	$customerdiscgroup="";
	$customerPayment="";
	if($row = sqlsrv_fetch_array( $smtpCustomerDiscGroup, SQLSRV_FETCH_ASSOC)){
				$customerdiscgroup=$row["Customer Disc. Group"];
				$customerPayment=$row["Payment Terms Code"];
	}
			
	$documentDate=new DateTime($json["Document Date"]["date"]);
	$orderDate=new DateTime($json["Order Date"]["date"]);
	$fechaLimiteDate=new DateTime($json["Fecha Limite Validez Oferta"]["date"]);

	
	$json_lines=$json["lines"];
	//print_r($json);

		$sql = 'INSERT INTO dbo.[Ind. Campollano Ferretería S.L$Sales Header]'." (
		[Document Type] ,
		[No.]   ,
		[Sell-to Customer No.]   ,
		[Bill-to Customer No.]   ,
		[Bill-to Name]   ,
		[Bill-to Name 2]   ,
		[Bill-to Address]   ,
		[Bill-to Address 2]   ,
		[Bill-to City]   ,
		[Bill-to Contact]   ,
		[Your Reference]   ,
		[Ship-to Code]   ,
		[Ship-to Name]   ,
		[Ship-to Name 2]   ,
		[Ship-to Address]   ,
		[Ship-to Address 2]   ,
		[Ship-to City]   ,
		[Ship-to Contact]   ,
		[Order Date] ,
		[Posting Date] ,
		[Shipment Date] ,
		[Posting Description]   ,
		[Payment Terms Code]   ,
		[Due Date] ,
		[Payment Discount %] ,
		[Pmt. Discount Date] ,
		[Shipment Method Code]   ,
		[Location Code]   ,
		[Shortcut Dimension 1 Code]   ,
		[Shortcut Dimension 2 Code]   ,
		[Customer Posting Group]   ,
		[Currency Code]   ,
		[Currency Factor] ,
		[Customer Price Group]   ,
		[Prices Including VAT] ,
		[Invoice Disc. Code]   ,
		[Customer Disc. Group]   ,
		[Language Code]   ,
		[Salesperson Code]   ,
		[Order Class]   ,
		[No. Printed] ,
		[On Hold]   ,
		[Applies-to Doc. Type] ,
		[Applies-to Doc. No.]   ,
		[Bal. Account No.]   ,
		[Ship] ,
		[Invoice] ,
		[Shipping No.]   ,
		[Posting No.]   ,
		[Last Shipping No.]   ,
		[Last Posting No.]   ,
		[Prepayment No.]   ,
		[Last Prepayment No.]   ,
		[Prepmt. Cr. Memo No.]   ,
		[Last Prepmt. Cr. Memo No.]   ,
		[VAT Registration No.]   ,
		[Combine Shipments] ,
		[Reason Code]   ,
		[Gen. Bus. Posting Group]   ,
		[EU 3-Party Trade] ,
		[Transaction Type]   ,
		[Transport Method]   ,
		[VAT Country_Region Code]   ,
		[Sell-to Customer Name]   ,
		[Sell-to Customer Name 2]   ,
		[Sell-to Address]   ,
		[Sell-to Address 2]   ,
		[Sell-to City]   ,
		[Sell-to Contact]   ,
		[Bill-to Post Code]   ,
		[Bill-to County]   ,
		[Bill-to Country_Region Code]   ,
		[Sell-to Post Code]   ,
		[Sell-to County]   ,
		[Sell-to Country_Region Code]   ,
		[Ship-to Post Code]   ,
		[Ship-to County]   ,
		[Ship-to Country_Region Code]   ,
		[Bal. Account Type] ,
		[Exit Point]   ,
		[Correction] ,
		[Document Date] ,
		[External Document No.]   ,
		[Area]   ,
		[Transaction Specification]   ,
		[Payment Method Code]   ,
		[Shipping Agent Code]   ,
		[Package Tracking No.]   ,
		[No. Series]   ,
		[Posting No. Series]   ,
		[Shipping No. Series]   ,
		[Tax Area Code]   ,
		[Tax Liable] ,
		[VAT Bus. Posting Group]   ,
		[Reserve] ,
		[Applies-to ID]   ,
		[VAT Base Discount %] ,
		[Status] ,
		[Invoice Discount Calculation] ,
		[Invoice Discount Value] ,
		[Send IC Document] ,
		[IC Status] ,
		[Sell-to IC Partner Code]   ,
		[Bill-to IC Partner Code]   ,
		[IC Direction] ,
		[Prepayment %] ,
		[Prepayment No. Series]   ,
		[Compress Prepayment] ,
		[Prepayment Due Date] ,
		[Prepmt. Cr. Memo No. Series]   ,
		[Prepmt. Posting Description]   ,
		[Prepmt. Pmt. Discount Date] ,
		[Prepmt. Payment Terms Code]   ,
		[Prepmt. Payment Discount %] ,
		[Doc. No. Occurrence] ,
		[Campaign No.]   ,
		[Sell-to Customer Template Code]   ,
		[Sell-to Contact No.]   ,
		[Bill-to Contact No.]   ,
		[Bill-to Customer Template Code]   ,
		[Opportunity No.]   ,
		[Responsibility Center]   ,
		[Shipping Advice] ,
		[Posting from Whse. Ref.] ,
		[Requested Delivery Date] ,
		[Promised Delivery Date] ,
		[Shipping Time]   ,
		[Outbound Whse. Handling Time]   ,
		[Shipping Agent Service Code]   ,
		[Receive] ,
		[Return Receipt No.]   ,
		[Return Receipt No. Series]   ,
		[Last Return Receipt No.]   ,
		[Allow Line Disc.] ,
		[Get Shipment Used] ,
		[Assigned User ID]   ,
		[Corrected Invoice No.]   ,
		[Enviado por completo] ,
		[Tarifa ASIDE]   ,
		[Porcentaje tarifa ASIDE] ,
		[Estado pedido] ,
		[Cod. Banco domic.]   ,
		[Fecha cierre] ,
		[Nº Caja]   ,
		[Nº Cuadre]   ,
		[TPV] ,
		[Doc. Rectificado]   ,
		[Tipo Doc. Rectificado] ,
		[Tiques agrupados desde]   ,
		[Tiques agrupados hasta]   ,
		[Número de tiques] ,
		[Tipo Facturas (349)] ,
		[TermPago1]   ,
		[ImportePago1] ,
		[FormaPago2]   ,
		[TermPago2]   ,
		[ImportePago2] ,
		[FormaPago3]   ,
		[TermPago3]   ,
		[ImportePago3] ,
		[FormaPago4]   ,
		[TermPago4]   ,
		[ImportePago4] ,
		[Nº Factura]   ,
		[A devolver] ,
		[Código centro responsabilidad]   ,
		[Generado Fact. Automática] ,
		[Ticket al registrar] ,
		[Applies-to Bill No.]   ,
		[Cust. Bank Acc. Code]   ,
		[Pay-at Code]   ,
		[Historic] ,
		[Proforma invoice] ,
		[Creation company]   ,
		[Envios en diferentes empresas] ,
		[Imprimir fecha envio] ,
		[Importe portes] ,
		[Entrega completa del articulo] ,
		[Referencias cliente] ,
		[Impresion cantidad pendiente] ,
		[Albaran directo] ,
		[Detalle en impresion] ,
		[No oferta relacionada]   ,
		[Fax Documento]   ,
		[Email Documento]   ,
		[Fecha Limite Validez Oferta] ,
		[Estado Oferta] ,
		[Es Devolucion] ,
		[Sales document type] ,
		[Center code]   ,
		[Cash code]   ,
		[Sales type] ,
		[POS action code]   ,
		[Date Received] ,
		[Time Received] ,
		[BizTalk Request for Sales Qte.] ,
		[BizTalk Sales Order] ,
		[Date Sent] ,
		[Time Sent] ,
		[BizTalk Sales Quote] ,
		[BizTalk Sales Order Cnfmn.] ,
		[Customer Quote No.]   ,
		[Customer Order No.]   ,
		[BizTalk Document Sent] ,
		[Pos Payment Amount 1] ,
		[Payment Method Code 2]   ,
		[Pos Payment Amount 2] ,
		[Pos To Return] ,
		[Register Company]   ,
		[Distribution %] ,
		[Pos Status] ,
		[Creation date] ,
		[Creation time] ,
		[Creation user]   ,
		[Sales origin] ,
		[Sales management type]   ,
		[SalesManager]   ,
		[Agent]   ,
		[SubAgent]   ,
		[Route code]   ,
		[Territory Code]   ,
		[Nueva creación] ,
		[Salesperson return code]   ,
		[Job Ship-to Code]   ,
		[FechaReclamacion] ,
		[Cod. Preparacion]   ,
		[Modalidad] ,
		[TipoFactura] ,
		[NumFacturaRectificar]   ,
		[NumVecesGeneradaFacturae] ,
		[CodMotivoRectificacion]   ,
		[CodCriterioRectificacion]   ,
		[CodOficinaContable]   ,
		[CodOrganoGestor]   ,
		[CodUdTramitadora]   ,
		[Telefono]   ,
		[Pedido WEB] ,
		[Hora Creacion] ,
		[Fecha Creacion] ,
		[user_app]   ,
		[CodOrganoPrepotente]
		) VALUES (0,
		'".$json["No."]."',
		'".$json["Bill-to Customer No."]."',
		'".$json["Bill-to Customer No."]."',
		'".$json["Bill-to Name"]."',
		'".$json["Bill-to Name 2"]."',
		'".$json["Bill-to Address"]."',
		'".$json["Bill-to Address 2"]."',
		'".$json["Bill-to City"]."',
		'',
		'',
		'',
		'".$json["Ship-to Name"]."',
		'".$json["Ship-to Name 2"]."',
		'".$json["Ship-to Address"]."',
		'".$json["Ship-to Address 2"]."',
		'',
		'',
		'".$orderDate->format("Y-m-d").'T00:00:00.000'."',
		'".$orderDate->format("Y-m-d").'T00:00:00.000'."',
		'".$orderDate->format("Y-m-d").'T00:00:00.000'."',
		'Pedido ".$json["No."]."',
		'".$customerPayment."',
		'".$orderDate->format("Y-m-d").'T00:00:00.000'."',
		0,
		'".$orderDate->format("Y-m-d").'T00:00:00.000'."',
		'',
		'ALM01',
		'',
		'',
		'NAC',
		'',
		0,
		'TARIFA1',
		0,
		'".$json["Bill-to Customer No."]."',
		'".$customerdiscgroup."',
		'',
		'".$salesperson."',
		'',
		0,
		'',
		0,
		'',
		'',
		0,
		0,
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		'".$json["VAT Registration No."]."',
		1,
		'',
		'NACIONAL',
		0,
		'',
		'',
		'ES',
		'".$json["Ship-to Name"]."',
		'".$json["Ship-to Name 2"]."',
		'".$json["Ship-to Address"]."',
		'".$json["Ship-to Address 2"]."',
		'".$json["Ship-to City"]."',
		'',
		'".$json["Bill-to Post Code"]."',
		'".$json["Bill-to County"]."',
		'ES',
		'".$json["Bill-to Post Code"]."',
		'".$json["Bill-to County"]."',
		'ES',
		'".$json["Ship-to Post Code"]."',
		'".$json["Ship-to County"]."',
		'ES',
		0,
		'',
		0,
		'".$documentDate->format("Y-m-d").'T00:00:00.000'."',
		'',
		'',
		'',
		'".$json["Payment Method Code"]."',
		'',
		'',
		'V-OFER',
		'V-FAC+',
		'V-ALB',
		'',
		0,
		'NAC',
		1,
		'',
		0,
		'".$json["Status"]."',
		1,
		0,
		0,
		0,
		'',
		'',
		0,
		0,
		'',
		1,
		'".$documentDate->format("Y-m-d").'T00:00:00.000'."',
		'',
		'',
		'".$documentDate->format("Y-m-d").'T00:00:00.000'."',
		'".$customerPayment."',
		0,
		1,
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		0,
		0,
		'1753-01-01T00:00:00.000',
		'1753-01-01T00:00:00.000',
		'',
		'',
		'',
		0,
		'',
		'',
		'',
		1,
		0,
		'".$userid."',
		'',
		0,
		'',
		0,
		0,
		'',
		'1753-01-01T00:00:00.000',
		'',
		'',
		0,
		'',
		0,
		'',
		'',
		0,
		0,
		'',
		0,
		'',
		'',
		0,
		'',
		'',
		0,
		'',
		'',
		0,
		'',
		0,
		'',
		0,
		0,
		'',
		'',
		'',
		0,
		0,
		'Ind. Campollano Ferretería S.L',
		0,
		1,
		0,
		0,
		0,
		1,
		0,
		0,
		'',
		'',
		'',
		'".$fechaLimiteDate->format("Y-m-d").'T00:00:00.000'."',
		0,
		".$json["Es devolucion"].",
		0,
		'',
		'',
		0,
		'',
		'1753-01-01T00:00:00.000',
		'1753-01-01T00:00:00.000',
		0,
		0,
		'1753-01-01T00:00:00.000',
		'1753-01-01T00:00:00.000',
		0,
		0,
		'',
		'',
		0,
		0,
		'',
		0,
		0,
		'',
		0,
		0,
		'".$documentDate->format("Y-m-d").'T00:00:00.000'."',
		'1753-01-01T00:00:00.000',
		'".$userid."',
		1,
		'',
		'',
		'".$agent."',
		'',
		'',
		'',
		0,
		'',
		'',
		'1753-01-01T00:00:00.000',
		'',
		0,
		0,
		'',
		0,
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		'1753-01-01T00:00:00.000',
		'".$documentDate->format("Y-m-d").'T00:00:00.000'."',
		'',
		''
		);";

//echo utf8_encode($sql);

			$stmt = sqlsrv_query( $connNavision, $sql );
			if(sqlsrv_errors(SQLSRV_ERR_ERRORS)===NULL) echo json_encode(["result"=>1]); else echo json_encode(["result"=>-12, "text"=>"1 Ocurrio un error en la consulta SQL de Navision"]);
			
			/*
				if( ($errors = sqlsrv_errors() ) != null) {
					foreach( $errors as $error ) {
						echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
						echo "code: ".$error[ 'code']."<br />";
						echo "message: ".$error[ 'message']."<br />";
					}
				}
				*/
			
foreach($json_lines as $line)
		{
			
			$sqlUnidadMedidaPrecio='SELECT [Unidad medida precio],[Item Category Code],[Product Group Code] from dbo.[Item] WHERE [No.]=\''.$line["No."].'\'';
			$smtpUnidadMedidaPrecio=sqlsrv_query( $connNavision, $sqlUnidadMedidaPrecio );
			
			$unidadmedidaprecio="UD";
			$codunidadmedidoprecio="UD";
			$descripcionumprecio="Unidades";
			
			$itemcategorycode="";
			$productgroupcode="";
			if($row = sqlsrv_fetch_array( $smtpUnidadMedidaPrecio, SQLSRV_FETCH_ASSOC)){
						$unidadmedidaprecio=$row["Unidad medida precio"];
						$itemcategorycode=$row["Item Category Code"];
						$productgroupcode=$row["Product Group Code"];
						
			}
					
			$unitpriceUMprecio=$line["Unit price UM precio"];
			if($unidadmedidaprecio=="C")
			{
				
				$codunidadmedidoprecio="C";
				$descripcionumprecio="Centenar";
				$unitpriceUMprecio=$line["Unit price UM precio"]*100;
			}

	$stmt = sqlsrv_query( $connNavision, $sql );
	
		$sql = 'INSERT INTO dbo.[Ind. Campollano Ferretería S.L$Sales Line]'." (
	[Document Type],
	[Document No.] ,
	[Line No.],
	[Sell-to Customer No.] ,
	[Type],
	[No.] ,
	[Location Code] ,
	[Posting Group] ,
	[Shipment Date],
	[Description] ,
	[Description 2] ,
	[Unit of Measure] ,
	[Quantity],
	[Outstanding Quantity],
	[Qty. to Invoice],
	[Qty. to Ship],
	[Unit Price],
	[Unit Cost (LCY)],
	[VAT %],
	[Line Discount %],
	[Line Discount Amount],
	[Amount],
	[Amount Including VAT],
	[Allow Invoice Disc.],
	[Gross Weight],
	[Net Weight],
	[Units per Parcel],
	[Unit Volume],
	[Appl.-to Item Entry],
	[Shortcut Dimension 1 Code] ,
	[Shortcut Dimension 2 Code] ,
	[Customer Price Group] ,
	[Job No.] ,
	[Work Type Code] ,
	[Outstanding Amount],
	[Qty. Shipped Not Invoiced],
	[Shipped Not Invoiced],
	[Quantity Shipped],
	[Quantity Invoiced],
	[Shipment No.] ,
	[Shipment Line No.],
	[Profit %],
	[Bill-to Customer No.] ,
	[Inv. Discount Amount],
	[Purchase Order No.] ,
	[Purch. Order Line No.],
	[Drop Shipment],
	[Gen. Bus. Posting Group] ,
	[Gen. Prod. Posting Group] ,
	[VAT Calculation Type],
	[Transaction Type] ,
	[Transport Method] ,
	[Attached to Line No.],
	[Exit Point] ,
	[Area] ,
	[Transaction Specification] ,
	[Tax Area Code] ,
	[Tax Liable],
	[Tax Group Code] ,
	[VAT Bus. Posting Group] ,
	[VAT Prod. Posting Group] ,
	[Currency Code] ,
	[Outstanding Amount (LCY)],
	[Shipped Not Invoiced (LCY)],
	[Reserve],
	[Blanket Order No.] ,
	[Blanket Order Line No.],
	[VAT Base Amount],
	[Unit Cost],
	[System-Created Entry],
	[Line Amount],
	[VAT Difference],
	[Inv. Disc. Amount to Invoice],
	[VAT Identifier] ,
	[IC Partner Ref. Type],
	[IC Partner Reference] ,
	[Prepayment %],
	[Prepmt. Line Amount],
	[Prepmt. Amt. Inv.],
	[Prepmt. Amt. Incl. VAT],
	[Prepayment Amount],
	[Prepmt. VAT Base Amt.],
	[Prepayment VAT %],
	[Prepmt. VAT Calc. Type],
	[Prepayment VAT Identifier] ,
	[Prepayment Tax Area Code] ,
	[Prepayment Tax Liable],
	[Prepayment Tax Group Code] ,
	[Prepmt Amt to Deduct],
	[Prepmt Amt Deducted],
	[Prepayment Line],
	[Prepmt. Amount Inv. Incl. VAT],
	[Prepmt. Amount Inv. (LCY)],
	[IC Partner Code] ,
	[Prepayment VAT Difference],
	[Prepmt VAT Diff. to Deduct],
	[Prepmt VAT Diff. Deducted],
	[Job Task No.] ,
	[Job Contract Entry No.],
	[Variant Code] ,
	[Bin Code] ,
	[Qty. per Unit of Measure],
	[Planned],
	[Unit of Measure Code] ,
	[Quantity (Base)],
	[Outstanding Qty. (Base)],
	[Qty. to Invoice (Base)],
	[Qty. to Ship (Base)],
	[Qty. Shipped Not Invd. (Base)],
	[Qty. Shipped (Base)],
	[Qty. Invoiced (Base)],
	[FA Posting Date],
	[Depreciation Book Code] ,
	[Depr. until FA Posting Date],
	[Duplicate in Depreciation Book] ,
	[Use Duplication List],
	[Responsibility Center] ,
	[Out-of-Stock Substitution],
	[Originally Ordered No.] ,
	[Originally Ordered Var. Code] ,
	[Cross-Reference No.] ,
	[Unit of Measure (Cross Ref.)] ,
	[Cross-Reference Type],
	[Cross-Reference Type No.] ,
	[Item Category Code] ,
	[Nonstock],
	[Purchasing Code] ,
	[Product Group Code] ,
	[Special Order],
	[Special Order Purchase No.] ,
	[Special Order Purch. Line No.],
	[Completely Shipped],
	[Requested Delivery Date],
	[Promised Delivery Date],
	[Shipping Time] ,
	[Outbound Whse. Handling Time] ,
	[Planned Delivery Date],
	[Planned Shipment Date],
	[Shipping Agent Code] ,
	[Shipping Agent Service Code] ,
	[Allow Item Charge Assignment],
	[Return Qty. to Receive],
	[Return Qty. to Receive (Base)],
	[Return Qty. Rcd. Not Invd.],
	[Ret. Qty. Rcd. Not Invd.(Base)],
	[Return Rcd. Not Invd.],
	[Return Rcd. Not Invd. (LCY)],
	[Return Qty. Received],
	[Return Qty. Received (Base)],
	[Appl.-from Item Entry],
	[BOM Item No.] ,
	[Return Receipt No.] ,
	[Return Receipt Line No.],
	[Return Reason Code] ,
	[Allow Line Disc.],
	[Customer Disc. Group] ,
	[Pmt. Disc. Given Amount],
	[EC %],
	[EC Difference],
	[Prepayment EC %],
	[Tarifa ASIDE] ,
	[Porcentaje tarifa ASIDE],
	[% incremento tarifa],
	[% Descuento 1],
	[% Descuento 2],
	[% Descuento 3],
	[% Descuento 4],
	[Estado línea pedido],
	[Cantidad inicial],
	[Cantidad inicial base],
	[Obliga Factura],
	[NS] ,
	[Código centro responsabilidad] ,
	[Cod. Marca] ,
	[Historic],
	[Importe pendiente base],
	[Importe pendiente base (DL)],
	[Canon RAE],
	[Canon Medioambiental],
	[Cod. unidad medida precio] ,
	[Unit price UM precio],
	[Unit Cost UM Precio],
	[Cdad por UM Precio],
	[Descripcion UM precio] ,
	[Pasar a pedido],
	[Procede de No oferta] ,
	[Fecha cierre linea],
	[Observaciones],
	[Neto],
	[Neto UM Precio],
	[Linea nueva],
	[Drop Shipment simul],
	[Purchase Order No. simul] ,
	[Purch. Order Line No. simul],
	[Cantidad modif.],
	[No albaran dev] ,
	[No linea alb. Dev.],
	[No linea alb],
	[Nº línea lista materiales],
	[Es Devolucion],
	[Amount Including VAT TPV],
	[Amount TPV],
	[Reserved],
	[Unit Price TPV],
	[Sales origin],
	[Sales management type] ,
	[SalesManager] ,
	[Agent] ,
	[SubAgent] ,
	[Route code] ,
	[Territory Code] ,
	[Salesperson Code] ,
	[Nueva creación],
	[Exclude from req. quantity],
	[Grouped Entry No],
	[SaltaTest],
	[Peso],
	[qty_scanned]) VALUES (
			0,
			'".$line["Document No."]."',
			'".$line["Line No."]."',
			'".$json["Bill-to Customer No."]."',
			2,
			'".$line["No."]."',
			'ALM01',
			'EXISTENCIA',
			'".$orderDate->format("Y-m-d").'T00:00:00.000'."',
			'".$line["Description"]."',
			'".$line["Description 2"]."',
			'".$descripcionumprecio."',
			".$line["Quantity"].",
			".$line["Quantity"].",
			".$line["Quantity"].",
			".$line["Quantity"].",
			".$line["Unit Price"].",
			".$line["Unit Cost"].",
			21,
			".$line["Discountperc"].",
			".$line["Discounttotal"].",
			".$line["Amount"].",
			".$line["Amount Including VAT"].",
			1,
			0,
			0,
			0,
			0,
			0,
			'',
			'',
			'TARIFA1',
			'',
			'',
			".$line["Amount Including VAT"].",
			0,
			0,
			0,
			0,
			'',
			0,
			0,
			'".$json["Bill-to Customer No."]."',
			0,
			'',
			0,
			0,
			'NACIONAL',
			'MERCADERIA',
			0,
			'',
			'',
			0,
			'',
			'',
			'',
			'',
			0,
			'',
			'NAC',
			'IVA21',
			'',
			".$line["Amount Including VAT"].",
			0,
			1,
			'',
			0,
			".$line["VAT Base Amount"].",
			".$line["Unit Cost"].",
			0,
			".$line["Line Amount"].",
			0,
			0,
			'VAT21',
			0,
			'',
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			'',
			'',
			0,
			'',
			0,
			0,
			0,
			0,
			0,
			'',
			0,
			0,
			0,
			'',
			0,
			'',
			'',
			1,
			0,
			'".$unidadmedidaprecio."',
			".$line["Quantity"].",
			".$line["Quantity"].",
			".$line["Quantity"].",
			".$line["Quantity"].",
			0,
			0,
			0,
			'1753-01-01T00:00:00.000',
			'',
			0,
			'',
			0,
			'',
			0,
			'',
			'',
			'',
			'',
			0,
			'',
			'".$itemcategorycode."',
			0,
			'',
			'".$productgroupcode."',
			0,
			'',
			0,
			0,
			'1753-01-01T00:00:00.000',
			'1753-01-01T00:00:00.000',
			'',
			'',
			'1753-01-01T00:00:00.000',
			'1753-01-01T00:00:00.000',
			'',
			'',
			1,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			'',
			'',
			0,
			'',
			1,
			'".$customerdiscgroup."',
			0,
			0,
			0,
			0,
			'',
			0,
			0,
			".$line["Discountperc"].",
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			'',
			'',
			'',
			0,
			".$line["Importe pendiente base"].",
			".$line["Importe pendiente base (DL)"].",
			0,
			0,
			'".$codunidadmedidoprecio."',
			".$unitpriceUMprecio.",
			0,
			1,
			'".$descripcionumprecio."',
			0,
			'',
			'1753-01-01T00:00:00.000',
			'',
			".$line["Amount"].",
			".$line["Amount"].",
			0,
			0,
			'',
			0,
			0,
			'',
			0,
			0,
			3,
			'".$json["Es devolucion"]."',
			0,
			0,
			0,
			".$line["Unit Price"].",
			0,
			'',
			'',
			'',
			'',
			'',
			'',
			'".$salesperson."',
			0,
			0,
			0,
			0,
			0,
			0);";


	//echo ($sql);
	
	$stmt = sqlsrv_query( $connNavision, $sql );
	if(sqlsrv_errors(SQLSRV_ERR_ERRORS)===NULL) echo json_encode(["result"=>1]); else echo json_encode(["result"=>-12, "text"=>"1 Ocurrio un error en la consulta SQL de Navision"]);

		
			if( ($errors = sqlsrv_errors() ) != null) {
					foreach( $errors as $error ) {
						echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
						echo "code: ".$error[ 'code']."<br />";
						echo "message: ".$error[ 'message']."<br />";
					}
				}
				
	
}	

	}
	
	else "ya existe";
	
	//sqlsrv_commit($connNavision);
	sqlsrv_close($connNavision);

?>