<?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=["serie", "folio", "uuid", "rfcemisor", "nombreemi", "tipodocto", "rfc_receptor", "fechaDocto", "fechaRecibido"];
$header_name = ["Serie", "Folio", "UUID", "RFC emisor", "Emisor", "Tipo documento", "RFC receptor", "Fecha documento", "Fecha recibido", "Moneda", "Total", "Serie", "Folio", "Documento relacionado"];

$objPHPExcel->setActiveSheetIndex(0);

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


// $auxQuery = $_SESSION['query_recibedoce']." and tipodocto in ('P CFDI 3.3','P CFDI 4.0')";
$auxQuery = $_SESSION['query_recibedoce'];
// $auxQuery = $_SESSION['query_recibedoce']." where tipodocto='P CFDI 3.3' and uuid='830ad168-e787-436b-986a-151317a111ee'";
// $auxQuery = $_SESSION['query_recibedoce']." where tipodocto='P CFDI 3.3' and uuid='B70CAE75-A2BB-4453-838C-073F9582678A'";

$auxSQL = str_replace("<<FILTROENGRID>>","",$auxQuery);

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

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

$num_row=1;

// 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);

while($tmp = mysqli_fetch_array($resultado,MYSQLI_ASSOC)){

	$qRel = "select rp.MonedaP, rp.Monto, rp.recibedoce_UUID, rpdr.uuidCFDIRelacionado, rpdr.ImpPagado, r.serie, r.folio from recibedoce_pagos rp left join recibedoce_pagos_docto_relacionado rpdr on rp.recibedoce_pagos_id = rpdr.recibedoce_pagos_id left join recibedoce r on rpdr.uuidCFDIRelacionado = r.uuid where rp.recibedoce_uuid = '".$tmp["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){
		$arrDetalle = [];
		while($tRel = mysqli_fetch_assoc($rRelacionados)){
			@$arrDetalle[@$tRel["MonedaP"]]["Monto"] = @$arrDetalle[@$tRel["MonedaP"]]["Monto"] + $tRel["ImpPagado"];
			if(@$arrDetalle[@$tRel["MonedaP"]]["UUID"] == ""){
				@$arrDetalle[@$tRel["MonedaP"]]["UUID"] = $tRel["uuidCFDIRelacionado"];
				@$arrDetalle[@$tRel["MonedaP"]]["ImpPagado"] = $tRel["ImpPagado"];
				@$arrDetalle[@$tRel["MonedaP"]]["serie"] = $tRel["serie"];
				@$arrDetalle[@$tRel["MonedaP"]]["folio"] = $tRel["folio"];
			}else{
				@$arrDetalle[@$tRel["MonedaP"]]["UUID"].= "|".$tRel["uuidCFDIRelacionado"];
				@$arrDetalle[@$tRel["MonedaP"]]["ImpPagado"].= "|".$tRel["ImpPagado"];
				@$arrDetalle[@$tRel["MonedaP"]]["serie"].= "|".$tRel["serie"];
				@$arrDetalle[@$tRel["MonedaP"]]["folio"].= "|".$tRel["folio"];
			}
		}
		foreach($arrDetalle as $clave => $valor){
			$num_row++;
			$colActual = 0;
			for($j=0; $j <= count($arrCampos); $j++){
				$objPHPExcel->getActiveSheet()->setCellValue(@$col_name[$j].$num_row, @$tmp[$arrCampos[($j)]]);
				$colActual = $j;
			}

			$auxColActual = $colActual;
			$objPHPExcel->getActiveSheet()->setCellValue($col_name[$auxColActual].$num_row, $clave);
			$auxColActual++;
			$objPHPExcel->getActiveSheet()->setCellValue($col_name[$auxColActual].$num_row, $arrDetalle[$clave]["Monto"]);

			$arrUUID = explode("|",$arrDetalle[$clave]["UUID"]);
			$arrImpPagado = explode("|",$arrDetalle[$clave]["ImpPagado"]);
			$arrSerie = explode("|",$arrDetalle[$clave]["serie"]);
			$arrFolio = explode("|",$arrDetalle[$clave]["folio"]);

			$auxColActual++;
			for($i = 0; $i < count($arrUUID); $i++){
				$num_row++;
				$objPHPExcel->getActiveSheet()->setCellValue($col_name[$auxColActual-1].$num_row, $arrImpPagado[$i]);
				$objPHPExcel->getActiveSheet()->setCellValue($col_name[$auxColActual].$num_row, $arrSerie[$i]);
				$objPHPExcel->getActiveSheet()->setCellValue($col_name[$auxColActual+1].$num_row, $arrFolio[$i]);
				$objPHPExcel->getActiveSheet()->setCellValue($col_name[$auxColActual+2].$num_row, $arrUUID[$i]);
			}
		}
	}
}



//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'
					)
				)
			)
	);
}

?>
