<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '4G');
date_default_timezone_set('Europe/Madrid');
//include("conexion.php");


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{
		 //echo "Conexion no se pudo establecer con Navision.\r\n";
		 die( print_r( sqlsrv_errors(), true));
	}
	

	/*solo sacamos el primer descuento porque el resto son cero siempre*/
	$sql='SELECT 
	s.[Sales Type] type,
	s.[Sales Code] salescode,
	s.[% Descuento 1] Discount, 
	s.[Starting Date] startingdate,
	s.[Ending Date] endingdate,
	i.[No.] productcode,
	i.[Precio venta UM Precio] pvp,
	i.[Precio Neto Compra UM Precio] neto
	FROM [Ind. Campollano Ferreterķa S.L$Sales Line Discount] s
	LEFT JOIN [Item] i ON i.[Item Disc. Group]=s.[Code]
	WHERE s.[Sales Type]=1 AND i.Blocked=0';

	/*$sql='SELECT [Item No.], [Cross-Reference Type No.], [Cross-Reference No.] FROM dbo."Item Cross Reference" WHERE [Cross-Reference Type]=3
	and [Cross-Reference Type No.]=\'C01448\'';*/
	//echo $sql;
	$stmt = sqlsrv_query( $connNavision, $sql );
		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;
			}
		}
	$prueba["class"]=$objects;
	$result[]=$prueba;
echo json_encode($result, JSON_PRETTY_PRINT);
?>