<?php

if($_SESSION["tipo_usuario"] == "Vendedor"){

  echo '<script>

    window.location = "inicio";

  </script>';

  return;

}

?>

<div class="content-wrapper">
    <section class="content-header">
        <div class="container-fluid">
            <h1 class="text-navy"><i class="fas fa-notes-medical"></i> Monitor de Triaje</h1>
        </div>
    </section>

    <section class="content">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-white">
                <h3 class="card-title text-muted">Pacientes Pendientes de Signos Vitales</h3>
            </div>
            <div class="card-body">
                <table class="table table-hover table-striped dt-responsive tablas">
                    <thead>
                        <tr>
                            <th>Hora Ingreso</th>
                            <th>H. Clínica</th>
                            <th>DNI</th>
                            <th>Paciente</th>
                            <th>Motivo</th>
                            <th>Seguro</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $item = null;
                        $valor = null;
                        // Este controlador traerá solo los ingresos con estado 'activo' sin triaje
                        $pacientesEspera = ControladorTriaje::ctrMostrarPacientesEspera($item, $valor);

                        foreach ($pacientesEspera as $key => $value) {
                            echo '<tr>
                                <td>'.date("H:i", strtotime($value["fecha_ingreso"])).'</td>
                                <td><span class="badge badge-secondary">'.$value["codigo_hc"].'</span></td>
                                <td><span class="badge badge-info font-weight-normal px-2 py-1">'.$value["dni"].'</span></td>
                                <td class="font-weight-bold">'.$value["nombres"].' '.$value["apellidos"].'</td>
                                <td>'.$value["motivo_consulta"].'</td>
                                <td>'.$value["tipo_seguro"].'</td>
                                <td>';
                                if (tienePermiso("TRIAJE", "CREAR")):
                                    echo'<button class="btn btn-danger btn-sm btnTomarSignos" idIngreso="'.$value["id_ingreso"].'" data-toggle="modal" data-target="#modalRegistrarTriaje">
                                        <i class="fas fa-heartbeat mr-1"></i> Tomar Signos
                                    </button>';
                                    endif;
                                echo'</td>
                            </tr>';
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </section>
</div>

<!--=====================================
MODAL AGREGAR TRIAJE
======================================-->
<div class="modal fade" id="modalRegistrarTriaje">
    <div class="modal-dialog modal-lg">
        <div class="modal-content border-0 shadow-lg">
            <form role="form" method="post">
                
                <div class="modal-header bg-gradient-navy text-white py-3">
                    <h4 class="modal-title h5 font-weight-bold">
                        <i class="fas fa-heartbeat mr-2"></i> Registro de Triaje y Signos Vitales
                    </h4>
                    <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                </div>

                <div class="modal-body p-0 bg-light">
                    <input type="hidden" name="id_ingreso" id="idIngresoTriaje">

                    <ul class="nav nav-tabs nav-fill bg-white" id="tabTriaje" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active py-3 font-weight-bold text-uppercase small" id="clinico-tab" data-toggle="tab" href="#clinico" role="tab">
                                <i class="fas fa-stethoscope mr-1"></i> 1. Evaluación Clínica
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link py-3 font-weight-bold text-uppercase small" id="logistica-tab" data-toggle="tab" href="#logistica" role="tab">
                                <i class="fas fa-clipboard-list mr-1"></i> 2. Logística y Acompañante
                            </a>
                        </li>
                    </ul>

                    <div class="tab-content p-4" id="tabTriajeContent">
                        
                        <div class="tab-pane fade show active" id="clinico" role="tabpanel">
                            
                            <p class="text-navy font-weight-bold small uppercase mb-3"><i class="fas fa-heartbeat mr-1"></i> Parámetros Vitales</p>
                            
                            <div class="row mb-4">
                                <div class="col-md-4 mb-3">
                                    <label class="small text-muted font-weight-bold">P. ARTERIAL</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" name="presion_arterial" placeholder="120/80" required>
                                        <div class="input-group-append"><span class="input-group-text">mmHg</span></div>
                                    </div>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="small text-muted font-weight-bold text-danger">PULSO / FC</label>
                                    <div class="input-group">
                                        <input type="number" class="form-control" name="pulso" placeholder="75" required>
                                        <div class="input-group-append"><span class="input-group-text">lpm</span></div>
                                    </div>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="small text-muted font-weight-bold">F. RESPIRATORIA</label>
                                    <div class="input-group">
                                        <input type="number" class="form-control" name="frecuencia_respiratoria" placeholder="18" required>
                                        <div class="input-group-append"><span class="input-group-text">rpm</span></div>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="small text-muted font-weight-bold text-orange">TEMPERATURA</label>
                                    <div class="input-group">
                                        <input type="number" step="0.1" class="form-control" name="temperatura" placeholder="36.5" required>
                                        <div class="input-group-append"><span class="input-group-text">°C</span></div>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="small text-muted font-weight-bold text-primary">SAT. SpO2</label>
                                    <div class="input-group">
                                        <input type="number" step="0.1" class="form-control" name="saturacion_oxigeno" placeholder="98" required>
                                        <div class="input-group-append"><span class="input-group-text">%</span></div>
                                    </div>
                                </div>
                            </div>

                            <p class="text-navy font-weight-bold small uppercase mb-2"><i class="fas fa-brain mr-1"></i> Escala de Glasgow</p>
                            <div class="row border rounded bg-white p-3 shadow-sm">
                                <div class="col-md-4 form-group">
                                    <label class="small font-weight-bold">Ocular (1-4)</label>
                                    <select class="form-control form-control-sm" name="glasgowOcular" id="gOcular">
                                        <option value="4">4 - Espontánea</option>
                                        <option value="3">3 - A la voz</option>
                                        <option value="2">2 - Al dolor</option>
                                        <option value="1">1 - Ninguna</option>
                                    </select>
                                </div>
                                <div class="col-md-4 form-group">
                                    <label class="small font-weight-bold">Verbal (1-5)</label>
                                    <select class="form-control form-control-sm" name="glasgowVerbal" id="gVerbal">
                                        <option value="5">5 - Orientado</option>
                                        <option value="4">4 - Confuso</option>
                                        <option value="3">3 - Inapropiado</option>
                                        <option value="2">2 - Incomprensible</option>
                                        <option value="1">1 - Ninguna</option>
                                    </select>
                                </div>
                                <div class="col-md-4 form-group">
                                    <label class="small font-weight-bold">Motor (1-6)</label>
                                    <select class="form-control form-control-sm" name="glasgowMotor" id="gMotor">
                                        <option value="6">6 - Obedece</option>
                                        <option value="5">5 - Localiza dolor</option>
                                        <option value="4">4 - Retira al dolor</option>
                                        <option value="3">3 - Flexión anormal</option>
                                        <option value="2">2 - Extensión anormal</option>
                                        <option value="1">1 - Ninguna</option>
                                    </select>
                                </div>
                                <div class="col-12 text-right">
                                    <span class="badge badge-dark p-2">Total Glasgow: <span id="totalGlasgow">15</span>/15</span>
                                </div>
                            </div>
                            
                            <div class="text-right mt-4">
                                <button type="button" class="btn btn-primary rounded-pill px-4 btnSiguienteTab">
                                    Siguiente: Logística <i class="fas fa-arrow-right ml-1"></i>
                                </button>
                            </div>
                        </div>

                        <div class="tab-pane fade" id="logistica" role="tabpanel">
                            
                            <div class="row mb-3">
                                <div class="col-md-6 mb-3">
                                    <label class="small text-muted font-weight-bold">¿CÓMO INGRESÓ EL PACIENTE?</label>
                                    <select class="form-control" name="modo_ingreso" required>
                                        <option value="">Seleccione...</option>
                                        <option value="Caminando">Caminando</option>
                                        <option value="Silla de Ruedas">Silla de Ruedas</option>
                                        <option value="Camilla">Camilla</option>
                                        <option value="En brazos">En brazos</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="small text-muted font-weight-bold text-primary">ÁREA A LA QUE SE DERIVA</label>
                                    <select class="form-control border-primary" name="id_area_destino" required>
                                        <option value="">Seleccionar Área...</option>
                                        <?php
                                            $areas = ControladorArea::ctrMostrarArea(null, null);
                                            foreach($areas as $a) echo '<option value="'.$a["id"].'">'.$a["nombre_area"].'</option>';
                                        ?>
                                    </select>
                                </div>
                            </div>

                            <p class="text-navy font-weight-bold small uppercase mb-2"><i class="fas fa-user-friends mr-1"></i> Información del Acompañante</p>
                            <div class="row border rounded bg-white p-3 shadow-sm mb-4">
                                <div class="col-md-4 mb-2">
                                    <label class="small font-weight-bold">DNI</label>
                                    <input type="text" class="form-control form-control-sm" name="acomp_dni" placeholder="DNI">
                                </div>
                                <div class="col-md-8 mb-2">
                                    <label class="small font-weight-bold">Nombre Completo</label>
                                    <input type="text" class="form-control form-control-sm" name="acomp_nombre" placeholder="Nombres y Apellidos">
                                </div>
                                <div class="col-md-5">
                                    <label class="small font-weight-bold">Teléfono</label>
                                    <input type="text" class="form-control form-control-sm" name="acomp_telefono" placeholder="Número de contacto">
                                </div>
                                <div class="col-md-7">
                                    <label class="small font-weight-bold">Dirección</label>
                                    <input type="text" class="form-control form-control-sm" name="acomp_direccion" placeholder="Dirección actual">
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-12 mb-3">
                                    <label class="small text-muted font-weight-bold text-warning"><i class="fas fa-exclamation-triangle mr-1"></i> NIVEL DE PRIORIDAD</label>
                                    <select class="form-control border-warning font-weight-bold" name="nivel_prioridad" required>
                                        <option value="">Asignar Prioridad...</option>
                                        <option value="I" class="text-danger">PRIORIDAD I - Rojo</option>
                                        <option value="II" class="text-orange">PRIORIDAD II - Naranja</option>
                                        <option value="III" class="text-warning">PRIORIDAD III - Amarillo</option>
                                        <option value="IV" class="text-success">PRIORIDAD IV - Verde</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="small text-muted font-weight-bold">OBSERVACIONES ADICIONALES</label>
                                <textarea class="form-control shadow-sm" name="observaciones" rows="2" placeholder="Notas relevantes..."></textarea>
                            </div>

                            <div class="mt-4 d-flex justify-content-between">
                                <button type="button" class="btn btn-outline-secondary rounded-pill px-4 btnAnteriorTab">
                                    <i class="fas fa-arrow-left mr-1"></i> Volver
                                </button>
                                <button type="submit" class="btn btn-navy rounded-pill px-4 shadow">
                                    Finalizar Registro <i class="fas fa-check-circle ml-1"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <?php
                    $registroTriaje = new ControladorTriaje();
                    $registroTriaje -> ctrCrearTriaje();
                ?>
            </form>
        </div>
    </div>
</div>
      
  
  <script src="./vistas/js/plantilla.js"></script>
  <script>
      function permite(elEvento, permitidos) {
      // Variables que definen los caracteres permitidos
      var numeros = "0123456789";
      var caracteres = " aábcdeéfghiíjklmnñoópqrstuvwxyzAÁBCDEÉFGHIÍJKLMNÑOÓPQRSTUVWXYZ";
      var numeros_caracteres = numeros + caracteres;
      var teclas_especiales = [8, 37, 39, 46];
      // 8 = BackSpace, 46 = Supr, 37 = flecha izquierda, 39 = flecha derecha
    
    
      // Seleccionar los caracteres a partir del parámetro de la función
      switch(permitidos) {
        case 'num':
          permitidos = numeros;
          break;
        case 'car':
          permitidos = caracteres;
          break;
        case 'num_car':
          permitidos = numeros_caracteres;
          break;
      }
    
      // Obtener la tecla pulsada 
      var evento = elEvento || window.event;
      var codigoCaracter = evento.charCode || evento.keyCode;
      var caracter = String.fromCharCode(codigoCaracter);
    
      // Comprobar si la tecla pulsada es alguna de las teclas especiales
      // (teclas de borrado y flechas horizontales)
      var tecla_especial = false;
      for(var i in teclas_especiales) {
        if(codigoCaracter == teclas_especiales[i]) {
          tecla_especial = true;
          break;
        }
      }
    
      // Comprobar si la tecla pulsada se encuentra en los caracteres permitidos
      // o si es una tecla especial
      return permitidos.indexOf(caracter) != -1 || tecla_especial;
    }
          
          var elemento = document.getElementById("almacen");
          elemento.className += " active";

          var elemento = document.getElementById("alma");
          elemento.className += " menu-open";

          var elemento = document.getElementById("triaje");
          elemento.className += " active";

          $(document).on("click", ".btnTomarSignos", function(){
          var idIngreso = $(this).attr("idIngreso");
          $("#idIngresoTriaje").val(idIngreso);
      })
      
$(document).ready(function() {
    function calcularGlasgow() {
        var ocular = parseInt($("#gOcular").val());
        var verbal = parseInt($("#gVerbal").val());
        var motor = parseInt($("#gMotor").val());
        var total = ocular + verbal + motor;
        $("#totalGlasgow").text(total);
    }

    $("#gOcular, #gVerbal, #gMotor").change(function() {
        calcularGlasgow();
    });
});

$(document).on("click", ".btnSiguienteTab", function(){
    $('#tabTriaje a[href="#logistica"]').tab('show');
});

$(document).on("click", ".btnAnteriorTab", function(){
    $('#tabTriaje a[href="#clinico"]').tab('show');
});
</script>

