<?php session_start(); include("../../bd/conexion.php"); // ★★★ DEPURACIÓN DE SESIÓN ★★★ $usuario_sesion = isset($_SESSION['DIGITA']) ? $_SESSION['DIGITA'] : 'NO_ENCONTRADO'; error_log("Usuario en sesión en select_epp.php: " . $usuario_sesion); // Si no hay usuario en la sesión, redirigir al login if(!isset($_SESSION['DIGITA']) || empty($_SESSION['DIGITA'])) { echo "<script>alert('Sesión expirada. Por favor, inicie sesión nuevamente.'); window.location.href='../login/index.html';</script>"; exit(); } // Variables para manejar la información del empleado $empleado_info = null; $mostrar_seleccion_epp = false; $mensaje_ultima_dotacion = ''; $detalles_ultima_dotacion = ''; // Procesar la búsqueda del empleado if(isset($_POST['buscar_empleado']) && !empty($_POST['cedula_empleado'])) { $cedula = mysqli_real_escape_string($conexion, $_POST['cedula_empleado']); // ★★★ PRIMERO BUSCAR EN LA TABLA EMPLEADO ★★★ $query_empleado_tabla = "SELECT * FROM empleado WHERE cedula = '$cedula'"; $result_empleado_tabla = mysqli_query($conexion, $query_empleado_tabla); if($result_empleado_tabla === false) { die("Error en la consulta empleado: " . mysqli_error($conexion)); } if(mysqli_num_rows($result_empleado_tabla) > 0) { // ★★★ EMPLEADO ENCONTRADO EN TABLA EMPLEADO ★★★ $empleado_info = mysqli_fetch_assoc($result_empleado_tabla); $mostrar_seleccion_epp = true; // Normalizar las claves del array para consistencia if(!isset($empleado_info['cedula']) && isset($empleado_info['CEDULA'])) { $empleado_info['cedula'] = $empleado_info['CEDULA']; } if(!isset($empleado_info['nombre']) && isset($empleado_info['NOMBRE'])) { $empleado_info['nombre'] = $empleado_info['NOMBRE']; } // Buscar la última entrega en dotxcc para mostrar información adicional $query_ultima_entrega = "SELECT * FROM dotxcc WHERE CEDULA = '$cedula' ORDER BY ID DESC LIMIT 1"; $result_ultima_entrega = mysqli_query($conexion, $query_ultima_entrega); if($result_ultima_entrega && mysqli_num_rows($result_ultima_entrega) > 0) { $ultima_entrega = mysqli_fetch_assoc($result_ultima_entrega); $fecha_ultima = date('d/m/Y', strtotime($ultima_entrega['FECHA'])); $mensaje_ultima_dotacion = "Empleado registrado - Última entrega de EPP: $fecha_ultima"; $detalles_ultima_dotacion = "<div class='mt-2'> <strong>Item:</strong> {$ultima_entrega['ITEM']}<br> <strong>Descripción:</strong> {$ultima_entrega['DESCRIPCION']}<br> <strong>Cantidad:</strong> {$ultima_entrega['CANTIDAD']} </div>"; } else { $mensaje_ultima_dotacion = "Empleado registrado - Sin entregas previas de EPP"; $detalles_ultima_dotacion = "<div class='mt-2'> <em>Este empleado no tiene entregas previas registradas</em> </div>"; } } else { // ★★★ NO ENCONTRADO EN TABLA EMPLEADO, BUSCAR EN DOTXCC ★★★ $query_dotxcc = "SELECT * FROM dotxcc WHERE CEDULA = '$cedula' ORDER BY ID DESC LIMIT 1"; $result_dotxcc = mysqli_query($conexion, $query_dotxcc); if($result_dotxcc === false) { die("Error en la consulta dotxcc: " . mysqli_error($conexion)); } if(mysqli_num_rows($result_dotxcc) > 0) { // Encontrado en dotxcc pero no en empleado (caso especial) $dotxcc_info = mysqli_fetch_assoc($result_dotxcc); $empleado_info = array( 'cedula' => $cedula, 'CEDULA' => $cedula, 'nombre' => '', // No tenemos nombre en dotxcc 'NOMBRE' => '', 'ccosto' => isset($dotxcc_info['CCOSTO']) ? $dotxcc_info['CCOSTO'] : '', 'cargo' => isset($dotxcc_info['CARGO']) ? $dotxcc_info['CARGO'] : '' ); $mostrar_seleccion_epp = true; $fecha_ultima = date('d/m/Y', strtotime($dotxcc_info['FECHA'])); $mensaje_ultima_dotacion = "Empleado con entregas previas pero no registrado en tabla empleado - Última entrega: $fecha_ultima"; $detalles_ultima_dotacion = "<div class='mt-2'> <strong>Item:</strong> {$dotxcc_info['ITEM']}<br> <strong>Descripción:</strong> {$dotxcc_info['DESCRIPCION']}<br> <div class='alert alert-warning mt-2'> <small><i class='fas fa-exclamation-triangle'></i> Se solicitará completar información del empleado</small> </div> </div>"; } else { // ★★★ EMPLEADO COMPLETAMENTE NUEVO ★★★ $mensaje_ultima_dotacion = "Empleado no encontrado. Será registrado como nuevo empleado."; $empleado_info = array( 'cedula' => $cedula, 'CEDULA' => $cedula, 'nombre' => '', 'NOMBRE' => '' ); $mostrar_seleccion_epp = true; } } } // ★★★ FUNCIÓN AUXILIAR PARA OBTENER VALORES SEGUROS ★★★ function obtener_valor_seguro($array, $claves_posibles, $valor_defecto = '') { if(!is_array($array)) return $valor_defecto; foreach($claves_posibles as $clave) { if(isset($array[$clave]) && !empty($array[$clave])) { return $array[$clave]; } } return $valor_defecto; } ?> <!DOCTYPE html> <html> <head> <title>Selección de EPP</title> <link rel="icon" type="image/png" href="../../img/icono.png"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <style> body { background-image: linear-gradient(to right, #e2e2e2, #ffe5c9); padding: 20px; } .container { max-width: 1000px; margin-top: 50px; } .inventory-container { margin-top: 20px; display: none; } .quantity-input { width: 70px; text-align: center; } table th { white-space: nowrap; } .user-info { background-color: #d4edda; border: 1px solid #c3e6cb; border-radius: 5px; padding: 10px; margin-bottom: 20px; } .empleado-info { background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 5px; padding: 15px; margin-bottom: 20px; } .empleado-registrado { background-color: #d4edda; border: 1px solid #c3e6cb; border-radius: 5px; padding: 15px; margin-bottom: 20px; } .ultima-dotacion { background-color: #d1ecf1; border: 1px solid #bee5eb; border-radius: 5px; padding: 10px; margin-bottom: 15px; } .detalles-dotacion { background-color: #f8f9fa; border-radius: 5px; padding: 10px; margin-top: 10px; border-left: 4px solid #17a2b8; } </style> </head> <body> <div class="container"> <a href="MENUP.PHP" class="btn btn-secondary"><i class="fas fa-home"></i> Menú Principal</a> <div class="user-info"> <strong><i class="fas fa-user"></i> Usuario logueado:</strong> <?php echo $_SESSION['DIGITA']; ?> </div> <div class="card"> <div class="card-header" style="background-color: #FF8A37; color: white;"> <h4>Selección de Elementos de Protección Personal</h4> </div> <div class="card-body"> <?php if(!$mostrar_seleccion_epp): ?> <form method="post" action=""> <div class="row"> <div class="col-md-8"> <label for="cedula_empleado">Cédula del Empleado:</label> <input type="text" class="form-control" id="cedula_empleado" name="cedula_empleado" placeholder="Ingrese el número de cédula" required> </div> <div class="col-md-4 d-flex align-items-end"> <button type="submit" name="buscar_empleado" class="btn" style="background-color: #FF8A37; color: white;"> <i class="fas fa-search"></i> Buscar Empleado </button> </div> </div> </form> <?php endif; ?> <?php if($empleado_info): ?> <?php // ★★★ OBTENER VALORES DE FORMA SEGURA ★★★ $cedula_mostrar = obtener_valor_seguro($empleado_info, ['cedula', 'CEDULA'], 'No disponible'); $nombre_mostrar = obtener_valor_seguro($empleado_info, ['nombre', 'NOMBRE'], ''); $ccosto_mostrar = obtener_valor_seguro($empleado_info, ['ccosto', 'CCOSTO'], ''); $cargo_mostrar = obtener_valor_seguro($empleado_info, ['cargo', 'CARGO'], ''); // Determinar si es un empleado ya registrado completamente $empleado_completo = !empty($nombre_mostrar); ?> <div class="<?php echo $empleado_completo ? 'empleado-registrado' : 'empleado-info'; ?>"> <h5> <i class="fas fa-user-check"></i> <?php echo $empleado_completo ? 'Empleado Registrado' : 'Información del Empleado'; ?> </h5> <div class="row"> <div class="col-md-6"> <p><strong>Cédula:</strong> <?php echo $cedula_mostrar; ?></p> <?php if(!empty($nombre_mostrar)): ?> <p><strong>Nombre:</strong> <?php echo $nombre_mostrar; ?></p> <?php else: ?> <p><em>Empleado nuevo - Se solicitará el nombre en el siguiente paso</em></p> <?php endif; ?> </div> <div class="col-md-6"> <?php if(!empty($ccosto_mostrar)): ?> <p><strong>Centro de Costo:</strong> <?php echo $ccosto_mostrar; ?></p> <?php endif; ?> <?php if(!empty($cargo_mostrar)): ?> <p><strong>Cargo:</strong> <?php echo $cargo_mostrar; ?></p> <?php endif; ?> </div> </div> <?php if($empleado_completo): ?> <div class="alert alert-success mt-2 mb-0"> <i class="fas fa-check-circle"></i> <strong>Empleado verificado</strong> - Información completa disponible </div> <?php endif; ?> </div> <div class="ultima-dotacion"> <i class="fas fa-info-circle"></i> <strong><?php echo $mensaje_ultima_dotacion; ?></strong> <?php if(!empty($detalles_ultima_dotacion)): ?> <div class="detalles-dotacion"> <?php echo $detalles_ultima_dotacion; ?> </div> <?php endif; ?> </div> <?php endif; ?> <?php if($mostrar_seleccion_epp): ?> <form id="eppForm" method="post" action="REG.php"> <?php // ★★★ OBTENER VALORES PARA LOS CAMPOS OCULTOS DE FORMA SEGURA ★★★ $cedula_para_enviar = obtener_valor_seguro($empleado_info, ['cedula', 'CEDULA'], ''); $nombre_para_enviar = obtener_valor_seguro($empleado_info, ['nombre', 'NOMBRE'], ''); $ccosto_para_enviar = obtener_valor_seguro($empleado_info, ['ccosto', 'CCOSTO'], ''); $cargo_para_enviar = obtener_valor_seguro($empleado_info, ['cargo', 'CARGO'], ''); // ★★★ DETERMINAR SI ES EMPLEADO NUEVO ★★★ $es_nuevo = empty($nombre_para_enviar) ? '1' : '0'; ?> <!-- ★★★ CAMPOS OCULTOS SEGUROS ★★★ --> <input type="hidden" name="usuario_logueado" value="<?php echo $_SESSION['DIGITA']; ?>"> <input type="hidden" name="cedula_empleado" value="<?php echo htmlspecialchars($cedula_para_enviar); ?>"> <input type="hidden" name="nombre_empleado" value="<?php echo htmlspecialchars($nombre_para_enviar); ?>"> <input type="hidden" name="ccosto_empleado" value="<?php echo htmlspecialchars($ccosto_para_enviar); ?>"> <input type="hidden" name="cargo_empleado" value="<?php echo htmlspecialchars($cargo_para_enviar); ?>"> <input type="hidden" name="es_empleado_nuevo" value="<?php echo $es_nuevo; ?>"> <input type="hidden" name="empleado_completo" value="<?php echo $empleado_completo ? '1' : '0'; ?>"> <!-- ★★★ CAMPOS DE DEPURACIÓN ★★★ --> <input type="hidden" name="debug_cedula" value="<?php echo htmlspecialchars($cedula_para_enviar); ?>"> <input type="hidden" name="debug_nombre" value="<?php echo htmlspecialchars($nombre_para_enviar); ?>"> <input type="hidden" name="debug_usuario" value="<?php echo htmlspecialchars($_SESSION['DIGITA']); ?>"> <input type="hidden" name="debug_array_keys" value="<?php echo htmlspecialchars(implode(',', array_keys($empleado_info))); ?>"> <div class="form-group"> <label for="tipoEpp">Tipo de EPP:</label> <select class="form-control" id="tipoEpp" name="tipoEpp" required> <option value="" selected disabled>Seleccione...</option> <option value="nuevo">Nuevo</option> <option value="usado">Reposicion</option> </select> </div> <div id="nuevoContainer" class="inventory-container"> <h5>Inventario Nuevo</h5> <div class="table-responsive"> <table class="table table-bordered table-hover"> <thead class="thead-light"> <tr> <th>Seleccionar</th> <th>Id</th> <th>Código</th> <th>Descripción</th> <th>Disponible</th> <th>Cantidad a Entregar</th> </tr> </thead> <tbody> <?php $query = "SELECT * FROM inventario WHERE CANTIDAD > 0"; $result = mysqli_query($conexion, $query); while($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td><input type='checkbox' name='epp_seleccionado[]' value='nuevo|".$row['ID']."|".$row['CODIGO']."|".$row['DESCRIPCION']."'></td>"; echo "<td>".$row['ID']."</td>"; echo "<td>".$row['CODIGO']."</td>"; echo "<td>".$row['DESCRIPCION']."</td>"; echo "<td>".$row['CANTIDAD']."</td>"; echo "<td><input type='number' class='form-control quantity-input' name='cantidad[".$row['ID']."]' min='1' max='".$row['CANTIDAD']."' value='1'></td>"; echo "</tr>"; } ?> </tbody> </table> </div> </div> <div id="usadoContainer" class="inventory-container"> <h5>Inventario Reposicion</h5> <div class="table-responsive"> <table class="table table-bordered table-hover"> <thead class="thead-light"> <tr> <th>Seleccionar</th> <th>Id</th> <th>Código</th> <th>Descripción</th> <th>Disponible</th> <th>Cantidad a Entregar</th> </tr> </thead> <tbody> <?php $query = "SELECT * FROM inventariousado WHERE CANTIDAD > 0"; $result = mysqli_query($conexion, $query); while($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td><input type='checkbox' name='epp_seleccionado[]' value='usado|".$row['ID']."|".$row['CODIGO']."|".$row['DESCRIPCION']."'></td>"; echo "<td>".$row['ID']."</td>"; echo "<td>".$row['CODIGO']."</td>"; echo "<td>".$row['DESCRIPCION']."</td>"; echo "<td>".$row['CANTIDAD']."</td>"; echo "<td><input type='number' class='form-control quantity-input' name='cantidad[".$row['ID']."]' min='1' max='".$row['CANTIDAD']."' value='1'></td>"; echo "</tr>"; } ?> </tbody> </table> </div> </div> <div class="mt-3"> <button type="submit" class="btn" style="background-color: #FF8A37; color: white;"> <i class="fas fa-arrow-right"></i> Continuar con la Entrega </button> <a href="select_epp.php" class="btn btn-secondary"> <i class="fas fa-search"></i> Buscar Otro Empleado </a> <a href="MENUP.PHP" class="btn btn-secondary"> <i class="fas fa-times"></i> Cancelar </a> </div> </form> <?php endif; ?> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script> <script> $(document).ready(function() { $('#tipoEpp').change(function() { var tipo = $(this).val(); $('.inventory-container').hide(); if(tipo === 'nuevo') { $('#nuevoContainer').show(); } else if(tipo === 'usado') { $('#usadoContainer').show(); } }); $('#eppForm').submit(function(e) { if($('input[name="epp_seleccionado[]"]:checked').length === 0) { alert('Debe seleccionar al menos un elemento'); e.preventDefault(); return false; } // ★★★ DEPURACIÓN ANTES DE ENVIAR ★★★ console.log('Cedula empleado:', $('input[name="cedula_empleado"]').val()); console.log('Nombre empleado:', $('input[name="nombre_empleado"]').val()); console.log('Usuario logueado:', $('input[name="usuario_logueado"]').val()); console.log('Empleado completo:', $('input[name="empleado_completo"]').val()); // Verificar que los campos críticos no estén vacíos if(!$('input[name="cedula_empleado"]').val()) { alert('Error: No se ha capturado la cédula del empleado'); e.preventDefault(); return false; } if(!$('input[name="usuario_logueado"]').val()) { alert('Error: No se ha capturado el usuario logueado'); e.preventDefault(); return false; } }); }); </script> </body> </html>