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

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 mssql_escape($str)
{
    if(get_magic_quotes_gpc())
    {
        $str= stripslashes($str);
    }
    return str_replace("'", "''", $str);
}


$connPrestashop = new mysqli($bdd_servidor, $bdd_usuario, $bdd_contrasena, $bdd_base_datos);
	if( $connPrestashop ) {
			 echo "Conexion establecida con Prestashop <br>";
	}else{
			 echo "Conexion no se pudo establecer con Prestashop.<br>";
			 die( print_r( sqlsrv_errors(), true));
}
$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 "Conexion establecida con Navision.\r\n";
	}else{
		 //echo "Conexion no se pudo establecer con Navision.\r\n";
		 die( print_r( sqlsrv_errors(), true));
	}


		$sql = 'SELECT 
				I.[No.], 
				R.[Cross-Reference No.]
				FROM Item I 
				LEFT JOIN dbo."Item Cross Reference" R
				ON R.[Item No.]=I.[No.] AND R.[Cross-Reference Type No.]=I.[Vendor No.] 
				WHERE I.[ProductoWEB]=1 AND [Cod. Marca]=\'SPEEDGLAS\' AND R.[Cross-Reference Type]=2 AND [Cross-Reference Type No.]=\'P00820\'';

		
		$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
		/*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();
		
	
		$sql = "SELECT p.id_product, p.reference, p.supplier_reference	
				FROM fcproduct p
				ORDER BY p.reference";
	  
		$stmtPrestashop = $connPrestashop->prepare($sql);
		$stmtPrestashop->execute();
		$resultPrestashop = $stmtPrestashop->get_result();
		while($rowPrestashop = $resultPrestashop->fetch_assoc()){
			$arrayProductosPrestashop[$rowPrestashop["reference"]]=$rowPrestashop;
		}

		
		foreach($arrayProductosPrestashop as $productoPrestashop) {
			
			$sku=($productoPrestashop['reference']);
			if(isset($arrayProductosNavision[$sku]['Cross-Reference No.']))
			{
				$supplier_reference=$arrayProductosNavision[$sku]['Cross-Reference No.'];
				if($productoPrestashop["supplier_reference"]!=$supplier_reference){
					echo "\t\t=> ".utf8_encode($productoPrestashop['reference'])." > Referencia del proveedor <br>";
					$sql = "UPDATE `fcproduct` SET `supplier_reference`='".$connPrestashop->real_escape_string($supplier_reference)."'
							WHERE id_product=".$productoPrestashop['id_product'].";";
					$stmtPrestashop = $connPrestashop->prepare($sql);
					$stmtPrestashop->execute();
					$needUpdate=true;
					}
			}
		}
		$connPrestashop->close();
		echo " \r\n \r\Finalizado \r\n"; 
?>
