<?php
    ob_start();
    session_start();
    
    // Incluir sistema de control de acceso
    require '../../backend/php/check_access.php';
    
    // Verificar si tiene sesión activa
    if(!isset($_SESSION['rol']) || !isset($_SESSION['id'])){
        header('location: ../login.php');
        exit();
    }
    
    // Si no es admin, verificar permisos personalizados
    if($_SESSION['rol'] != 1) {
        // Verificar permiso para ver documentos de usuarios
        if(!isset($_SESSION['menu_permissions']['usuarios_documentos']) || $_SESSION['menu_permissions']['usuarios_documentos'] != 1) {
            header('location: ../acceso_denegado.php');
            exit();
        }
    }
    
    $id = $_SESSION['id'];
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <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=8.0">
    <link rel="icon" type="image/png" sizes="96x96" href="../../backend/img/ico.svg">
    



    <title>Clínica Salud | Documentos del USUARIO</title>
</head>
<body>

       <!-- SIDEBAR -->
   <!-- SIDEBAR DINÁMICO -->
    <?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/documentos.php">Documentos de los Usuarios</a></li>
                <li class="divider">></li>
                <li><a href="#" class="active">Nuevo documento</a></li>
            </ul>
           <br>

           <?php 
require '../../backend/bd/Conexion.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">

                    <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" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">
    <!-- Contenedor 1: Nuevo documento -->
    <div class="content-data">
        <div class="head">
            <h3>Nuevo documento</h3>
            <div class="botonsa-modals">
                <label for="btnsa-modals">
                    Nuevo
                </label>
            </div>         
        </div>
        <div class="flexbox">
            <table style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="background-color: #f5f5f5; border-bottom: 2px solid #ddd;">
                        <th style="padding: 10px; text-align: left;">Título del Documento</th>
                        <th style="padding: 10px; text-align: center; width: 200px;">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                <?php 
                $id = $_GET['id'];
                $sentencia = $connect->prepare("SELECT * FROM document WHERE idpa= '$id' AND (tipo='general' OR tipo IS NULL OR tipo='');");
                $sentencia->execute();

                $data = array();
                if($sentencia){
                    while($r = $sentencia->fetchObject()){
                        $data[] = $r;
                    }
                }
                ?>
                <?php if(count($data)>0):?>

                <?php foreach($data as $e):?> 
                    <tr style="border-bottom: 1px solid #eee;">
                        <td style="padding: 12px;">
                            <strong><?php echo $e->nomfi; ?></strong>
                        </td>
                        <td style="padding: 12px; text-align: center;">
                            <div style="display: flex; gap: 10px; justify-content: center;">
                                <a href="../../backend/img/subidas/<?php echo $e->foto; ?>" class="flex-card-button" download style="padding: 8px 15px; font-size: 14px;">Download</a>
                                <button class="flex-card-button" style="background-color: #dc3545; padding: 8px 15px; font-size: 14px;" onclick="confirmDelete(<?php echo $e->iddoc; ?>, '<?php echo $e->foto; ?>')" type="button">Eliminar</button>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
  
                <?php else:?>
                    <tr>
                        <td colspan="2" style="padding: 20px; text-align: center;">
                            <p class="alert alert-warning">No existe ningun documento</p>
                        </td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Contenedor 2: Firma -->
    <div class="content-data">
        <div class="head">
            <h3>Firma</h3>
            <div class="botonsa-modals">
                <label for="btnsa-modals-firma">
                    Nuevo
                </label>
            </div>         
        </div>
        <div class="flexbox">
            <ul class="flex-card-list">
                <?php 
                $sentencia_firma = $connect->prepare("SELECT * FROM document WHERE idpa= '$id' AND tipo='firma';");
                $sentencia_firma->execute();

                $data_firma = array();
                if($sentencia_firma){
                    while($r = $sentencia_firma->fetchObject()){
                        $data_firma[] = $r;
                    }
                }
                ?>
                <?php if(count($data_firma)>0):?>

                <?php foreach($data_firma as $e):?> 
                    <li class="flex-card-listitem">
                        <div class="flex-card">
                            <div class="flex-card-image">
                                <img src="../../backend/img/subidas/<?php echo $e->foto; ?>" />
                            </div>
                            <div class="flex-card-content">
                                <h4><?php echo $e->nomfi; ?></h4>
                                <div style="display: flex; gap: 10px; margin-top: 10px;">
                                    <a href="../../backend/img/subidas/<?php echo $e->foto; ?>" class="flex-card-button" download>Download</a>
                                    <button class="flex-card-button" style="background-color: #dc3545;" onclick="confirmDelete(<?php echo $e->iddoc; ?>, '<?php echo $e->foto; ?>')" type="button">Eliminar</button>
                                </div>
                            </div>
                        </div>
                    </li>
                <?php endforeach; ?>
  
                <?php else:?>
                    <p class="alert alert-warning">No existe ninguna firma</p>
                <?php endif; ?>

            </ul>
        </div>
    </div>

    <!-- Contenedor 3: Autorización tratamientos de datos -->
    <div class="content-data">
        <div class="head">
            <h3>Autorización tratamientos de datos</h3>
        </div>
        <div class="flexbox">
            <?php 
                $sentencia_autorizacion = $connect->prepare("SELECT * FROM document WHERE idpa= '$id' AND tipo='autorizacion';");
                $sentencia_autorizacion->execute();

                $data_autorizacion = array();
                if($sentencia_autorizacion){
                    while($r = $sentencia_autorizacion->fetchObject()){
                        $data_autorizacion[] = $r;
                    }
                }
                
                // Check if exists
                $existing_auth = null;
                $auth_status = null;
                if(count($data_autorizacion) > 0) {
                    $existing_auth = $data_autorizacion[0];
                    // Extract status from description
                    if (strpos($existing_auth->nomfi, 'AUTORIZADO: SÍ') !== false) {
                        $auth_status = 'SÍ';
                    } elseif (strpos($existing_auth->nomfi, 'AUTORIZADO: NO') !== false) {
                        $auth_status = 'NO';
                    }
                }
            ?>
            <div style="margin-bottom: 20px; padding: 20px; border: 1px solid #eee; border-radius: 8px;">
                <form enctype="multipart/form-data" method="POST" action="" autocomplete="off">
                    <div id="err"></div>
                    
                    <div style="margin-bottom: 20px;">
                        <label><b>¿Autoriza Tratamiento de Datos?</b></label><span class="badge-warning">*</span>
                        <div style="margin-top: 10px;">
                            <label style="display: inline-block; margin-right: 20px; cursor: pointer;">
                                <input type="radio" name="autoriza_status" value="SÍ" required <?php if($auth_status == 'SÍ') echo 'checked'; ?>> SÍ
                            </label>
                            <label style="display: inline-block; cursor: pointer;">
                                <input type="radio" name="autoriza_status" value="NO" <?php if($auth_status == 'NO') echo 'checked'; ?>> NO
                            </label>
                        </div>
                    </div>

                    <input type="hidden" name="docidpa" value="<?php echo $d->idpa; ?>">
                    <input type="hidden" name="docnopa" value="<?php echo $d->nompa; ?>">
                    <input type="hidden" name="doctipo" value="autorizacion">
                    
                    <?php if($existing_auth): ?>
                        <input type="hidden" name="id_doc_autorizacion" value="<?php echo $existing_auth->iddoc; ?>">
                        <input class="registerbtn" name="add_docu" type="submit" value="Actualizar">
                    <?php else: ?>
                        <input class="registerbtn" name="add_docu" type="submit" value="Guardar">
                    <?php endif; ?>
                </form>
            </div>
            <ul class="flex-card-list">
                <?php if(count($data_autorizacion)>0):?>

                <?php foreach($data_autorizacion as $e):?> 
                    <li class="flex-card-listitem">
                        <div class="flex-card">
                            <div class="flex-card-content">
                                <h4><?php echo $e->nomfi; ?></h4>
                                <div style="display: flex; gap: 10px; margin-top: 10px;">
                                    <button class="flex-card-button" style="background-color: #dc3545;" onclick="confirmDelete(<?php echo $e->iddoc; ?>, '<?php echo $e->foto; ?>')" type="button">Eliminar</button>
                                </div>
                            </div>
                        </div>
                    </li>
                <?php endforeach; ?>
  
                <?php else:?>
                    <p class="alert alert-warning">No existe ninguna autorización</p>
                <?php endif; ?>

            </ul>
        </div>
    </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 src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
<?php include_once '../../backend/modal/md_docu.php' ?>
<?php include_once '../../backend/php/add_docu.php' ?>
<?php include_once '../../backend/php/delete_docu.php' ?>

<script>
function confirmDelete(iddoc, foto) {
    swal({
        title: "¿Estás seguro?",
        text: "Una vez eliminado, no podrás recuperar este documento",
        icon: "warning",
        buttons: ["Cancelar", "Eliminar"],
        dangerMode: true,
    }).then((willDelete) => {
        if (willDelete) {
            // Crear formulario y enviarlo
            var form = document.createElement('form');
            form.method = 'POST';
            form.action = '';
            
            var inputId = document.createElement('input');
            inputId.type = 'hidden';
            inputId.name = 'iddoc';
            inputId.value = iddoc;
            form.appendChild(inputId);
            
            var inputFoto = document.createElement('input');
            inputFoto.type = 'hidden';
            inputFoto.name = 'foto';
            inputFoto.value = foto;
            form.appendChild(inputFoto);
            
            var inputDelete = document.createElement('input');
            inputDelete.type = 'hidden';
            inputDelete.name = 'delete_docu';
            inputDelete.value = '1';
            form.appendChild(inputDelete);
            
            document.body.appendChild(form);
            form.submit();
        }
    });
}
</script>




</body>
</html>


