<?php
if(!isset($_SESSION)) {
    session_start();
}

require_once($_SERVER['DOCUMENT_ROOT'].'/librerias/PHPExcel.php');


$correcto = false;
$mensaje = 'No se pudo generar el Reporte Estructurado';

require_once($_SERVER['DOCUMENT_ROOT'].'/varios/varios.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/clases/Varios.Class.php');

if( Varios::isActiveSession() 
    && Varios::hasModuleAccess(12)
	&& isset($_SESSION[_SYSTEM_SESIONID.'userId'])
) {
		
	$page               = 0;
	/*
	$fechaInicio        = filter_var($_POST["fechaInicio"], FILTER_SANITIZE_STRING);
	$fechaFin           = filter_var($_POST["fechaFin"], FILTER_SANITIZE_STRING);
	$cliente            = filter_var($_POST["cliente"], FILTER_SANITIZE_NUMBER_INT);
	$proveedorSils      = filter_var($_POST["proveedorSils"], FILTER_SANITIZE_NUMBER_INT);
	$proveedorCliente   = filter_var($_POST["proveedorCliente"], FILTER_SANITIZE_NUMBER_INT);
	$bodega             = filter_var($_POST["bodega"], FILTER_SANITIZE_NUMBER_INT);
	$puerta             = filter_var($_POST["puerta"], FILTER_SANITIZE_NUMBER_INT);
	$razonSocial        = filter_var($_POST["razonSocial"], FILTER_SANITIZE_STRING);
	$numero             = filter_var($_POST["numero"], FILTER_SANITIZE_STRING);
	$estado             = filter_var($_POST["estado"], FILTER_SANITIZE_NUMBER_INT);
	
  */
  $fechaInicio        = null;
  $fechaFin           = null;
  $cliente            = null;
  $proveedorSils      = null;
  $proveedorCliente   = null;
  $bodega             = null;
  $puerta             = null;
  $razonSocial        = null;
  $numero             = null;
  $estado             = null;

  if( isset($_SESSION['filtroReporteReservasFechaInicio']) 
  && strlen($_SESSION['filtroReporteReservasFechaInicio']) > 0
) {
  $fechaInicio     = filter_var( $_SESSION['filtroReporteReservasFechaInicio'] , FILTER_SANITIZE_STRING);
  $fechaInicio     = Varios::formatFechaSQL2($fechaInicio);
}
if( isset($_SESSION['filtroReporteReservasFechaFin']) 
  && strlen($_SESSION['filtroReporteReservasFechaFin']) > 0
) {
  $fechaFin     = filter_var( $_SESSION['filtroReporteReservasFechaFin'] , FILTER_SANITIZE_STRING);
  $fechaFin     = Varios::formatFechaSQL2($fechaFin);
}
if( isset($_SESSION['filtroReporteReservasCliente']) 
&& strlen($_SESSION['filtroReporteReservasCliente']) > 0
) {
  $cliente     = filter_var( $_SESSION['filtroReporteReservasCliente'] , FILTER_SANITIZE_NUMBER_INT);
}
if( isset($_SESSION['filtroReporteReservasProveedorSils']) 
&& strlen($_SESSION['filtroReporteReservasProveedorSils']) > 0
) {
  $proveedorSils     = filter_var( $_SESSION['filtroReporteReservasProveedorSils'] , FILTER_SANITIZE_NUMBER_INT);
}
if( isset($_SESSION['filtroReporteReservasProveedorCliente']) 
&& strlen($_SESSION['filtroReporteReservasProveedorCliente']) > 0
) {
  $proveedorCliente     = filter_var( $_SESSION['filtroReporteReservasProveedorCliente'] , FILTER_SANITIZE_NUMBER_INT);
}
if( isset($_SESSION['filtroReporteReservasBodega']) 
&& strlen($_SESSION['filtroReporteReservasBodega']) > 0
) {
  $bodega     = filter_var( $_SESSION['filtroReporteReservasBodega'] , FILTER_SANITIZE_NUMBER_INT);
}
if( isset($_SESSION['filtroReporteReservasPuerta']) 
&& strlen($_SESSION['filtroReporteReservasPuerta']) > 0
) {
  $puerta     = filter_var( $_SESSION['filtroReporteReservasPuerta'] , FILTER_SANITIZE_NUMBER_INT);
}
if( isset($_SESSION['filtroReporteReservasRazonSocial']) 
&& strlen($_SESSION['filtroReporteReservasRazonSocial']) > 0
) {
  $razonSocial     = filter_var( $_SESSION['filtroReporteReservasRazonSocial'] , FILTER_SANITIZE_STRING);
}
if( isset($_SESSION['filtroReporteReservasNumero']) 
&& strlen($_SESSION['filtroReporteReservasNumero']) > 0
) {
  $numero = filter_var( $_SESSION['filtroReporteReservasNumero'] , FILTER_SANITIZE_STRING);
}  
if( isset($_SESSION['filtroReporteReservasEstado']) 
  && strlen($_SESSION['filtroReporteReservasEstado']) > 0
) {
  $estado     = filter_var( $_SESSION['filtroReporteReservasEstado'] , FILTER_SANITIZE_NUMBER_INT);
}  

	require_once($_SERVER['DOCUMENT_ROOT'].'/clases/Reporte.Class.php');
	$datos_obj 	= new Reporte(null);
	$fechas_inf = $datos_obj->informacionReservaFechaMinMaxReporte();
	$fechaInicioFormato 	= ''; 
	$fechaFinFormato 		= '';
	$quantity           	= $fechas_inf['cantidad_reservas'];
	if(strlen($fechaInicio) > 0) {
		$fechaInicioFormato 	= $fechaInicio ;
		$fechaInicio = Funciones::formatFechaSQL2($fechaInicio);	
	} else {
		$fechaInicio = null;
		$fechaInicioFormato = $fechas_inf['fecha_minima_formato'];
	}
	if(strlen($fechaFin) > 0) {	
		$fechaFinFormato 	= $fechaFin ;	
		$fechaFin 	  = Funciones::formatFechaSQL2($fechaFin);	
	} else {
		$fechaFin 	  = null;
		$fechaFinFormato = $fechas_inf['fecha_maxima_formato'];
	}
	$cliente 			= Varios::verifyNull( $cliente );
	$proveedorSils 		= Varios::verifyNull( $proveedorSils );
	$proveedorCliente 	= Varios::verifyNull( $proveedorCliente );
	$bodega 			= Varios::verifyNull( $bodega );
	$puerta 			= Varios::verifyNull( $puerta );
	$razonSocial 		= Varios::verifyNull( $razonSocial );
	$numero 			= Varios::verifyNull( $numero );
	$estado 			=	 Varios::verifyNull( $estado );
	

	if(true) 
	{
		 //sanitiza parámetros
        
		$objPHPExcel = new PHPExcel();
		// Establecer propiedades
		$objPHPExcel->getProperties()
			->setCreator("Amo mi negocio")
			->setTitle('Listado de reservas')
			->setDescription('Listado de reservas')
			->setKeywords("reservas")
			->setCategory("Reporte");
		
		//---------------------------------ESTILO DEL TÍTULO ---------------------------------
		$styletTitulo = array(
			'font' => array(
				'bold' => true,
				'size' => 15,
				'name' => 'Arial'
			),
			'alignment' => array(
				'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
				'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
			)
		);
		
		//---------------------------------ESTILO DEL SUBTÍTULO ---------------------------------
		$styletSubTitulo = array(
			'font' => array(
				'bold' => true,
				'size' => 9,
				'name' => 'Arial'
			),
			'alignment' => array(
				'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
				'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
			)
		);
				
		//---------------------------------ESTILO DEL TÍTULO DE LA TABLA---------------------------------

		$styleTitDatos = array(
			'font' => array(
				'size' => 8,
				'name' => 'Arial',
				'bold' => true
			),
			'alignment' => array(
				'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
				'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
			),
			'borders' => array(
				'allborders' => array(
					'style' => PHPExcel_Style_Border::BORDER_THIN,
				)
			),
			'fill' => array(
				'type' => PHPExcel_Style_Fill::FILL_SOLID,
				'color' => array('rgb' => 'A4A4A4')
			)
		);

		
		//---------------------------------ESTILO DE LOS DATOS---------------------------------
		$styleDatos = array(
			'font' => array(
				'size' => 8,
				'name' => 'Arial',
				'bold' => false
			),
			'alignment' => array(
				//'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
				'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
			),
			'borders' => array(
				'allborders' => array(
					'style' => PHPExcel_Style_Border::BORDER_THIN,
				)
			)
		);

		//-----------------------------------------VARIABLES-------------------------------------------------------
		$fila_titulo = 12;		
		$fila = 12;
		$col = 2; 
		$i = 1;
		$alim_ID = '';

		
		
		
		//-------------------------------------CREANDO NUEVA HOJA-----------------------------------------------------------------
		
		$objPHPExcel->getActiveSheet()->setTitle('Reservas'); 
		$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(12);
		$objPHPExcel->getActiveSheet()->setShowGridlines(false);
		//-----------------------------------------TITULO---------------------------------------------------------
		$objPHPExcel->getActiveSheet()->setCellValue('A1', 'DETALLE DE RESERVAS');
		$objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styletTitulo);
		$objPHPExcel->getActiveSheet()->mergeCells('A1:K1');
		$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(40);
		//-----------------------------------------subtitulo---------------------------------------------------------  
		
		$objPHPExcel->getActiveSheet()->setCellValue('A2', 'DEL '.$fechaInicioFormato.' AL '.$fechaFinFormato);
		$objPHPExcel->getActiveSheet()->getStyle('A2')->applyFromArray($styletSubTitulo);
		$objPHPExcel->getActiveSheet()->mergeCells('A2:K2');
		$objPHPExcel->getActiveSheet()->getRowDimension(3)->setRowHeight(20);		

		//-----------------------------------------CABECERA DE LA TABLA---------------------------------------------------------  
		$nro_fila = 4;
		$objPHPExcel->getActiveSheet()->setCellValue('A'.$nro_fila, 'N°');
		$objPHPExcel->getActiveSheet()->setCellValue('B'.$nro_fila, 'Fecha');
		$objPHPExcel->getActiveSheet()->setCellValue('C'.$nro_fila, 'Razón Social');
		$objPHPExcel->getActiveSheet()->setCellValue('D'.$nro_fila, 'Carga Para');
		$objPHPExcel->getActiveSheet()->setCellValue('E'.$nro_fila, 'Número');
		$objPHPExcel->getActiveSheet()->setCellValue('F'.$nro_fila, 'Bodega');
		$objPHPExcel->getActiveSheet()->setCellValue('G'.$nro_fila, 'Puerta');
		$objPHPExcel->getActiveSheet()->setCellValue('H'.$nro_fila, 'Horario');
		$objPHPExcel->getActiveSheet()->setCellValue('I'.$nro_fila, 'Rut - persona que entrega');
		$objPHPExcel->getActiveSheet()->setCellValue('J'.$nro_fila, 'Nombre - persona que entrega');
		$objPHPExcel->getActiveSheet()->setCellValue('K'.$nro_fila, 'Estado');
		
		$objPHPExcel->getActiveSheet()->getStyle('A'.$nro_fila.':k'.$nro_fila)->applyFromArray($styleTitDatos);
		$objPHPExcel->getActiveSheet()->getStyle('C'.$nro_fila.':C'.$nro_fila)->getAlignment()->setWrapText(true);
		$objPHPExcel->getActiveSheet()->getStyle('D'.$nro_fila.':D'.$nro_fila)->getAlignment()->setWrapText(true);
		$objPHPExcel->getActiveSheet()->getStyle('F'.$nro_fila.':F'.$nro_fila)->getAlignment()->setWrapText(true);
		$objPHPExcel->getActiveSheet()->getStyle('G'.$nro_fila.':G'.$nro_fila)->getAlignment()->setWrapText(true);
		$objPHPExcel->getActiveSheet()->getStyle('I'.$nro_fila.':I'.$nro_fila)->getAlignment()->setWrapText(true);
		$objPHPExcel->getActiveSheet()->getStyle('J'.$nro_fila.':J'.$nro_fila)->getAlignment()->setWrapText(true);

		$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(0))->setWidth(3);
		$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(1))->setWidth(15);			
		$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(2))->setWidth(25);
		$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(3))->setWidth(25);
		$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(4))->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(5))->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(6))->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(7))->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(8))->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(9))->setWidth(25);
		$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(10))->setWidth(25);

		
		$datos_inf 	= $datos_obj->informacionReporteReserva($fechaInicio , $fechaFin , $cliente, $proveedorSils, $proveedorCliente, $bodega, $puerta, $razonSocial, $numero, $estado, $page, $quantity);
		$i = 1; $monto = 0; 
		$fila = $nro_fila + 1; $total = 0;
		foreach( $datos_inf as $dato ) 			
		{	
			$objPHPExcel->setActiveSheetIndex(0)
			->setCellValueByColumnAndRow(0, $fila, $i)
			->setCellValueByColumnAndRow(1, $fila, $dato['rese_fecha_formato'])
			->setCellValueByColumnAndRow(2, $fila, $dato['pers_razon_social'])
			->setCellValueByColumnAndRow(3, $fila, $dato['cliente'])
			->setCellValueByColumnAndRow(4, $fila, $dato['res_tipo_orden'].' '.$dato['rese_numero'])
			->setCellValueByColumnAndRow(5, $fila, $dato['bodega_descripcion'])
			->setCellValueByColumnAndRow(6, $fila, $dato['puer_descripcion'])
			->setCellValueByColumnAndRow(7, $fila, $dato['res_bloq_inicio'].'-'.$dato['res_bloq_fin'])
			->setCellValueByColumnAndRow(8, $fila, $dato['reen_rut'])
			->setCellValueByColumnAndRow(9, $fila, $dato['reen_nombre'])
			->setCellValueByColumnAndRow(10, $fila, $dato['rese_estado']);
			 $objPHPExcel->getActiveSheet()->getStyle('C'.$fila.':C'.$fila)->getAlignment()->setWrapText(true);
			 $objPHPExcel->getActiveSheet()->getStyle('D'.$fila.':D'.$fila)->getAlignment()->setWrapText(true);
			 $objPHPExcel->getActiveSheet()->getStyle('F'.$fila.':F'.$fila)->getAlignment()->setWrapText(true);
			 $objPHPExcel->getActiveSheet()->getStyle('G'.$fila.':G'.$fila)->getAlignment()->setWrapText(true);
			 $objPHPExcel->getActiveSheet()->getStyle('I'.$fila.':I'.$fila)->getAlignment()->setWrapText(true);
			 $objPHPExcel->getActiveSheet()->getStyle('J'.$fila.':J'.$fila)->getAlignment()->setWrapText(true);
			$i++; $fila++;
		}
		$objPHPExcel->getActiveSheet()->getStyle('A'.($nro_fila).':K'.($fila-1))->applyFromArray($styleDatos);
		//$objPHPExcel->getActiveSheet()->getStyle('A'.($nro_fila + 1).':K'.$fila)->applyFromArray($styleDatos);
		
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="ListadoReservas_'.date('d-m-Y-H-i-s').'.xlsx"');
		header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$objWriter->save('php://output');
			
	} else {
		
		echo 'Problema de Seguridad';	
		
	}

}
else
 	echo $mensaje;