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

$arrCampos=array();

$cont=1;
for($i=1; $i <= 40;$i++){
	$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

$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;

$resultado = mysqli_query($conexion->CONEXION,$_SESSION['query_recibedoce']);

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

	while($tmp = mysqli_fetch_array($resultado,MYSQLI_ASSOC)){
		for($j=0; $j < count($arrConf); $j++){
				if($arrConf[$j] == "totalPagoCC"){
					$tmp[$arrConf[$j]] = $tmp['totalPagoDocumentosRef']+$tmp['totalIngresoCompensado'];
				}
				if($arrConf[$j] == "totalComCC"){
					$tmp[$arrConf[$j]] = $tmp['ImpPagadoComplemento']+$tmp['totalIngresoCompensado'];
				}
				
				$banValidaFechaInicio= false;
				if($arrConf[$j] == "status_pagada" && $tmp["tipoComprobante"]== "I"){
					$totalPago = $tmp['totalPagoDocumentosRef']+$tmp['totalIngresoCompensado'];
					$totalComplemento = $tmp['ImpPagadoComplemento']+$tmp['totalIngresoCompensado'];
					if($tmp['totalPagoDocumentosRef'] == 0 || trim($tmp['totalPagoDocumentosRef']) == ""){
						if($notificar_fecha_inicio != ""){
							if( str_replace(":","",str_replace(" ","",str_replace("-","",$tmp["fechaDocto"]))) < str_replace(":","",str_replace(" ","",str_replace("-","",$notificar_fecha_inicio))) ){
								$tmp['status_pagada']="";
								$banValidaFechaInicio = true;
							}else{
								$tmp['status_pagada']='NINGUN PAGO';
							}
						}else{
							$tmp['status_pagada']='NINGUN PAGO';
						}
					}else if($totalPago < $tmp["total"]){
						$diferencia = (float) $tmp["total"] - (float) $totalPago;
						$arrDiferencia = explode(".",($diferencia*1000000));
						$arrTolerancia = explode(".",($tConfig["tolerancia_FacturaPagada"]*1000000));
						if($arrDiferencia[0] > $arrTolerancia[0]){
							$tmp['status_pagada']="ALGUNOS PAGOS";
						}else{
							$tmp['status_pagada']="TOTALMENTE PAGADA";
						}
					}else if($totalPago > $tmp["total"]){
						$diferencia = (float) $totalPago - (float) $tmp["total"];
						$arrDiferencia = explode(".",($diferencia*1000000));
						$arrTolerancia = explode(".",($tConfig["tolerancia_FacturaPagada"]*1000000));
						if($arrDiferencia[0] > $arrTolerancia[0]){
							$tmp['status_pagada']="TOTAL PAGADO MAYOR AL DOCUMENTO";
						}else{
							$tmp['status_pagada']="TOTALMENTE PAGADA";
						}
					}else{
						$tmp['status_pagada']="TOTALMENTE PAGADA";
					}
					
					if($tmp['totalPagoDocumentosRef'] > 0){
						if($notificar_fecha_inicio != ""){
							if( str_replace(":","",str_replace(" ","",str_replace("-","",$tmp["FechaNP"]))) < str_replace(":","",str_replace(" ","",str_replace("-","",$notificar_fecha_inicio))) ){
								$tmp['status_pagada']="";
								$banValidaFechaInicio = true;
							}
						}
					}
					if($banValidaFechaInicio == false){
						if($tmp['ImpPagadoComplemento'] == 0 || trim($tmp['ImpPagadoComplemento']) == ""){
							$tmp['status_pagada'].=" / NINGUN PAGO";
						}else if($totalComplemento < $tmp["total"]){
							$diferencia = (float) $tmp["total"] - (float) $totalComplemento;
							$arrDiferencia = explode(".",($diferencia*1000000));
							$arrTolerancia = explode(".",($tConfig["tolerancia_FacturaPagada"]*1000000));
							if($arrDiferencia[0] > $arrTolerancia[0]){
								$tmp['status_pagada'] .= " / ALGUNOS PAGOS";
							}else{
								$tmp['status_pagada'].= " / TOTALMENTE PAGADA";
							}
						}else if($totalComplemento > $tmp["total"]){
							$diferencia = (float) $totalComplemento - (float) $tmp["total"];
							$arrDiferencia = explode(".",($diferencia*1000000));
							$arrTolerancia = explode(".",($tConfig["tolerancia_FacturaPagada"]*1000000));
							if($arrDiferencia[0] > $arrTolerancia[0]){
								$tmp['status_pagada'].= " / TOTAL PAGADO MAYOR AL DOCUMENTO";
							}else{
								$tmp['status_pagada'].= " / TOTALMENTE PAGADA";
							}
						}else{
							$tmp['status_pagada'].=" / TOTALMENTE PAGADA";
						}
					}
					if(trim($tmp['marcar_como_pagada']) == "1"){
						$tmp['status_pagada']='TOTALMENTE PAGADA';
						$tmp['status_pagada'].=' / TOTALMENTE PAGADA';
					}
					$tmp['status_compensada']="";
					$tmp['totalPagoCC'] = $totalPago;
					$tmp['totalComCC'] = $totalComplemento;
					
				}else if($arrConf[$j] == "status_pagada" && $tmp["tipoComprobante"] == "E"){
					if($tmp['totalEgresoCompensado'] == 0){
						$tmp['status_compensada'].='NINGUNA COMPENSACION';
					}else if($tmp['totalEgresoCompensado'] < $tmp["total"]){
						$diferencia =  (float) $tmp["total"] - (float) $tmp['totalEgresoCompensado'];
						$arrDiferencia = explode(".",($diferencia*1000000));
						$arrTolerancia = explode(".",($tConfig["tolerancia_CompensacionEgreso"]*1000000));
						if($arrDiferencia[0] > $arrTolerancia[0]){
							$tmp['status_compensada'].='ALGUNAS COMPENSACIONES';
						}else{
							$tmp['status_compensada'].='TOTALMENTE COMPENSADA';
						}
					}else{
						$diferencia = (float) $tmp['totalEgresoCompensado'] - (float) $tmp["total"];
						$arrDiferencia = explode(".",($diferencia*1000000));
						$arrTolerancia = explode(".",($tConfig["tolerancia_CompensacionEgreso"]*1000000));
						if($arrDiferencia[0] > $arrTolerancia[0]){
							$tmp['status_compensada'].='TOTAL COMPENSADO MAYOR AL DOCUMENTO';
						}else{
							$tmp['status_compensada'].='TOTALMENTE COMPENSADA';
						}
					}
					$tmp['status_pagada']="";
				}
				//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;
}
?>