<?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");
$deleteProductsChange = [];
if(isset($_REQUEST["deleteProductsChange"])) 
	$deleteProductsChange=json_decode($_REQUEST["deleteProductsChange"],true); 

// 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"=>-11 , "text"=>"No se pudo conectar con Navision"]);
	  die;
}

$result		= [];

foreach($deleteProductsChange as $key=>$change_object){
	// Borrado del cambio
	$sql = "DELETE FROM [navisionChanges] WHERE entidad='ITEM' AND accion='".$change_object['accion']."' AND REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(codigo_antiguo)), ' ',''),'''',''), CHAR(9), ''), CHAR(10), ''), CHAR(13), ''), CHAR(160), '')='".$change_object['codigo_antiguo']."' AND REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(codigo_nuevo)), ' ',''),'''',''), CHAR(9), ''), CHAR(10), ''), CHAR(13), ''), CHAR(160), '')='".$change_object['codigo_nuevo']."'";
	$stmt_delete_changes = sqlsrv_query( $connNavision, $sql);
	if(sqlsrv_errors(SQLSRV_ERR_ERRORS)!==NULL) {
		echo json_encode(["result"=>-12, "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 borrar la lista de cambios de productos"));
		die;
	}
}

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