<?php
session_start();

if (!isset($_SESSION['usuario'])) {
    header("Location: planos_acceso.php");
    exit;
}

$tipo = $_SESSION['tipo'];
$usuario_actual = $_SESSION['usuario'];

// Conexión a la base de datos
require_once('planos_conexion.php');

$conn = new mysqli($host, $user, $pass, $db);
$conn->set_charset("utf8mb4");

if ($conn->connect_error) {
    die("Conexi贸n fallida: " . $conn->connect_error);
}

// Obtener datos del usuario conectado
$sql_usuario = $conn->prepare("SELECT FOLIO_USUARIO, NOMBRE_APELLIDO FROM PLANOS_USUARIOS WHERE USUARIO_SIS = ?");
$sql_usuario->bind_param("s", $usuario_actual);
$sql_usuario->execute();
$result_usuario = $sql_usuario->get_result();
$datos_usuario = $result_usuario->fetch_assoc();

$folio_actual = $datos_usuario['FOLIO_USUARIO'];
$nombre_actual = $datos_usuario['NOMBRE_APELLIDO'];

// Obtener usuarios "Ver"
$result_ver = $conn->query("SELECT FOLIO_USUARIO, NOMBRE_APELLIDO FROM PLANOS_USUARIOS WHERE TIPO_USUARIO_SIS = 'Ver'");

// Obtener planos
$result_planos = $conn->query("SELECT CLAVE, NOMBRE FROM PLANOS WHERE VIGENTE = 1");

// Convertir a arrays para JS y datalist
$usuariosVer = [];
while ($u = $result_ver->fetch_assoc()) $usuariosVer[] = $u;

$planos = [];
while ($p = $result_planos->fetch_assoc()) $planos[] = $p;
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="planos_estilo.css" />
    <link rel="icon" href="Iconos/planos_icono_vineta.png" type="image/x-icon"> 
    <title>Entrega Planos</title>

    
    
    

    <style>

        body {
            font-family: 'Helvetica', sans-serif;
            padding: 20px;
            margin: 0;
            height: 100vh;
background: linear-gradient(135deg, #1d4f4d 0%, #3caea3 40%, #58d3b5 75%, #a0f0d0 100%);
            background-size: cover;
        }


/* Estio del form ****************** */


        form {
            max-width: 1800px;
            margin: 10px auto;
            background-color: rgba(255, 255, 255, 0.95); /* Ligera transparencia */
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); /* Sombra m谩s suave y elegante */
            font-family: 'Helvetica', sans-serif;
            backdrop-filter: blur(2px); /* Si quieres un efecto tipo vidrio (opcional) */
        }
                
        
        fieldset {
            border: 1px solid #ccc;
            border-radius: 8px;
            margin-bottom: 20px;
            padding: 20px;
            background-color: #fdfdfd;
        }
        legend {
            font-family: 'Helvetica', sans-serif;
            color: #00185d;
            font-size: 1.0em;
        }
        label {
            font-family: 'Helvetica', sans-serif;
            color: #00185d;
            font-size: 1.0em;
            width: 100px;
            margin-right: 10px;
        }
        input[type="text"],
        select {
            padding: 8px;
            border-radius: 6px;
            border: 1px solid #ccc;
            width: 220px;
            margin-bottom: 10px;
        }
        
        .fila-detalle input,
        .fila-detalle select,
        .fila-detalle textarea {
            width: 95%;
            padding: 6px;
            border-radius: 4px;
            box-sizing: border-box;
            font-size: 0.9em;
            border: 1px solid #ccc;
            font-family: 'Helvetica', sans-serif;
            color: #00185d;
            resize: none;
            overflow: hidden;
            margin: 0; /* elimina espacios verticales no deseados */
            line-height: 1.2;
        }

        .boton-eliminar {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 6px 10px;
            cursor: pointer;
            border-radius: 4px;
        }
        .boton-eliminar:hover {
            background-color: #c0392b;
        }
        
        /* boton grabar */ 
        .botones {               
            margin-top: 15px;
            text-align: center;
        }
        
         /* boton agregar mapa */ 
        .boton-izquierda {
            text-align: left;
            margin-top: 15px;
            font-size: 0.8em;
        }       
        
        .grabar {
            background-color: #06569c;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            font-size: 1em;
            cursor: pointer;
        }
        .grabar:hover {
            background-color: #044a88;
        }
        .tabla-detalle {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
            table-layout: fixed;
        }
        .tabla-detalle th,
        .tabla-detalle td {
            border: 1px solid #06569c;
            padding: 6px;
            text-align: center;
            vertical-align: middle;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 0.8em;
        }
        .tabla-detalle th {
            background-color: #06569c;
            color: white;
            font-size: 0.8m;
        }
        
        input[type="text"],
        select {
            font-size: 0.9em;
        }

        .tabla-detalle td {
          vertical-align: middle;
        }

        .icono-botonm2 {
            width: 40px;
            height: 40px;
            vertical-align: middle; 
            margin-right: 10px;
        }
        
        
        .botonesm button {
        display: flex;              /* Coloca   cono y texto en l  nea horizontal */
        align-items: center;        /* Centra verticalmente */
        justify-content: flex-start;/* Alinea todo a la izquierda */
        gap: 0px;                  /* Espacio entre   cono y texto */
        padding-left: 20px;         /* Margen interno a la izquierda */
        width: 90%;
        max-width: 280px;
        margin: 15px auto;
        padding-top: 4px;
        padding-bottom: 4px;
        font-size: 14px;
        font-family: 'Helvetica', sans-serif;
        background-color:   #0c4896;    
        color: white;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        transition: background-color 0.3s;
        text-align: left;           /* Por si acaso, fuerza texto alineado a la izquierda */
    }
    
    .botonesm button:hover {
        background-color: #09356c;
    }
    
    
    .texto-labelhdr {
    color: #28a19b;       /* Azul oscuro, igual al resto del dise帽o */
    font-weight: bold;    /* Opcional */
    font-size: 1em;       /* Opcional: para mantener consistencia */
    }


/***********  estilo de la cabecera  *********/


.encabezado-formulario {
    display: flex;
    justify-content: space-between;
    align-items: center; /* 馃憟 Alineaci贸n vertical centrada */
    padding: 10px 20px;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 10px;
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
    max-width: 1600px;
    margin: 3px auto;
    height: 20px auto;
}

.titulo-menu {
    display: flex;
    align-items: center;
    gap: 10px;
}

.titulo-menu img.icono-menu-ver {
    width: 35px;
    height: 35px;
    vertical-align: middle;
}

.titulo-menu h1 {
    font-size: 18px;
    margin: 0;
    line-height: 1.2;
}

.botones button {
    background-color: #0c4896;
    color: white;
    border: none;
    border-radius: 6px;
    padding: 10px 15px;
    font-size: 14px;
    cursor: pointer;
    transition: background-color 0.3s;
    height: 40px;              /* 馃憟 Coincidir con altura del icono */
    display: flex;
    align-items: center;       /* 馃憟 Centrar texto dentro del bot贸n */
    width: auto;


}
     
    </style>
</head>


<!-- CSS de Select2 -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<!-- JS de Select2 (requiere jQuery) -->
<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>


<body>
    
       <div class="encabezado-formulario">
    <div class="titulo-menu">
        <img src="Iconos/planos_icono_entrega.png" alt="Icono" class="icono-menu-ver">
        <h1>Entrega de Planos</h1>
    </div>
    <div class="botones">
        <button onclick="location.href='planos_menuentregas.php'">Volver al Men煤 Principal</button>
    </div>
    </div>
    

    <form method="POST" action="planos_entrega_exe.php" autocomplete="off">
        <fieldset>
            <legend><strong>Informaci贸n de Entrega</strong></legend>

            <label><strong>Fecha:</strong></label>
            <span style="font-family: 'Helvetica', sans-serif; color: #28a19b; font-weight: bold;font-size: 1em; width: 100px; margin-right: 10px; display: inline-block;">
                <?= date('d M Y') ?>
            </span>
            <input type="hidden" name="fecha" value="<?= date('d/m/Y') ?>" />

            <div style="display: inline-block; margin-right: 40px;">
                <label><strong>Entregado por:</strong></label>
                <span class="texto-labelhdr"><?= htmlspecialchars($nombre_actual) ?></span>
                <input type="hidden" name="folio_usuario" value="<?= htmlspecialchars($folio_actual) ?>" />
            </div>
            
            <div style="display: inline-block;">
                <label><strong>Para:</strong></label>
                <input type="text" name="nombre_usuario_recibe" list="lista-usuarios" placeholder="Escriba y seleccione..." oninput="asignarFolio(this)" required style="width: 300px;" />
                <input type="hidden" name="folio_usuario_recibe" />
            </div>


        </fieldset>

        <fieldset>
            <legend><strong>Planos por Entregar</strong></legend>

            <table class="tabla-detalle">
                <thead>
                    <tr>
                        <th style="width: 15%;">Clave Plano</th>
                        <th style="width: 30%;">Nombre Plano</th>
                        <th style="width: 28%;">Observaci贸n</th>
                        <th style="width: 6%;">PAE</th>
                        <th style="width: 7%;">Acci贸n</th>
                    </tr>
                </thead>
                <tbody id="detalle-contenedor">
                    <!-- Filas se agregar谩n con JS -->
                </tbody>
            </table>

            <div class="boton-izquierda">
                <button type="button" onclick="agregarDetalle()" class="grabar">Agregar otro plano</button>
                <span id="contador-planos" style="margin-left: 20px; font-weight: bold; color: #06569c;">
                    Planos seleccionados para entregar: 1
                </span>
            </div>

            <div class="botones">
                <input type="submit" value="Grabar Entrega" class="grabar" tabindex="-1" />
            </div>
            
        </fieldset>


        <!-- DATALIST para autocompletado usuarios -->
        <datalist id="lista-usuarios">
            <?php foreach ($usuariosVer as $u): ?>
                <option value="<?= htmlspecialchars($u['NOMBRE_APELLIDO']) ?>" data-folio="<?= htmlspecialchars($u['FOLIO_USUARIO']) ?>"></option>
            <?php endforeach; ?>
        </datalist>

        <!-- DATALIST para autocompletado claves -->
        <datalist id="lista-claves">
            <?php foreach ($planos as $p): ?>
                <option value="<?= htmlspecialchars($p['CLAVE']) ?>" data-nombre="<?= htmlspecialchars($p['NOMBRE']) ?>"></option>
            <?php endforeach; ?>
        </datalist>
    </form>

    <script>
        const usuariosVer = <?= json_encode($usuariosVer) ?>;
        const planos = <?= json_encode($planos) ?>;

        function actualizarNombreDesdeClave(inputClave) {
            const clave = inputClave.value.trim();
            const inputNombre = inputClave.closest('tr').querySelector('input[name="detalle_nombre_plano[]"]');
            const plano = planos.find(p => p.CLAVE === clave);
        
            if (plano) {
                inputNombre.value = plano.NOMBRE;
                inputNombre.title = plano.NOMBRE;
        
                // Bandera para no agregar m煤ltiples veces
                if (!inputClave.dataset.lineaAgregada) {
                    inputClave.dataset.lineaAgregada = "true";
        
                    setTimeout(() => {
                        agregarDetalle();
        
                        // Esperamos un momento breve y luego movemos el foco al nuevo input
                        setTimeout(() => {
                            const filas = document.querySelectorAll("#detalle-contenedor tr");
                            const ultimaFila = filas[filas.length - 1];
                            const nuevoInputClave = ultimaFila.querySelector('input[name="detalle_clave[]"]');
                            if (nuevoInputClave) {
                                nuevoInputClave.focus();
                            }
                        }, 100); // Peque帽o delay para asegurar que la fila se agreg贸
                    }, 150);
                }
            } else {
                inputNombre.value = '';
                inputNombre.title = '';
            }

            actualizarContadorPlanos();

        }


        // Si quieres tambi茅n obtener el FOLIO_USUARIO del nombre escrito
        // para enviar, puedes tener otro campo oculto si lo necesitas.
        // Aqu铆 solo dejamos que env铆e el nombre escrito.

        function agregarDetalle() {
            const tbody = document.getElementById("detalle-contenedor");

            const fila = document.createElement("tr");
            fila.classList.add("fila-detalle");
            fila.innerHTML = `
                

                <td>
                    <input type="text" name="detalle_clave[]" list="lista-claves" placeholder="Escriba y elija..." oninput="actualizarNombreDesdeClave(this)" required />
                </td>
                <td>
                    <input type="text" name="detalle_nombre_plano[]" readonly />
                </td>
                <td>

                <textarea name="detalle_observacion[]" rows="1" placeholder=""
                    oninput="autoResize(this)"
                    onfocus="limpiarTextoDefault(this)"
                    onblur="restaurarTextoDefault(this)">Sin observaciones</textarea>


                </td>
                <td>
                    <select name="detalle_entrega_anterior[]" required>
                        <option value="N/A">N/A</option>
                        <option value="Si">S铆</option>
                        <option value="No">No</option>

                    </select>
                    </select>
                </td>
                <td>
                    <button type="button" onclick="this.closest('tr').remove(); actualizarContadorPlanos()" class="boton-eliminar">Eliminar</button>
                </td>
            `;

            tbody.appendChild(fila);
            actualizarContadorPlanos();

        }





function actualizarContadorPlanos() {
    const filas = document.querySelectorAll("#detalle-contenedor tr");
    let contador = 0;

    filas.forEach(fila => {
        const inputClave = fila.querySelector('input[name="detalle_clave[]"]');
        if (inputClave && inputClave.value.trim() !== "") {
            contador++;
        }
    });

    document.getElementById("contador-planos").textContent = `Planos seleccionados para entregar: ${contador}`;
}






        // Validaci贸n simple antes de enviar
        document.querySelector("form").addEventListener("submit", function(e) {
            let valido = true;
            // Validar inputs requeridos en detalle
            const inputsRequeridos = this.querySelectorAll("input[required], select[required]");
            inputsRequeridos.forEach(input => {
                if (input.value.trim() === "") {
                    valido = false;
                    input.style.border = "2px solid red";
                } else {
                    input.style.border = "";
                }
            });
            if (!valido) {
                alert("Por favor, complete todos los campos obligatorios del detalle.");
                e.preventDefault();
            }
        });

        // Agregar una fila por defecto al cargar la p谩gina
        window.onload = agregarDetalle;
        
        
        function asignarFolio(input) {
            const nombre = input.value.trim();
            const usuario = usuariosVer.find(u => u.NOMBRE_APELLIDO === nombre);
            const inputHidden = input.nextElementSibling; // el <input type="hidden">
            inputHidden.value = usuario ? usuario.FOLIO_USUARIO : '';
        }


        function autoResize(textarea) {
            textarea.style.height = 'auto'; // Reinicia la altura
            textarea.style.height = (textarea.scrollHeight) + 'px'; // Ajusta a contenido
        }


        function limpiarTextoDefault(textarea) {
            if (textarea.value.trim() === 'Sin observaciones') {
                textarea.value = '';
                autoResize(textarea); // Ajusta altura si se borra
            }
        }


        function restaurarTextoDefault(textarea) {
            if (textarea.value.trim() === '') {
                textarea.value = 'Sin observaciones';
                autoResize(textarea);
            }
        }


          $(document).ready(function() {
            $('#select-usuario').select2({
              placeholder: "Seleccione...",
              allowClear: true
            });
          });

    </script>


    <script>
        // Solo permitir clic de mouse en botones espec铆ficos
        document.addEventListener('DOMContentLoaded', function () {
            // Bot贸n Grabar Entrega
            const grabarBtn = document.querySelector('input[type="submit"]');
            let mouseClicked = false;
    
            grabarBtn.addEventListener('mousedown', () => mouseClicked = true);
            grabarBtn.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    mouseClicked = false;
                }
            });
    
            grabarBtn.addEventListener('click', function (e) {
                if (!mouseClicked) {
                    e.preventDefault(); // Evita env铆o si no fue un click real
                }
                mouseClicked = false; // Reset
            });
    
            // Bot贸n Volver al Men煤
            const volverBtn = document.querySelector('.botonesm button');
            let mouseClickVolver = false;
    
            volverBtn.addEventListener('mousedown', () => mouseClickVolver = true);
            volverBtn.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    mouseClickVolver = false;
                }
            });
    
            volverBtn.addEventListener('click', function (e) {
                if (!mouseClickVolver) {
                    e.preventDefault();
                }
                mouseClickVolver = false;
            });
        });
    </script>



</body>
</html>