<? session_start();

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");
include("calendario/calendario.php");
$enlace = cargar_conexion();
$accion = $_REQUEST["accion"];
$cedula = ($_POST['graba'] == '1' ? $_POST['cedula'] : $_REQUEST["cedula"]);
$codigo = $_REQUEST["codigo"];
$fecha = $_REQUEST["fecha"];
$monto = $_REQUEST["monto"];

$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 = '';
menu();

/////////////////////////////////////////////////MOSTRAR SOLICITUD DEL TRABAJADOR ////////////////////////////////////////////////////////////////
if ((!$_POST && $accion != 1 && $accion != 2 && $_POST['grabar'] != 1) || $_POST['busca'] == 1) {

	echo "<center><b>Opciones:</b>";
	//echo " &nbsp;&nbsp;<img border = 0 src='img2/monitor.png' alt='Seleccionar'>&nbsp;Seleccionar Trabajador";
	echo " &nbsp;&nbsp;<img border = 0 src='img2/archivo.png' alt='importar_remuneraciones'>:<a href='prestaciones_remuneracion_importar.php?cedula=" . $cedula . "'>Importar Datos EXCEL</a>
	<hr>";
	echo "</center>";

	echo "<h2><center>Actualizaci&oacute;n de Remuneraciones de Trabajadores</center></h2>";

	echo "<form name = 'entrada' action = '" . $_SERVER['PHP_SELF'] . "' method = 'POST'  enctype='multipart/form-data'>";
	echo "<input type = 'hidden' name = 'busca' value = '1'>";
	echo "<table cellpadding=2 cellspacing=0 width='500' align='center'>";
	echo "<tr>";
	echo "<td align=right> C&eacute;dula/Nombre/Apellido:</td>";
	echo "<td> <input name='cedula' id='cedula' size='30' maxlength='12' onkeyup='buscarEmpleado(this.value)'>
			<div id='sugerencias' style='background:white; border:0px solid #ccc; position:absolute; width:300px; z-index:1000;'></div></td>";
	echo "</tr>";
	echo "<tr>";
	echo "<td align=right> Ordenado por:</td>";
	echo "<td colspan = 3>";
	echo "	<input type = 'radio' name = 'orden' value = 'ced' checked> cedula";
	echo "	<input type = 'radio' name = 'orden' value = 'nom'> nombre";
	echo "	<input type = 'radio' name = 'orden' value = 'ape'> apellido";
	echo "	<input type = 'radio' name = 'orden' value = 'fechai'> Fecha Ingreso";
	echo "</tr>";
	echo "</table>";
	echo "	<script language='javascript' type='text/javascript'>";
	echo "		document.entrada.cedula.focus()";
	echo "	</script>";
	echo "<table border=0  align = 'center'><tr>";
	echo "<td><input type = 'submit' class='boton' value = 'Buscar Registros'></td>";
	echo "</tr></table></form>";

	$query1 = "";
	if ($_POST['cedula'] != "") {
		$query1 = " and (codigo like '%" . $_POST['cedula'] . "%' or nombres like '%" . $_POST['cedula'] . "%' or apellidos like '%" . $_POST['cedula'] . "%') ";
	}
	if ($_POST['orden'] == "fechai") $query2 = " order by fechai";
	else if ($_POST['orden'] == "ced") $query2 = " order by codigo";
	else if ($_POST['orden'] == "ape") $query2 = " order by apellidos";
	else $query2 = " order by nombres";

	//$consulta="select * from personal where id='".$_SESSION['id_validar']."' and status<>'I' ".$query1.$query2;
	$consulta = "select * from personal where id='" . $_SESSION['id_validar'] . "' " . $query1 . $query2;
	$resultado = mysqli_query($enlace, $consulta) or die('verificaci&oacute; del c&oacute;digo fall&oacute;: ' . mysqli_error($enlace));
	$num_rows = mysqli_num_rows($resultado);
	if ($num_rows != 0) {
		echo "<table rules=none border=0 cellpadding=2 cellspacing=0 align='center'>";
		echo "<tr class='encabezadoTabla'>";
		//echo "<th align = center><font color='white'> Foto </font></th>";
		echo "<th align = left><font color='white'> C&eacute;dula </font></th>";
		echo "<th align = left><font color='white'> Nombres </font></th>";
		echo "<th align = left><font color='white'> Apellidos </font></th>";
		//echo "<th align = left><font color='white'> Ficha </font></th>";
		echo "<th align = center><font color='white'> Status </font></th>";
		echo "<th align = center><font color='white'> Ingreso </font></th>";
		echo "<th colspan = 4 align = center><font color='white'> Acci&oacute;n </font></th>";
		for ($cont = 0; $cont < $num_rows; $cont++) {
			$row = mysqli_fetch_array($resultado);
			$cedula = $row['codigo'];
			if ($color) {
				$tcolor = "#CFE7DE";
				if (file_exists('fotos/' . $cedula . '.jpg')) $imagen = 'fotos/' . $cedula . '.jpg';
				else $imagen = 'img2/nohay2.jpg';
			} else {
				$tcolor = "white";
				if (file_exists('fotos/' . $cedula . '.jpg')) $imagen = 'fotos/' . $cedula . '.jpg';
				else $imagen = 'img2/nohay.jpg';
			}
			echo '<tr bgcolor=' . $tcolor . ' >';
			//echo "<td align'center'><img src='" . $imagen . "' height='64' width='64'></td>";
			echo "<td width='100'><a href='" . $_SERVER['PHP_SELF'] . "?accion=1&cedula=" . $cedula . "'>" . $row['codigo'] . "</a></td>";
			echo "<td width='250'>" . trim($row['nombres']) . " " . $row['nombres1'] . "</td>";
			echo "<td width='250'>" . trim($row['apellidos']) . " " . $row['apellidos1'] . "</td>";
			//echo "<td width='100'>" . $row['sso'] . "</td>";
			if ($row['status'] == 'A') {
						echo "<td width='50' align='center'><img src=img2/status_ver_doble_zaul.png></td>";
					} elseif ($row['status'] == 'C') {
						echo "<td width='50' align='center'><img src=img2/status_ver.png></td>";
					} elseif ($row['status'] == 'S') {
						echo "<td width='50' align='center'><img src=img2/status_ver_naranja.png></td>";
					} elseif ($row['status'] == 'I') {
						echo "<td width='50' align='center'><img src=img2/trabajador_inactivo.png></td>";
					}
			echo "<td width='120' align=center>" . mostrar_fecha($row['fechai']) . "</td>";

			echo "<td width='30' align='center'><a href='" . $_SERVER['PHP_SELF'] . "?accion=1&cedula=" . $cedula . "'><img border = 0 src='img2/monitor.png' alt='Seleccionar Ã©ste registro'></a></td>";

			echo '</tr>';
			$color = !$color;
		}
		echo '</table>';
	} else echo "<hr>";
	mysqli_free_result($resultado);
}

///////////////////////////////////////////////// MOSTRAR DATA A INGRESAR ////////////////////////////////////////////////////////////////
if ($accion == 1 || $accion == 2 || $_POST['graba'] == 1 || $_POST['nuevo'] == 1) {

	echo "<b>Opciones:</b>";
	echo "&nbsp;&nbsp;
      <a href='" . $_SERVER['PHP_SELF'] . "'>
          <img border='0' src='img2/regresa.png' alt='Regresar'>
          Regresar
      </a>";

	echo "<h2><center>Actualizaci&oacute;n de Remuneraciones de Trabajadores</center></h2>";
	///////////////////////////////////////////////// graba registros  ////////////////////////////////////////////////////////////////
	if ($_POST['graba'] == 1) {
		if ($_POST['mon'] == '' || $_POST['mon'] <= 0) $men = 'Falta completar Datos..';
		else {
			$fing = substr($_POST['fec'], 4, 4) . '-' . substr($_POST['fec'], 2, 2) . '-' . substr($_POST['fec'], 0, 2);
			$query = "insert into personal_sueldo  ( id, codigo, fec, sueldo) values('" . $_SESSION['id_validar'] . "',ucase(trim('" . $_POST['cedula'] . "')), ucase(trim('" . $fing . "')), '" . $_POST['mon'] . "') ";
			$consulta = mysqli_query($enlace, $query) or die("no se pudo ingresar los datos..." . mysqli_error($enlace) . $query);
			$consulta = "select * from personal_sueldo where id='" . $_SESSION['id_validar'] . "' and codigo='" . $cedula . "' order by fec desc limit 1";
			$resultado = mysqli_query($enlace, $consulta) or die($consulta . mysqli_error($enlace));
			$num_rows = mysqli_num_rows($resultado);
			/*if ($num_rows!=0) {
				$row=mysqli_fetch_array($resultado);
				$sue=$row['sueldo'];
				$consulta="update personal set smes=$sue where id='".$_SESSION['id_validar']."' and codigo='".$cedula."' and smes<".$sue."";
				$resultado = mysqli_query($enlace,$consulta) or die($consulta . mysqli_error($enlace));
			}*/
		}
		$accion = 3;
		$cedula = $_POST['cedula'];
	}


	////////////////////////////////////////////  eliminar item
	if ($accion == 2) {
		$consulta = "delete from personal_sueldo where id='" . $_SESSION['id_validar'] . "' and codigo= '" . $cedula . "' and fec='" . $fecha . "' and sueldo='" . $monto . "' ";
		$resultado = mysqli_query($enlace, $consulta)  or die($consulta . mysqli_error($enlace));
		$men = "Registro Eliminado..";
	}

	//////////////////////////////////////////// 

		////////////////////////MOSTRAR TRABAJADOR

	$consulta = "select * from personal where id='" . $_SESSION['id_validar'] . "' and codigo='" . $cedula . "' ";
	$resultado = mysqli_query($enlace, $consulta) or die('verificaci&oacute; del c&oacute;digo fall&oacute;: ' . mysqli_error($enlace));
	$num_rows = mysqli_num_rows($resultado);
	if ($num_rows != 0) {
		$row = mysqli_fetch_array($resultado);

		/* if (file_exists('fotos/' . $cedula . '.jpg')) $imagen = 'fotos/' . $cedula . '.jpg';
		else $imagen = 'img2/nohay2.jpg'; */ ///innecesario mostrar la foto

		//echo "<br><center><img style='border-width: 1px; border-color: 75263C;border-style: solid;' src='" . $imagen . "' height='30' width='30'>&nbsp;<font color=black size=5>&nbsp;" . trim($row['nombres']) . " " . trim($row['nombres1']) . ' ' . trim($row['apellidos']) . " " . trim($row['apellidos1']) . " (<font color=black size=4>C.I.: " . substr($cedula, 0, 2) . '.' . substr($cedula, 2, 3) . '.' . substr($cedula, 5, 3) . "</font>)</font></center>";
		echo "<br><center>&nbsp;<font color=black size=5>&nbsp;" . trim($row['nombres']) . " " . trim($row['nombres1']) . ' ' . trim($row['apellidos']) . " " . trim($row['apellidos1']) . "</font></center>";
		echo "<br><center>&nbsp;<font color=black size=5>&nbsp;" .  " <font color=black size=4>C.I.: " . $cedula . "</font></font></center>";

		echo "<form name = 'entrada' action = '" . $_SERVER['PHP_SELF'] . "' method = 'POST'  enctype='multipart/form-data'>";
		echo "<input type = 'hidden' name = 'graba' value = '1'>";
		echo "<input type = 'hidden' name = 'cedula' value = '" . $cedula . "'>";
		echo "<br><center><font color=red>Datos a Ingresar</font></center>";
?>
		<form name='entrada' action='<? echo $_SERVER['PHP_SELF']; ?>' method='POST'>
			<input type='hidden' name='graba' value='1'>
			<input type='hidden' name='cedula' value='<? echo $row['codigo']; ?>'>
			<table align='center'>
				<tr>
					<td align='right'>Fecha (DDMMAAAA)?</b></td>
					<td><input type='text' name='fec' size='20' maxlength='8'>
					</td>
				</tr>
				<tr>
					<td align='right'>Nuevo Sueldo?</td>
					<td><input type='text' name='mon' size='20'>
					</td>
				</tr>
				<tr>
					<td colspan=2>&nbsp;</td>
				</tr>
			</table>
			<center>
				<font size=3 face='Verdana' color='red'><b><? echo $men; ?></b></font>
			</center>
	<?
		echo "<table width = '20%' align ='center'>";
		echo "<tr><td><input type = 'submit' class='boton' value = 'Grabar Nuevo Sueldo'></td>";
		echo "<script language='javascript' type='text/javascript'>	document.entrada.fec.focus(); </script>";
		echo "</tr></table>";

		$consulta = "select * from personal_sueldo where id='" . $_SESSION['id_validar'] . "' and codigo='" . $cedula . "' order by fec";
		$resultado = mysqli_query($enlace, $consulta) or die($consulta . mysqli_error($enlace));
		$num_rows = mysqli_num_rows($resultado);
		if ($num_rows != 0) {
			$total = 0;
			$linea = 0;
			echo "<br><table border=1 cellpadding=2 cellspacing=0 align='center'>";
			echo "<tr class='encabezadoTabla'>";
			echo "<th ali = center><font face='verdana' size=2> #</font></th>";
			echo "<th ali = center><font face='verdana' size=2> Fecha</font></th>";
			echo "<th ali = center><font face='verdana' size=2> Devengado</font></th>";
			echo "<th ali = center><font face='verdana' size=2> Eliminar </font></th></tr>";
			for ($cont = 0; $cont < $num_rows; $cont++) {
				$linea++;
				$color = !$color;
				if ($color) echo '<tr bgcolor="#CFE7DE" >';
				else echo '<tr bgcolor="#ffffff">';
				$row = mysqli_fetch_array($resultado);
				echo "<td width='50' class='numeroFila'>" . $linea . "</td>";
				echo "<td width='100'>" . mostrar_fecha($row['fec']) . "</td>";
				echo "<td width='100' align='right'>" . number_format($row['sueldo'], 2) . "</td>";

				if (substr($_SESSION['acceso_validar'],18,1)=='1'){
					echo "<td width='30' align='center'><a onclick='return validar_elimina()' href='" . $_SERVER['PHP_SELF'] . "?accion=2&cedula=" . $cedula . "&monto=" . $row['sueldo'] . "&fecha=" . $row['fec'] . "'><img border = 0 src='img2/borrar.png' alt='Eliminar'></a></td>";
				}else echo "<td width='60' align='center'>&nbsp;</td>";

				echo '</tr>';
				
			}
			echo '</tr></table></form>';
		}
		mysqli_free_result($resultado);
	}
}

mysqli_close($enlace);
echo "<br><br><br><br></body>";
echo "</html>";
?>


<!--Script JavaScript para hacer predictivo el cuadro de búsqueda de empleados -->
<script>
function buscarEmpleado(texto) {
    if (texto.length < 2) {
        document.getElementById("sugerencias").innerHTML = "";
        return;
    }

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "buscar_empleado_todos.php", true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById("sugerencias").innerHTML = xhr.responseText;
        }
    };

    xhr.send("q=" + texto);
}
</script>

	<style>
	.numeroFila {
		color: black;
		font-weight: bold;
		}

	.boton {
		border-radius: 8px;      /* Bordes redondeados */
		padding: 8px 16px;       /* Más espacio interno */
		border: none;            /* Quita el borde feo por defecto */
		cursor: pointer;         /* Mano al pasar */
		transition: 0.2s ease;   /* Animación suave */
		}

		.boton:hover {
		transform: scale(1.03);  /* Efecto sutil al pasar el mouse */
		}



	/*Encabezado tablas */
	.encabezadoTabla {
    background: #43bced;
    height: 35px;
	}

	.encabezadoTabla th {
		padding: 8px 12px;
		text-align: left;
		color: white;
		font-weight: bold;
		font-size: 14px;
		letter-spacing: 0.5px;
		border-bottom: 2px solid #2fa3c9;
	}

	.encabezadoTabla th:nth-child(1),
	.encabezadoTabla th:nth-child(2),
	.encabezadoTabla th:nth-child(3),
	.encabezadoTabla th:nth-child(4),
	.encabezadoTabla th:nth-child(5),
	.encabezadoTabla th:nth-child(6)
	 {
		text-align: center;
	}
	/*hasta aquí Encabezado tablas */
		
	</style>