<?php
	error_reporting(E_ALL);
	ini_set('display_errors', 1);
	date_default_timezone_set('Europe/Madrid');

	// Parámetros
	$discordchannel	= "883046233017552956";
	$serverName 	= "localhost";
	$connectionInfo = array( "Database"=>"ICF", "UID"=>"VAIO", "PWD"=>"VAIO");

	// Conexión con Navision
	$connNavision=false;
	$retries=0;
	while(!$connNavision && $retries<3){
		$connNavision = sqlsrv_connect( $serverName, $connectionInfo);
		$retries++;
	}

	if($connNavision) {
		 //echo "Conexion establecida con Navision.\r\n";
	}else{
		file_get_contents("https://icfbot.ferreteriacampollano.com/message.php?channel=".$discordchannel."&msg=".urlencode(":sos:"."SCRIPT ".basename(__FILE__, '.php').": No se pudo establecer la conexion con Navision"));
		echo json_encode(["result"=>-1 , "text"=>"No se pudo conectar con Navision"]);
		die;
	}

	$result = [];

	// Obtención de los productos que han cambiado
	$sql = "SELECT 
		codigo_antiguo as product_code,
		codigo_nuevo as quantity
		FROM [navisionChanges]
		WHERE entidad='ITEMENTRY' 
		ORDER BY fecha asc";

	$stmt_changes = sqlsrv_query( $connNavision, $sql);
	if(sqlsrv_errors(SQLSRV_ERR_ERRORS)!==NULL) {
		echo json_encode(["result"=>-2, "text"=>"Ocurrio un error en la consulta SQL de Navision"]);
		file_get_contents("https://icfbot.ferreteriacampollano.com/message.php?channel=".$discordchannel."&msg=".urlencode(":sos:"."SCRIPT ".basename(__FILE__, '.php').": No se pudo obtener la lista de albaranes de compra de Navision que han cambiado"));
		die;
	}
	
	/* Logica antigua que se hacia por albaran de entrada y por pedido
	if($stmt_changes !== false){
		while($row = sqlsrv_fetch_array($stmt_changes, SQLSRV_FETCH_ASSOC)){		
			$cambio_object=[];
			foreach($row as $key=>$object){
				$cambio_object[$key]=!is_object($object)?utf8_encode($object):$object;
			}	
			if (isset($cambio_object['deliveryNote_code'])){
				$sBuyDeliveryNote_code = trim($cambio_object['deliveryNote_code']);			
				// Se obtienen las lineas de cada albarán
				$sql = "SELECT 
					[Order No.] as orderid,
					[No.] as product_code,
					[Variant Code] as variant_name,
					[Quantity] as quantity,
					[Location Code] as location_code
					FROM [".'Ind. Campollano Ferretería S.L$Purch. Rcpt. Line]'."
					WHERE [Document No.]='$sBuyDeliveryNote_code' 
					ORDER BY [Line No.] asc";
				$stmt_lines = sqlsrv_query($connNavision, $sql);
				if(sqlsrv_errors(SQLSRV_ERR_ERRORS)!==NULL){
					print_r(sqlsrv_errors(SQLSRV_ERR_ERRORS));
					echo json_encode(["result"=>-3, "text"=>"Ocurrio un error en la consulta SQL de Navision de obtencion de líneas de albarán de compra"]);
					file_get_contents("https://icfbot.ferreteriacampollano.com/message.php?channel=".$discordchannel."&msg=".urlencode(":sos:"."SCRIPT ".basename(__FILE__, '.php').": No se pudo obtener la lista de transferencias de Navision que han cambiado"));
					die;
				}
				if($stmt_lines !== false){
					$orders = [];
					while($row2 = sqlsrv_fetch_array($stmt_lines, SQLSRV_FETCH_ASSOC)){		
						$line=[];
						foreach($row2 as $key=>$object){
							$line[$key]=!is_object($object)?utf8_encode($object):$object;
						}
						$orderid = $line['orderid'];
						if (!isset($orders[$orderid]))
							$orders[$orderid] = [];
						unset($line['orderid']);
						$orders[$orderid][] = $line;
					}
					$result[$sBuyDeliveryNote_code] = $orders;
				}
			}
		}
	}
	*/
	
	//Nueva lógica		
		if($stmt_changes !== false){
			while($row = sqlsrv_fetch_array($stmt_changes, SQLSRV_FETCH_ASSOC)){					
				$aLine = [];
				foreach($row as $key=>$object){
					$aLine[$key] = !is_object($object)?utf8_encode($object):$object;
				}
				$result[] = $aLine;
			}				
		}
	//

	header('Content-Type: application/json');
	echo json_encode($result, JSON_PRETTY_PRINT);
?>
