<?php
    ob_start();
    session_start();
    
    // Incluir sistema de control de acceso
    require '../../backend/php/check_access.php';
    
    // Verificar que tenga permiso para ver historial
    if(!hasModulePermission('usuarios') && !hasSubmenuPermission('usuarios_historial')){
        header('location: ../acceso_denegado.php');
        exit;
    }
    
    require '../../backend/bd/Conexion.php';
    
    // Obtener permisos del usuario desde menu_permissions
    $userId = $_SESSION['id'];
    $userPermissions = [];
    
    // Admin siempre tiene acceso total
    if($_SESSION['rol'] == 1) {
        $userPermissions = [
            'view_valoracion_riesgo' => 1,
            'edit_valoracion_riesgo' => 1,
            'view_salud_oral' => 1,
            'edit_salud_oral' => 1,
            'view_salud_mental' => 1,
            'edit_salud_mental' => 1,
            'view_signos_vitales' => 1,
            'edit_signos_vitales' => 1,
            'view_medicamentos' => 1,
            'edit_medicamentos' => 1,
            'view_diagnostico' => 1,
            'edit_diagnostico' => 1,
            'view_antecedentes' => 1,
            'edit_antecedentes' => 1,
            'view_examenes' => 1,
            'edit_examenes' => 1,
            'view_fisioterapia' => 1,
            'edit_fisioterapia' => 1
        ];
    } else {
        // Obtener permisos de menu_permissions
        if(isset($_SESSION['menu_permissions'])) {
            $menuPerms = $_SESSION['menu_permissions'];
            
            $userPermissions = [
                'view_valoracion_riesgo' => isset($menuPerms['historia_riesgo_social_ver']) ? $menuPerms['historia_riesgo_social_ver'] : 0,
                'edit_valoracion_riesgo' => isset($menuPerms['historia_riesgo_social_modificar']) ? $menuPerms['historia_riesgo_social_modificar'] : 0,
                'view_salud_oral' => isset($menuPerms['historia_salud_oral_ver']) ? $menuPerms['historia_salud_oral_ver'] : 0,
                'edit_salud_oral' => isset($menuPerms['historia_salud_oral_modificar']) ? $menuPerms['historia_salud_oral_modificar'] : 0,
                'view_salud_mental' => isset($menuPerms['historia_salud_mental_ver']) ? $menuPerms['historia_salud_mental_ver'] : 0,
                'edit_salud_mental' => isset($menuPerms['historia_salud_mental_modificar']) ? $menuPerms['historia_salud_mental_modificar'] : 0,
                'view_signos_vitales' => isset($menuPerms['historia_signos_vitales_ver']) ? $menuPerms['historia_signos_vitales_ver'] : 0,
                'edit_signos_vitales' => isset($menuPerms['historia_signos_vitales_modificar']) ? $menuPerms['historia_signos_vitales_modificar'] : 0,
                'view_medicamentos' => isset($menuPerms['historia_medicamentos_ver']) ? $menuPerms['historia_medicamentos_ver'] : 0,
                'edit_medicamentos' => isset($menuPerms['historia_medicamentos_modificar']) ? $menuPerms['historia_medicamentos_modificar'] : 0,
                'view_diagnostico' => isset($menuPerms['historia_diagnostico_ver']) ? $menuPerms['historia_diagnostico_ver'] : 0,
                'edit_diagnostico' => isset($menuPerms['historia_diagnostico_modificar']) ? $menuPerms['historia_diagnostico_modificar'] : 0,
                'view_antecedentes' => isset($menuPerms['historia_antecedentes_ver']) ? $menuPerms['historia_antecedentes_ver'] : 0,
                'edit_antecedentes' => isset($menuPerms['historia_antecedentes_modificar']) ? $menuPerms['historia_antecedentes_modificar'] : 0,
                'view_examenes' => isset($menuPerms['historia_examenes_ver']) ? $menuPerms['historia_examenes_ver'] : 0,
                'edit_examenes' => isset($menuPerms['historia_examenes_modificar']) ? $menuPerms['historia_examenes_modificar'] : 0,
                'view_fisioterapia' => isset($menuPerms['historia_fisioterapia_ver']) ? $menuPerms['historia_fisioterapia_ver'] : 0,
                'edit_fisioterapia' => isset($menuPerms['historia_fisioterapia_modificar']) ? $menuPerms['historia_fisioterapia_modificar'] : 0
            ];
        } else {
            // Sin permisos configurados
            $userPermissions = [
                'view_valoracion_riesgo' => 0,
                'edit_valoracion_riesgo' => 0,
                'view_salud_oral' => 0,
                'edit_salud_oral' => 0,
                'view_salud_mental' => 0,
                'edit_salud_mental' => 0,
                'view_signos_vitales' => 0,
                'edit_signos_vitales' => 0,
                'view_medicamentos' => 0,
                'edit_medicamentos' => 0,
                'view_diagnostico' => 0,
                'edit_diagnostico' => 0,
                'view_antecedentes' => 0,
                'edit_antecedentes' => 0,
                'view_examenes' => 0,
                'edit_examenes' => 0,
                'view_fisioterapia' => 0,
                'edit_fisioterapia' => 0
            ];
        }
    }
    
    // Incluir helper de permisos
    require '../../backend/php/apply_permissions_historia.php';
    
    $id=$_SESSION['id'];
?>
<!DOCTYPE html>
<html lang="es">
<head>


<style>
/* Estilos para el checkbox y modal */

#btns-riesgo {
    display: none;
}

#btns-riesgo:checked ~ .container-modal {
    display: flex;
}

#btns-medicamentos {
    display: none;
}

#btns-medicamentos:checked ~ .container-modal {
    display: flex;
}


#btns-toral {
    display: none;
}

#btns-toral:checked ~ .container-modal {
    display: flex;
}

#btns-saludmental {
    display: none;
}

#btns-saludmental:checked ~ .container-modal {
    display: flex;
}

.botons-modals label {
    display: inline-block;
    padding: 10px 15px;
    background-color: #4CAF50;
    color: white;
    cursor: pointer;
    border-radius: 5px;
}

.botons-modals label:hover {
    background-color: #45a049;
}

/* Ajustes adicionales para el modal */
.container-modal {
    width: 100%;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    background-color: rgba(53, 9, 73, 0.8);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 99100;
    overflow-y: auto;
}
</style>




    <meta charset="UTF-8">
    <link href='https://unpkg.com/boxicons@2.0.9/css/boxicons.min.css' rel='stylesheet'>
    <link rel="stylesheet" href="../../backend/css/admin.css?v=7.0">
    <link rel="icon" type="image/png" sizes="96x96" href="../../backend/img/ico.svg">
    



    <title>Programa Persona Mayor | Historia clínica</title>
</head>
<body>

    <?php include '../../backend/php/sidebar_menu.php'; ?>


    <!-- NAVBAR -->
    <section id="content">

        <!-- NAVBAR -->
        <nav>
            <i class='bx bx-menu toggle-sidebar' ></i>
            <form action="#">
                <div class="form-group">
                    <input type="text" placeholder="Search...">
                    <i class='bx bx-search icon' ></i>
                </div>
            </form>
            
           
            <span class="divider"></span>
            <div class="profile">
                <img src="https://images.unsplash.com/photo-1517841905240-472988babdf9?ixid=MnwxMjA3fDB8MHxzZWFyY2h8NHx8cGVvcGxlfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" alt="">
                <ul class="profile-link">
              <li><a href="../profile/mostrar.php"><i class='bx bxs-user-circle icon' ></i> Profile</a></li>
                    
                    <li>
                     <a href="../salir.php"><i class='bx bxs-log-out-circle' ></i> Logout</a>
                    </li>
                   
                </ul>
            </div>
        </nav>
        <!-- NAVBAR -->

        <!-- MAIN -->

        <main>
            <h1 class="title">Bienvenido <?php echo '<strong>'.$_SESSION['username'].'</strong>'; ?></h1>
            <ul class="breadcrumbs">
                <li><a href="../admin/escritorio.php">Home</a></li>
                <li class="divider">></li>
                <li><a href="../pacientes/mostrar.php">Listado de los Abuelos</a></li>
                <li class="divider">></li>
                <li><a href="#" class="active">Historia clínica del Abuelos</a></li>
            </ul>
           <br>

           <?php 
 $id = $_GET['id'];
 $sentencia = $connect->prepare("SELECT * FROM patients  WHERE idpa= '$id';");
 $sentencia->execute();

$data =  array();
if($sentencia){
  while($r = $sentencia->fetchObject()){
    $data[] = $r;
  }
}
   ?>
   <?php if(count($data)>0):?>
        <?php foreach($data as $d):?>
<div class="input-block">
    
    <a type="button" href="../pacientes/imprimir.php?id=<?php echo $d->idpa; ?>" class="button">IMPRIMIR</a>

                    <div class="wrap-line">

                                <!-- Inputs -->
        <div class="brise-input">
            
            <input type="text" value="<?php echo $d->numhs; ?>" name="text" required>
            
            <span class="line"></span>
        </div>
        <div class="brise-input">
            
            <input type="text" value="<?php echo $d->nompa; ?>" name="text" required>
           
            <span class="line"></span>
        </div>

                <!-- Inputs -->
        <div class="brise-input">
            
            <input type="text" value="<?php echo $d->apepa; ?>" name="text" required>
            
            <span class="line"></span>
        </div>
        <div class="brise-input">
           
            <input type="text" value="<?php echo $d->direc; ?>" name="text" required>
            
            <span class="line"></span>
        </div>

        <div class="brise-input">
          
            <input type="text" value="<?php echo $d->cump; ?>" name="text" required>
            
            <span class="line"></span>
        </div>


        <div class="brise-input">
          
            <input type="text" value="<?php echo $d->sex; ?>" name="text" required>
            
            <span class="line"></span>
        </div>

                <div class="brise-input">
            
            <input type="text" value="<?php echo $d->grup; ?>" name="text" required>
            
            <span class="line"></span>
        </div>

        <div class="brise-input">
           
            <input type="text" value="<?php echo $d->phon; ?>" name="text" required>
            
            <span class="line"></span>
        </div>
                        
                    </div>

</div>





<div class="data">



    <div class="content-data">



    <?php if(!shouldHideSection('valoracion_riesgo')): ?>
    <button class="accordion">VALORACION DEL RIESGO SOCIAL <?php echo showPermissionBadge('valoracion_riesgo'); ?></button>
<div class="panel">
    <div class="botons-modals">
        <label for="btns-riesgo" <?php echo getButtonStyle('valoracion_riesgo'); ?>>
            Nuevo
        </label>
    </div>

    <div class="table-responsive" style="overflow-x:auto;">
        <?php 
        $id = $_GET['id'];
$sentencia = $connect->prepare("SELECT * FROM valoracionriesgo  WHERE idpa= '$id';");
 $sentencia->execute();
$data =  array();
if($sentencia){
  while($r = $sentencia->fetchObject()){
    $data[] = $r;
  }
}
         ?>
         <?php if(count($data)>0):?>
        <table class="responsive-table">
            <thead>
                <tr>
                    <th scope="col">Fecha</th>
                    <th scope="col">Enfermedad</th>
                    <th scope="col">Fuma</th>
                    <th scope="col">Consume</th>
                    <th scope="col">Humo</th>
                    <th scope="col">Sal</th>
                    <th scope="col">Cocina</th>
                    <th scope="col">Baño</th>
                    <th scope="col">Dia</th>
                    <th scope="col">mes</th>
                    <th scope="col">año</th>
                    <th scope="col">municipio</th>
                   
                </tr>
            </thead>

            <tbody>
                <?php foreach($data as $f):?>
                <tr>
                     <th scope="row"><?php echo $f->fere; ?></th>
                     <th scope="row"><?php echo $f->enfermedadd; ?></th>
                     <td data-title="fuma"><?php echo $f->fuma; ?></td>
                     <td data-title="consumo"><?php echo $f->consumo; ?></td>
                     <td data-title="humo"><?php echo $f->humo; ?></td>
                     <td data-title="sal"><?php echo $f->sal; ?></td>
                     <td data-title="cocina"><?php echo $f->cocina; ?></td>
                     <td data-title="vestir"><?php echo $f->vestir; ?></td>
                     <td data-title="diahoy"><?php echo $f->diahoy; ?></td>
                     <td data-title="meshoy"><?php echo $f->meshoy; ?></td>
                     <td data-title="anohoy"><?php echo $f->anohoy; ?></td>
                     <td data-title="municipio"><?php echo $f->municipio; ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else:?>
      <p class="alert alert-warning">No hay datos</p>
    <?php endif; ?>
    </div>

</div>
<?php endif; // Fin de valoracion_riesgo ?>


 <!-- *//AQUI EMPIAZA CODIGO INGRESADO* -->
 
<?php if(!shouldHideSection('salud_oral')): ?>
 <button class="accordion">TAMIZAJE SALUD ORAL <?php echo showPermissionBadge('salud_oral'); ?></button>
<div class="panel">
    <div class="botons-modal">
        <label for="btns-toral" <?php echo getButtonStyle('salud_oral'); ?>>
            Nuevo
        </label>
    </div>

    <div class="table-responsive" style="overflow-x:auto;">
        <?php 
        $id = $_GET['id'];
$sentencia = $connect->prepare("SELECT * FROM toral WHERE idpa= '$id';");
 $sentencia->execute();
$data =  array();
if($sentencia){
  while($r = $sentencia->fetchObject()){
    $data[] = $r;
  }
}
         ?>
         <?php if(count($data)>0):?>
        <table class="responsive-table">
            <thead>
                <tr>
                    <th scope="col">lavadientes</th>
                    <th scope="col">golpeb</th>
                    <th scope="col">sangred</th>
                    <th scope="col">protesisd</th>
                    <th scope="col">comesonrie</th>
                    <th scope="col">limpiab</th>
                    <th scope="col">dolorc</th>
                    <th scope="col">perdidadientes</th>
                    <th scope="col">maltratoprotesis</th>
                    <th scope="col">cicatriz</th>
                    <th scope="col">bocabano</th>
                    <th scope="col">consultaodont</th>
                    <th scope="col">observaciones</th>
                </tr>
            </thead>

            <tbody>
                <?php foreach($data as $f):?>
                <tr>
                     <th scope="row"><?php echo $f->lavadientes; ?></th>
                     <td data-title="Motivo"><?php echo $f->golpeb; ?></td>
                     <td data-title="sangred"><?php echo $f->sangred; ?></td>
                     <td data-title="protesisd"><?php echo $f->protesisd; ?></td>
                     <td data-title="comesonrie"><?php echo $f->comesonrie; ?></td>
                     <td data-title="limpiab"><?php echo $f->limpiab; ?></td>
                     <td data-title="dolorc"><?php echo $f->dolorc; ?></td>
                     <td data-title="perdidadientes"><?php echo $f->perdidadientes; ?></td>
                     <td data-title="maltratoprotesis"><?php echo $f->maltratoprotesis; ?></td>
                     <td data-title="cicatriz"><?php echo $f->cicatriz; ?></td>
                     <td data-title="bocabano"><?php echo $f->bocabano; ?></td>
                     <td data-title="consultaodont"><?php echo $f->consultaodont; ?></td>
                     <td data-title="observaciones"><?php echo $f->observaciones; ?></td>


                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else:?>
      <p class="alert alert-warning">No hay datos</p>
    <?php endif; ?>
    </div>
  
</div>
<?php endif; // Fin de salud_oral ?>


<!-- *//AQUI EMPIAZA CODIGO INGRESADO* -->
 
<?php if(!shouldHideSection('salud_mental')): ?>
<button class="accordion">TAMIZAJE SALUD MENTAL <?php echo showPermissionBadge('salud_mental'); ?></button>
<div class="panel">
    <div class="botons-modal">
        <label for="btns-saludmental" <?php echo getButtonStyle('salud_mental'); ?>>
            Nuevo
        </label>
    </div>

    <div class="table-responsive" style="overflow-x:auto;">
        <?php 
        $id = $_GET['id'];
$sentencia = $connect->prepare("SELECT * FROM saludmental WHERE idpa= '$id';");
 $sentencia->execute();
$data =  array();
if($sentencia){
  while($r = $sentencia->fetchObject()){
    $data[] = $r;
  }
}
         ?>
         <?php if(count($data)>0):?>
        <table class="responsive-table">
            <thead>
                <tr>
                    <th scope="col">Maltrato</th>
                    <th scope="col">Problemas Sueño</th>
                    <th scope="col">Sentido Mal</th>
                    <th scope="col">Arrepentido</th>
                    <th scope="col">Abandono</th>
                    <th scope="col">Obligado</th>
                    <th scope="col">A Gusto Cuerpo</th>
                    <th scope="col">Subido/Perdido Peso</th>
                    <th scope="col">Vomito</th>
                    <th scope="col">Apetito</th>
                    <th scope="col">Reconocimiento</th>
                    <th scope="col">Emborrachado</th>
                    <th scope="col">Sustancia</th>
                    <th scope="col">Bebida</th>
                    <th scope="col">Cigarrillo</th>
                    <th scope="col">Aconsejado</th>
                    <th scope="col">Bebida Alta</th>
                    <th scope="col">Beber Podido</th>
                    <th scope="col">Aburrido</th>
                    <th scope="col">Frecuencia Llora</th>
                    <th scope="col">Actividades F</th>
                    <th scope="col">Tomar Decisiones</th>
                    <th scope="col">Agresividad</th>
                    <th scope="col">Permanece Triste</th>
                    <th scope="col">Permanece Temeroso</th>
                    <th scope="col">Muerte</th>
                    <th scope="col">Daño</th>
                    <th scope="col">Aislado</th>
                    <th scope="col">Motiva</th>
                    <th scope="col">Sentimiento</th>
                    <th scope="col">Dificil</th>
                    <th scope="col">Habilidad</th>
                    <th scope="col">Alegre y Animo</th>
                    <th scope="col">Relajado Tranquilidad</th>
                    <th scope="col">Activo Energia</th>
                    <th scope="col">Bien Descanso</th>
                    <th scope="col">Momento Interesante</th>
                </tr>
            </thead>

            <tbody>
                <?php foreach($data as $f):?>
                <tr>
                     <td data-title="Maltrato"><?php echo $f->maltrato; ?></td>
                     <td data-title="Problemas"><?php echo $f->problemas; ?></td>
                     <td data-title="Sentido Mal"><?php echo $f->sentidomal; ?></td>
                     <td data-title="Arrepentido"><?php echo $f->arrepentido; ?></td>
                     <td data-title="Abandono"><?php echo $f->abandono; ?></td>
                     <td data-title="Obligado"><?php echo $f->obligado; ?></td>
                     <td data-title="Cuerpo"><?php echo $f->cuerpo; ?></td>
                     <td data-title="Subido"><?php echo $f->subido; ?></td>
                     <td data-title="Vomito"><?php echo $f->vomito; ?></td>
                     <td data-title="Apetito"><?php echo $f->apetito; ?></td>
                     <td data-title="Reconocimiento"><?php echo $f->reconocimiento; ?></td>
                     <td data-title="Emborracho"><?php echo $f->emborracho; ?></td>
                     <td data-title="Sustancia"><?php echo $f->sustancia; ?></td>
                     <td data-title="Bebida"><?php echo $f->bebida; ?></td>
                     <td data-title="Cigarrillo"><?php echo $f->cigarrillo; ?></td>
                     <td data-title="Aconsejado"><?php echo $f->aconsejado; ?></td>
                     <td data-title="Bebida Alta"><?php echo $f->bebidaalta; ?></td>
                     <td data-title="Beber Podido"><?php echo $f->beberpodido; ?></td>
                     <td data-title="Aburrido"><?php echo $f->aburrido; ?></td>
                     <td data-title="Frecuencia"><?php echo $f->frecuencia; ?></td>
                     <td data-title="Actividades F"><?php echo $f->actividadesf; ?></td>
                     <td data-title="Tomar Decisiones"><?php echo $f->tomardecisiones; ?></td>
                     <td data-title="Agresividad"><?php echo $f->agresividad; ?></td>
                     <td data-title="Permanece Triste"><?php echo $f->ptriste; ?></td>
                     <td data-title="Permanece Temeroso"><?php echo $f->ptemeroso; ?></td>
                     <td data-title="Muerte"><?php echo $f->muerte; ?></td>
                     <td data-title="Daño"><?php echo $f->dano; ?></td>
                     <td data-title="Aislado"><?php echo $f->aislado; ?></td>
                     <td data-title="Motiva"><?php echo $f->motiva1; ?></td>
                     <td data-title="Sentimiento"><?php echo $f->sentimiento; ?></td>
                     <td data-title="Dificil"><?php echo $f->dificil; ?></td>
                     <td data-title="Habilidad"><?php echo $f->habilidad; ?></td>
                     <td data-title="Alegre y Animo"><?php echo $f->alegreyanimo; ?></td>
                     <td data-title="Relajado Tranquilidad"><?php echo $f->relajadotranquilidad; ?></td>
                     <td data-title="Activo Energia"><?php echo $f->activoenergia; ?></td>
                     <td data-title="Bien Descanso"><?php echo $f->biendescanso; ?></td>
                     <td data-title="Momento Interesante"><?php echo $f->momentointeresante; ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else:?>
      <p class="alert alert-warning">No hay datos</p>
    <?php endif; ?>
    </div>
  
</div>
<?php endif; // Fin de salud_mental ?>


<!-- Aqui Finaliza* -->


<!-- *//AQUI EMPIAZA CODIGO INGRESADO* -->
 
<?php if(!shouldHideSection('medicamentos')): ?>
<button class="accordion">MEDICAMENTOS <?php echo showPermissionBadge('medicamentos'); ?></button>
<div class="panel">
    <div class="botons-modal">
        <label for="btns-medicamentos" <?php echo getButtonStyle('medicamentos'); ?>>
            Nuevo
        </label>
    </div>

    <div class="table-responsive" style="overflow-x:auto;">
        <?php 
        $id = $_GET['id'];
$sentencia = $connect->prepare("SELECT * FROM medicamentos WHERE idpa = ? AND state = 1 ORDER BY fere DESC");
$sentencia->execute([$id]);
$data = array();
if($sentencia){
  while($r = $sentencia->fetchObject()){
    $data[] = $r;
  }
}
         ?>
         <?php if(count($data)>0):?>
        <table class="responsive-table">
            <thead>
                <tr>
                    <th scope="col">¿Toma medicamentos?</th>
                    <th scope="col">¿Cuáles medicamentos?</th>
                    <th scope="col">¿Con prescripción?</th>
                    <th scope="col">¿Se automedica?</th>
                    <th scope="col">Ant. quirúrgicos</th>
                    <th scope="col">Hospitalizaciones</th>
                    <th scope="col">Ant. traumáticos</th>
                    <th scope="col">Hipertensión</th>
                    <th scope="col">Ant. tóxicos</th>
                    <th scope="col">Ant. alérgicos</th>
                    <th scope="col">Ant. infecciosos</th>
                    <th scope="col">Enf. relevantes</th>
                    <th scope="col">Úlcera</th>
                    <th scope="col">Lepra</th>
                    <th scope="col">Diabetes</th>
                    <th scope="col">Asma</th>
                    <th scope="col">Cáncer</th>
                    <th scope="col">EPOC</th>
                    <th scope="col">Epilepsia</th>
                    <th scope="col">Enf. autoinmunes</th>
                    <th scope="col">Ingresos urgencias</th>
                    <th scope="col">Otros antecedentes</th>
                </tr>
            </thead>

            <tbody>
                <?php foreach($data as $f):?>
                <tr>
                     <td data-title="tomam"><?php echo $f->tomam; ?></td>
                     <td data-title="cualm"><?php echo $f->cualm; ?></td>
                     <td data-title="prescripcion"><?php echo $f->prescripcion; ?></td>
                     <td data-title="automedicacion"><?php echo $f->automedicacion; ?></td>
                     <td data-title="quirurgicos"><?php echo $f->quirurgicos; ?></td>
                     <td data-title="hospitalizacion"><?php echo $f->hospitalizacion; ?></td>
                     <td data-title="traumaticos"><?php echo $f->traumaticos; ?></td>
                     <td data-title="hipertencion"><?php echo $f->hipertencion; ?></td>
                     <td data-title="toxico"><?php echo $f->toxico; ?></td>
                     <td data-title="alergico"><?php echo $f->alergico; ?></td>
                     <td data-title="infeccioso"><?php echo $f->infeccioso; ?></td>
                     <td data-title="enfermedadr"><?php echo $f->enfermedadr; ?></td>
                     <td data-title="ulcera"><?php echo $f->ulcera; ?></td>
                     <td data-title="lepra"><?php echo $f->lepra; ?></td>
                     <td data-title="diabetes"><?php echo $f->diabetes; ?></td>
                     <td data-title="asma"><?php echo $f->asma; ?></td>
                     <td data-title="cancer"><?php echo $f->cancer; ?></td>
                     <td data-title="epoc"><?php echo $f->epoc; ?></td>
                     <td data-title="epilepsia"><?php echo $f->epilepsia; ?></td>
                     <td data-title="autoinmunes"><?php echo $f->autoinmunes; ?></td>
                     <td data-title="ingresourgencias"><?php echo $f->ingresourgencias; ?></td>
                     <td data-title="otrom"><?php echo $f->otrom; ?></td>


                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else:?>
      <p class="alert alert-warning">No hay datos</p>
    <?php endif; ?>
    </div>
  
</div>
<?php endif; // Fin de medicamentos ?>


<!-- Aqui Finaliza* -->


<?php if(!shouldHideSection('signos_vitales')): ?>
<button class="accordion">VALORACION FISICA Y DE SEGUIMIENTO (SIGNOS VITALES) <?php echo showPermissionBadge('signos_vitales'); ?></button>
<div class="panel">
    <div class="botons-modal">
        <label for="btns-modal" <?php echo getButtonStyle('signos_vitales'); ?>>
            Nuevo
        </label>
    </div>

    <div class="table-responsive" style="overflow-x:auto;">
        <?php 
        $id = $_GET['id'];
$sentencia = $connect->prepare("SELECT * FROM consult WHERE idpa = ? AND state = 1 ORDER BY fere DESC");
$sentencia->execute([$id]);
$data = array();
if($sentencia){
  while($r = $sentencia->fetchObject()){
    $data[] = $r;
  }
}
         ?>
         <?php if(count($data)>0):?>
        <table class="responsive-table">
            <thead>
                <tr>
                    <th scope="col">Fecha Consult</th>    
                    <th scope="col">Motivo</th>
                    <th scope="col">SV</th>
                    <th scope="col">FC</th>
                    <th scope="col">FR</th>
                    <th scope="col">TMP</th>
                    <th scope="col">T</th>
                    <th scope="col">P</th>
                    <th scope="col">IMC</th>
                    <th scope="col">PA</th>
                    <th scope="col">PC</th>
                    <th scope="col">GL</th>
                    <th scope="col">TV</th>
                    <th scope="col">TA</th>
                    <th scope="col">CB_CL</th>
                    <th scope="col">NEU</th>
                    <th scope="col">TRX</th>
                    <th scope="col">DOR</th>
                    <th scope="col">ABD</th>
                    <th scope="col">PIE</th>
                    <th scope="col">GUN</th>
                    <th scope="col">EXT</th>
                    <th scope="col">LIM</th>
                  
                </tr>
            </thead>

            <tbody>
                <?php foreach($data as $f):?>
                <tr>
                    
                    <td data-title="Fecha"><?php echo $f->fere; ?></td>
                     <td data-title="mtcl"><?php echo $f->mtcl; ?></td>
                     <td data-title="SV"><?php echo $f->SV; ?></td>
                     <td data-title="FC"><?php echo $f->FC; ?></td>
                     <td data-title="FR"><?php echo $f->FR; ?></td>
                     <td data-title="TMP"><?php echo $f->TMP; ?></td>
                     <td data-title="T"><?php echo $f->T; ?></td>
                     <td data-title="P"><?php echo $f->P; ?></td>
                     <td data-title="IMC"><?php echo $f->IMC; ?></td>
                     <td data-title="PA"><?php echo $f->PA; ?></td>
                     <td data-title="PC"><?php echo $f->PC; ?></td>
                     <td data-title="GL"><?php echo $f->GL; ?></td>
                     <td data-title="TV"><?php echo $f->TV; ?></td>
                     <td data-title="TA"><?php echo $f->TA; ?></td>
                     <td data-title="CB_CL"><?php echo $f->CB_CL; ?></td>
                     <td data-title="NEU"><?php echo $f->NEU; ?></td>
                     <td data-title="TRX"><?php echo $f->TRX; ?></td>
                     <td data-title="DOR"><?php echo $f->DOR; ?></td>
                     <td data-title="ABD"><?php echo $f->ABD; ?></td>
                     <td data-title="PIE"><?php echo $f->PIE; ?></td>
                     <td data-title="GUN"><?php echo $f->GUN; ?></td>
                     <td data-title="EXT"><?php echo $f->EXT; ?></td>
                     <td data-title="LIM"><?php echo $f->LIM; ?></td>

                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else:?>
      <p class="alert alert-warning">No hay datos</p>
    <?php endif; ?>
    </div>
  
</div>
<?php endif; // Fin de signos_vitales ?>


<?php if(!shouldHideSection('diagnostico')): ?>
       <button class="accordion">EVOLUCIONES PSICOLOGIA/FISIOTERAPIA/ENFERMERIA/EDUCO.FISICOS (DIAGNÓSTICO) <?php echo showPermissionBadge('diagnostico'); ?></button>
<div class="panel">
    <div class="boton-modal">
        <label for="btn-modal" <?php echo getButtonStyle('diagnostico'); ?>>
            Nuevo
        </label>
    </div>


<div class="timeline">
    <?php 
$id = $_GET['id'];
 $sentencia = $connect->prepare("SELECT * FROM genogram  WHERE idpa= '$id';");
 $sentencia->execute();

$data =  array();
if($sentencia){
  while($r = $sentencia->fetchObject()){
    $data[] = $r;
  }
}

 ?>
 <?php  if(count($data)>0):?>

        <?php foreach($data as $e):?>
    <div class="entry" style="margin-top: 20px;" id="tbody">
      <div class="core">
      <h3><?php echo $e->fere; ?></h3>
        <?php echo $e->detage; ?>
      </div>
    </div>

<?php endforeach; ?>
  
    <?php else:?>
      <p class="alert alert-warning">No hay datos</p>
    <?php endif; ?>
   
</div>


</div>
<?php endif; // Fin de diagnostico ?>


<?php if(!shouldHideSection('antecedentes')): ?>
<button class="accordion">TRATAMIENTO, RESUMEN DE CASO O AMPLIACIÓN DE INFORMACIÓN (ANTECEDENTES) <?php echo showPermissionBadge('antecedentes'); ?></button>
<div class="panel">

    <div class="botons-modals">

        <label for="btns-modals" <?php echo getButtonStyle('antecedentes'); ?>>
            Nuevo
        </label>
    </div>

    <div class="table-responsive" style="overflow-x:auto;">
<?php 
        $id = $_GET['id'];
$sentencia = $connect->prepare("SELECT * FROM treatment  WHERE idpa= '$id';");
 $sentencia->execute();
$data =  array();
if($sentencia){
  while($r = $sentencia->fetchObject()){
    $data[] = $r;
  }
}
         ?>
         <?php if(count($data)>0):?>
        <table class="responsive-table">
            <thead>
                <tr>
                    <th scope="col">USUARIO</th>
                    <th scope="col">Tratamiento</th>
                    <th scope="col">Fecha</th>
                    
                </tr>
            </thead>

            <tbody>
                 <?php foreach($data as $a):?>
                 <tr>
                     <th scope="row"><?php echo $a->nompa; ?></th>
                     <td data-title="Motivo"><?php echo $a->nomtra; ?></td>
                     <td data-title="Fecha"><?php echo $a->fere; ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php else:?>
      <p class="alert alert-warning">No hay datos</p>
    <?php endif; ?>
    </div>

</div> 

<?php endif; // Fin de antecedentes ?>


<!-- FISIOTERAPIA -->
<?php if(!shouldHideSection('fisioterapia')): ?>
<button class="accordion">FISIOTERAPIA <?php echo showPermissionBadge('fisioterapia'); ?></button>
<div class="panel">
    <div class="botons-modal">
        <label for="btns-fisioterapia" <?php echo getButtonStyle('fisioterapia'); ?>>
            Nuevo
        </label>
    </div>

    <div class="table-responsive" style="overflow-x:auto;">
        <?php 
        $id = $_GET['id'];
        $sentencia = $connect->prepare("SELECT * FROM fisioterapia WHERE idpa = ? AND state = 1 ORDER BY fere DESC");
        $sentencia->execute([$id]);
        $data = array();
        if($sentencia){
            while($r = $sentencia->fetchObject()){
                $data[] = $r;
            }
        }
        ?>
        <?php if(count($data)>0):?>
        <table class="responsive-table">
            <thead>
                <tr>
                    <th scope="col">Fecha</th>
                    <th scope="col">Usuario</th>
                    <th scope="col">Sentarse y Levantarse</th>
                    <th scope="col">Flexiones de Brazo</th>
                    <th scope="col">Flexión de Tronco</th>
                    <th scope="col">Juntar Manos Atrás</th>
                    <th scope="col">Romberg</th>
                    <th scope="col">IPAQ</th>
                    <th scope="col">Alcance Funcional</th>
                    <th scope="col">BARTHEL</th>
                    <th scope="col">Funcionalidad</th>
                </tr>
            </thead>

            <tbody>
                <?php foreach($data as $f):?>
                <tr>
                    <td data-title="Fecha"><?php echo $f->fere; ?></td>
                    <td data-title="Usuario"><?php echo $f->nompa; ?></td>
                    <td data-title="Sentarse y Levantarse"><?php echo $f->sentarse_levantarse; ?></td>
                    <td data-title="Flexiones de Brazo"><?php echo $f->flexiones_brazo; ?></td>
                    <td data-title="Flexión de Tronco"><?php echo $f->flexion_tronco; ?></td>
                    <td data-title="Juntar Manos Atrás"><?php echo $f->juntar_manos_atras; ?></td>
                    <td data-title="Romberg"><?php echo $f->romberg; ?></td>
                    <td data-title="IPAQ"><?php echo $f->ipaq; ?></td>
                    <td data-title="Alcance Funcional"><?php echo $f->alcance_funcional; ?></td>
                    <td data-title="BARTHEL"><?php echo $f->barthel; ?></td>
                    <td data-title="Funcionalidad"><?php echo $f->funcionalidad; ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php else:?>
            <p class="alert alert-warning">No hay datos</p>
        <?php endif; ?>
    </div>
</div>
<?php endif; // Fin de fisioterapia ?>
<!-- FIN FISIOTERAPIA -->

    </div>
    
</div>

        <?php endforeach; ?>
  
    <?php else:?>
      <p class="alert alert-warning">No hay datos</p>
    <?php endif; ?>

        </main>
        <!-- MAIN -->
    </section>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>


    <!-- NAVBAR -->
    
    <script src="../../backend/js/script.js"></script>
    <script src="../../backend/js/multistep.js"></script>
    <script src="../../backend/js/vpat.js"></script>
    

    <script type="text/javascript">
    let popUp = document.getElementById("cookiePopup");
//When user clicks the accept button
document.getElementById("acceptCookie").addEventListener("click", () => {
  //Create date object
  let d = new Date();
  //Increment the current time by 1 minute (cookie will expire after 1 minute)
  d.setMinutes(2 + d.getMinutes());
  //Create Cookie withname = myCookieName, value = thisIsMyCookie and expiry time=1 minute
  document.cookie = "myCookieName=thisIsMyCookie; expires = " + d + ";";
  //Hide the popup
  popUp.classList.add("hide");
  popUp.classList.remove("shows");
});
//Check if cookie is already present
const checkCookie = () => {
  //Read the cookie and split on "="
  let input = document.cookie.split("=");
  //Check for our cookie
  if (input[0] == "myCookieName") {
    //Hide the popup
    popUp.classList.add("hide");
    popUp.classList.remove("shows");
  } else {
    //Show the popup
    popUp.classList.add("shows");
    popUp.classList.remove("hide");
  }
};
//Check if cookie exists when page loads
window.onload = () => {
  setTimeout(() => {
    checkCookie();
  }, 2000);
};
    </script>

    <script>
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
<?php include_once '../../backend/modal/md_geog.php' ?>
<?php include_once '../../backend/modal/md_consul.php' ?>
<?php include_once '../../backend/modal/md_trat.php' ?>
<?php include_once '../../backend/modal/md_riesgo.php' ?>
<?php include_once '../../backend/modal/md_toral.php' ?>
<?php include_once '../../backend/modal/md_saludmental.php' ?>
<?php include_once '../../backend/modal/md_medicamentos.php' ?>
<?php include_once '../../backend/modal/md_fisioterapia.php' ?>



<script type="text/javascript">
    $(document).ready(function(){
$("#submit").click(function(){
var gedet = $("#gedet").val();
var geidpa = $("#geidpa").val();
var genopa = $("#genopa").val();

// Returns successful data submission message when the entered information is stored in database.
var dataString = 'det1='+ gedet + '&pa1='+ geidpa + '&nomp1='+ genopa;
if(gedet==''||geidpa==''||genopa=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "add_ge.php",
data: dataString,
cache: false,
success: function(result){

alert(result);
$('#tbody').html(result);
}
});
}
return false;
});
});


  
</script>

<script type="text/javascript">
   function enviar(){
    var consl = document.getElementById('consl').value;
    var CSV = document.getElementById('CSV').value;
    var CFC = document.getElementById('CFC').value;
    var CFR = document.getElementById('CFR').value;
    var CTMP = document.getElementById('CTMP').value;
    var CT = document.getElementById('CT').value;
    var CP = document.getElementById('CP').value;
    var CIMC = document.getElementById('CIMC').value;
    var CPA = document.getElementById('CPA').value;
    var CPC = document.getElementById('CPC').value;
    var CGL = document.getElementById('CGL').value;
    var CTV = document.getElementById('CTV').value;
    var CTA = document.getElementById('CTA').value;
    var CB_CL = document.getElementById('CCB_CL').value;
    var CNEU = document.getElementById('CNEU').value;
    var CTRX = document.getElementById('CTRX').value;
    var CDOR = document.getElementById('CDOR').value;
    var CABD = document.getElementById('CABD').value;
    var CPIE = document.getElementById('CPIE').value;
    var CGUN = document.getElementById('CGUN').value;
    var CEXT = document.getElementById('CEXT').value;
    var CLIM = document.getElementById('CLIM').value;
    var csidpa = document.getElementById('csidpa').value;
    var csnopa = document.getElementById('csnopa').value;


    console.log("consl:", consl);
    console.log("CSV:", CSV);
    console.log("CFC:", CFC);
    console.log("CFR:", CFR);
    console.log("CTMP:", CTMP);
    console.log("CT:", CT);
    console.log("CP:", CP);
    console.log("CIMC:", CIMC);
    console.log("CPA:", CPA);
    console.log("CPC:", CPC);
    console.log("CGL:", CGL);
    console.log("CTV:", CTV);
    console.log("CTA:", CTA);
    console.log("CCB_CL:", CCB_CL);
    console.log("CNEU:", CNEU);
    console.log("CTRX:", CTRX);
    console.log("CDOR:", CDOR);
    console.log("CABD:", CABD);
    console.log("CPIE:", CPIE);
    console.log("CGUN:", CGUN);
    console.log("CEXT:", CEXT);
    console.log("CLIM:", CLIM);

    console.log("csidpa:", csidpa);
    console.log("csnopa:", csnopa);

    var dataen = 'consl='+consl + '&csidpa='+csidpa +'&csnopa='+csnopa +'&CSV='+CSV +'&CFC='+CFC +'&CFR='+CFR +'&CTMP='+CTMP +'&CT='+CT +'&CP='+CP   
    +'&CIMC='+CIMC +'&CPA='+CPA +'&CPC='+CPC +'&CGL='+CGL +'&CTV='+CTV +'&CTA='+CTA +'&CCB_CL='+CCB_CL +'&CNEU='+CNEU +'&CTRX='+CTRX +'&CDOR='+CDOR +'&CABD='+CABD +'&CPIE='+CPIE +'&CGUN='+CGUN + '&CEXT='+CEXT + '&CLIM='+CLIM 
    
    
    ;
    console.log("dataen:", dataen);
    
    $.ajax({
        type: "POST",
        url: "add_consut.php",
        data: dataen,
        cache: false,
        success: function(result){
            console.log("Respuesta:", result);
            if(result.includes('Agregado correctamente')) {
                swal(
                    'Agregado correctamente',
                    'Buen trabajo',
                    'success'
                ).then(function() {
                    location.reload();
                });
            } else {
                swal(
                    'Error',
                    result,
                    'error'
                );
            }
        },
        error: function(xhr, status, error) {
            console.error("Error:", error);
            swal(
                'Error',
                'Ha ocurrido un problema: ' + error,
                'error'
            )
        }
    });
}
</script>

<script type="text/javascript">
    function trata(){
       var trat = document.getElementById('trat').value; 
       var tratdpa = document.getElementById('tratdpa').value; 
       var tratnopa = document.getElementById('tratnopa').value;

       var dataens = 'trat='+trat +'&tratdpa='+tratdpa +'&tratnopa='+tratnopa;

       $.ajax({
                    type: "POST", //definimos el método de envío
                    url: "add_trat.php", //el archivo al cual se enviaran
                    data:dataens,
                    cache: false,
                    success: function(result){

                    swal(
                            'Agregado correctamente',
                            'Buen trabajo',
                            'success'
                          )
}
                }); 
    };
</script>






<script type="text/javascript">
    // MEDICAMENTOS
   function insertarmedicamentos(){
    var formulariom= $("#formmedicamentos").serialize();

   
    $.ajax({
        type: "POST",
        url: "add_medicamentos.php",
        data: formulariom,
        cache: false,
        success: function(result){
            console.log("Respuesta:", result);
            if(result.includes('Agregado correctamente')) {
                swal(
                    'Agregado correctamente',
                    'Buen trabajo',
                    'success'
                ).then(function() {
                    location.reload();
                });
            } else {
                swal(
                    'Error',
                    result,
                    'error'
                );
            }
        },
        error: function(xhr, status, error) {
            console.error("Error:", error);
            swal(
                'Error',
                'Ha ocurrido un problema: ' + error,
                'error'
            )
        }
    });
}
</script>




<script type="text/javascript">
   function insertariesgo(){
    
    var consl = document.getElementById('consl').value;
    var venfermedadd = document.getElementById('venfermedadd').value;
    var vfuma = document.getElementById('vfuma').value;
    var vhumo = document.getElementById('vhumo').value;
    var vconsumo = document.getElementById('vconsumo').value;
    var vsal = document.getElementById('vsal').value;
    var vcocina = document.getElementById('vcocina').value;
    var vvestir = document.getElementById('vvestir').value;
    var vdiahoy = document.getElementById('vdiahoy').value;
    var vmeshoy = document.getElementById('vmeshoy').value;
    var vanohoy = document.getElementById('vanohoy').value;
    var vmunicipio = document.getElementById('vmunicipio').value;
    var csidpa = document.getElementById('csidpa').value;
    var csnopa = document.getElementById('csnopa').value;

    console.log("consl:", consl);
    console.log("venfermedadd:", venfermedadd);
    console.log("vfuma:", vfuma);
    console.log("vhumo:", vhumo);
    console.log("vconsumo:", vconsumo);
    console.log("vsal:", vsal);
    console.log("vcocina:", vcocina);
    console.log("vvestir:", vvestir);
    console.log("vdiahoy:", vdiahoy);
    console.log("vmeshoy:", vmeshoy);
    console.log("vanohoy:", vanohoy);
    console.log("vmunicipio:", vmunicipio);
    
    console.log("csidpa:", csidpa);
    console.log("csnopa:", csnopa);

    var dataen = 'consl='+consl + '&csidpa='+csidpa +'&csnopa='+csnopa +'&venfermedadd='+venfermedadd +'&vfuma='+vfuma +'&vhumo='+vhumo +'&vconsumo='+vconsumo +'&vsal='+vsal +'&vcocina='+vcocina +'&vvestir='+vvestir   
    +'&vdiahoy='+vdiahoy +'&vmeshoy='+vmeshoy +'&vanohoy='+vanohoy +'&vmunicipio='+vmunicipio ;
    console.log("dataen:", dataen);
    
    $.ajax({
        type: "POST",
        url: "add_riesgo.php",
        data: dataen,
        cache: false,
        success: function(result){
            console.log("Respuesta:", result);
            swal(
                'Agregado correctamente',
                'Buen trabajo',
                'success'
            ).then(function() {
                location.reload();
            });
        },
        error: function(xhr, status, error) {
            console.error("Error:", error);
            swal(
                'Error',
                'Ha ocurrido un problema: ' + error,
                'error'
            )
        }
    });
}
</script>




<script type="text/javascript">
   function insertartoral(){
    
    var formulario= $("#formtoral").serialize();

   
    $.ajax({
        type: "POST",
        url: "add_toral.php",
        data: formulario,
        cache: false,
        success: function(result){
            console.log("Respuesta:", result);
            swal(
                'Agregado correctamente',
                'Buen trabajo',
                'success'
            ).then(function() {
                location.reload();
            });
        },
        error: function(xhr, status, error) {
            console.error("Error:", error);
            swal(
                'Error',
                'Ha ocurrido un problema: ' + error,
                'error'
            )
        }
    });
}
</script>



<script type="text/javascript">
   function insertarsaludmental(){
    
    var formularios= $("#formsaludmental").serialize();

   
    $.ajax({
        type: "POST",
        url: "add_saludmental.php",
        data: formularios,
        cache: false,
        success: function(result){
            console.log("Respuesta:", result);
            swal(
                'Agregado correctamente',
                'Buen trabajo',
                'success'
            ).then(function() {
                location.reload();
            });
        },
        error: function(xhr, status, error) {
            console.error("Error:", error);
            swal(
                'Error',
                'Ha ocurrido un problema: ' + error,
                'error'
            )
        }
    });
}
</script>


<script type="text/javascript">
   function insertarfisioterapia(){
    
    var formulariof = $("#formfisioterapia").serialize();

   
    $.ajax({
        type: "POST",
        url: "add_fisioterapia.php",
        data: formulariof,
        cache: false,
        success: function(result){
            console.log("Respuesta:", result);
            if(result.includes('Agregado correctamente')) {
                swal(
                    'Agregado correctamente',
                    'Buen trabajo',
                    'success'
                ).then(function() {
                    location.reload();
                });
            } else {
                swal(
                    'Error',
                    result,
                    'error'
                );
            }
        },
        error: function(xhr, status, error) {
            console.error("Error:", error);
            swal(
                'Error',
                'Ha ocurrido un problema: ' + error,
                'error'
            )
        }
    });
}
</script>


<style>
.scroll-buttons {
    text-align: center;
    margin: 10px 0;
}
.scroll-buttons button {
    background-color: #007bff;
    border: none;
    color: white;
    padding: 8px 16px;
    font-size: 16px;
    border-radius: 5px;
    cursor: pointer;
    margin: 0 5px;
}
.scroll-buttons button:hover {
    background-color: #0056b3;
}
</style>



</body>
</html>
