<?php include "../index/conexion.inc" ?>
<?php include "../index/validacion.php" ?>
<?php
	// conexión
	$servername = $svr_servidor;
	$conectioninfo = array("Database"=>$svr_base, "UID"=>$svr_usuario, "PWD"=>$svr_contrasena, "CharacterSet"=>"UTF-8");
	$conexion = sqlsrv_connect($servername, $conectioninfo);
	if ($conexion == false)
	{
		$mensaje = "Existe un error al intentar conectarse con el servidor...";
	}
	else
	{
		// VARIABLES
		// CONSULTA SQL
		$cV00 = $_GET['id1'];
		$cV01 = $_GET['id2'];
		$cV02 = $_GET['id3'];
		$cV03 = $_GET['id4'];
		// PARAMETROS PARA EXPORTAR
		header("Pragma: public");
		header("Expires: 0");
		$filename = "StockBodegas.xls";
		header("Content-type: application/x-msdownload");
		header("Content-Disposition: attachment; filename=$filename");
		header("Pragma: no-cache");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		echo "
			<table>
				<thead>
					<tr>
						<th>DOCUMENTO</th>
						<th>GONDOLA</th>
						<th>BODEGA</th>
						<th>ALMACEN</th>
						<th>C1</th>
						<th>C2</th>
						<th>C1-C2</th>
						<th>FECHA</th>
						<th>NESTADO</th>
					</tr>
				</thead>
				<tbody>";
					// CONSULTA SQL
					$sql = "SELECT C.BODEGA, A.NOMBREALMACEN, C.GONDOLA, C.DOCUMENTO, SUM(C.UNIDADES) AS C1, SUm( ISNULL(dbo.JOIN_INV_REV (C.CODBARRAS , C.GONDOLA , C.UBICACION, 1),0)) C2,SUM(C.UNIDADES) -SUm( ISNULL(dbo.JOIN_INV_REV (C.CODBARRAS , C.GONDOLA , C.UBICACION, 1),0)) 'C1-C2', '' CAJAMASTER, CONVERT(DATE,C.FECHAALTA,3) FECHAALTA, CASE WHEN C.IDESTADO =1 THEN 'ANULADO' ELSE  ( CASE WHEN C.IDESTADO =2 THEN 'APROBADO' ELSE  'SIN ESTADO' END) END AS NESTADO ,C.IDESTADO \n"
						  ."FROM JOIN_INVENTARIO_FISICO AS C \n"
						  ."LEFT JOIN ALMACEN AS A ON (C.BODEGA = A.CODALMACEN COLLATE Latin1_General_CS_AI) \n"
						  ."WHERE (C.BODEGA = '".$cV01."') AND (CONVERT(DATE, C.FECHAALTA) >= '".$cV02."' AND CONVERT(DATE, C.FECHAALTA) <= '".$cV03."') \n"
						  ."GROUP BY C.BODEGA, A.NOMBREALMACEN, C.GONDOLA, C.DOCUMENTO,  CONVERT(DATE,C.FECHAALTA,3), C.IDESTADO \n"
						  ."ORDER BY C.DOCUMENTO DESC";
					$pa1 = array();
					$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
					// Lanzar la consulta
					$re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
					while($fila = sqlsrv_fetch_array($re1))
					{
						echo "
							<tr>
								<td>".$fila['DOCUMENTO']."</td>
								<td>".$fila['GONDOLA']."</td>
								<td>".$fila['BODEGA']."</td>
								<td>".$fila['NOMBREALMACEN']."</td>
								<td>".$fila['C1']."</td>
								<td>".$fila['C2']."</td>
								<td>".$fila['C1-C2']."</td>
								<td>".$fila['FECHAALTA']->format('Y-m-d h:m:s')."</td>
								<td>".$fila['NESTADO']."</td>
							</tr>
						";
					}
				echo "
				</tbody>
			</table>
		";
	}
	// Desconexion
	sqlsrv_close($conexion);
?>