<?php
$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";

$arrCampos=array();

$cont=1;
for($i=1; $i <= 40;$i++){
	if($_REQUEST["pagos"] == "SI"){
		$valorIni = getINI("CAMPOP_".$cont."=","../config.ini");
	}else{
		$valorIni = getINI("CAMPO_".$cont."=","../config.ini");
	}
	if($valorIni){
		
		$arrConf = explode("||",$valorIni);
		array_push($arrCampos,$arrConf[0]);
		
		$cont++;
	}else{
		break;
	}
}

//Extraigo Configuracion General de notificaciones
$notificar_fecha_inicio="";
$qConfig = "select notificar_dias,notificar_despuesde,notificar_repetirdias,notificar_correos,notificar_asunto,notificar_correos_cc,notificar_fecha_inicio,tolerancia_NPvsComplemento,tolerancia_NPvsFactura,tolerancia_FacturaPagada,tolerancia_CompensacionEgreso,tolerancia_tipoCambio from configpagina where rfc_receptor='".$_SESSION['RFC_RECEPTOR_PORTAL']."' limit 1";
if($rConfig = mysqli_query($conexion->CONEXION,$qConfig)){	
	if(mysqli_num_rows($rConfig) > 0){
		$tConfig = mysqli_fetch_assoc($rConfig);
		$notificar_fecha_inicio = $tConfig["notificar_fecha_inicio"];
		$tConfig["tolerancia_NPvsComplemento"] = (float) $tConfig["tolerancia_NPvsComplemento"];
		$tConfig["tolerancia_NPvsFactura"] = (float) $tConfig["tolerancia_NPvsFactura"];
		$tConfig["tolerancia_FacturaPagada"] = (float) $tConfig["tolerancia_FacturaPagada"];
		$tConfig["tolerancia_CompensacionEgreso"] = (float) $tConfig["tolerancia_CompensacionEgreso"];
		$tConfig["tolerancia_tipoCambio"] = (float) $tConfig["tolerancia_tipoCambio"];
	}
}
//Termina extracción de configuración general de notificaciones

$header_name=$arrCampos;
$ignorarCol = explode(",",$_POST['ignorarCol']);
//print_r($ignorarCol);exit;
for($i = 2; $i < count($ignorarCol); $i++){
	$ignorarCol[$i-2] = ($ignorarCol[$i]-2);
	$ignorarCol[$i] = -1;
}
// print_r($ignorarCol);exit;
$objPHPExcel->setActiveSheetIndex(0);
// Encabezado

if($_REQUEST["pagos"] == "SI"){
	$valorIni = getINI("CAMPOSP_ORDEN=","../config.ini");
}else{
	$valorIni = getINI("CAMPOS_ORDEN=","../config.ini");
}


$arrConf = explode(",",$valorIni);

$col=0;
$autofilter=0;
// print_r($ignorarCol);
// print_r($arrConf);
// print_r($header_name);exit;

for($row=0; $row < count($header_name); $row++){
	if(!array_keys($ignorarCol,($row)) || trim($_POST['ignorarCol'])==""){
			$objPHPExcel->getActiveSheet()->setCellValue($col_name[$col].'1', $header_name[$row]);
			$objPHPExcel->getActiveSheet()->getColumnDimension($col_name[$col])->setAutoSize(true);
			$autofilter++;
			$col++;
	}else{
		$arrConf[$row] = "<<ELIMINAR>>";
	}
}
$arrConf = array_values(array_diff($arrConf, array('<<ELIMINAR>>')));
// print_r($arrConf);exit;
$auxSQL = str_replace("<<FILTROENGRID>>","",$_SESSION['query_recibedoce']);
 
$resultado = mysqli_query($conexion->CONEXION,$auxSQL);

if(mysqli_num_rows($resultado) == 0) exit;
	
$num_row=2;

	while($tmp = mysqli_fetch_array($resultado,MYSQLI_ASSOC)){
		for($j=0; $j < count($arrConf); $j++){
					$tmp['status_pagada']='';
					$tmp['status_compensada']='';
					if($_REQUEST["pagos"] == "SI"){
						//Agrego los status de pagos
						if($tmp['tipoComprobante'] == 'I'){
							if($tmp['statusNP'] != 99){
								switch($tmp['statusNP']){
											case 0: 
													$tmp['status_pagada'] = "Sin pagos";
													break;
											case 1: 
													$tmp['status_pagada'] = "Con Pagos";
													break;
											case 2: 
													$tmp['status_pagada'] = "Pago mayor al documento";
													break;
											case 4: 
													$tmp['status_pagada'] = "Pago completo";
													break;
											case 5: 
													$tmp['status_pagada'] = "PUE pago duplicado";
													break;
											case 6: 
													$tmp['status_pagada'] = "PUE pagado despues de vigencia";
													break;
											case 7: 
													$tmp['status_pagada'] = "PUE vencido";
													break;
											case 9: 
													$tmp['status_pagada'] = "Con compensaciones";
													break;
											case 10: 
													$tmp['status_pagada'] = "Liquidada por compensación";
													break;
								}
								if($tmp['MetodoDePago'] == "PPD"){
									switch($tmp['statusPCFDI']){
										case 0: 
												$tmp['status_pagada'] .= " / Sin Pagos";
												break;
										case 1: 
												$tmp['status_pagada'] .= " / Con Pagos";
												break;
										case 2: 
												$tmp['status_pagada'] .= " / Pago mayor al documento";
												break;
										case 4: 
												$tmp['status_pagada'] .= " / Pago completo";
												break;
									}
								}else{
									$tmp['status_pagada'] .= " / No Aplica";
								}
							}
						}elseif($tmp['tipoComprobante'] == 'E'){
							switch($tmp['statusEgreso']){
									case 0: 
											$tmp['status_compensada'] = "Sin compensaciones";
											break;
									case 1: 
											$tmp['status_compensada'] = "Compensada parcialmente";
											break;
									case 2: 
											$tmp['status_compensada'] = "Compensada mayor al documento";
											break;
									case 4: 
											$tmp['status_compensada'] = "Compensada completamente";
											break;
								}
						}
					//Termina agregar status de pagos
					}
				
				//if(!array_keys($ignorarCol,$j) || trim($_POST['ignorarCol'])==""){
					$objPHPExcel->getActiveSheet()->setCellValue($col_name[$j].$num_row, $tmp[$arrConf[$j]]);
				//}
		}
		
		$num_row++;
	}
	
//header style
$objPHPExcel->getActiveSheet()->getStyle('A1:'.$col_name[$autofilter-1].'1')->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_GRADIENT_LINEAR,
	  			'rotation'   => 90,
	 			'startcolor' => array(
	 				'argb' => 'FFA0A0A0'
	 			),
	 			'endcolor'   => array(
	 				'argb' => 'FFFFFFFF'
	 			)
	 		)
		)
);

//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 getINI($etiqueta,$archivo){
	if(file_exists($archivo)){
		$vlineas = file($archivo);
	
		foreach ($vlineas as $sLinea) {
				if(substr($sLinea,0,strlen($etiqueta)) == $etiqueta){
					return trim(substr($sLinea,strlen($etiqueta)));
				}						
		}
	}
	return false;
}
?>