<?php
if(!isset($_SESSION['usuario_p_prov_absa']) || trim($_SESSION['usuario_p_prov_absa']) == "" || trim(strtoupper($_SESSION["URL_PORTAL"]."admin.php")) != trim(strtoupper($_SERVER['HTTP_REFERER']))){
	?><script>window.location.href="<?=$_SESSION["URL_PORTAL"]."index.php"?>"</script><?
	exit;
}
$col_name[0]="A";
$col_name[1]="B";
$col_name[2]="C";
$col_name[3]="D";
$col_name[4]="E";
$col_name[5]="F";
$col_name[6]="G";
$col_name[7]="H";
$col_name[8]="I";
$col_name[9]="J";
$col_name[10]="K";
$col_name[11]="L";
$col_name[12]="M";
$col_name[13]="N";
$col_name[14]="O";
$col_name[15]="P";
$col_name[16]="Q";
$col_name[17]="R";
$col_name[18]="S";
$col_name[19]="T";
$col_name[20]="U";
$col_name[21]="V";
$col_name[22]="W";
$col_name[23]="X";
$col_name[24]="Y";
$col_name[25]="Z";
$col_name[26]="AA";
$col_name[27]="AB";
$col_name[28]="AC";
$col_name[29]="AD";
$col_name[30]="AE";
$col_name[31]="AF";
$col_name[32]="AG";
$col_name[33]="AH";
$col_name[34]="AI";
$col_name[35]="AJ";
$col_name[36]="AK";
$col_name[37]="AL";
$col_name[38]="AM";
$col_name[39]="AN";
$col_name[40]="AO";

$campos = getINI("CAMPOS_ORDEN_RELACIONADOS=","../config.ini");
$valorIni = getINI("TITULOS_ORDEN_RELACIONADOS=","../config.ini");
if(trim($campos) == "" || trim($valorIni) == ""){
	?><h1>No se encontro la configuración de los campos a exportar</h1><?exit;
}

$arrCampos=explode(",",$campos);
$header_name = explode(",",$valorIni);

$objPHPExcel->setActiveSheetIndex(0);

$autofilter=0;
// print_r($header_name);exit;


$registrosXPagina = ((int) $_GET["registrosXPagina"]);
$pagina1 = ((int) $_GET["pagina1"]);
$pagina2 = ((int) $_GET["pagina2"]);
$pagina1 = ($pagina1-1);
$start = $pagina1*$registrosXPagina;
$limit = $registrosXPagina*$pagina2;
$auxSQL = str_replace("<<FILTROENGRID>>","",$_SESSION['query_recibedoce']);
$auxSQL = $auxSQL." limit $start,$limit";

 // echo $auxSQL;exit;
if(!$resultado = mysqli_query($conexion->CONEXION,$auxSQL)){
	?><h1>Ocurrio un error en la consulta.</h1><?exit;
}

if(mysqli_num_rows($resultado) == 0){
	?><h1>La consulta no regreso información.</h1><?exit;
}

$num_row=0;

while($tmp = mysqli_fetch_array($resultado,MYSQLI_ASSOC)){
	$num_row++;
	// Titulos encabezado
	$col=0;
	for($row=0; $row < count($header_name); $row++){
		$objPHPExcel->getActiveSheet()->setCellValue($col_name[$col].$num_row, $header_name[$row]);
		$objPHPExcel->getActiveSheet()->getColumnDimension($col_name[$col])->setAutoSize(true);
		$col++;
	}
	// 'A1:'.$col_name[$autofilter-1].'1'
	headerStyle("A".$num_row.":".$col_name[(count($header_name)-1)].$num_row);
	
	$num_row++;
	for($j=0; $j <= count($arrCampos); $j++){
		$objPHPExcel->getActiveSheet()->setCellValue($col_name[$j].$num_row, $tmp[$arrCampos[($j)]]);
	}
	
	
	$qRel = "select $campos from 
	(select uuidHijo  from (select * from recibedoce where uuid='".$tmp["uuid"]."') as r inner join cfdirelacionados on uuidPadre = uuid) as rel left join recibedoce on uuidHijo=uuid";
	
	/*$qRel = "select id, rfcemisor, tipodocto, serie, folio, uuidHijo as uuid, fechaDocto, rfc_receptor, total, tipoMoneda, status, fechaRecibido, nombreemi, comentarios, adicional, tipo_documento, fecha_pago, asignado_a, nombrerec, totalmxn, tipo_cambio, subtotal, subtotal_xml, comentario_status, status_pago, referencia, verificacionSAT, concepto_pago, TipoCambio, tipoComprobante, FormaDePago, status_pagada, status_compensada, status_activa, MetodoDePago, marcar_como_pagada, reporte_pagada_generado, bloqueadoPP, fechaPP, IdPP from 
	(select uuidHijo  from (select * from recibedoce where uuid='".$tmp["uuid"]."') as r inner join cfdirelacionados on uuidPadre = uuid) as rel left join recibedoce on uuidHijo=uuid";*/
	if(!$rRelacionados = mysqli_query($conexion->CONEXION,$qRel)){
		?><h1>Ocurrio un error al consultar los documentos relacionados del UUID -> <?=$tmp["uuid"]?></h1><?exit;
	}
	if(mysqli_num_rows($rRelacionados) > 0){
		$num_row++;
			// Titulos Detalle iniciando en la segunda columna
			$col=1;
			for($row=0; $row < count($header_name); $row++){
				$objPHPExcel->getActiveSheet()->setCellValue($col_name[$col].$num_row, $header_name[$row]);
				$objPHPExcel->getActiveSheet()->getColumnDimension($col_name[$col])->setAutoSize(true);
				$col++;
			}
			headerStyle("B".$num_row.":".$col_name[(count($header_name))].$num_row);
		while($tRel = mysqli_fetch_assoc($rRelacionados)){
			$num_row++;
			// Documentos relacionados iniciando en la segunda columna
			for($j=0; $j <= count($arrCampos); $j++){
				$objPHPExcel->getActiveSheet()->setCellValue($col_name[$j+1].$num_row, $tRel[$arrCampos[($j)]]);
			}
		}
	}
}
	


//Autofilter
// $objPHPExcel->getActiveSheet()->setAutoFilter('A1:'.$col_name[$autofilter-1].'1');

/*$objPHPExcel->getActiveSheet()->setCellValue('D1', PHPExcel_Shared_Date::PHPToExcel( gmmktime(0,0,0,date('m'),date('d'),date('Y')) ));
$objPHPExcel->getActiveSheet()->getStyle('D1')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15);
$objPHPExcel->getActiveSheet()->setCellValue('E1', '#12566');*/

$objPHPExcel->getActiveSheet()->setTitle("Documentos");

function limpiar_caracteres_especiales($s) {
	$s = preg_replace("[áàâãª]","a",$s);
	$s = preg_replace("[ÁÀÂÃ]","A",$s);
	$s = preg_replace("[éèê]","e",$s);
	$s = preg_replace("[ÉÈÊ]","E",$s);
	$s = preg_replace("[íìî]","i",$s);
	$s = preg_replace("[ÍÌÎ]","I",$s);
	$s = preg_replace("[óòôõº]","o",$s);
	$s = preg_replace("[ÓÒÔÕ]","O",$s);
	$s = preg_replace("[úùû]","u",$s);
	$s = preg_replace("[ÚÙÛ]","U",$s);
	$s = str_replace(" ","-",$s);
	$s = str_replace("ñ","n",$s);
	$s = str_replace("Ñ","N",$s);
	//para ampliar los caracteres a reemplazar agregar lineas de este tipo:
	//$s = str_replace("caracter-que-queremos-cambiar","caracter-por-el-cual-lo-vamos-a-cambiar",$s);
	return $s;
}

function headerStyle($rango){
	global $objPHPExcel;
	//header style
	$objPHPExcel->getActiveSheet()->getStyle($rango)->applyFromArray(
			array(
				'font'    => array(
					'bold'      => true
				),
				'alignment' => array(
					'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
				),
				'borders' => array(
					'top'     => array(
						'style' => PHPExcel_Style_Border::BORDER_THIN
					)
				),
				'fill' => array(
					'type'       => PHPExcel_Style_Fill::FILL_SOLID,
					'rotation'   => 90,
					'startcolor' => array(
						'argb' => 'EEEEEE'
					),
					'endcolor'   => array(
						'argb' => 'FFFFFFFF'
					)
				)
			)
	);
}

?>