<? session_start();

//RESTRICCIÓN DE ACCESO A TRABAJADOR (ACCESO INDIVIDUAL)
if (isset($_SESSION['tipousuario'])) {
	if ($_SESSION['tipousuario'] == '1')
		header('location:menu_personal.php');
}

if (trim($_SESSION['nombre_validar']) == '') header('location:index.php');
include("fphp.php");
$enlace = cargar_conexion();
$consulta = mysqli_query($enlace, "select * from periodo where id='" . $_SESSION['id_validar'] . "' order by nomina,periodo desc limit 1");
if (mysqli_num_rows($consulta) != 0) {
	$row = mysqli_fetch_array($consulta);
	$per = mostrar_fecha($row['desde']) . ' al ' . mostrar_fecha($row['hasta']) . " (Nom:" . $row['nomina'] . ")";
} else $per = '';
////////////////////////////////// generando FAOV
if ($_POST['treporte'] == 1) {
?>
	<html>

	<head>
		<meta charset="UTF-8">
	</head>

	<body>
		<?php


		$query = '';
		if ($_POST['nomina'] != '') $query .= " and personal.nomina = '" . substr($_POST['per1'], 13, 3) . "' ";
		if ($_POST['gerencia'] != '') $query .= " and personal.gerencia = '" . $_POST['gerencia'] . "' ";
		if ($_POST['division'] != '') $query .= " and personal.division = '" . $_POST['division'] . "' ";
		if ($_POST['departamento'] != '') $query .= " and personal.departamento = '" . $_POST['departamento'] . "' ";
		$consulta = "select * from personal where id='" . $_SESSION['id_validar'] . "' AND personal.nomina='" . substr($_POST['per1'], 13, 3) . "' AND (fechae>='" . substr($_POST['per1'], 19, 10) . "' OR fechae='0000-00-00') AND status!='S'

		$query order by codigo"; //and status<>'I'
		$resultado = mysqli_query($enlace, $consulta) or die('verificaci&oacute; del c&oacute;digo fall&oacute;: ' . mysqli_error($enlace));
		$data = array();

		//Generación de archivo
		$fecha_lote_otros = date("dmY-His"); //Fecha a imprimir en archivo (Fecha sin ceros a la izquierda)
		$fileName = "pago_faov-" . $fecha_lote_otros . ".txt";
		$fo = "faov_txt/" . $fileName;
		$fileReporte = fopen($fo, "w+");

		while ($row = mysqli_fetch_array($resultado)) {

			$nac = (strtoupper($row['nacionalidad']) != 'E' ? 'V' : 'E');
			if ($nac != 'V') $nac = 'E';
			if ($row['status'] == 'C') $fechae = '';
			else {
				if ($row['fechae'] == '0000-00-00') $fechae = '';
				else $fechae = $row['fechae'];
			}

			///consulto mayores de 60 años
			/*
			$consultaEdad="Select codigo from personal where fechan>='1961-11-09'  AND status!='I' AND nomina='".substr($_POST['per1'],13,3)."' ";
			$resultadoEdad = mysqli_query($enlace,$consultaEdad) or die ("no se pudo realizar la consulta...".$consultaEdad.'='.mysqli_error($enlace));
			if (mysqli_num_rows($resultadoEdad)!=0) {
			   $rowEdad=mysqli_fetch_array($resultadoEdad);
			   $MayorFaov=$rowEdad['codigo'];
			}
			*/

			///Busco los trabajadores y lo retenido a cada uno por RPVH
			//FROM costo_laboral AS costo_laboral JOIN personal AS personal ON
			//$consulta2="Select sum(h.monto) as total, h.cedula, c.cedula FROM historico AS h JOIN concepto_empleado AS c ON c.cedula!=h.cedula where c.cedula!=h.cedula AND h.id='".$_SESSION['id_validar']."' and h.cedula='".$row['codigo']."' and substring(h.concepto,1,1)='1' AND h.concepto!='1490' AND h.concepto!='1498' AND h.concepto!='1499' AND h.concepto!='1581' AND h.concepto!='1590' AND h.concepto!='1598' AND h.concepto!='1599' and h.nomina='".substr($_POST['per1'],13,3)."' and h.periodo>='".substr($_POST['per1'],0,3)."' and h.periodo<='".substr($_POST['per2'],0,3)."' ";



			$consulta2 = "Select sum(monto) as total from historico where historico.id='" . $_SESSION['id_validar'] . "' and cedula='" . $row['codigo'] . "'AND historico.tipo='A' AND substr(concepto,1,1)='1' and historico.nomina='" . substr($_POST['per1'], 13, 3) . "' and periodo>='" . substr($_POST['per1'], 0, 3) . "' and periodo<='" . substr($_POST['per2'], 0, 3) . "' AND concepto NOT IN('1498' ,'1499' ,'1598' ,'1599' ,'3490' ,'3498','3499','3590','3598' ,'3599','1525','1526')";
			$resultado2 = mysqli_query($enlace, $consulta2) or die("no se pudo realizar la consulta..." . $consulta2 . '=' . mysqli_error($enlace));
			///////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			///// En este devengado se debe restar los montos de los conceptos 2064 y 2069--Miguelangel -10/01/2022

			if (mysqli_num_rows($resultado2) != 0) {
				$row2 = mysqli_fetch_array($resultado2);
				$total = $row2['total'];

				$consulta22 = "Select sum(monto) as total from historico where historico.id='" . $_SESSION['id_validar'] . "' and cedula='" . $row['codigo'] . "'AND historico.tipo='D' AND  historico.nomina='" . substr($_POST['per1'], 13, 3) . "' and periodo>='" . substr($_POST['per1'], 0, 3) . "' and periodo<='" . substr($_POST['per2'], 0, 3) . "' AND concepto IN('2064','2069')  ";
				$resultado22 = mysqli_query($enlace, $consulta22) or die("no se pudo realizar la consulta..." . $consulta22 . '=' . mysqli_error($enlace));
				///////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
				///// En este devengado se debe restar los montos de los conceptos 2064 y 2069--Miguelangel -10/01/2022


				$row22 = mysqli_fetch_array($resultado22);
				$totalDed = $row22['total'];

				$total = $total - $totalDed;

				//////////Consulta para traer lo retenido Faov en Utilidades
				$consulta33 = "Select monto from utilidades where id='" . $_SESSION['id_validar'] . "' and cedula='" . $row['codigo'] . "' and concepto IN('8018','8118') and fecha>='" . substr($_POST['per1'], 19, 10) . "' and fecha<='" . substr($_POST['per2'], 33, 10) . "' ";
				$resultado33 = mysqli_query($enlace, $consulta33) or die("no se pudo realizar la consulta..." . $consulta33 . '=' . mysqli_error($enlace));
				$row33 = mysqli_fetch_array($resultado33);
				$rpvhUtilidades = $row33['monto'] * 100;

				///////////Consulta para traer lo retenido Faov en Vacaciones
				$consulta44 = "Select SUM(total_pago_vaca) as monto from vacacion where id='" . $_SESSION['id_validar'] . "' and cedula='" . $row['codigo'] . "' and fecha_pago>='" . substr($_POST['per1'], 19, 10) . "' and fecha_pago<='" . substr($_POST['per2'], 33, 7) . "-30" . "'";
				$resultado44 = mysqli_query($enlace, $consulta44) or die("no se pudo realizar la consulta..." . $consulta2 . '=' . mysqli_error($enlace));
				$row44 = mysqli_fetch_array($resultado44);
				$rpvhVacaciones = $row44['monto'];

				///////////Consulta para traer lo retenido Faov en LIQUIDACIONES
				$consulta55 = "Select faov as monto from liquidaciones where id='" . $_SESSION['id_validar'] . "' and cedula='" . $row['codigo'] . "' and fecha_retiro>='" . substr($_POST['per1'], 19, 10) . "' and fecha_retiro<='" . substr($_POST['per2'], 33, 7) . "-30" . "'";
				$resultado55 = mysqli_query($enlace, $consulta55) or die("no se pudo realizar la consulta..." . $consulta2 . '=' . mysqli_error($enlace));
				$row55 = mysqli_fetch_array($resultado55);
				$rpvhLiquidaciones = $row55['monto'] * 100;

				// if(floatval($total)>0){
				$total = $total;
				//$total.="00";
				//$total=round(floatval($total)/0.01,2);
				//$ingreso=substr($total,0,strlen($total)-3).substr($total,strlen($total)-2,2);




				$ingreso = ($total + $rpvhUtilidades + $rpvhVacaciones + $rpvhLiquidaciones);
				$ingreso = number_format($ingreso, 2, '', '');

				if ($ingreso >= 13000) {
					$ingreso = $ingreso;
				} else $ingreso = 13000;
				//$ingreso=number_format($total,2,'');
				//$ingreso=str_replace($total,".","");
				//Consulta para calcular la edad
				$consultaEdad = "Select fechan from personal where id='" . $_SESSION['id_validar'] . "' and codigo='" . $row['codigo'] . "' ";
				$consultaEdad = mysqli_query($enlace, $consultaEdad) or die("no se pudo realizar la consulta..." . $consultaEdad . '=' . mysqli_error($enlace));
				$rowEdad = mysqli_fetch_array($consultaEdad);
				$fechaNac = $rowEdad['fechan'];
				$fechaHoy = $fechaActual = date('Y-m-d');
				$date1 = $fechaNac;
				$date2 = $fechaHoy;

				$dateDifference = abs(strtotime($date2) - strtotime($date1));
				$years  = floor($dateDifference / (365 * 60 * 60 * 24));
				$months = floor(($dateDifference - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
				$days   = floor(($dateDifference - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));
				$edad = $years + ($months / 12) + ($days / 30 / 12);
				//echo $years." year,  ".$months." months and ".$days." days";

				if ($edad < 60) { ///Menos de 60 Años retiene
					//echo ($nac.",".trim($row['codigo']).",".trim($row['nombres']).",".trim($row['nombres1']).",".trim($row['apellidos']).",".trim($row['apellidos1']).",".trim($ingreso).",".substr($row['fechai'],8,2).substr($row['fechai'],5,2).substr($row['fechai'],0,4).",".substr($fechae,8,2).substr($fechae,5,2).substr($fechae,0,4)."<br/>");

					fwrite($fileReporte, $nac . "," . trim($row['codigo']) . "," . trim($row['nombres']) . "," . trim($row['nombres1']) . "," . trim($row['apellidos']) . "," . trim($row['apellidos1']) . "," . trim($ingreso) . "," . substr($row['fechai'], 8, 2) . substr($row['fechai'], 5, 2) . substr($row['fechai'], 0, 4) . "," . substr($fechae, 8, 2) . substr($fechae, 5, 2) . substr($fechae, 0, 4));
					fwrite($fileReporte, "\r\n"); //Nueva Linea
				}
			}
		}
		fclose($fileOtros);

		echo "<style>
			.regristrado{
					color: green;
					margin-left: 7%;
					font-weight: bold;
			}
		</style>";
		echo "<p class='regristrado' >Reporte generado correctamente <a href = 'generar_txt.php?specialPayment=$fileName&directory=faov_txt';>Descargar</a><p>";

		echo "<a id='link1' target='_blank' href = 'generar_txt.php?specialPayment=$fileName&directory=faov_txt';></a>";
		echo "<script> document.getElementById('link1').click();</script>";

		/*$data=implode("\n",$data);
	$arch="FAOV.txt";
	header("Content-type: text/csv;charset=UTF-8");
	header("Content-Disposition: attachment; filename=".$arch);
	header("Pragma: no-cache");
	header("Expires: 0");
	echo ($data);*/
		?>
	</body>

	</html>
<?php } ?>
<?php
	exit();


///////////////////////Genenerando Archivo de ISLR
if ($_POST['treporte'] == 2) {
	$query = '';
	if ($_POST['nomina'] != '') $query .= " and personal.nomina = '" . substr($_POST['per1'], 13, 3) . "' ";
	//$consulta = "select * from personal where id='".$_SESSION['id_validar']."' and status<>'I' $query order by codigo";
	$consulta = "SELECT sso,cedula,fechan,nombres,nombres1,apellidos,apellidos1,cantidad,sum(monto) as monto FROM historico,personal
		WHERE historico.cedula=personal.codigo and historico.id=personal.id and periodo>='" . substr($_POST['per1'], 0, 3) . "' and periodo<='" . substr($_POST['per2'], 0, 3) . "' and
		historico.id=" . $_SESSION['id_validar'] . " and concepto=2300  group by cedula,cantidad order by cedula";

	$resultado = mysqli_query($enlace, $consulta) or die('verificaci&oacute; del c&oacute;digo fall&oacute;: ' . mysqli_error($enlace));
	$cont = 0;
	$data = array();
	$cabecera = array("RIF", "CEDULA", "NOMBRE1", "NOMBRE2", "APELLIDO1", "APELLIDO2", "%RETENCION", "MONTO");
	$cabecera = implode(";", $cabecera);
	while ($row = mysqli_fetch_row($resultado)) {
		$cont++;
		$data[] = implode(";", $row);
	}
	$data = implode("\n", $data);
	$arch = "ISLR.csv";
	header("Content-type: text/csv");
	header("Content-Disposition: attachment; filename=" . $arch);
	header("Pragma: no-cache");
	header("Expires: 0");
	echo $cabecera . "\n";
	echo utf8_decode($data);

	exit();
}
////////////////////GENERAR ARCHIVO TOTAL ASIGNACIONES
if ($_POST['treporte'] == 3) {
	$query = '';
	if ($_POST['nomina'] != '') $query .= " and personal.nomina = '" . substr($_POST['per1'], 13, 3) . "' ";
	//$consulta = "select * from personal where id='".$_SESSION['id_validar']."' and status<>'I' $query order by codigo";
	$consulta = "select sso,cedula,nombres,nombres1,apellidos,apellidos1,group_concat(monto order by monto desc SEPARATOR ';') from (SELECT sso,cedula,nombres,nombres1,apellidos,apellidos1,sum(monto) as monto FROM historico,personal
		WHERE historico.cedula=personal.codigo and historico.id=personal.id and periodo>='" . substr($_POST['per1'], 0, 3) . "' and periodo<='" . substr($_POST['per2'], 0, 3) . "' and
		historico.id=" . $_SESSION['id_validar'] . " and concepto BETWEEN '1000' and '1999' AND historico.tipo='A' group by cedula,historico.tipo order by cedula ) as a group by cedula";
	$resultado = mysqli_query($enlace, $consulta) or die('verificaci&oacute; del c&oacute;digo fall&oacute;: ' . mysqli_error($enlace));
	$cont = 0;
	$data = array();
	$cabecera = array("RIF", "CEDULA", "NOMBRE1", "NOMBRE2", "APELLIDO1", "APELLIDO2", "TOTAL ASIGNACIONES");
	$cabecera = implode(";", $cabecera);
	while ($row = mysqli_fetch_row($resultado)) {
		$cont++;
		$data[] = implode(";", $row);
	}
	$data = implode("\n", $data);
	$arch = "TotalAsigDeduc.csv";
	header("Content-type: text/csv");
	header("Content-Disposition: attachment; filename=" . $arch);
	header("Pragma: no-cache");
	header("Expires: 0");
	echo $cabecera . "\n";
	echo utf8_decode($data);

	exit();
}

/*
////////////////////REGISTRO DE VACACIONES PAGADAS (LIBRO DE VACACIONES LOTTT)
if ($_POST['treporte']==4) {
 $query='';
 if ($_POST['nomina']!='') $query .= " and personal.nomina = '".substr($_POST['per1'],13,3)."' ";
 		//$consulta = "select * from personal where id='".$_SESSION['id_validar']."' and status<>'I' $query order by codigo";
		$consulta = "SELECT cedula, CONCAT(nombres,' ',nombres1,' ',apellidos,' ',apellidos1),fechai,antiguedad, sueldo DIV 30, dvac, dias_ext, dbon, dias_ext2, otros, sum(dvac + dias_ext + dbon + dias_ext2 + otros), ((sum(dvac + dias_ext + dbon + dias_ext2 + otros)*sueldo)div 30), sum(dvac + dias_ext + otros), fdesde, fhasta FROM vacacion,personal
		WHERE vacacion.cedula=personal.codigo and vacacion.id=personal.id and vacacion.id=".$_SESSION['id_validar']."  group by cedula,fdesde order by fdesde";

		$resultado = mysqli_query($enlace,$consulta) or die('verificaci&oacute; del c&oacute;digo fall&oacute;: ' . mysqli_error($enlace));

		$cont=0;
		$data=array();
		$cabecera=array("Cedula","Nombre y Apellidos Trabajador","Fech_Ing","Anos_Servicio","Salario_diario","Dias_Hab (Art. 190)","Dias_Adic. (Art. 190)","Dias_Bono_Vac (Art. 192)","Dias_Adic_Bono_Vac (Art. 192)","Dias_descanso","Total_dias_a_pagar","Monto_a_pagar_Bs.","Total_dias_disfrute","Fec_Desde","Fec_hasta");
		$cabecera=implode(";",$cabecera);
		while ($row=mysqli_fetch_row($resultado)) {
		     $cont++;
			 $data[]=implode(";",$row);
		}
		$data=implode("\n",$data);
$arch="libro_vacaciones.csv";
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=".$arch);
header("Pragma: no-cache");
header("Expires: 0");
echo "Empresa: ".$_SESSION['empresa_validar']."\n";
echo " \n";
echo "Registro de Vacaciones pagadas Art. 203 LOTTT \n";
echo "\n";
//echo substr($_POST['per1'],19,10)."\n";
echo $cabecera."\n";
echo utf8_decode($data);

 exit();
}
*/

/*

////////////////////GENERAR ARCHIVO INCES
if ($_POST['treporte']==5) {
 $query='';
 if ($_POST['nomina']!='') $query .= " and personal.nomina = '".substr($_POST['per1'],13,3)."' ";
 		//$consulta = "select * from personal where id='".$_SESSION['id_validar']."' $query order by codigo";



		$pocentajeIncesPatrono = 0.02;
		$consulta = "select sso,personal_sueldo.codigo,nombres,nombres1,apellidos,apellidos1,status, REPLACE(REPLACE(FORMAT(SUM(sueldo),2),',',''),'.',',') AS monto, REPLACE(REPLACE(FORMAT(SUM(sueldo)*'".$pocentajeIncesPatrono."', 2), ',', ''), '.', ',') as aporte,
		(SELECT REPLACE(REPLACE(FORMAT(monto,2),',',''),'.',',') FROM utilidades WHERE utilidades.cedula=personal.codigo AND utilidades.id=".$_SESSION['id_validar']." AND fecha>='".substr($_POST['per1'],19,10)."' and fecha<='".substr($_POST['per2'],33,10)."' AND concepto='8005') as utilidad,

		(SELECT REPLACE(REPLACE(FORMAT(monto,2),',',''),'.',',') FROM utilidades WHERE utilidades.cedula=personal.codigo AND utilidades.id=".$_SESSION['id_validar']." AND fecha>='".substr($_POST['per1'],19,10)."' and fecha<='".substr($_POST['per2'],33,10)."' AND concepto='8004') as retenido,

		(SELECT REPLACE(REPLACE(FORMAT(valor_utilid_pagar,2),',',''),'.',',') FROM liquidaciones WHERE liquidaciones.cedula=personal.codigo AND liquidaciones.id=".$_SESSION['id_validar']." AND status='I' AND egreso>='".substr($_POST['per1'],19,10)."' AND egreso<='".substr($_POST['per2'],33,10)."') as util_liquid,

		(SELECT REPLACE(REPLACE(FORMAT(inces,2),',',''),'.',',') FROM liquidaciones WHERE liquidaciones.cedula=personal.codigo AND liquidaciones.id=".$_SESSION['id_validar']." AND status='I' AND egreso>='".substr($_POST['per1'],19,10)."' AND egreso<='".substr($_POST['per2'],33,10)."') as retenido_liquid

		FROM personal_sueldo,personal WHERE personal_sueldo.codigo=personal.codigo and personal_sueldo.id=personal.id and fec>='".substr($_POST['per1'],19,10)."' and fec<='".substr($_POST['per2'],33,10)."' and personal_sueldo.id=".$_SESSION['id_validar']."  group by codigo order by codigo ";
		$resultado = mysqli_query($enlace,$consulta) or die('verificaci&oacute; del c&oacute;digo fall&oacute;: ' . mysqli_error($enlace));
		$cont=0;

		$data=array();
		$cabecera=array("RIF","CEDULA","NOMBRE1","NOMBRE2","APELLIDO1","APELLIDO2","Estatus_trabajador","Total_salarios_periodo","Aporte 2% patrono","Utilidades pagadas","0,5% retenido_trabajador","Util_en_liquid_retiro","0,5%_retenido_liquid", "Total_INCES_trabajador");
		$cabecera=implode(";",$cabecera);
		$h=0;
		$i=0;
		$j=0;
		$k=0;
		$l=0;
		$m=0;
		$n=0;
		$total_inces_trabajador=0.0;

		while ($row=mysqli_fetch_row($resultado)) {
	        $cont++;
	        $total_inces_trabajador_= str_replace(",",".",$row[8])+ str_replace(",",".",$row[10])+str_replace(",",".",$row[12]);
            $total_inces_trabajador=str_replace(".",",",$total_inces_trabajador_);
            $h+=str_replace(",",".",$row[7]);
            $i+=str_replace(",",".",$row[8]);
            $j+=str_replace(",",".",$row[9]);
            $k+=str_replace(",",".",$row[10]);
            $l+=str_replace(",",".",$row[11]);
            $m+=str_replace(",",".",$row[12]);
            $n+=$total_inces_trabajador_;
            array_push($row, $total_inces_trabajador);
		    $data[]=implode(";",$row);
		}

		array_push($data, ";;;;;;;".str_replace(".",",",$h).";".str_replace(".",",",$i).";".str_replace(".",",",$j).";".str_replace(".",",",$k).";".str_replace(".",",",$l).";".str_replace(".",",",$m).";".str_replace(".",",",$n)."\n");
		$data=implode("\n",$data);


    $arch="Reporte_INCES.csv";
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=".$arch);
    header("Pragma: no-cache");
    header("Expires: 0");
    echo $cabecera."\n";
    echo utf8_decode($data);

     exit();
}
*/

////////////////////GENERAR ARCHIVO COSTO LABORAL 11/05/2020 -- Miguelangel

if ($_POST['treporte'] == 6) {
	$query = '';
	if ($_POST['nomina'] != '') $query .= "personal.nomina = '" . substr($_POST['per1'], 13, 3) . "' ";
	//$consulta = "select * from personal where id='".$_SESSION['id_validar']."' and status<>'I' $query order by codigo";
	$consulta = "SELECT cedula, CONCAT( personal.nombres, ' ', personal.nombres1, ' ', personal.apellidos, ' ', personal.apellidos1 ), periodo, fecha_pago,
		REPLACE(REPLACE(FORMAT(salario_mes,2),',',''),'.',','), REPLACE(REPLACE(FORMAT(cestatic,2),',',''),'.',','), REPLACE(REPLACE(FORMAT(prestac_mes,2),',',''),'.',','),
		REPLACE(REPLACE(FORMAT(interes_mes,2),',',''),'.',','),
		REPLACE(REPLACE(FORMAT(utilidad_mes,2),',',''),'.',','),
		REPLACE(REPLACE(FORMAT(vacac_provis_mes,2),',',''),'.',','),
		REPLACE(REPLACE(FORMAT(bonovac_provis_mes,2),',',''),'.',','),
		REPLACE(REPLACE(FORMAT(sso_patrono_mes,2),',',''),'.',','),
		REPLACE(REPLACE(FORMAT(rpe_patrono_mes,2),',',''),'.',','),
		REPLACE(REPLACE(FORMAT(faov_patrono_mes,2),',',''),'.',','),
		REPLACE(REPLACE(FORMAT(inces_mes,2),',',''),'.',','),
		REPLACE(REPLACE(FORMAT(costo_laboral_mes,2),',',''),'.',',')
		FROM costo_laboral AS costo_laboral JOIN personal AS personal ON personal.codigo = costo_laboral.cedula  WHERE costo_laboral.periodo >= '" . substr($_POST['per1'], 0, 3) . "' AND costo_laboral.periodo <='" . substr($_POST['per2'], 0, 3) . "' and costo_laboral.cedula=personal.codigo and costo_laboral.id=personal.id and costo_laboral.id=" . $_SESSION['id_validar'] . "  order by cedula,periodo";

	$resultado = mysqli_query($enlace, $consulta) or die('verificaci&oacute; del c&oacute;digo fall&oacute;: ' . mysqli_error($enlace));

	$cont = 0;
	$data = array();
	$cabecera = array("Cedula", "Nombre y Apellidos Trabajador", "Periodo", "Fecha_remuner", "Salario(Bs)", "Cestaticket(Bs)", "Prestaciones(Bs)", "Inter_mes(Bs)", "Utilidades(Bs)", "Vacaciones(Bs)", "Bono_Vacacional(Bs)", "SSO(Bs)", "RPE(Bs)", "FAOV(Bs)", "INCES(Bs)", "Costo Laboral total(Bs)");
	$cabecera = implode(";", $cabecera);
	while ($row = mysqli_fetch_row($resultado)) {
		$cont++;
		$data[] = implode(";", $row);
	}
	$data = implode("\n", $data);
	$arch = "Costo_laboral.csv";
	header("Content-type: text/csv");
	header("Content-Disposition: attachment; filename=" . $arch);
	header("Pragma: no-cache");
	header("Expires: 0");
	echo "Empresa: " . $_SESSION['empresa_validar'] . "\n";
	echo " \n";
	echo "Costo laboral calulado por trabajador \n";
	echo "\n";
	echo "Periodo del: " . substr($_POST['per1'], 19, 10) . " al " . substr($_POST['per2'], 33, 10) . "\n";
	echo "\n";

	echo $cabecera . "\n";
	echo utf8_decode($data);

	exit();
}
////////////////////FIN DE REPORTE COSTO LABORAL


/////////////////////////////////////////////////asientos contables nomina
if ($_POST['treporte'] == 7) {
	$consulta = "
		SELECT h.cedula,
			h.concepto,
			h.desconcepto,
			c.cuenta,
			h.tipo,
			h.monto,
			p.departamento,
			p.cuenta_labor,
			p.subcuenta_labor,
			c.subcuenta,
			h.desperiodo
		FROM historico AS h
		JOIN concepto as c ON h.concepto = c.codigo
		JOIN personal AS p ON h.cedula = p.codigo
		WHERE c.id = h.id
		AND h.periodo >= '" . substr($_POST['per1'], 0, 3) . "' AND h.periodo <='" . substr($_POST['per2'], 0, 3) . "'
		ORDER BY h.periodo ASC, h.cedula ASC";

	if (substr($_POST['per1'], 13, 3) == 100) {
		$consulta_concepto_total = "SELECT * FROM concepto WHERE codigo = '7100' LIMIT 1";
	} elseif (substr($_POST['per1'], 13, 3) == 200) {
		$consulta_concepto_total = "SELECT * FROM concepto WHERE codigo = '7200' LIMIT 1";
	}
	include_once("Asientos.php");
}

////////// fin asientos contables nomina

/////////////////////////////////////////////////asientos contables Utilidades
if ($_POST['treporte'] == 8) {
	$consulta = "
		SELECT u.cedula,
			u.concepto,
			u.fecha,
			u.desconcepto,
			u.fecha,
			c.cuenta,
			c.subcuenta,
			u.tipo,
			u.monto,
			p.departamento,
			u.detalle
		FROM utilidades AS u
		JOIN concepto as c ON u.concepto = c.codigo
		JOIN personal AS p ON u.cedula = p.codigo
		WHERE c.id = u.id AND
		u.concepto IN('8017','8018','8019','8020','8021','8117','8118','8119','8120','8121')


		AND u.fecha = '2022-04-08' AND monto >0 AND u.nomina='" . substr($_POST['per1'], 13, 3) . "'
		ORDER BY u.fecha ASC, u.cedula ASC, u.concepto ASC";

	$consulta_concepto_total = "SELECT * FROM concepto WHERE codigo IN ('8025','8125') LIMIT 1";

	include_once("Asientos_utilidades.php");
}

////////// fin asientos contables Utilidades





?>
<html>

<head>
	<link rel='stylesheet' type='text/css' href='styles.css' />
</head>

<body>
	<?
	menu();
	?>
	<br>
	<table border=0 cellpadding=0 cellspacing=0 width='100%'>
		<tr>
			<td width='100%' align='left'>
				<font size=2 color='black' face='verdana'>Empresa: <b><? echo $_SESSION['empresa_validar']; ?></b> - Per&iacute;odo: <b>
						<font color=red><? echo $per; ?></font>
					</b> - Usuario: <b><? echo $_SESSION['nombre_validar']; ?></b></font>
			</td>
		</tr>
	</table>
	<hr>
	<?
	echo "<font face='Verdana, Arial, Helvetica, sans-serif' size=4>Generar Archivos Textos</font>";
	echo "<font face='verdana' size=2>";
	echo "
	<br><br><form name='entrada' action='" . $_SERVER['PHP_SELF'] . "' target='blank' method='POST' enctype='multipart/form-data'>
	<table align='center'>";
	if ($per != '') {
		echo "<tr><td align='righta'>Per&iacute;odo Actual:</td>
						  <td align='left'><font color=red>" . $per . "</font></td>
						  </tr>";
	}
	echo "
				<tr><td align='righta'>Tipo de Archivo:</td>
				<td align='left'>
					<select style='width:300px;' name='treporte'>
						<option value='1'>Texto Habitacional (FAOV)</option>
						<option value='2'>ISLR</option>
						<option value='3'>TOTAL ASIGNACIONES</option>
						<option value='6'>Costo Laboral Integral</option>
						<option value='7'>Asientos Contables</option>
						<option value='8'>Asientos de Utilidades</option>




					</select>
				</td>
				</tr>";
	//<option value='5'>Reporte INCES</option> lo saqué aparte (reporte_INCES.php)
	//<option value='4'>Libro de Vacaciones</option> lo saqué en un archivo aparte (reporte_vacaciones.php)
	//Miguelangel 20-04-2020

	$consulta = mysqli_query($enlace, "select * from periodo where id='" . $_SESSION['id_validar'] . "' order by nomina,periodo DESC") or die("select * from periodo order by nomina,periodo DESC");
	$numr = mysqli_num_rows($consulta);
	echo "<td align = ''> <font color=red>Per&iacute;odo Desde: </font></td>";
	echo "<td align = 'left'> <select style='width:300px;' name = 'per1'>";
	for ($x = 1; $x <= $numr; $x++) {
		$row1 = mysqli_fetch_array($consulta);
		if ($x != 1) {
			echo "<option>" . $row1['periodo'] . " - Nomina:" . $row1['nomina'] . " - " . $row1['desde'] . " al " . $row1['hasta'];
		}
	}
	echo "</select>";
	echo "</td></tr>";

	$consulta = mysqli_query($enlace, "select * from periodo where id='" . $_SESSION['id_validar'] . "' order by nomina,periodo DESC") or die("select * from periodo order by nomina,periodo DESC");
	$numr = mysqli_num_rows($consulta);
	echo "<td align = ''> <font color=red>Per&iacute;odo Hasta: </font></td>";
	echo "<td align = 'left'> <select style='width:300px;' name = 'per2'>";
	for ($x = 1; $x <= $numr; $x++) {
		$row1 = mysqli_fetch_array($consulta);
		if ($x != 1) {
			echo "<option>" . $row1['periodo'] . " - Nomina:" . $row1['nomina'] . " - " . $row1['desde'] . " al " . $row1['hasta'];
		}
	}
	echo "</select>";
	echo "</td></tr>";

	echo "<tr>";
	$consulta = "Select * from tablas where tabla=ucase('GERENCIA') and id='" . $_SESSION['id_validar'] . "'  order by codigo,detalle";
	$consulta = mysqli_query($enlace, $consulta) or die("no se pudo realizar la consulta..." . $consulta . '=' . mysqli_error($enlace));
	$resultado = mysqli_num_rows($consulta);
	echo "<td align = 'righta'> Gerencia: </td>";
	echo "<td align = 'left'> <select style='width:300px;' name = 'gerencia'><option>";
	if ($resultado != 0) {
		for ($i = 0; $i < $resultado; $i++) {
			$row1 = mysqli_fetch_array($consulta);
			echo "<option width = '30%'>" . $row1['codigo'] . " - " . $row1['detalle'];
		}
	}
	echo "</select>";
	echo "</td>";
	echo "</tr>";

	echo "<tr>";
	$consulta = "Select * from tablas where tabla=ucase('DIVISION') and id='" . $_SESSION['id_validar'] . "' order by codigo,detalle";
	$consulta = mysqli_query($enlace, $consulta) or die("no se pudo realizar la consulta..." . $consulta . '=' . mysqli_error($enlace));
	$resultado = mysqli_num_rows($consulta);
	echo "<td align = 'righta'> Divisi&oacute;n: </td>";
	echo "<td align = 'left'> <select style='width:300px;' name = 'division'><option>";
	if ($resultado != 0) {
		for ($i = 0; $i < $resultado; $i++) {
			$row1 = mysqli_fetch_array($consulta);
			echo "<option width = '30%'>" . $row1['codigo'] . " - " . $row1['detalle'];
		}
	}
	echo "</select>";
	echo "</td>";
	echo "</tr>";

	echo "<tr>";
	$consulta = "Select * from tablas where tabla=ucase('DEPARTAMENTO') and id='" . $_SESSION['id_validar'] . "' order by codigo,detalle";
	$consulta = mysqli_query($enlace, $consulta) or die("no se pudo realizar la consulta..." . $consulta . '=' . mysqli_error($enlace));
	$resultado = mysqli_num_rows($consulta);
	echo "<td align = 'righta'> Departamento: </td>";
	echo "<td align = 'left'> <select style='width:300px;' name = 'departamento'><option>";
	if ($resultado != 0) {
		for ($i = 0; $i < $resultado; $i++) {
			$row1 = mysqli_fetch_array($consulta);
			echo "<option width = '30%'>" . $row1['codigo'] . " - " . $row1['detalle'];
		}
	}
	echo "</select>";
	echo "</td>";

	echo "<tr><td colspan='4' align='center'>";
	echo "<input name='ver' type='submit' style='margin-left:5px; height:35px; width:200px' value='GENERAR REPORTE'>";
	echo "</td></tr>";
	echo "</table></form></font>";
	?>

</body>

</html>
