<?php
//include("atributos.php");
//include("categorias.php");

error_reporting(E_ALL);
ini_set('display_errors', 1);
date_default_timezone_set('Europe/Madrid');
include("conexion_inaer.php");


//$rutaImportacionImagenes="/home/operador/www/ferreteriacampollano.com/media/import/";
//$rutaImagenes="/home/operador/www/ferreteriacampollano.com/media/catalog/product/";

function adaptarPrecio($precio){
	$str=str_replace('.','',$precio);
	$str=str_replace(',','.',$str);

	return $str;

}

function Slug($string)
{
	return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8')), '-'));
}

function obtenerEntityID($conn){
	$stmt = $conn->prepare("SELECT entity_type_id FROM fceav_entity_type  WHERE entity_type_code='catalog_product'");
	$stmt->execute();
	$result = $stmt->get_result();
	if($row_m = $result->fetch_assoc()) return $row_m['entity_type_id'];
		else return -1;

}


function obtenerIDProducto($sku, $conn){
	$stmt = $conn->prepare("SELECT id_product FROM fcproduct WHERE reference='$sku'");
	$stmt->execute();
	$result = $stmt->get_result();
	if($row_m = $result->fetch_assoc()) return $row_m['id_product'];
		else return -1;
}


function existeProducto($sku, $conn){
	$stmt = $conn->prepare("SELECT * FROM fccatalog_product_entity WHERE sku='$sku'");
	$stmt->execute();
	$result = $stmt->get_result();
	if($row_m = $result->fetch_assoc()) return true;
		else return false;
}

function obtenerIDPadrePadres($path_categoria, $nombre, $conn){
	$arr_todas_categorias=explode("/",$path_categoria);
	$count_array=count($arr_todas_categorias);
	/*Eliminamos el hijo*/
	unset($arr_todas_categorias[$count_array-1]);
	$cont=0;
	$encontrado=0;
	foreach($arr_todas_categorias as $item){
		
		if($encontrado==1){
			unset($arr_todas_categorias[$cont]);
		}
		
		if($item==$nombre){
			$encontrado=1;	
		}
		$cont++;
	}
	
	
	
	$padre=-2;
	if(count($arr_todas_categorias)>4){
		
		
		foreach($arr_todas_categorias as $item){$padre++;}
		$tataraabuelo=$padre-3;
		$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_todas_categorias[$tataraabuelo]'");
		$stmt->execute();
		$result = $stmt->get_result();
		$row_m = $result->fetch_assoc();
		$id_aux_tatarabuelo=$row_m['categoria'];
		
		
		$bisabuelo=$padre-2;
		/*id del abuelo padre para asegurarnos de que no hay dos categorias con ese nombre*/
		$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_todas_categorias[$bisabuelo]' AND c.id_parent='$id_aux_tatarabuelo'");
		$stmt->execute();
		$result = $stmt->get_result();
		$row_m = $result->fetch_assoc();
		$id_aux_bisabuelo=$row_m['categoria'];
		
		$padre_anterior=$padre-1;
			/*id del padre del padre para asegurarnos de que no hay dos categorias en ese nivel con ese nombre*/
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_todas_categorias[$padre_anterior]' AND c.id_parent='$id_aux_bisabuelo'");
			$stmt->execute();
			$result = $stmt->get_result();
			$row_m = $result->fetch_assoc();
			$id_aux=$row_m['categoria'];
			
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_todas_categorias[$padre]' AND c.id_parent='$id_aux'");
			$stmt->execute();
			
			$result = $stmt->get_result();
			if($row_m = $result->fetch_assoc()) return $row_m['categoria'];
				else return -1;
		
		}
		
		
		else if(count($arr_todas_categorias)==4){
			
			
			foreach($arr_todas_categorias as $item){$padre++;}
			
			$bisabuelo=$padre-2;
			/*id del abuelo padre para asegurarnos de que no hay dos categorias con ese nombre*/
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_todas_categorias[$bisabuelo]'");
			$stmt->execute();
			$result = $stmt->get_result();
			$row_m = $result->fetch_assoc();
			$id_aux_bisabuelo=$row_m['categoria'];
			
			$padre_anterior=$padre-1;
			/*id del padre del padre para asegurarnos de que no hay dos categorias en ese nivel con ese nombre*/
			$stmt = $conn->prepare("SELECT c.id_category categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_todas_categorias[$padre_anterior]' AND c.id_parent='$id_aux_bisabuelo'");
			$stmt->execute();
			$result = $stmt->get_result();
			$row_m = $result->fetch_assoc();
			$id_aux=$row_m['categoria'];
			
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_todas_categorias[$padre]' AND c.id_parent='$id_aux'");
			$stmt->execute();
			
			$result = $stmt->get_result();
			if($row_m = $result->fetch_assoc()) return $row_m['categoria'];
				else return -1;
			
			
		}
		
		else if(count($arr_todas_categorias)==3){
		
			foreach($arr_todas_categorias as $item){$padre++;}
			$padre_anterior=$padre-1;
			/*id del padre del padre para asegurarnos de que no hay dos categorias en ese nivel con ese nombre*/
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_todas_categorias[$padre_anterior]'");
			$stmt->execute();
			$result = $stmt->get_result();
			$row_m = $result->fetch_assoc();
			$id_aux=$row_m['categoria'];
			
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_todas_categorias[$padre]' AND c.id_parent='$id_aux'");
			$stmt->execute();
			
			$result = $stmt->get_result();
			if($row_m = $result->fetch_assoc()) return $row_m['categoria'];
				else return -1;
		
		}
		
		
		
		
		else if(count($arr_todas_categorias)==2){
		
			foreach($arr_todas_categorias as $item){$padre++;}
									
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_todas_categorias[$padre]'");
			$stmt->execute();
			
			$result = $stmt->get_result();
			if($row_m = $result->fetch_assoc()) return $row_m['categoria'];
				else return -1;
		}
		
		else if(count($arr_todas_categorias)==1){
			
			return 1;
		}
			
	
	
}






function obtenerIDPadre($path_categoria, $conn){

		$padre=-2;
		$arr_categorias=explode("/",$path_categoria);
	
		
		if(count($arr_categorias)>4){
		
		foreach($arr_categorias as $item){$padre++;}
		$tataraabuelo=$padre-3;
		$stmt = $conn->prepare("SELECT c.id_category categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_categorias[$tataraabuelo]'");
		$stmt->execute();
		$result = $stmt->get_result();
		$row_m = $result->fetch_assoc();
		$id_aux_tatarabuelo=$row_m['categoria'];
		
		
		$bisabuelo=$padre-2;
		/*id del abuelo padre para asegurarnos de que no hay dos categorias con ese nombre*/
		$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_categorias[$bisabuelo]' AND c.id_parent='$id_aux_tatarabuelo'");
		$stmt->execute();
		$result = $stmt->get_result();
		$row_m = $result->fetch_assoc();
		$id_aux_bisabuelo=$row_m['categoria'];
		
		$padre_anterior=$padre-1;
			/*id del padre del padre para asegurarnos de que no hay dos categorias en ese nivel con ese nombre*/
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_categorias[$padre_anterior]' AND c.id_parent='$id_aux_bisabuelo'");
			$stmt->execute();
			$result = $stmt->get_result();
			$row_m = $result->fetch_assoc();
			$id_aux=$row_m['categoria'];
			
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and l.link_rewrite='$arr_categorias[$padre]' AND c.id_parent='$id_aux'");
			$stmt->execute();
			
			$result = $stmt->get_result();
			if($row_m = $result->fetch_assoc()) return $row_m['categoria'];
				else return -1;
		
		}
		
		
		else if(count($arr_categorias)==4){
			
			
			foreach($arr_categorias as $item){$padre++;}
			
			$bisabuelo=$padre-2;
			
			/*id del abuelo padre para asegurarnos de que no hay dos categorias con ese nombre*/
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l WHERE c.id_category=l.id_category and l.link_rewrite='$arr_categorias[$bisabuelo]'");
			$stmt->execute();
			$result = $stmt->get_result();
			$row_m = $result->fetch_assoc();
			$id_aux_bisabuelo=$row_m['categoria'];
			
			$padre_anterior=$padre-1;
			/*id del padre del padre para asegurarnos de que no hay dos categorias en ese nivel con ese nombre*/
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l WHERE c.id_category=l.id_category and l.link_rewrite='$arr_categorias[$padre_anterior]' AND c.id_parent='$id_aux_bisabuelo'");
			$stmt->execute();
			$result = $stmt->get_result();
			$row_m = $result->fetch_assoc();
			$id_aux=$row_m['categoria'];
			
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_categorias[$padre]' AND c.id_parent='$id_aux'");
			$stmt->execute();
			
			$result = $stmt->get_result();
			if($row_m = $result->fetch_assoc()) return $row_m['categoria'];
				else return -1;
			
			
		}
		
		else if(count($arr_categorias)==3){
		
			foreach($arr_categorias as $item){$padre++;}
			$padre_anterior=$padre-1;
			/*id del padre del padre para asegurarnos de que no hay dos categorias en ese nivel con ese nombre*/
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_categorias[$padre_anterior]'");
			$stmt->execute();
			$result = $stmt->get_result();
			$row_m = $result->fetch_assoc();
			$id_aux=$row_m['categoria'];
			
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_categorias[$padre]' AND c.id_parent='$id_aux'");
			$stmt->execute();
			
			$result = $stmt->get_result();
			if($row_m = $result->fetch_assoc()) return $row_m['categoria'];
				else return -1;
		
		}
		
		
		
		else if(count($arr_categorias)==2){
		
			foreach($arr_categorias as $item){$padre++;}
						
			$stmt = $conn->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l  WHERE c.id_category=l.id_category and  l.link_rewrite='$arr_categorias[$padre]'");
			$stmt->execute();
			
			$result = $stmt->get_result();
			if($row_m = $result->fetch_assoc()) return $row_m['categoria'];
				else return -1;
		}
		
		else if(count($arr_categorias)==1){
			return 1;
		}
		

	
	
}



function obtenerAnchorTextCategoria($path_categoria, $conn){
	
	$arr_categorias=explode("/",$path_categoria);
	return end($arr_categorias);
	

}







function aplanarNombreProducto($nombreproducto){
	$str = preg_replace("/[^a-zA-Z0-9\s\-Ññ]/", "", $nombreproducto);
	$str = preg_replace("/[\s]/", "-", $str);
	return strtolower($str);
}


function htmlNombreProducto($nombreproducto){
	return aplanarNombreProducto($nombreproducto).".html";
}
while(true){
		$connPrestashop = new mysqli($bdd_servidor, $bdd_usuario, $bdd_contrasena, $bdd_base_datos);
		if( $connPrestashop ) {
			 echo "Conexion establecida con Inaer.\r\n";
		}else{
			 echo "Conexion no se pudo establecer con Inaer.\r\n";
			 die( print_r( sqlsrv_errors(), true));
		}

		$serverName = "localhost";
		$connectionInfo = array( "Database"=>"ICF", "UID"=>"VAIO", "PWD"=>"VAIO");
		$connNavision = sqlsrv_connect( $serverName, $connectionInfo);

		if( $connNavision ) {
			 echo "Conexion establecida con Navision.\r\n";
		}else{
			 echo "Conexion no se pudo establecer con Navision.\r\n";
			 die( print_r( sqlsrv_errors(), true));
		}

		echo "\r\n\r\nSincronizando productos:\r\n\r\n";

		$sql = ' 
					SELECT I.[No.], CONCAT(I.[Description], I.[Description 2]) Description, [DescripcionCortaWEB], CONCAT([DescripcionWEB],[Descripcion2WEB], [FamiliaWEB], [AgrupacionWEB]) desclarga, [MetadatosWEB], [MetadatosDescripcionWEB],
						 [Item Disc. Group], [NovedadWEB], [OutlerWEB], [DestacadoWEB], [NoRotacion], [Cod. Marca], [Gross Weight], [CantidadPedidoWeb], [Unidad medida precio], TipoAgrupWEB,
						 I.[Precio venta UM precio] precio, I.[PrecioWEB], I.[precioDestacadoWEB], I.[Sales Unit of Measure] unidad_minima_venta,
						(I.[Precio venta UM precio]-(I.[Precio venta UM precio]*(ISNULL(
								(SELECT TOP 1 [Line Discount %] descuento FROM
								[Ind. Campollano Ferretería S.L$Sales Line Discount]
								WHERE [Sales Code] = \'GDTO1\' AND Code LIKE I.[Item Disc. Group] AND [Starting Date]<=SYSDATETIME()
								AND ([Ending Date]>=SYSDATETIME() or [Ending Date] = \'1753-01-01 00:00:00.000\'))
						,0)/100))) GDTO1,
							(I.[Precio venta UM precio]-(I.[Precio venta UM precio]*(ISNULL(
								(SELECT TOP 1 [Line Discount %] descuento FROM
								[Ind. Campollano Ferretería S.L$Sales Line Discount]
								WHERE [Sales Code] = \'GDTO2\' AND Code LIKE I.[Item Disc. Group] AND [Starting Date]<=SYSDATETIME()
								AND ([Ending Date]>=SYSDATETIME() or [Ending Date] = \'1753-01-01 00:00:00.000\'))
						,0)/100))) GDTO2,
							(I.[Precio venta UM precio]-(I.[Precio venta UM precio]*(ISNULL(
								(SELECT TOP 1 [Line Discount %] descuento FROM
								[Ind. Campollano Ferretería S.L$Sales Line Discount]
								WHERE [Sales Code] = \'GDTO3\' AND Code LIKE I.[Item Disc. Group] AND [Starting Date]<=SYSDATETIME()
								AND ([Ending Date]>=SYSDATETIME() or [Ending Date] = \'1753-01-01 00:00:00.000\'))
						,0)/100))) GDTO3,	
						(SELECT ISNULL(MIN([Unit price UM precio]),0) From [Ind. Campollano Ferretería S.L$Sales Price] p WHERE [Item No.]=I.[No.]
						AND [Sales Type]=\'0\'
						AND [Sales Code]=\'C01448\'
						AND [Minimum Quantity]<=1 
						AND [Starting Date]<SYSDATETIME()
						AND ([Ending Date]=\'1753-01-01 00:00:00.000\' OR [Ending Date]>SYSDATETIME())) precioTarifa,
						(SELECT ISNULL(Sum(Quantity),0) stock FROM dbo.[Item Ledger Entry] WHERE [Item No.]=I.[No.]) stock,
						(SELECT ISNULL(Sum([Outstanding Quantity]),0) pendiente FROM dbo.[Ind. Campollano Ferretería S.L$Sales Line] sl WHERE [Document Type]=1 AND [Type]=2 AND [No.]=I.[No.]) pendiente,
						STUFF((SELECT \'|\' + Description FROM [Item Charge] WHERE Description <>\'\' AND Tipo=0 AND [No.]=I.[No.] FOR XML PATH(\'\'), TYPE).value(\'.\', \'nvarchar(max)\'), 1, 1, \'\') familiaWeb
					 FROM Item I Where ProductoWebINAER=1 and Blocked=0
					 
		';	
		

/*AND I.[No.]=\'0208933212\'*/
		
		$stmt = sqlsrv_query( $connNavision, $sql );
		if( $stmt === false) {
			die( print_r( sqlsrv_errors(), true) );
		}
			
		//Preparamos Array de productos en Navision
		$arrayProductosNavision=array();
		while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
			$arrayProductosNavision[$row['No.']]=$row;
		}

		//Preparamos Array de productos en Prestashop
		/*Añado la tabla fcproduct_shop porque es la que gestiona las cantidades mínimas de los pedidos*/
		/* Añado fcstock_available para gestionar que se denieguen los pedidos al llegar a cero cuando el producto esté marcado como outlet */
		
		$arrayProductosPrestashop=array();
		
		//price_web, price_tarifa
		$sql = "SELECT p.id_product, l.name, l.description descripcion, l.description_short short_descripcion, l.meta_title meta_titulo, l.meta_description meta_descripcion,  p.price, p.reference, m.name marca, p.weight peso, s.minimal_quantity cantida_minima, a.out_of_stock fuera_stock, 
				(SELECT price FROM fcspecific_price WHERE id_group = 7 AND id_product=p.id_product LIMIT 1) price_gdto1,
				(SELECT price FROM fcspecific_price WHERE id_group = 8 AND id_product=p.id_product LIMIT 1) price_gdto2,
				(SELECT price FROM fcspecific_price WHERE id_group = 6 AND id_product=p.id_product LIMIT 1) price_gdto3,		
				(SELECT quantity FROM fcstock_available WHERE id_product=p.id_product LIMIT 1) stock,
				(SELECT GROUP_CONCAT(id_category SEPARATOR ',') FROM fccategory_product WHERE id_product=p.id_product) familias		
				FROM fcproduct p
				left join fcmanufacturer m on m.id_manufacturer=p.id_manufacturer
				left join fcproduct_lang l on l.id_product=p.id_product
				left join fcfeature_product f_color on f_color.id_product=p.id_product AND f_color.id_feature=11
				left join fcfeature_product f_long on f_long.id_product=p.id_product AND f_long.id_feature=12
				left join fcproduct_shop s on s.id_product=p.id_product
				left join fcstock_available a on a.id_product=p.id_product
				WHERE p.id_product=l.id_product ORDER BY p.reference";
	  
		$stmtPrestashop = $connPrestashop->prepare($sql);
		$stmtPrestashop->execute();
		$resultPrestashop = $stmtPrestashop->get_result();
		while($rowPrestashop = $resultPrestashop->fetch_assoc()){
			$arrayProductosPrestashop[$rowPrestashop["reference"]]=$rowPrestashop;
		}

		
		
		foreach($arrayProductosNavision as $productoNavision) {
			  //$entity_id=obtenerIDProducto(($productoNavision['No.']), $connPrestashop);
			  $entity_id=obtenerIDProducto(($productoNavision['No.']), $connPrestashop);
			  $sku=($productoNavision['No.']);
 			// echo "------Nuevo producto------- \n";
		         echo "sku: ".$sku."\n";                      


			   /* 
			      nuevos valores añadidos: Cantidad Pedido Mínimo, peso y unidad medida precio, que se utilizará para los artículos que se vendan con P% 
			      Cada uno de los precios lo divido entre el valor de unidad de medida, ya que de no hacerlo, en la web
			      aparece el precio total, no de cada unidad.	
			
			  */

			 
			  $cantidad_pedido_minimo_new=($productoNavision['CantidadPedidoWeb']);
			  if($cantidad_pedido_minimo_new<1) $cantidad_pedido_minimo_new=1;				  
 			  $marca_new=($productoNavision['Cod. Marca']);
			  $peso_new=($productoNavision['Gross Weight']);
		       //   $voluminoso_new=($productoNavision['ArticuloVoluminosoWeb']);
		          if($productoNavision['Unidad medida precio']=='M') $unidad_medida_precio=1000; 
 			  else if($productoNavision['Unidad medida precio']=='C') $unidad_medida_precio=100; 
		          else $unidad_medida_precio=1;	
			  
			  $precio_PVP=($productoNavision['precio']*1)/$unidad_medida_precio;
			  $precio_GDTO1_new=($productoNavision['GDTO1']*1)/$unidad_medida_precio;
			//  echo "Precio 1: ".$precio_GDTO1_new."\n";
			  $precio_GDTO2_new=($productoNavision['GDTO2']*1)/$unidad_medida_precio;
			 // echo "Precio 2: ".$precio_GDTO2_new."\n";
			  $precio_GDTO3_new=($productoNavision['GDTO3']*1)/$unidad_medida_precio;
			 // echo "Precio 3: ".$precio_GDTO3_new."\n";
		      $precio_new=($productoNavision['GDTO3']*1)/$unidad_medida_precio;
			  //$precio_new=$productoNavision['precio']*1;
			  $precio_web_new=($productoNavision['PrecioWEB']*1)/$unidad_medida_precio;
			 // echo "Precio web: ".$precio_web_new."\n";
              // $precioDestacadoWEB_new=$productoNavision['precioDestacadoWEB']*1;
			  $precio_tarifa_new=($productoNavision['precioTarifa']*1)/$unidad_medida_precio;
			//  echo "Precio tarifa: ".$precio_tarifa_new."\n\n";
			  
			//$precio_tarifa_especial_new=($productoNavision['precioTarifaEspecial']*1)/$unidad_medida_precio;
			  //if($precio_tarifa_especial_new>1) echo "Tarifa especial: ".$precio_tarifa_especial_new."\n\n";

			
			//ajuste para poner en la web el precio por bolsa de los filtros de 3M
			$unidad_minima_venta=$productoNavision['unidad_minima_venta'];
			if($unidad_minima_venta=="DOS/PZS")
			{
				
			 $precio_PVP=(($productoNavision['precio']*1)/$unidad_medida_precio)*2;
			 $precio_GDTO1_new=(($productoNavision['GDTO1']*1)/$unidad_medida_precio)*2;
			 $precio_GDTO2_new=(($productoNavision['GDTO2']*1)/$unidad_medida_precio)*2;
			 $precio_GDTO3_new=(($productoNavision['GDTO3']*1)/$unidad_medida_precio)*2;
  		     $precio_new=(($productoNavision['GDTO3']*1)/$unidad_medida_precio)*2;
			 $precio_web_new=(($productoNavision['PrecioWEB']*1)/$unidad_medida_precio)*2;
			 $precio_tarifa_new=(($productoNavision['precioTarifa']*1)/$unidad_medida_precio)*2;
				
				
			}
			 
			else{
				
			
			 $precio_PVP=($productoNavision['precio']*1)/$unidad_medida_precio;
			 $precio_GDTO1_new=($productoNavision['GDTO1']*1)/$unidad_medida_precio;
			 $precio_GDTO2_new=($productoNavision['GDTO2']*1)/$unidad_medida_precio;
			 $precio_GDTO3_new=($productoNavision['GDTO3']*1)/$unidad_medida_precio;
  		     $precio_new=($productoNavision['GDTO3']*1)/$unidad_medida_precio;
			 $precio_web_new=($productoNavision['PrecioWEB']*1)/$unidad_medida_precio;
			 $precio_tarifa_new=($productoNavision['precioTarifa']*1)/$unidad_medida_precio;
			
			}

			
			
			
			
			
		 /*Si el producto no es de Petzl y existe precio_web y/o precio_tarifa, se actualizan los diferentes precios*/
						
			if($marca_new!="PETZL")
			{
			/*
				if($precio_web_new>0){
					
					$precio_new=$precio_web_new;
			  		$precio_GDTO1_new=$precio_web_new;
					$precio_GDTO2_new=$precio_web_new;
			  		$precio_GDTO3_new=$precio_web_new;

	      
				}
*/	
				if($precio_tarifa_new>0){
					$precio_new=$precio_tarifa_new;
			  		$precio_GDTO1_new=$precio_tarifa_new;
					$precio_GDTO2_new=$precio_tarifa_new;
			  		$precio_GDTO3_new=$precio_tarifa_new;
				 }	
			
			}


			/*Si el producto es de Petzl todo se pone con el precio PVP*/
			
			else{

			$precio_new=$precio_PVP;
			$precio_GDTO1_new=$precio_PVP;
 			$precio_GDTO2_new=$precio_PVP;
 			$precio_GDTO3_new=$precio_PVP;
		
			}



			


		  //echo "PRecio nuevo: ".$precio_new."\n\n";
		     //  if(($precio_web_new<$precio_new) && ($precio_web_new>0)) $precio_new=$precio_web_new;
			 // if(($precio_tarifa_new<$precio_new)&& ($precio_tarifa_new>0)) $precio_new=$precio_tarifa_new;

			 
			  $stock_new=round($productoNavision['stock']-$productoNavision['pendiente']);
			  
			 // echo "STock: ".$stock_new."\n\n";
			  //$pendiente=$productoNavision['pendiente_servir'];
			  //echo "Pendiente de servir: ".$pendiente."\n\n";


			  
			  $nombre_new=trim(preg_replace("[\n|\r|\n\r]","",$productoNavision['Description']));
			  //$nombre_new=utf8_decode($productoNavision['Description']);
		      $nombre_new=str_replace("p%","",$nombre_new);
		      $nombre_new=str_replace("P%","",$nombre_new);
 			  $nombre_new=str_replace("v/metro","",$nombre_new);
			  $nombre_new=str_replace(chr(160), chr(32), $nombre_new);
			  $desglose_nombre=explode(" ",$nombre_new); 
			  $primera_palabra= $desglose_nombre[0];
			  
			  $descripcion_larga_new=trim(preg_replace("[\n|\r|\n\r]","",$productoNavision['desclarga']));
		          $descripcion_corta_new=trim(preg_replace("[\n|\r|\n\r]","",$productoNavision['DescripcionCortaWEB']));
			  $descripcion_larga_new=str_replace(chr(160), chr(32), $descripcion_larga_new);
			  $descripcion_corta_new=str_replace(chr(160), chr(32), $descripcion_corta_new);
			  $metadatos_new=trim(preg_replace("[\n|\r|\n\r]","",$productoNavision['MetadatosWEB']));
			  $metadatos_new=str_replace(chr(160), chr(32), $metadatos_new);
			  $metadatos_descripcion_new=trim(preg_replace("[\n|\r|\n\r]","",$productoNavision['MetadatosDescripcionWEB']));
			  $metadatos_descripcion_new=str_replace(chr(160), chr(32), $metadatos_descripcion_new);
			  $gpoDto=($productoNavision['Item Disc. Group']);
			  //$marca_new=($productoNavision['Cod. Marca']);
                         
			  //$idgpoDto_new=altaDtoProducto($gpoDto, $att_grupo_dto_producto, $connPrestashop);
			  $novedad_new=$productoNavision['NovedadWEB']; //Poner en apartado novedad en portada 
			  $outlet_new=$productoNavision['OutlerWEB'];
			  $destacado_new=$productoNavision['DestacadoWEB']; //Poner en apartado destacado en portada
			  $noRotacion_new=$productoNavision['NoRotacion'];
			  $familiasWeb=explode('|', $productoNavision['familiaWeb']); 
			  	 
			  $control_familia=0;
			  $familias_new=array();
			  foreach($familiasWeb as $familiaWeb){

					$idPadre=obtenerIdPadre($familiaWeb, $connPrestashop);
					$anchorTextCategoria=obtenerAnchorTextCategoria($familiaWeb,$connPrestashop);	
					if($idPadre==1){
					
						$stmt = $connPrestashop->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l WHERE c.id_category=l.id_category AND l.link_rewrite='$anchorTextCategoria'");
				
					}

					else{
						$stmt = $connPrestashop->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l WHERE c.id_category=l.id_category AND l.link_rewrite='$anchorTextCategoria' AND c.id_parent='$idPadre'");							
					}

					
					$stmt->execute();
					$result = $stmt->get_result();
					$row_m = $result->fetch_assoc();
					
					$id_categoria=$row_m["categoria"];
					if($id_categoria==NULL){
					
						unset($familias_new);
						$familias_new=array();						
						break;				
					
					}
					
									
					if($id_categoria!=2)if(!array_search($id_categoria, $familias_new)){

								$id_categoria_defecto=$id_categoria;
					}
					
		

					$split_familia=explode('/',$familiaWeb);
				
					$count_array=count($split_familia);
					unset($split_familia[$count_array-1]);

	
					foreach($split_familia as $cat){
					
						$idpadre=obtenerIDPadrePadres($familiaWeb,$cat,$connPrestashop);			
						if($idpadre==1){
							$stmt = $connPrestashop->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l WHERE c.id_category=l.id_category AND l.link_rewrite='$cat'");
						}
						else{
							$stmt = $connPrestashop->prepare("SELECT c.id_category as categoria FROM fccategory c, fccategory_lang l WHERE c.id_category=l.id_category AND l.link_rewrite='$cat' AND c.id_parent='$idpadre'");							
						}

						 
	
						$stmt->execute();
						$result = $stmt->get_result();
						$row_m = $result->fetch_assoc();
						$id_categoria=$row_m["categoria"];
						
						if($id_categoria!=2){
							if(!array_search($id_categoria, $familias_new)){
							array_push($familias_new, $id_categoria);
							}
						}
						

					}//foreach
			
			if(!array_search($id_categoria_defecto, $familias_new)){
				array_push($familias_new, $id_categoria_defecto);
			}
			
			

			
			
			}//foreach

			

			if(count($familias_new)==0) array_push($familias_new, 2);
	
			
			  
			/*
			$n=1;
			foreach($familias_new as $padre){

				echo "Categoría $n: ".$padre."\n\n";
				$n++;
			}
			*/
	
			  	
				//Preparamos Array de Variantes
				$sql = 'SELECT v.[Item No.],v.Code, CONCAT(v.Description, v.[Description 2]) Description, ISNULL(Sum(l.Quantity),0) stock FROM [Item Variant] as v left join [Item Ledger Entry] as l on v.[Item No.]=l.[Item No.] and [Variant Code]=v.Code WHERE v.[Item No.]=\''.$sku.'\' group by v.[Item No.], v.Code, CONCAT(v.Description, v.[Description 2])';
				$arrayVariantes=array();
				$variantes=false;
				$stmt = sqlsrv_query( $connNavision, $sql );
				if( $stmt === false) {
					die( print_r( sqlsrv_errors(), true) );
				}	
				while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
					$arrayVariantes[$row['Code']]=$row;
					$variantes=true;
				}
				sqlsrv_free_stmt($stmt);
			  
			  
			  
			  if(isset($arrayProductosPrestashop[$sku])){
				

				 $familias_old=explode(',',$arrayProductosPrestashop[$sku]["familias"]);
				 if(count(array_diff($familias_new, $familias_old))){
					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Categorias \r\n";
					$sql = "DELETE FROM `fccategory_product` WHERE id_product=".$connPrestashop->real_escape_string($entity_id);
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					
					$default_familia=null;
					foreach($familias_new as $familia){
						$sql = "
						INSERT INTO `fccategory_product`
							(
								`id_category`,
								`id_product`,
								`position`
							)
						VALUES
							(
								".$familia.",
								".$connPrestashop->real_escape_string($entity_id).",
								2
							);
						";
				
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute();
						$default_familia=$familia;
						
						//Insertar todas las categorias padre hasta llegar a 2
						$aux_familia=$familia;
						$sql = "SELECT id_parent FROM fccategory WHERE id_category=$aux_familia";
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute();
						$resultPrestashop = $stmtPrestashop->get_result();
						$id_parent=null;
						if($rowPrestashop = $resultPrestashop->fetch_assoc()){
							$id_parent=$rowPrestashop["id_parent"];
						}
						while($id_parent!=2 && $id_parent!=null){
							$sql=
									"INSERT INTO `fccategory_product`
										(
											`id_category`,
											`id_product`,
											`position`
										)
									VALUES
										(
											".$id_parent.",
											".$connPrestashop->real_escape_string($entity_id).",
											2
										);
									";
							$stmtPrestashop = $connPrestashop->prepare($sql);
							$stmtPrestashop->execute();
							$aux_familia=$id_parent;
							$sql = "SELECT id_parent FROM fccategory WHERE id_category=$aux_familia";
							$stmtPrestashop = $connPrestashop->prepare($sql);
							$stmtPrestashop->execute();
							$resultPrestashop = $stmtPrestashop->get_result();
							$id_parent=null;
							if($rowPrestashop = $resultPrestashop->fetch_assoc()){
								$id_parent=$rowPrestashop["id_parent"];
							}
						}						
						

					}
					$sql = "UPDATE `fcproduct_shop` SET id_category_default=".$default_familia." WHERE id_product=".$connPrestashop->real_escape_string($entity_id).";";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					$sql = "UPDATE `fcproduct` SET id_category_default=".$default_familia." WHERE id_product=".$connPrestashop->real_escape_string($entity_id).";";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
				}


/*
			
				if($arrayProductosPrestashop[$sku]["marca"]!=$marca_new){
					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Marca \r\n";
					$marca_new=$connPrestashop->real_escape_string($marca_new);
					$sql = "SELECT id_manufacturer FROM fcmanufacturer WHERE name LIKE '".$marca_new."'";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					$resultPrestashop = $stmtPrestashop->get_result();
					$manufacturer_id=null;
					if($rowPrestashop = $resultPrestashop->fetch_assoc()){
						$manufacturer_id=$rowPrestashop["id_manufacturer"];
						
					}else{
						echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Creando marca \r\n";
						$sql="INSERT INTO fcmanufacturer (name, date_add, date_upd, active) VALUES('".$marca_new."', NOW(), NOW(), 1);";
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute();
						$manufacturer_id=$connPrestashop->insert_id;
						$sql="INSERT INTO fcmanufacturer_lang (id_manufacturer, id_lang) VALUES(".$manufacturer_id.", 1);";
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute();
						$sql="INSERT INTO fcmanufacturer_shop (id_manufacturer, id_shop) VALUES(".$manufacturer_id.", 1);";
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute();
					}
					
					$sql = "UPDATE `fcproduct` SET `id_manufacturer`='".$manufacturer_id."'	WHERE id_product=".$entity_id.";";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
						
				}
				
		
				if($arrayProductosPrestashop[$sku]["name"]!=$nombre_new){
					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Nombre \r\n";
					$sql = "UPDATE `fcproduct_lang` SET `name`='".$connPrestashop->real_escape_string($nombre_new)."'
						WHERE id_product=".$entity_id.";";

					$stmtPrestashop = $connPrestashop->prepare($sql);
					//echo " -> ".$sql."\r\n";
					$stmtPrestashop->execute();
				}


	
				if($arrayProductosPrestashop[$sku]["descripcion"]!=$descripcion_larga_new){
					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Descripcion \r\n";
					//$descripcion_larga_new=$connPrestashop->real_escape_string($descripcion_larga_new);
					$sql = "UPDATE `fcproduct_lang` SET `description`='".$connPrestashop->real_escape_string($descripcion_larga_new)."'
						WHERE id_product=".$entity_id.";";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					//echo "\r\n -> ".$sql."\r\n";
					$stmtPrestashop->execute();

				}



			
				if($arrayProductosPrestashop[$sku]["short_descripcion"]!=$descripcion_corta_new){
					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Descripcion corta \r\n";
					
					//$descripcion_corta_new=$connPrestashop->real_escape_string($descripcion_corta_new);
					
					$sql = "UPDATE `fcproduct_lang` SET `description_short`='".$connPrestashop->real_escape_string($descripcion_corta_new)."'
						WHERE id_product=".$entity_id.";";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					//echo "\r\n -> ".$sql."\r\n";
					$stmtPrestashop->execute();
				}


				if($arrayProductosPrestashop[$sku]["meta_titulo"]!=$metadatos_new){
					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Meta título \r\n";
					
					
					$sql = "UPDATE `fcproduct_lang` SET `meta_title`='".$connPrestashop->real_escape_string($metadatos_new)."'
						WHERE id_product=".$entity_id.";";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					//echo "\r\n -> ".$sql."\r\n";
					$stmtPrestashop->execute();
				}



			
				if($arrayProductosPrestashop[$sku]["meta_descripcion"]!=$metadatos_descripcion_new){
					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Meta descripción \r\n";
					
					
					$sql = "UPDATE `fcproduct_lang` SET `meta_description`='".$connPrestashop->real_escape_string($metadatos_descripcion_new)."'
						WHERE id_product=".$entity_id.";";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					//echo "\r\n -> ".$sql."\r\n";
					$stmtPrestashop->execute();
				}


				

				if($arrayProductosPrestashop[$sku]["peso"]!=$peso_new){
					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Peso \r\n";
					
					
					$sql = "UPDATE `fcproduct` SET `weight`='".$peso_new."'
						WHERE id_product=".$entity_id.";";
					
					$stmtPrestashop = $connPrestashop->prepare($sql);
					//echo "\r\n -> ".$sql."\r\n";
					$stmtPrestashop->execute();

*/
/*

				if($arrayProductosPrestashop[$sku]["voluminoso"]!=$voluminoso_new){
					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Producto Voluminoso \r\n";
					
					
					$sql = "UPDATE `fcproduct` SET `voluminoso`='".$voluminoso_new."'
						WHERE id_product=".$entity_id.";";
					
					$stmtPrestashop = $connPrestashop->prepare($sql);
					//echo "\r\n -> ".$sql."\r\n";
					$stmtPrestashop->execute();


					$sql = "UPDATE `fcproduct_shop` SET `voluminoso`='".$voluminoso_new."'
						WHERE id_product=".$entity_id.";";
					
					$stmtPrestashop = $connPrestashop->prepare($sql);
					//echo "\r\n -> ".$sql."\r\n";
					$stmtPrestashop->execute();




				
				}
	*/			
				
				if($outlet_new==1 and $arrayProductosPrestashop[$sku]["fuera_stock"]!=0){

					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Outlet \r\n";
					
					
					$sql = "UPDATE `fcstock_available` SET `out_of_stock`='0'
						WHERE id_product=".$entity_id.";";
					
					$stmtPrestashop = $connPrestashop->prepare($sql);
					//echo "\r\n -> ".$sql."\r\n";
					$stmtPrestashop->execute();



				
				}
			
			
			//esta cuerda se vende en bobinas completas de 100m en nuestra web, pero interesa venderse a Babcock por 10m. Metemos por tanto este filtro
			if($productoNavision['No.']=="15CPP10") $cantidad_pedido_minimo_new=10;

			if(round($arrayProductosPrestashop[$sku]["cantida_minima"])!=round($cantidad_pedido_minimo_new)){
					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Cantidad pedido mínimo \r\n";
					
					$sql = "UPDATE `fcproduct_shop` SET `minimal_quantity`='".$cantidad_pedido_minimo_new."'
						WHERE id_product=".$entity_id.";";
					
					$stmtPrestashop = $connPrestashop->prepare($sql);
					//echo "\r\n -> ".$sql."\r\n";
					$stmtPrestashop->execute();
				
				}
				



		if($precio_PVP!=0){

					if(round($arrayProductosPrestashop[$sku]["price"]*1,5)!=round($precio_new,5)){
						echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Precio \r\n"; 
						$sql = "UPDATE `fcproduct_shop` SET price=".round($precio_new,5)."
							WHERE id_product=".$entity_id.";";
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute(); 
					
						$sql = "UPDATE `fcproduct` SET price=".round($precio_new,5)."
							WHERE id_product=".$entity_id.";";
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute(); 
					}
					
					if(round($arrayProductosPrestashop[$sku]["price_gdto1"]*1,5)!=round($precio_GDTO1_new,5)){
						echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Precio gdto1 ".$arrayProductosPrestashop[$sku]["price_gdto1"]." - ".$precio_GDTO1_new."\r\n"; 
						$sql = "UPDATE `fcspecific_price` SET price=".round($precio_GDTO1_new,5)." WHERE id_group=7 AND from_quantity=1 AND 
							id_product=".$entity_id.";";
						$stmtPrestashop = $connPrestashop->prepare($sql);
						//echo " -> ".$sql."\r\n";
						$stmtPrestashop->execute(); 
					}
					
					if(round($arrayProductosPrestashop[$sku]["price_gdto2"]*1,5)!=round($precio_GDTO2_new,5)){
						echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Precio gdto2 ".$arrayProductosPrestashop[$sku]["price_gdto2"]." - ".$precio_GDTO2_new."\r\n"; 
						$sql = "UPDATE `fcspecific_price` SET price=".round($precio_GDTO2_new,5)." WHERE id_group=8 AND from_quantity=1 AND 
							id_product=".$entity_id.";";
						
						$stmtPrestashop = $connPrestashop->prepare($sql);
						//echo " -> ".$sql."\r\n";
						$stmtPrestashop->execute(); 
					}
					
					if(round($arrayProductosPrestashop[$sku]["price_gdto3"]*1,5)!=round($precio_GDTO3_new,5)){
						echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Precio gdto3 ".$arrayProductosPrestashop[$sku]["price_gdto3"]." - ".$precio_GDTO3_new."\r\n"; 
						$sql = "UPDATE `fcspecific_price` SET price=".round($precio_GDTO3_new,5)." WHERE id_group=6 AND from_quantity=1 AND 
							id_product=".$entity_id.";";
						
						$stmtPrestashop = $connPrestashop->prepare($sql);
						//echo " -> ".$sql."\r\n";
						$stmtPrestashop->execute(); 
					}
				
				}
				
				if($variantes && ($productoNavision['TipoAgrupWEB']!=null)){
					//Verificamos si existe el grupo de atributos
					$sql="SELECT g.id_attribute_group, l.name FROM fcattribute_group g, fcattribute_group_lang l WHERE g.id_attribute_group=l.id_attribute_group AND l.name LIKE '%".$productoNavision['TipoAgrupWEB']."%'";
					$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute();
						$resultPrestashop = $stmtPrestashop->get_result();
						$attribute_group_id=null;
						if($rowPrestashop = $resultPrestashop->fetch_assoc()){
							$attribute_group_id=$rowPrestashop["id_attribute_group"];
						}else{
							//Creamos el atributos
							echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Creando grupo de atributos \r\n";
							$sql="INSERT INTO fcattribute_group (is_color_group, group_type) VALUES (0, 'select');";
							$stmtPrestashop = $connPrestashop->prepare($sql);
							$stmtPrestashop->execute();
							$attribute_group_id=$connPrestashop->insert_id;
							$sql="INSERT INTO fcattribute_group (id_attribute_group, id_lang, name, public_name) VALUES ($attribute_group_id, 1, '".$connPrestashop->real_escape_string($productoNavision['TipoAgrupWEB'])."', '".$connPrestashop->real_escape_string($productoNavision['TipoAgrupWEB'])."');";
							$stmtPrestashop = $connPrestashop->prepare($sql);
							$stmtPrestashop->execute();
							$sql="INSERT INTO fcattribute_group_shop (id_attribute_group, id_shop) VALUES ($attribute_group_id, 1);";
							$stmtPrestashop = $connPrestashop->prepare($sql);
							$stmtPrestashop->execute();
						}

					//Verificamos si existen las variantes
					$stock_global=0;
					foreach($arrayVariantes as $variante){
						$sql="SELECT a.id_attribute FROM fcattribute a, fcattribute_lang l WHERE a.id_attribute=l.id_attribute AND  l.name='".$variante["Code"]."'";
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute();
						$resultPrestashop = $stmtPrestashop->get_result();
						$attribute_id=null;
						if($rowPrestashop = $resultPrestashop->fetch_assoc()){
							$attribute_id=$rowPrestashop["id_attribute"];
						}else{
							//Creamos el atributos
							echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Creando variante \r\n";
							$sql="INSERT INTO fcattribute (id_attribute_group) VALUES($attribute_group_id);";
							$stmtPrestashop = $connPrestashop->prepare($sql);
							$stmtPrestashop->execute();
							$attribute_id=$connPrestashop->insert_id;
							$sql="INSERT INTO fcattribute_lang (id_attribute, id_lang, name) VALUES($attribute_id, 1, '".$connPrestashop->real_escape_string($variante["Code"])."');";
							$stmtPrestashop = $connPrestashop->prepare($sql);
							$stmtPrestashop->execute();
							$sql="INSERT INTO fcattribute_shop (id_attribute, id_shop) VALUES ($attribute_id, 1);";
							$stmtPrestashop = $connPrestashop->prepare($sql);
							$stmtPrestashop->execute();
						}
						//Verificamos si existe la relacion producto-atributos
						$sql="SELECT a.id_product_attribute FROM fcproduct_attribute a, fcproduct_attribute_combination c, fcproduct p WHERE a.id_product_attribute=c.id_product_attribute AND a.id_product=p.id_product AND p.id_product=$entity_id AND id_attribute=$attribute_id";
						//echo $sql;
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute();
						$resultPrestashop = $stmtPrestashop->get_result();
						$attribute_product_id=null;
						if($rowPrestashop = $resultPrestashop->fetch_assoc()){
							$attribute_product_id=$rowPrestashop["id_product_attribute"];
						}else{
							//Creamos el atributos
							echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Creando variante-product \r\n";
							$sql="INSERT INTO fcproduct_attribute (id_product,quantity) VALUES(".$arrayProductosPrestashop[$sku]["id_product"].", 0);";
							$stmtPrestashop = $connPrestashop->prepare($sql);
							$stmtPrestashop->execute();
							$attribute_product_id=$connPrestashop->insert_id;
							$sql="INSERT INTO fcproduct_attribute_shop (id_product, id_product_attribute, id_shop) VALUES(".$arrayProductosPrestashop[$sku]["id_product"].", $attribute_product_id, 1);";
							$stmtPrestashop = $connPrestashop->prepare($sql);
							$stmtPrestashop->execute();
							$sql="INSERT INTO fcproduct_attribute_combination (id_attribute, id_product_attribute) VALUES ($attribute_id, $attribute_product_id);";
							$stmtPrestashop = $connPrestashop->prepare($sql);
							$stmtPrestashop->execute();
						}
						
						
						$sql="SELECT id_stock_available FROM fcstock_available WHERE id_product=$entity_id AND id_product_attribute=$attribute_product_id";
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute();
						$resultPrestashop = $stmtPrestashop->get_result();
						$stock_available_id=null;
						if($rowPrestashop = $resultPrestashop->fetch_assoc()){
							$stock_available_id=$rowPrestashop["id_stock_available"];
						}else{
							//Creamos el atributos
							echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Creando stock variante-product \r\n";
							$sql="INSERT INTO fcstock_available (id_product, id_product_attribute, id_shop, id_shop_group) VALUES($entity_id, $attribute_product_id,1,0);";
							//echo $sql;
							$stmtPrestashop = $connPrestashop->prepare($sql);
							$stmtPrestashop->execute();
							$stock_available_id=$connPrestashop->insert_id;
						}
						$sql = "UPDATE `fcstock_available` SET quantity=".$variante["stock"]." WHERE id_stock_available=$stock_available_id;";
						$stock_global+=$variante["stock"];
						$stmtPrestashop = $connPrestashop->prepare($sql);
						//echo $sql;
						$stmtPrestashop->execute();
					}
						echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Stock \r\n";
						$sql = "UPDATE `fcstock_available` SET quantity=".$stock_global."
							WHERE id_product=".$entity_id." and id_product_attribute=0;;";
						
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute(); 
					
				}else{
					//Metodos especificos de los productos sin variantes
					
					if($arrayProductosPrestashop[$sku]["stock"]!=$stock_new){
						echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Stock \r\n";
						$sql = "UPDATE `fcstock_available` SET quantity=".$stock_new."
							WHERE id_product=".$entity_id." and id_product_attribute=0;";
						
						$stmtPrestashop = $connPrestashop->prepare($sql);
						//echo " -> ".$sql."\r\n";
						$stmtPrestashop->execute(); 
					}
					
				}
				
				
						  
			  }else{
				  //Creamos el producto
				echo "\t\t=> CREANDO ".utf8_encode($productoNavision['No.'])."\r\n";
				
				$connPrestashop->begin_transaction();
				
				$sql = "
						INSERT INTO	`fcproduct`
							(
								`id_supplier`,
								`id_manufacturer`,
								`id_category_default`,
								`id_shop_default`,
								`id_tax_rules_group`,
								`ean13`,
								`upc`,
								`quantity`,
								`price`,
								`reference`,
								`active`,
								`redirect_type`,
								`date_add`,
								`date_upd`,
								`weight`
							)
						VALUES
							(
								null,
								null,
								null,
								1,
								1,
								null,
								null,
								".$stock_new.",
								".round($precio_new,5).",
								'".$sku."',
								1,
								'404',
								NOW(),
								NOW(),
								".$peso_new."
				);";
				//echo $sql;
				$stmtPrestashop = $connPrestashop->prepare($sql);
				$stmtPrestashop->execute();
				$entity_id=$connPrestashop->insert_id;
				  
				$sql = "
					INSERT INTO `fcproduct_lang`
						(
							`id_product`,
							`id_shop`,
							`id_lang`,
							`description`,
							`description_short`,
							`link_rewrite`,
							`meta_description`,
							`meta_keywords`,
							`meta_title`,
							`name`,
							`available_now`,
							`available_later`
						)
					VALUES
						(
							".$connPrestashop->real_escape_string($entity_id).",
							1,
							1,
							'".$descripcion_larga_new."',
							'".$connPrestashop->real_escape_string($descripcion_corta_new)."',
							'".$connPrestashop->real_escape_string(Slug($nombre_new))."',
							'".$connPrestashop->real_escape_string($metadatos_descripcion_new)."',
							'".$connPrestashop->real_escape_string('')."',
							'".$connPrestashop->real_escape_string($metadatos_new)."',
							'".$connPrestashop->real_escape_string($nombre_new)."',
							'En stock',
							'Sin stock'
					);";
					

					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					
					
					$sql = "
						INSERT INTO `fcproduct_shop`
							(
								`id_product`,
								`id_shop`,
								`id_category_default`,
								`id_tax_rules_group`,
								`on_sale`,
								`price`,
								`active`,
								`redirect_type`,
								`date_add`,
								`date_upd`,
								`minimal_quantity`
							)
						VALUES
							(
								".$connPrestashop->real_escape_string($entity_id).",
								1,
								null,
								1,
								0,
								".round($precio_new,5).",
								1,
								'".$connPrestashop->real_escape_string('404')."',
								NOW(),
								NOW(),
								".$cantidad_pedido_minimo_new."
								
							);
					";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					if($outlet_new==1) $outofstock=0;
					else $outofstock=2;
					
					$sql = "
						
							INSERT INTO `fcstock_available`
								(
									`id_stock_available`,
									`id_product`,
									`id_product_attribute`,
									`id_shop`,
									`id_shop_group`,
									`quantity`,
									`depends_on_stock`,
									`out_of_stock`
								)
							VALUES
								(
									null,
									".$connPrestashop->real_escape_string($entity_id).",
									0,
									1,
									0,
									".$stock_new.",
									0,
									".$outofstock."
								);
						
						";
					
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					
					
					//Precios Especificos
					$sql = "
							INSERT INTO `fcspecific_price` 
								(
									`id_specific_price_rule`,
									`id_cart`,
									`id_product`,
									`id_shop`,
									`id_shop_group`,
									`id_currency`,
									`id_country`,
									`id_group`,
									`id_customer`, 
									`id_product_attribute`,
									`price`,
									`from_quantity`,
									`reduction`,
									`reduction_tax`,
									`reduction_type`,
									`from`,
									`to` 
								)VALUES(
									0,
									0,
									".$connPrestashop->real_escape_string($entity_id).",
									1,
									0,
									0,
									0,
									7,
									0,
									0,
									".round($precio_GDTO1_new,5).",
									1,
									0,
									1,
									'amount',
									'0000-00-00 00:00:00',
									'0000-00-00 00:00:00'				
								);";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					
					
					$sql = "
							INSERT INTO `fcspecific_price` 
								(
									`id_specific_price_rule`,
									`id_cart`,
									`id_product`,
									`id_shop`,
									`id_shop_group`,
									`id_currency`,
									`id_country`,
									`id_group`,
									`id_customer`, 
									`id_product_attribute`,
									`price`,
									`from_quantity`,
									`reduction`,
									`reduction_tax`,
									`reduction_type`,
									`from`,
									`to` 
								)VALUES(
									0,
									0,
									".$connPrestashop->real_escape_string($entity_id).",
									1,
									0,
									0,
									0,
									8,
									0,
									0,
									".round($precio_GDTO2_new,5).",
									1,
									0,
									1,
									'amount',
									'0000-00-00 00:00:00',
									'0000-00-00 00:00:00'				
								);";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					
					$sql = "
							INSERT INTO `fcspecific_price` 
								(
									`id_specific_price_rule`,
									`id_cart`,
									`id_product`,
									`id_shop`,
									`id_shop_group`,
									`id_currency`,
									`id_country`,
									`id_group`,
									`id_customer`, 
									`id_product_attribute`,
									`price`,
									`from_quantity`,
									`reduction`,
									`reduction_tax`,
									`reduction_type`,
									`from`,
									`to` 
								)VALUES(
									0,
									0,
									".$connPrestashop->real_escape_string($entity_id).",
									1,
									0,
									0,
									0,
									6,
									0,
									0,
									".round($precio_GDTO3_new,5).",
									1,
									0,
									1,
									'amount',
									'0000-00-00 00:00:00',
									'0000-00-00 00:00:00'				
								);";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					$connPrestashop->commit();
					
					
					
					

					$default_familia=null;
					foreach($familias_new as $familia){
						$sql = "
						INSERT INTO `fccategory_product`
							(
								`id_category`,
								`id_product`,
								`position`
							)
						VALUES
							(
								".$familia.",
								".$connPrestashop->real_escape_string($entity_id).",
								2
							);
						";
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute();
						$default_familia=$familia;
					}
					$sql = "UPDATE `fcproduct_shop` SET id_category_default=".$default_familia." WHERE id_product=".$connPrestashop->real_escape_string($entity_id).";";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					$sql = "UPDATE `fcproduct` SET id_category_default=".$default_familia." WHERE id_product=".$connPrestashop->real_escape_string($entity_id).";";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					
					
					
					//*********GESTION DE ETIQUETAS****************//
				
				//consulto si existe ya la etiqueta asociada a la primera palabra del producto
				$sql = "SELECT id_tag FROM fctag WHERE name='".$primera_palabra."'";
				$stmtPrestashop = $connPrestashop->prepare($sql);
				$stmtPrestashop->execute();
				$resultPrestashop = $stmtPrestashop->get_result();
				
				//si no existe la etiqueta la creamos
				if(!($rowPrestashop = $resultPrestashop->fetch_assoc())){
						//echo "No existe la etiqueta ".$primera_palabra."\n";
						$sql = "INSERT INTO `fctag`	(`id_tag`,`id_lang`,`name`)	VALUES (NULL,1,'".$primera_palabra."');";
						
						echo $sql."\n";
				
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute();
							
				}
				
				//si existe la etiqueta, comprobarmos si va asociada al producto y si no la asociamos
				else{
					
					$id_tag_existente=$rowPrestashop["id_tag"];
					/*
					$sql = "SELECT * FROM fcproduct_tag WHERE id_tag=".$id_tag_existente." AND id_product=".$entity_id.";";
					//echo $sql."\n";
					
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					$resultPrestashop = $stmtPrestashop->get_result();
								
					
					*/
					
					//el producto no tiene asociada la etiqueta
					
				//	if(!($rowPrestashop = $resultPrestashop->fetch_assoc())){						
						
					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Etiqueta asociada al producto \r\n";
					$sql = "INSERT INTO `fcproduct_tag`	(`id_product`,`id_tag`,`id_lang`) VALUES (".$entity_id.",".$id_tag_existente.",1);";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();

					//}
					
		
					
				}
				
				//consulto si existe ya la etiqueta asociada a la MARCA del producto
				$sql = "SELECT id_tag FROM fctag WHERE name='".$marca_new."'";
				$stmtPrestashop = $connPrestashop->prepare($sql);
				$stmtPrestashop->execute();
				$resultPrestashop = $stmtPrestashop->get_result();
				
				
				
				//si no existe la etiqueta de la MARCA la creamos
				if(!($rowPrestashop = $resultPrestashop->fetch_assoc())){
					//	echo "No existe la etiqueta de la marca ".$marca_new."\n";
						$sql = "INSERT INTO `fctag`	(`id_tag`,`id_lang`,`name`)	VALUES (NULL,1,'".$marca_new."');";
									
						$stmtPrestashop = $connPrestashop->prepare($sql);
						$stmtPrestashop->execute();
							
				}
				
				
				//si existe la etiqueta de la MARCA la asociamos
				else{
					
					$id_tag_marca=$rowPrestashop["id_tag"];
					
					//$sql = "SELECT * FROM fcproduct_tag WHERE id_tag=".$id_tag_marca." AND id_product=".$entity_id.";";
					//echo $sql."\n";
					
					//$stmtPrestashop = $connPrestashop->prepare($sql);
					//$stmtPrestashop->execute();
					//$resultPrestashop = $stmtPrestashop->get_result();
								
					
					
					
					//el producto no tiene asociada la etiqueta de MARCA
					
					///if(!($rowPrestashop = $resultPrestashop->fetch_assoc())){						
					echo "\t\t=> ".utf8_encode($productoNavision['No.'])." > Etiqueta de MARCA asociada al producto \r\n";
					$sql = "INSERT INTO `fcproduct_tag`	(`id_product`,`id_tag`,`id_lang`) VALUES (".$entity_id.",".$id_tag_marca.",1);";		
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();

					/*}*/
				}
					
							
				
			}
		}
		$connPrestashop->close();
		echo " \r\n \r\nDurmiendo \r\n"; 
		sleep(900); //15 minutos
		
}

