<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//ini_set('memory_limit', '2048M');
date_default_timezone_set('Europe/Madrid');
//include("conexion.php");
if(isset($_REQUEST["from"])) //Formato linux timestamp
	$from=$_REQUEST["from"]; else $from=0;
//$from=date('d/m/Y', $from);
$discordchannel="883046233017552956";
$resultProducts=[];

function mssql_escape($str)
{
    if(get_magic_quotes_gpc())
    {
        $str= stripslashes($str);
    }
    return str_replace("'", "''", $str);
}

$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{
		  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;
	}

		$objects=[];
		$prueba=[];
		
		//GET MAX TIMESTAMP
		$maxtimestamp=0;
		$sql = 'SELECT CAST(MAX(TIMESTAMP) AS BIGINT) timestamp FROM [Item]';
		$stmt = sqlsrv_query( $connNavision, $sql );
		if( $stmt !== false) {
			if($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
				$maxtimestamp=$row['timestamp'];
			}
		}
		
		$sql = 'SELECT 
				[No.] code,
				CONCAT([Description], [Description 2]) Description, 
				[Coste de Tarifa Compra] ShoppingPrice,
				[Vendor No.] Supplier, 
				[Gross Weight] Weight, 
				[Minimum Order Quantity] minimumquantityofbuy, 
				[Order Multiple] multiplicity, 
				[Include Inventory] rotation, 
				CONCAT([Item Category Code], [Product Group Code]) category, 
				[Blocked],
				[Cod. Marca] Manufacturer,
				[ProductoWEB],
				[Unidad medida precio]
				FROM [Item]
				WHERE CAST(TIMESTAMP AS BIGINT)>'.$from;

		$stmt = 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 obtener la información de los productos"));
			die;
		}
		if( $stmt !== false) {
			while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
				
				$temp=[];
				foreach($row as $key=>$object){
					$temp_object[$key]=!is_object($object)?utf8_encode($object):$object;
				}
				
				$objects[]=$temp_object;
			}
		}
		//var_dump($objects);
		$prueba["maxtimestamp"]=$maxtimestamp;
		$prueba["class"]=$objects;
		$result[]=$prueba;
header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT);

?>
