<?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 tr
		FROM [navisionChanges]
		WHERE entidad='TRANSFERS' 
		ORDER BY fecha asc";

$stmt_changes = sqlsrv_query( $connNavision, $sql);
if(sqlsrv_errors(SQLSRV_ERR_ERRORS)!==NULL) {
	echo json_encode(["result"=>-2, "text"=>"1 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 transferencias de Navision que han cambiado"));
	die;
}
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['tr'])){
			$transfer = trim($cambio_object['tr']);			
			// Se obtienen las lineas de cada traspaso
			$sql = "SELECT 
					[Item No.] as product_code,
					[Variant Code] as variant,
					[Quantity] as quantity,
					[Transfer-to Code] store_destination
					FROM [".'Ind. Campollano Ferretería S.L$Transfer Shipment Line]'."
					WHERE [Transfer Order No.]='$transfer' 
					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 lineas de traspaso"]);
				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) {
				$lines = [];
				while($row2 = sqlsrv_fetch_array( $stmt_lines, SQLSRV_FETCH_ASSOC)){		
					$cambio_line=[];
					foreach($row2 as $key=>$object){
						$cambio_line[$key]=!is_object($object)?utf8_encode($object):$object;
					}	
					$lines[] = $cambio_line;
				}
				$result[$transfer] = $lines;
			}
		}
	}
}

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