<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '2G');
date_default_timezone_set('Europe/Madrid');
if(isset($_REQUEST["customer"])) 
	$customer=$_REQUEST["customer"]; 

if($customer==null) die;
$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++;
}
	$objects=[];

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

	//Obtenemos los precios de venta especificos
	//SQL Completa para depuracion
	/*$sql='SELECT 
	s.[Item No.] code,
	CONCAT(i.[Description],i.[Description 2]) name,
	s.[Sales Type] type,
	s.[Sales Code] salescode, 
	s.[Starting Date] startingdate,
	s.[Ending Date] endingdate,
	s.[Unit price UM precio] price,
	s.[Minimum Quantity] quantity
	FROM [Ind. Campollano Ferretería S.L$Sales Price] s
	LEFT JOIN [ICF].[dbo].[Item] i ON s.[Item No.] = i.[No.] 
	WHERE (s.[Sales Type]=0 OR s.[Sales Type]=2) AND [Sales Code]=\''.$customer.'\' 
	AND (s.[Ending Date]=\'1753-01-01 00:00:00.000\' OR s.[Ending Date]>=GETDATE())
	AND s.[Starting Date] <= GETDATE()';*/
	
	//SQL minima para producción
	$sql='SELECT 
	s.[Item No.] code,
	s.[Unit Price] price,
	i.[Last Direct Cost] cost,
	s.[Minimum Quantity] quantity
	FROM [Ind. Campollano Ferretería S.L$Sales Price] s
	LEFT JOIN [ICF].[dbo].[Item] i ON s.[Item No.] = i.[No.] 
	WHERE (s.[Sales Type]=0 OR s.[Sales Type]=2) AND [Sales Code]=\''.$customer.'\' 
	AND (s.[Ending Date]=\'1753-01-01 00:00:00.000\' OR s.[Ending Date]>=GETDATE())
	AND s.[Starting Date] <= GETDATE()';

	$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 pudieron obtener los precios especificos de los clientes de Sistemas de Gestión Logística"));
			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;
					if($key=="price") $temp_object["price"] = round($temp_object["price"]*1,4);
					if($key=="quantity") $temp_object["quantity"] = round($temp_object["quantity"]*1);
					if($key=="cost") $temp_object["cost"] = round($temp_object["cost"]*1,4);
					
					
					
					
				}
				
				$objects[]=$temp_object;
			}
		}

echo json_encode($objects, JSON_PRETTY_PRINT);
?>