<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$discordchannel="883046233017552956";

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

$result 					= [];
$result['products_prices'] 	= [];
$result['increments'] 		= [];
// Productos de la categorķa
$products = [];
if (isset($_REQUEST["products"])) 
	$products=json_decode($_REQUEST["products"],true);
if (is_array($products) && count($products)){
	for($i=0; $i<count($products); $i++){
		$product = $products[$i]['code'];
		$result['products_prices'][$product] = [];
		// Por cada producto se saca el incremento por clientes
		$increment 	= null;
		$prices		= [];
		$sql='SELECT i.[Precio Neto Compra UM Precio] AS price, d.[Line Discount %] AS discount, (case when i.[Unidad medida precio]=\'C\' then i.[Unit Price]*100  when i.[Unidad medida precio]=\'M\' then i.[Unit Price]*1000 else i.[Unit Price] end) as pvpr, i.[Precio venta UM Precio] as pvp, d.[Sales Code] as customer, d.[Starting Date] as start, d.[Ending Date] as ending, d.[Code] as groupdto FROM dbo.[Item] i
				LEFT JOIN [Ind. Campollano Ferreterķa S.L$Sales Line Discount] d ON d.[Code]=i.[Item Disc. Group]
					WHERE i.[No.]=\''.$product.'\' and d.[Sales Type]=\'0\' and d.[Sales Code]<>\'\' and d.[Code]<>\'\' and i.[Blocked]=0 and i.[Discontinuado]=0';
					
		$stmt = sqlsrv_query( $connNavision, $sql );
		if( $stmt !== false) {				
			while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
				foreach($row as $key=>$object)
					$prices[$key]=!is_object($object)?utf8_encode($object):$object;					
				if (count($prices)==8){			
					$price 		= $prices['price'];
					$discount 	= $prices['discount'];
					$pvpr 		= $prices['pvpr'];
					$pvp 		= $prices['pvp'];
					//$group 		= preg_replace("/[^A-Za-z0-9.!?]/",'',$prices['groupdto']);
					$customer 	= $prices['customer'];
					if ($customer=='C01034' || $customer=='C01832' || $customer=='C00580' || $customer=='C01148' || $customer=='C01039' || $customer=='C04413' || 
						$customer=='C01448' || $customer=='C06409' || $customer=='C00119' || $customer=='C01585' || $customer=='C01366' || $customer=='C00371' || 
						$customer=='C03351' || $customer=='C01017' || $customer=='C06019' || $customer=='C06022'){
						$start 		= $prices['start']->format("Y-m-d h:i:s.u");					
						$end 		= $prices['ending']->format("Y-m-d h:i:s.u");
						if ($price!=0){
							if ($pvp!=$pvpr)
								$increment = ((($pvpr-(($discount*$pvpr)/100))/$price)-1)*100;					
							else	
								$increment = ((($pvp-(($discount*$pvp)/100))/$price)-1)*100;										
						}else{
							$increment = 0;
						}
						$result['products_prices'][$product][$customer] = [];
						$result['products_prices'][$product][$customer]['increment'] = round($increment);
						$result['products_prices'][$product][$customer]['start'] = $start;
						$result['products_prices'][$product][$customer]['end'] = $end;
						$result['increments'][$customer] = [];
						$result['increments'][$customer]['increment'] = round($increment);
						$result['increments'][$customer]['start'] = $start;
						$result['increments'][$customer]['end'] = $end;
					}
				}					
			}				
		}	  
		
	}
}
unset($result['products_prices']);
header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT);
?>
