<?php
session_start();
$host = 'localhost';
$db = 'trabajadores';
$username = 'root';
$password = 'root';

if (!isset($_SESSION['usuario'])) {
    header("Location: index.html");
    exit;
}

try {
    $conn = new mysqli($host, $username, $password, $db);

    if ($conn->connect_error) {
        die("Conexión fallida: " . $conn->connect_error);
    }

    $usuario = $_SESSION['usuario'];

    $sql = "SELECT NOMBRE, ROL FROM personal WHERE USUARIO = '$usuario'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $nombre = $row['NOMBRE'];
        $rol = $row['ROL'];

        // 👉 Agregamos la función para sacar iniciales
        function obtenerIniciales($nombreCompleto)
        {
            $partes = explode(' ', $nombreCompleto);
            $iniciales = '';

            foreach ($partes as $parte) {
                if (!empty($parte)) {
                    $iniciales .= strtoupper($parte[0]);
                }
            }
            return $iniciales;
        }

        // 👉 Ahora creamos las iniciales
        $inicialesUsuario = obtenerIniciales($nombre);
    } else {
        $nombre = "Usuario";
        $rol = "Usuario";
        $inicialesUsuario = "US"; // Algo por defecto
    }

    $conn->close();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en" class="light-style layout-menu-fixed" dir="ltr" data-theme="theme-default" data-assets-path="../assets/" data-template="vertical-menu-template-free">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
    <title>Datos</title>
    <meta name="description" content="" />
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="../assets/img/favicon/favicon.ico" />
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Public+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet" />

    <!-- Icons. Uncomment required icon fonts -->
    <link rel="stylesheet" href="../assets/vendor/fonts/boxicons.css" />

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/estilosdetablas.css">
    <link rel="stylesheet" href="../css/botonesfiltros.css">
    <link rel="stylesheet" href="../css/botonexportar.css">


    <!-- Core CSS -->
    <link rel="stylesheet" href="../assets/vendor/css/core.css" class="template-customizer-core-css" />
    <link rel="stylesheet" href="../assets/vendor/css/theme-default.css" class="template-customizer-theme-css" />
    <link rel="stylesheet" href="../assets/css/demo.css" />

    <!-- Vendors CSS -->
    <link rel="stylesheet" href="../assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.css" />

    <link rel="stylesheet" href="../assets/vendor/libs/apex-charts/apex-charts.css" />

    <!-- Leaflet -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />

    <!-- Page CSS -->

    <!-- Helpers -->
    <script src="../assets/vendor/js/helpers.js"></script>
    <script src="../assets/js/config.js"></script>

    <!-- Animate.css -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">

    <style>
        .wow {
            visibility: hidden;
        }

        /* Estilos para el desplegable */
        .search-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            z-index: 9999;
            margin-top: 0.2rem;
            background: white;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            border-radius: 0.25rem;
            overflow-y: auto;
            max-height: 300px;
        }

        .search-dropdown li {
            cursor: pointer;
        }

        .search-dropdown li:hover {
            background-color: #f0f0f0;
        }

        /* Ocultar resultados inicialmente */
        #modalSearchResults {
            display: none;
            max-height: 300px;
            overflow-y: auto;
        }

        .btn-icon {
            background-color: #e0e0e0;
            /* gris suave */
            border: none;
            /* sin borde */
            border-radius: 50%;
            /* redondo */
            padding: 10px;
            /* espacio interno */
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }

        .btn-icon:hover {
            background-color: #d5d5d5;
            /* un poco más oscuro al pasar el mouse */
        }

        .btn-icon i {
            font-size: 20px;
            /* tamaño del ícono */
            color: #919191ff;
            /* color del ícono */
        }

        #tablaCuentas {
            --bs-table-color: unset;
        }
    </style>
</head>

<body>
    <!-- Layout wrapper -->
    <div class="layout-wrapper layout-content-navbar">
        <div class="layout-container">
            <!-- Menu -->

            <aside id="layout-menu" class="layout-menu menu-vertical menu bg-menu-theme">
                <div class="app-brand demo">
                    <a href="index.html" class="app-brand-link">
                        <span class="app-brand-logo demo">
                            <svg
                                version="1.1"
                                xmlns="http://www.w3.org/2000/svg"
                                xmlns:xlink="http://www.w3.org/1999/xlink"
                                x="0px"
                                y="0px"
                                viewBox="0 0 2000 2000"
                                style="enable-background:new 0 0 2000 2000;"
                                xml:space="preserve"
                                width="100"
                                height="100">
                                <style type="text/css">
                                    .st0 {
                                        display: none;
                                    }

                                    .st1 {
                                        fill: #009DFF;
                                    }
                                </style>
                                <g id="Capa_1" class="st0">
                                    <image style="display:inline;overflow:visible;" width="2550" height="1558" transform="matrix(1 0 0 1 494.3726 289.1373)"></image>
                                </g>
                                <g id="Capa_2">
                                    <g>
                                        <rect x="183.89" y="18.31" class="st1" width="1632.23" height="526.02" />
                                        <polygon class="st1" points="1031.3,1629.99 1031.3,1711.86 1308.44,1711.86 1308.44,1825.3 1031.3,1825.3 1031.3,1907.13 1308.44,1907.13 1308.44,1981.69 691.56,1981.69 691.56,682.4 1308.44,682.4 1308.44,1629.99" />
                                    </g>
                                </g>
                                <g id="Capa_3" class="st0"></g>
                            </svg>
                        </span>
                        <span class="app-brand-text demo menu-text fw-bolder ms-2">Trax</span>
                    </a>

                    <a href="javascript:void(0);" class="layout-menu-toggle menu-link text-large ms-auto d-block d-xl-none">
                        <i class="bx bx-chevron-left bx-sm align-middle"></i>
                    </a>
                </div>

                <div class="menu-inner-shadow"></div>

                <ul class="menu-inner py-1">
                    <!-- Dashboard
            <li class="menu-item active">
              <a href="index.html" class="menu-link">
                <i class="menu-icon tf-icons bx bx-home-circle"></i>
                <div data-i18n="Analytics">Dashboard</div>
              </a>
            </li> -->

                    <!-- Layouts -->
                    <li class="menu-item ">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-layout"></i>
                            <div data-i18n="Layouts">Inicio</div>
                        </a>

                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="tablero.php" class="menu-link">
                                    <div data-i18n="Without menu">Tablero</div>
                                </a>
                            </li>
                            <!--
                            <li class="menu-item">
                                <a href="nuevo_cliente.php" class="menu-link">
                                    <div data-i18n="Without navbar">Agregar Cliente</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="nuevo_proveedor.php" class="menu-link">
                                    <div data-i18n="Container">Agregar Proveedor</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="nueva_cotizacion.php" class="menu-link">
                                    <div data-i18n="Fluid">Agregar Cotizacion</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="nuevo_producto-php" class="menu-link">
                                    <div data-i18n="Blank">Agregar Producto</div>
                                </a>
                            </li>

                            <li class="menu-item">
                                <a href="nueva_compra.php" class="menu-link">
                                    <div data-i18n="Blank">Agregar Compra</div>
                                </a>
                            </li>

                            <li class="menu-item">
                                <a href="nueva_factura.php" class="menu-link">
                                    <div data-i18n="Blank">Agregar Factura</div>
                                </a>
                            </li>
                                -->
                        </ul>
                    </li>

                    <li class="menu-header small text-uppercase">
                        <span class="menu-header-text">Aspel SAE</span>
                    </li>
                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-line-chart"></i>
                            <div data-i18n="Account Settings">Ventas</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="facturas.php" class="menu-link">
                                    <div data-i18n="Account">Facturas</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="notasdeventa.php" class="menu-link">
                                    <div data-i18n="Notifications">Notas de Venta</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="trasladoscartaporte.php" class="menu-link">
                                    <div data-i18n="Connections">Carta Porte</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="remisiones.php" class="menu-link">
                                    <div data-i18n="Connections">Remisiones</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="pedidos.php" class="menu-link">
                                    <div data-i18n="Connections">Pedidos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="cotizaciones.php" class="menu-link">
                                    <div data-i18n="Connections">Cotizaciones</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="devoluciones.php" class="menu-link">
                                    <div data-i18n="Connections">Devoluciones</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="notasdecredito.php" class="menu-link">
                                    <div data-i18n="Connections">Notas de Crédito</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="parcialidades.php" class="menu-link">
                                    <div data-i18n="Connections">Parcialidades</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="comprobantesdepago.php" class="menu-link">
                                    <div data-i18n="Connections">Comprobantes</div>
                                </a>
                            <li class="menu-item">
                                <a href="estadisticas.php" class="menu-link">
                                    <div data-i18n="Connections">Estadisticas</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="estadisticascli.php" class="menu-link">
                                    <div data-i18n="Connections">Ventas X Cliente</div>
                                </a>
                            </li>
                        </ul>
                    </li>

                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-user"></i>
                            <div data-i18n="Authentications">Clientes</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="clientes.php" class="menu-link">
                                    <div data-i18n="Basic">Clientes</div>
                                </a>
                            </li>
                            <li class="menu-item ">
                                <a href="correos.php" class="menu-link">
                                    <div data-i18n="Basic">Correos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="cuentasxcobrar.php" class="menu-link">
                                    <div data-i18n="Basic">Cuentas X Cobrar</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="clientespoliza.php" class="menu-link">
                                    <div data-i18n="Basic">Clientes con Póliza</div>
                                </a>
                            </li>

                            <li class="menu-item">
                                <a href="clientestimbres.php" class="menu-link">
                                    <div data-i18n="ClientStamps">Clientes Timbres</div>
                                </a>
                            </li>

                            <li class="menu-item">
                                <a href="clientesistemas.php" class="menu-link">
                                    <div data-i18n="ClientSystems">Clientes Sistemas</div>
                                </a>
                            </li>
                        </ul>
                    </li>


                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-package"></i>
                            <div data-i18n="Misc">Inventarios</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="productos.php" class="menu-link">
                                    <div data-i18n="Error">Productos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="existencias.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Existencias</div>
                                </a>
                            </li>
                        </ul>
                    </li>


                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-shopping-bag"></i>
                            <div data-i18n="Misc">Compras</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="compras.php" class="menu-link">
                                    <div data-i18n="Error">Compras</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="recepciones.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Recepciones</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="ordenes.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Ordenes</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="requisiciones.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Requisiciones</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="devolucionescom.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Devoluciones</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="estadisticasprove.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Compras X Proveedor</div>
                                </a>
                            </li>
                        </ul>
                    </li>


                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-group"></i>
                            <div data-i18n="Misc">Proveedores</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="proveedores.php" class="menu-link">
                                    <div data-i18n="Error">Proveedores</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="cuentasxpagar.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Cuentas X Pagar</div>
                                </a>
                            </li>
                        </ul>
                    </li>


                    <!-- Aspel COI -->
                    <li class="menu-header small text-uppercase"><span class="menu-header-text">Aspel COI</span></li>

                    <!-- Extended components -->
                    <li class="menu-item active open">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-copy"></i>
                            <div data-i18n="Extended UI">Cuentas y Pólizas</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="cuentas.php" class="menu-link">
                                    <div data-i18n="Perfect Scrollbar">Cuentas</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="polizas.php" class="menu-link">
                                    <div data-i18n="Text Divider">Pólizas</div>
                                </a>
                            </li>
                            <li class="menu-item ">
                                <a href="activos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Activos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="auxiliares.php" class="menu-link">
                                    <div data-i18n="Text Divider">Auxiliares</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="presupuestos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Presupuestos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="presupuestosPD.php" class="menu-link">
                                    <div data-i18n="Text Divider">Presupuestos DP</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="monedas.php" class="menu-link">
                                    <div data-i18n="Text Divider">Monedas</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="departamentos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Departamentos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="otrosimpuestos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Otros Impuestos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="activosgenerales.php" class="menu-link">
                                    <div data-i18n="Text Divider">Activos Generales</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="saldos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Saldos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="saldosDP.php" class="menu-link">
                                    <div data-i18n="Text Divider">Saldos DP</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="rubros.php" class="menu-link">
                                    <div data-i18n="Text Divider">Rubros</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="ccostos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Centro de Costos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="concepto.php" class="menu-link">
                                    <div data-i18n="Text Divider">Conceptos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="regpol.php" class="menu-link">
                                    <div data-i18n="Text Divider">Registro de Pólizas</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="impuestos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Impuestos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="timbres.php" class="menu-link">
                                    <div data-i18n="Text Divider">Timbres</div>
                                </a>
                            </li>
                        </ul>
                    </li>

                    <!-- Aspel BANCO -->
                    <li class="menu-header small text-uppercase"><span class="menu-header-text">Aspel BANCO</span></li>
                    <!-- Forms -->
                    <li class="menu-item ">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-credit-card"></i>
                            <div data-i18n="Form Elements">Movimientos</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item ">
                                <a href="movimientos.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Movimientos</div>
                                </a>

                            </li>
                            <li class="menu-item ">
                                <a href="moneda.php" class="menu-link ">
                                    <div data-i18n="Basic Inputs">Moneda</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="beneficiosxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Beneficios</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="cuentasxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Cuentas ban</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="formadepagoxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Forma de pago</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="parametrosxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Partidas de movimientos</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="comprobantedeldocumentoxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Comprobante del documento</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="centrodecuentasxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Conceptos de movimientos</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="historialxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Historial</div>
                                </a>

                            </li>
                        </ul>
                    </li>

                    <li class="menu-header small text-uppercase">
                        <span class="menu-header-text">Mantenimiento y Soporte</span>
                    </li>
                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-credit-card"></i>
                            <div data-i18n="Form Elements">Mantenimiento</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="ordenservicio.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Ordenes de Servicio</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="registrossemana.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Registros</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="estadisticasord.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Estadisticas</div>
                                </a>
                            </li>
                        </ul>
                    </li>
                    <li class="menu-header small text-uppercase">
                        <span class="menu-header-text">Logistica</span>
                    </li>
                    <li class="menu-item  active open">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon icon-base bx bx-car"></i>
                            <div data-i18n="Form Elements">Logistica</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item active">
                                <a href="datos_logistica.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Datos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="logistica.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Nueva Ruta</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="altas_logistica.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Catalogo De Logistica</div>
                                </a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </aside>
            <!-- / Menu -->


            <!-- Layout container -->
            <div class="layout-page">
                <!-- Navbar -->
                <nav class="layout-navbar container-xxl navbar-detached navbar navbar-expand-xl align-items-center bg-navbar-theme" id="layout-navbar">
                    <div class="layout-menu-toggle navbar-nav align-items-xl-center me-3 me-xl-0 d-xl-none">
                        <a class="nav-item nav-link px-0 me-xl-4" href="javascript:void(0)">
                            <i class="bx bx-menu bx-sm"></i>
                        </a>
                    </div>

                    <div class="navbar-nav-right d-flex align-items-center" id="navbar-collapse">
                        <!-- Search -->
                        <div class="navbar-nav align-items-center">
                            <div class="nav-item d-flex align-items-center">
                                <i class="bx bx-search fs-4 lh-0"></i>
                                <input
                                    type="text"
                                    class="form-control border-0 shadow-none"
                                    placeholder="Buscar..."
                                    data-bs-toggle="modal"
                                    data-bs-target="#modalBusqueda" />

                                <!-- Resultados -->
                                <ul id="searchResults" class="list-group search-dropdown"></ul>
                            </div>
                        </div>

                        <!-- /Search -->

                        <ul class="navbar-nav flex-row align-items-center ms-auto">

                            <li class="nav-item dropdown-language dropdown me-2 me-xl-0">
                                <a class="nav-link dropdown-toggle hide-arrow" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class="icon-base bx bx-globe icon-md"></i>
                                </a>
                                <ul class="dropdown-menu dropdown-menu-end" data-bs-popper="static">
                                    <li>
                                        <a class="dropdown-item active" href="javascript:void(0);" data-language="en" data-text-direction="ltr">
                                            <span>English</span>
                                        </a>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="javascript:void(0);" data-language="fr" data-text-direction="ltr">
                                            <span>French</span>
                                        </a>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="javascript:void(0);" data-language="ar" data-text-direction="rtl">
                                            <span>Arabic</span>
                                        </a>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="javascript:void(0);" data-language="de" data-text-direction="ltr">
                                            <span>German</span>
                                        </a>
                                    </li>
                                </ul>
                            </li>


                            <!-- Icono de modo oscuro -->
                            <li class="nav-item dropdown me-2 me-xl-0">
                                <a class="nav-link dropdown-toggle hide-arrow" id="nav-theme" href="javascript:void(0);" data-bs-toggle="dropdown" aria-label="Toggle theme (light)">
                                    <i class="bx-sun icon-base bx icon-md theme-icon-active"></i>
                                    <span class="d-none ms-2" id="nav-theme-text">Toggle theme</span>
                                </a>


                                <!-- Submenu de modo oscuro -->
                                <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="nav-theme-text" data-bs-popper="static">
                                    <li>
                                        <button type="button" class="dropdown-item align-items-center active" data-bs-theme-value="light" aria-pressed="true">
                                            <span>
                                                <i class="icon-base bx bx-sun icon-md me-3" data-icon="sun"></i>Claro
                                            </span>
                                        </button>
                                    </li>

                                    <li>
                                        <button type="button" class="dropdown-item align-items-center" data-bs-theme-value="dark" aria-pressed="false">
                                            <span>
                                                <i class="icon-base bx bx-moon icon-md me-3" data-icon="moon"></i>Oscuro
                                            </span>
                                        </button>
                                    </li>

                                    <li>
                                        <button type="button" class="dropdown-item align-items-center" data-bs-theme-value="system" aria-pressed="false">
                                            <span>
                                                <i class="icon-base bx bx-desktop icon-md me-3" data-icon="desktop"></i>Dispositivo
                                            </span>
                                        </button>
                                    </li>

                                </ul>

                                <!-- Aquí termina submenu -->
                            </li>


                            <li class="nav-item dropdown-shortcuts navbar-dropdown dropdown me-2 me-xl-0">
                                <a class="nav-link dropdown-toggle hide-arrow" href="javascript:void(0);" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
                                    <i class="icon-base bx bx-grid-alt icon-md"></i>
                                </a>
                                <!-- submenu -->
                                <div class="dropdown-menu dropdown-menu-end p-0">
                                    <div class="dropdown-menu-header border-bottom">
                                        <div class="dropdown-header d-flex align-items-center py-3">
                                            <h6 class="mb-0 me-auto">Shortcuts</h6>
                                            <a href="javascript:void(0)" class="dropdown-shortcuts-add py-2" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="Add shortcuts" data-bs-original-title="Add shortcuts"><i class="icon-base bx bx-plus-circle text-heading"></i></a>
                                        </div>
                                    </div>
                                    <div class="dropdown-shortcuts-list scrollable-container ps">
                                        <div class="row row-bordered overflow-visible g-0">
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-calendar icon-26px text-heading"></i>
                                                </span>
                                                <a href="app-calendar.html" class="stretched-link">Calendar</a>
                                                <small>Appointments</small>
                                            </div>
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-food-menu icon-26px text-heading"></i>
                                                </span>
                                                <a href="app-invoice-list.html" class="stretched-link">Invoice App</a>
                                                <small>Manage Accounts</small>
                                            </div>
                                        </div>
                                        <div class="row row-bordered overflow-visible g-0">
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-user icon-26px text-heading"></i>
                                                </span>
                                                <a href="app-user-list.html" class="stretched-link">User App</a>
                                                <small>Manage Users</small>
                                            </div>
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-check-shield icon-26px text-heading"></i>
                                                </span>
                                                <a href="app-access-roles.html" class="stretched-link">Role Management</a>
                                                <small>Permission</small>
                                            </div>
                                        </div>
                                        <div class="row row-bordered overflow-visible g-0">
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-pie-chart-alt-2 icon-26px text-heading"></i>
                                                </span>
                                                <a href="index.html" class="stretched-link">Dashboard</a>
                                                <small>User Dashboard</small>
                                            </div>
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-cog icon-26px text-heading"></i>
                                                </span>
                                                <a href="pages-account-settings-account.html" class="stretched-link">Setting</a>
                                                <small>Account Settings</small>
                                            </div>
                                        </div>
                                        <div class="row row-bordered overflow-visible g-0">
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-help-circle icon-26px text-heading"></i>
                                                </span>
                                                <a href="pages-faq.html" class="stretched-link">FAQs</a>
                                                <small>FAQs &amp; Articles</small>
                                            </div>
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-window-open icon-26px text-heading"></i>
                                                </span>
                                                <a href="modal-examples.html" class="stretched-link">Modals</a>
                                                <small>Useful Popups</small>
                                            </div>
                                        </div>
                                        <div class="ps__rail-x" style="left: 0px; bottom: 0px;">
                                            <div class="ps__thumb-x" tabindex="0" style="left: 0px; width: 0px;"></div>
                                        </div>
                                        <div class="ps__rail-y" style="top: 0px; right: 0px;">
                                            <div class="ps__thumb-y" tabindex="0" style="top: 0px; height: 0px;"></div>
                                        </div>
                                    </div>
                                </div>
                                <!-- aqui termina submenu -->

                            </li>

                            <li class="nav-item dropdown-notifications navbar-dropdown dropdown me-3 me-xl-2">
                                <a class="nav-link dropdown-toggle hide-arrow" href="javascript:void(0);" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
                                    <span class="position-relative">
                                        <i class="icon-base bx bx-bell icon-md"></i>
                                        <span class="badge rounded-pill bg-danger badge-dot badge-notifications border"></span>
                                    </span>
                                </a>

                                <!--empiezan las notificaciones -->
                                <ul class="dropdown-menu dropdown-menu-end p-0">
                                    <li class="dropdown-menu-header border-bottom">
                                        <div class="dropdown-header d-flex align-items-center py-3">
                                            <h6 class="mb-0 me-auto">Notification</h6>
                                            <div class="d-flex align-items-center h6 mb-0">
                                                <span class="badge bg-label-primary me-2">8 New</span>
                                                <a href="javascript:void(0)" class="dropdown-notifications-all p-2" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="Mark all as read" data-bs-original-title="Mark all as read"><i class="icon-base bx bx-envelope-open text-heading"></i></a>
                                            </div>
                                        </div>
                                    </li>


                                    <li class="dropdown-notifications-list scrollable-container ps">
                                        <ul class="list-group list-group-flush">
                                            <li class="list-group-item list-group-item-action dropdown-notifications-item">
                                                <div class="d-flex">
                                                    <div class="flex-shrink-0 me-3">
                                                        <div class="avatar">
                                                            <img src="../../assets/img/avatars/1.png" alt="" class="rounded-circle">
                                                        </div>
                                                    </div>
                                                    <div class="flex-grow-1">
                                                        <h6 class="small mb-0">Congratulation Lettie 🎉</h6>
                                                        <small class="mb-1 d-block text-body">Won the monthly best seller gold badge</small>
                                                        <small class="text-body-secondary">1h ago</small>
                                                    </div>
                                                    <div class="flex-shrink-0 dropdown-notifications-actions">
                                                        <a href="javascript:void(0)" class="dropdown-notifications-read"><span class="badge badge-dot"></span></a>
                                                        <a href="javascript:void(0)" class="dropdown-notifications-archive"><span class="icon-base bx bx-x"></span></a>
                                                    </div>
                                                </div>
                                            </li>
                                            <li class="list-group-item list-group-item-action dropdown-notifications-item">
                                                <div class="d-flex">
                                                    <div class="flex-shrink-0 me-3">
                                                        <div class="avatar">
                                                            <span class="avatar-initial rounded-circle bg-label-danger">CF</span>
                                                        </div>
                                                    </div>
                                                    <div class="flex-grow-1">
                                                        <h6 class="small mb-0">Charles Franklin</h6>
                                                        <small class="mb-1 d-block text-body">Accepted your connection</small>
                                                        <small class="text-body-secondary">12hr ago</small>
                                                    </div>
                                                    <div class="flex-shrink-0 dropdown-notifications-actions">
                                                        <a href="javascript:void(0)" class="dropdown-notifications-read"><span class="badge badge-dot"></span></a>
                                                        <a href="javascript:void(0)" class="dropdown-notifications-archive"><span class="icon-base bx bx-x"></span></a>
                                                    </div>
                                                </div>
                                            </li>
                                            <li class="list-group-item list-group-item-action dropdown-notifications-item marked-as-read">
                                                <div class="d-flex">
                                                    <div class="flex-shrink-0 me-3">
                                                        <div class="avatar">
                                                            <img src="../../assets/img/avatars/2.png" alt="" class="rounded-circle">
                                                        </div>
                                                    </div>
                                                    <div class="flex-grow-1">
                                                        <h6 class="small mb-0">New Message ✉️</h6>
                                                        <small class="mb-1 d-block text-body">You have new message from Natalie</small>
                                                        <small class="text-body-secondary">1h ago</small>
                                                    </div>
                                                    <div class="flex-shrink-0 dropdown-notifications-actions">
                                                        <a href="javascript:void(0)" class="dropdown-notifications-read"><span class="badge badge-dot"></span></a>
                                                        <a href="javascript:void(0)" class="dropdown-notifications-archive"><span class="icon-base bx bx-x"></span></a>
                                                    </div>
                                                </div>
                                            </li>
                                        </ul>

                                        <div class="ps__rail-x" style="left: 0px; bottom: 0px;">
                                            <div class="ps__thumb-x" tabindex="0" style="left: 0px; width: 0px;"></div>
                                        </div>
                                        <div class="ps__rail-y" style="top: 0px; right: 0px;">
                                            <div class="ps__thumb-y" tabindex="0" style="top: 0px; height: 0px;"></div>
                                        </div>
                                    </li>

                                    <li class="border-top">
                                        <div class="d-grid p-4">
                                            <a class="btn btn-primary btn-sm d-flex" href="javascript:void(0);">
                                                <small class="align-middle">View all notifications</small>
                                            </a>
                                        </div>
                                    </li>
                                </ul> <!-- termina submenu de notificaciones -->
                            </li>



                            <!-- User -->
                            <li class="nav-item navbar-dropdown dropdown-user dropdown">
                                <a class="nav-link dropdown-toggle hide-arrow" href="javascript:void(0);" data-bs-toggle="dropdown">
                                    <div class="avatar avatar-online">
                                        <span class="avatar-initial rounded-circle bg-label-primary"><?php echo htmlspecialchars($inicialesUsuario); ?></span>
                                    </div>
                                </a>
                                <ul class="dropdown-menu dropdown-menu-end">
                                    <li>
                                        <a class="dropdown-item" href="#">
                                            <div class="d-flex">
                                                <div class="flex-shrink-0 me-3">
                                                    <div class="avatar avatar-online">
                                                        <span class="avatar-initial rounded-circle bg-label-primary"><?php echo htmlspecialchars($inicialesUsuario); ?></span>
                                                    </div>
                                                </div>
                                                <div class="flex-grow-1">
                                                    <span class="fw-semibold d-block"><?php echo htmlspecialchars($nombre); ?></span>
                                                    <small class="text-muted"><?php echo htmlspecialchars($rol); ?></small>
                                                </div>
                                            </div>
                                        </a>
                                    </li>
                                    <li>
                                        <div class="dropdown-divider"></div>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="index.html">
                                            <i class="bx bx-power-off me-2"></i>
                                            <span class="align-middle">Cerrar Sesión</span>
                                        </a>
                                    </li>
                                </ul>
                            </li>
                            <!--/ User -->
                        </ul>
                    </div>
                </nav>
                <!-- / Navbar -->

                <!-- Content wrapper -->
                <div class="content-wrapper">
                    <!-- Content -->


                    <div class="container-xxl flex-grow-1 container-p-y">
                        <div class="row">
                            <!--/ Total Revenue -->
                            <div class="col-12 col-md-12 col-lg-12 order-3 order-md-2">
                                <div class="row">


                                    <!-- <div class="col-sm-6 col-xl-4 mb-4 wow animate__animated animate__fadeInUp" data-wow-delay="0.2s">
                                        <div class="card">
                                            <div class="card-body">
                                                <div class="d-flex align-items-center justify-content-between">
                                                    <div class="content-left">
                                                        <small>Total de Registros</small>

                                                    </div>
                                                    <span class="badge bg-label-primary rounded-circle p-2">
                                                        <i class="icon-base bx bx-dollar icon-lg"></i>
                                                    </span>

                                                </div>

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


                                    <div class="col-sm-6 col-xl-4 mb-4 wow animate__animated animate__fadeInUp" data-wow-delay="0.4s">
                                        <div class="card">
                                            <div class="card-body">
                                                <div class="d-flex align-items-center justify-content-between">
                                                    <div class="content-left">
                                                        <small>Total de Registros</small>

                                                    </div>
                                                    <span class="badge bg-label-success rounded-circle p-2">
                                                        <i class="icon-base bx bx-task icon-lg"></i>
                                                    </span>
                                                </div>

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


                                    <div class="col-sm-12 col-xl-4 mb-4 wow animate__animated animate__fadeInUp" data-wow-delay="0.6s">
                                        <div class="card">
                                            <div class="card-body">
                                                <div class="d-flex align-items-center justify-content-between">
                                                    <div class="content-left">
                                                        <small>Total de Registros</small>

                                                    </div>
                                                    <span class="badge bg-label-danger rounded-circle p-2">
                                                        <i class="icon-base bx bx-task-x icon-lg"></i>
                                                    </span>
                                                </div>

                                            </div>
                                        </div>
                                    </div> -->
                                    <!-- </div>
                    <div class="row"> -->
                                </div>
                            </div>
                        </div>

                        <!-- <h4 class="fw-bold py-3 mb-4"><span class="text-muted fw-light">Tables /</span> Basic Tables</h4> -->

                        <!-- Basic Bootstrap Table -->
                        <div class="card wow animate__animated animate__fadeInUp" data-wow-delay="0.8s">
                            <!-- <h5 class="card-header">Compras</h5> -->
                            <div>


                                <div class="content">

                                    <?php
                                    $host = 'localhost';
                                    $username = 'root';
                                    $database = 'rastreo';
                                    $password = 'root';

                                    try {
                                        $pdo = new PDO("mysql:host=$host;dbname=$database;charset=UTF8", $username, $password);
                                        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                                        // Consulta rutas con repartidores y autos
                                        $stmt = $pdo->prepare("
                                                               SELECT 
                                                                   r.id_ruta, 
                                                                   r.lat, 
                                                                   r.lon, 
                                                                   r.repartidor_id, 
                                                                   r.auto_id,  
                                                                   r.pedido_id, 
                                                                   r.direccion, 
                                                                   r.STAT_PED, 
                                                                   r.STAT_REP,
                                                                   r.lon_alm, 
                                                                   r.lat_alm,
                                                                   rep.nombre AS repartidor_nombre, 
                                                                   rep.traker_id,
                                                                   rep.telefono AS telefono_conductor,
                                                                   rep.foto_repartidor AS foto_repartidor,
                                                                   rep.correo,
                                                                   a.imagen AS img_unidad, 
                                                                   a.marca AS auto_marca, 
                                                                   a.modelo AS auto_modelo,
                                                                   a.placa AS auto_placa,
                                                                   a.color AS auto_color,
                                                                   a.tipo_combustible AS auto_combustible,
                                                                   a.anio AS auto_anio
                                                               FROM rutas r
                                                               INNER JOIN repartidores rep ON r.repartidor_id = rep.id
                                                               LEFT JOIN autos a ON r.auto_id = a.id_unidad   
                                                               ORDER BY r.repartidor_id, r.id_ruta;
                                                           ");
                                        $stmt->execute();

                                        // Agrupamos por id_ruta
                                        $data = [];
                                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                            $id_ruta = $row['id_ruta'];
                                            if (!isset($data[$id_ruta])) {
                                                $data[$id_ruta] = [
                                                    'id_ruta' => $id_ruta,
                                                    'repartidor_id' => $row['repartidor_id'],
                                                    'nombre' => $row['repartidor_nombre'],
                                                    'traker_id' => $row['traker_id'],
                                                    'stat_rep' => $row['STAT_REP'],
                                                    'telefono_conductor' => $row['telefono_conductor'],
                                                    'correo' => $row['correo'],

                                                    'img_unidad' => !empty($row['img_unidad'])
                                                        ? "imagenes_vehiculos/" . $row['img_unidad']
                                                        : "placeholder_auto.png",

                                                    'img_repartidor' => !empty($row['foto_repartidor'])
                                                        ? (strpos($row['foto_repartidor'], 'http') === 0
                                                            ? $row['foto_repartidor']
                                                            : $row['foto_repartidor'])
                                                        : "placeholder_repartidor.png",

                                                    'unidad' => trim(
                                                        $row['auto_marca'] . ' ' .
                                                            $row['auto_modelo'] . ' ' .
                                                            ucfirst($row['auto_color']) . ', placas: ' .
                                                            $row['auto_placa']
                                                    ),

                                                    'auto_marca' => $row['auto_marca'],
                                                    'auto_modelo' => $row['auto_modelo'],
                                                    'auto_color' => $row['auto_color'],
                                                    'auto_placa' => $row['auto_placa'],
                                                    'auto_anio' => $row['auto_anio'],
                                                    'auto_combustible' => $row['auto_combustible'],

                                                    'pedidos' => [],
                                                    'coordenadas_rutas' => [],
                                                    'ubicaciones' => [],
                                                    'almacen' => ['lat' => $row['lat_alm'], 'lon' => $row['lon_alm']],
                                                    'progreso' => 0
                                                ];
                                            }

                                            // Guardar pedidos
                                            $data[$id_ruta]['pedidos'][] = [
                                                'id' => $row['pedido_id'],
                                                'direccion' => $row['direccion'],
                                                'status' => $row['STAT_PED']
                                            ];
                                            $data[$id_ruta]['coordenadas_rutas'][] = ['lat' => $row['lat'], 'lon' => $row['lon']];
                                        }

                                        // Calcular progreso (entregados vs total)
                                        foreach ($data as &$info) {
                                            $totalPedidos = count($info['pedidos']);
                                            $entregados = 0;

                                            foreach ($info['pedidos'] as $p) {
                                                if ($p['status'] === 'E') {
                                                    $entregados++;
                                                }
                                            }

                                            $info['progreso'] = $totalPedidos > 0 ? round(($entregados / $totalPedidos) * 100) : 0;
                                        }
                                        unset($info);

                                        // Traemos ubicaciones
                                        $stmtUb = $pdo->prepare("SELECT nombre, lat, lon FROM ubicaciones");
                                        $stmtUb->execute();
                                        $ubicaciones = $stmtUb->fetchAll(PDO::FETCH_ASSOC);

                                        foreach ($data as &$info) {
                                            foreach ($ubicaciones as $u) {
                                                if ($u['nombre'] == $info['traker_id']) {
                                                    $info['ubicaciones'][] = ['lat' => $u['lat'], 'lon' => $u['lon']];
                                                }
                                            }
                                        }
                                        unset($info);
                                    } catch (PDOException $e) {
                                        die("<div class='container mt-5'><h2>Error de conexión:</h2><p>" . $e->getMessage() . "</p></div>");
                                    }
                                    ?>


                                    <div class="container mt-5">
                                        <h1><strong>Vehículos en ruta</strong></h1>
                                        <table id="tablaCuentas" class="table table-hover text-nowrap">
                                            <thead class="table-dark">
                                                <tr>
                                                    <th>Ubicación</th>
                                                    <th>Repartidor</th>
                                                    <th>Datos</th>
                                                    <th>Prgreso</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($data as $id_ruta => $info): ?>
                                                    <tr>
                                                        <td class="d-flex align-items-center">
                                                            <button class="btn-icon me-2" data-bs-toggle="modal" data-bs-target="#modal<?= $id_ruta ?>">
                                                                <i class="icon-base bx bxs-truck icon-lg"></i>
                                                            </button>
                                                            <span>Ver Ubicación</span>
                                                        </td>
                                                        <td><?= htmlspecialchars($info['nombre']) ?></td>
                                                        <td><?= htmlspecialchars(ucwords($info['unidad'])) ?></td>
                                                        <td>
                                                            <div class="d-flex align-items-center" style="gap: 10px; margin-bottom: 10px;">
                                                                <!-- Barra -->
                                                                <div class="progress flex-grow-1" style="height: 10px; right:5rem; width: 70px;">
                                                                    <div class="progress-bar  
                                                                        <?php if ($info['progreso'] < 50): ?>
                                                                        <?php elseif ($info['progreso'] < 80): ?>
                                                                        <?php else: ?>bg-success<?php endif; ?>"
                                                                        role="progressbar"
                                                                        style="width: <?= $info['progreso'] ?>%;"
                                                                        aria-valuenow="<?= $info['progreso'] ?>"
                                                                        aria-valuemin="0"
                                                                        aria-valuemax="100">
                                                                    </div>
                                                                </div>
                                                                <!-- Texto al lado -->
                                                                <span style="min-width: 50px; font-weight: bold;">
                                                                    <?= $info['progreso'] ?>%
                                                                </span>
                                                            </div>

                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>

                                    <!-- Modales -->
                                    <?php foreach ($data as $id_ruta => $info): ?>
                                        <!-- Modal principal de la ruta -->
                                        <div class="modal fade" id="modal<?= $id_ruta ?>" tabindex="-1" aria-hidden="true">
                                            <div class="modal-dialog modal-xl">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <div class="container-fluid">
                                                            <div class="row">
                                                                <!-- Columna izquierda -->
                                                                <div class="col-md-3">
                                                                    <h4><strong>Información de la ruta</strong></h4>
                                                                    <ul style="list-style: none; padding: 0; margin: 0;">
                                                                        <li style="display: flex; align-items: center; gap: 10px; font-size: 0.9rem; margin-bottom: 8px;">
                                                                            <i class="icon-base bx bx-car icon-lg" style="font-size: 1.5rem; color: #555;"></i>
                                                                            <div style="display: flex; flex-direction: column;">
                                                                                <strong><?= htmlspecialchars($info['nombre']) ?></strong>
                                                                                <span style="color: #888;"><?= htmlspecialchars(ucwords($info['unidad'])) ?></span>
                                                                            </div>
                                                                        </li>
                                                                        <div class="d-flex align-items-center" style="gap: 10px; margin-bottom: 10px;">
                                                                            <div class="progress flex-grow-1" style="height: 8px; width: 90px;">
                                                                                <div class="progress-bar  
                                                                                    <?php if ($info['progreso'] < 50): ?>
                                                                                    <?php elseif ($info['progreso'] < 80): ?>
                                                                                    <?php else: ?>bg-success<?php endif; ?>"
                                                                                    role="progressbar"
                                                                                    style="width: <?= $info['progreso'] ?>%;"
                                                                                    aria-valuenow="<?= $info['progreso'] ?>"
                                                                                    aria-valuemin="0"
                                                                                    aria-valuemax="100">
                                                                                </div>
                                                                            </div>
                                                                            <span style="min-width: 50px; font-weight: bold;">
                                                                                <?= $info['progreso'] ?>%
                                                                            </span>
                                                                        </div>
                                                                    </ul>

                                                                    <h5><strong>Pedidos</strong></h5>
                                                                    <ul style="max-height:400px; overflow-y:auto; list-style:none; margin:0; padding:0;">
                                                                        <?php foreach ($info['pedidos'] as $index => $pedido): ?>
                                                                            <?php
                                                                            switch ($pedido['status']) {
                                                                                case 'N':
                                                                                    $statusText = 'En Almacén';
                                                                                    $iconClass = 'bx bx-store';
                                                                                    $iconColor = '#828282ff';
                                                                                    break;
                                                                                case 'C':
                                                                                    $statusText = 'En Camino';
                                                                                    $iconClass = 'icon-base bx bxs-truck';
                                                                                    $iconColor = '#007bff';
                                                                                    break;
                                                                                case 'E':
                                                                                    $statusText = 'Entregado';
                                                                                    $iconClass = 'bx bx-check-circle';
                                                                                    $iconColor = 'green';
                                                                                    break;
                                                                                default:
                                                                                    $statusText = 'Desconocido';
                                                                                    $iconClass = 'bx bx-question-mark';
                                                                                    $iconColor = '#ff0000ff';
                                                                            }
                                                                            ?>
                                                                            <li style="margin-bottom:15px; font-size:0.85rem; padding:10px; border:1px solid #eee; border-radius:6px;">
                                                                                <div style="display:flex; align-items:center; gap:10px; cursor:pointer;"
                                                                                    onclick="togglePedidoDetailAnimated('pedidoDetail<?= $id_ruta ?>_<?= $index ?>')">
                                                                                    <i class="icon-base <?= $iconClass ?>" style="font-size:1.2rem; color:<?= $iconColor ?>;"></i>
                                                                                    <strong>#<?= htmlspecialchars($pedido['id']) ?></strong>
                                                                                </div>

                                                                                <div id="pedidoDetail<?= $id_ruta ?>_<?= $index ?>" class="pedido-detail"
                                                                                    style="max-height:0; overflow:hidden; margin-left:25px; color:#555; transition: max-height 0.4s ease;">
                                                                                    <p><strong>Dirección:</strong> <?= htmlspecialchars($pedido['direccion']) ?></p>
                                                                                    <p><strong>Estatus:</strong> <?= $statusText ?></p>
                                                                                    <p><strong>Recibido a las:</strong> <em>Pendiente</em></p>
                                                                                    <?php if ($pedido['status'] !== 'E'): ?>
                                                                                        <p>
                                                                                            <a href="javascript:void(0);"
                                                                                                onclick="focusMarker(<?= $id_ruta ?>, '<?= htmlspecialchars($pedido['direccion'], ENT_QUOTES) ?>')"
                                                                                                style="color:#007bff; text-decoration:underline;">Mostrar en el mapa</a>
                                                                                        </p>
                                                                                    <?php endif; ?>
                                                                                </div>
                                                                            </li>
                                                                        <?php endforeach; ?>
                                                                    </ul>

                                                                    <!-- Botón para abrir modal de detalles -->
                                                                    <button type="button" class="btn btn-primary w-100"
                                                                        onclick="abrirDetalle(<?= $id_ruta ?>)">
                                                                        Más Información
                                                                    </button>


                                                                </div>

                                                                <!-- Columna derecha (mapa) -->
                                                                <div class="col-md-9">
                                                                    <div id="map<?= $id_ruta ?>" style="height:550px; border-radius:10px;"></div>
                                                                    <div id="infoBox<?= $id_ruta ?>"
                                                                        style="position:absolute; top:10px; right:20px; background:rgba(255,255,255,0.9); 
                                                                          padding:10px; border-radius:8px; box-shadow:0 2px 6px rgba(0,0,0,0.2); z-index:1000;width:200px;height:200px;">
                                                                        <strong>Información del Repartidor</strong>
                                                                        <p id="infoText<?= $id_ruta ?>">Selecciona un pedido para ver detalles aquí</p>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                        </div>

                                        <!-- Modal de detalles de unidad y conductor -->
                                        <div class="modal fade" id="detalleUnidad<?= $id_ruta ?>" tabindex="-1" aria-hidden="true">
                                            <div class="modal-dialog modal-lg">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title">Detalles de la Unidad y Conductor</h5>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <div class="container-fluid">
                                                            <div class="row">
                                                                <!-- Columna Conductor -->
                                                                <div class="col-md-6">
                                                                    <h6><strong>Conductor</strong></h6>
                                                                    <img src="<?= htmlspecialchars($info['img_repartidor'] ?? 'placeholder_repartidor.png') ?>"
                                                                        alt="Conductor" class="img-fluid rounded mb-2" style="max-height:150px;">
                                                                    <p><strong>Nombre:</strong> <?= htmlspecialchars($info['nombre']) ?></p>
                                                                    <p><strong>Teléfono:</strong> <?= htmlspecialchars($info['telefono_conductor']) ?></p>
                                                                    <p><strong>Correo:</strong> <?= htmlspecialchars($info['correo']) ?></p>
                                                                </div>


                                                                <!-- Columna Unidad -->
                                                                <div class="col-md-6">
                                                                    <h6><strong>Unidad</strong></h6>
                                                                    <img src="<?= htmlspecialchars($info['img_unidad'] ?? 'placeholder_auto.png') ?>"
                                                                        alt="Unidad" class="img-fluid rounded mb-2" style="max-height:150px;">
                                                                    <p><strong>Marca:</strong> <?= htmlspecialchars($info['auto_marca'] ?? '-') ?></p>
                                                                    <p><strong>Modelo:</strong> <?= htmlspecialchars($info['auto_modelo'] ?? '-') ?></p>
                                                                    <p><strong>Color:</strong> <?= htmlspecialchars($info['auto_color'] ?? '-') ?></p>
                                                                    <p><strong>Placas:</strong> <?= htmlspecialchars($info['auto_placa'] ?? '-') ?></p>
                                                                    <p><strong>Año:</strong> <?= htmlspecialchars($info['auto_anio'] ?? '-') ?></p>
                                                                </div>
                                                            </div>

                                                            <!-- Botón para regresar al modal principal -->
                                                            <div class="row mt-3">
                                                                <div class="col-12 text-center">
                                                                    <button type="button" class="btn btn-secondary"
                                                                        onclick="regresarDatosGenerales(<?= $id_ruta ?>)">
                                                                        Regresar a Datos Generales
                                                                    </button>


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

                                    <?php endforeach; ?>

                                    <!-- Overlay -->
                                    <div class="layout-overlay layout-menu-toggle"></div>
                                </div>
                                <!-- / Layout wrapper -->

                                <script src="https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js"></script>
                                <script>
                                    new WOW().init();
                                </script>

                                <!-- Core JS -->
                                <!-- build:js assets/vendor/js/core.js -->
                                <script src="../assets/vendor/libs/jquery/jquery.js"></script>
                                <script src="../assets/vendor/libs/popper/popper.js"></script>
                                <script src="../assets/vendor/js/bootstrap.js"></script>
                                <script src="../assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.js"></script>

                                <script src="../assets/vendor/js/menu.js"></script>
                                <!-- endbuild -->

                                <!-- Vendors JS -->
                                <script src="../assets/vendor/libs/apex-charts/apexcharts.js"></script>

                                <!-- Main JS -->
                                <script src="../assets/js/main.js"></script>

                                <!-- Page JS -->
                                <script src="../assets/js/dashboards-analytics.js"></script>

                                <!-- Place this tag in your head or just before your close body tag. -->
                                <script async defer src="https://buttons.github.io/buttons.js"></script>

                                <div class="modal fade" id="modalBusqueda" tabindex="-1" aria-hidden="true">
                                    <div class="modal-dialog modal-xl modal-dialog-centered">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title">Buscar módulo</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                                            </div>
                                            <div class="modal-body">
                                                <div class="input-group mb-4">
                                                    <span class="input-group-text"><i class="bx bx-search"></i></span>
                                                    <input type="text" id="modalSearchInput" class="form-control" placeholder="Buscar módulo..." autocomplete="off">
                                                </div>

                                                <div class="row" id="modulosEstaticos">
                                                    <!-- Columna 1 -->
                                                    <div class="col-md-4 mb-4">
                                                        <!-- Inicio -->
                                                        <div class="mb-3">
                                                            <small class="text-uppercase text-muted fw-bold d-block mb-2">
                                                                <i class="bx bx-home me-1"></i> Inicio
                                                            </small>
                                                            <ul class="list-group list-group-flush">
                                                                <li class="list-group-item px-0 py-1">
                                                                    <a href="tablero.php"><i class="bx bx-home-smile me-2"></i> Panel principal</a>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                        <!-- Ventas -->
                                                        <div class="mb-3">
                                                            <small class="text-uppercase text-muted fw-bold d-block mb-2">
                                                                <i class="bx bx-money me-1"></i> Ventas
                                                            </small>
                                                            <ul class="list-group list-group-flush">
                                                                <li class="list-group-item px-0 py-1"><a href="facturas.php"><i class="bx bx-file me-2"></i> Facturas</a></li>
                                                            </ul>
                                                        </div>
                                                        <!-- Clientes -->
                                                        <div class="mb-3">
                                                            <small class="text-uppercase text-muted fw-bold d-block mb-2">
                                                                <i class="bx bx-user me-1"></i> Clientes
                                                            </small>
                                                            <ul class="list-group list-group-flush">
                                                                <li class="list-group-item px-0 py-1"><a href="clientes.php"><i class="bx bx-user-pin me-2"></i> Clientes</a></li>
                                                            </ul>
                                                        </div>
                                                    </div>

                                                    <!-- Columna 2 -->
                                                    <div class="col-md-4 mb-4">
                                                        <!-- Inventario -->
                                                        <div class="mb-3">
                                                            <small class="text-uppercase text-muted fw-bold d-block mb-2">
                                                                <i class="bx bx-package me-1"></i> Inventario
                                                            </small>
                                                            <ul class="list-group list-group-flush">
                                                                <li class="list-group-item px-0 py-1"><a href="productos.php"><i class="bx bx-cube me-2"></i> Productos</a></li>
                                                            </ul>
                                                        </div>
                                                        <!-- Compras -->
                                                        <div class="mb-3">
                                                            <small class="text-uppercase text-muted fw-bold d-block mb-2">
                                                                <i class="bx bx-cart me-1"></i> Compras
                                                            </small>
                                                            <ul class="list-group list-group-flush">
                                                                <li class="list-group-item px-0 py-1"><a href="compras.php"><i class="bx bx-purchase-tag me-2"></i> Compras</a></li>
                                                            </ul>
                                                        </div>
                                                    </div>

                                                    <!-- Columna 3 -->
                                                    <div class="col-md-4 mb-4">
                                                        <!-- Proveedores -->
                                                        <div class="mb-3">
                                                            <small class="text-uppercase text-muted fw-bold d-block mb-2">
                                                                <i class="bx bx-building me-1"></i> Proveedores
                                                            </small>
                                                            <ul class="list-group list-group-flush">
                                                                <li class="list-group-item px-0 py-1"><a href="proveedores.php"><i class="bx bx-user-voice me-2"></i> Proveedores</a></li>
                                                            </ul>
                                                        </div>
                                                        <!-- Cuentas -->
                                                        <div class="mb-3">
                                                            <small class="text-uppercase text-muted fw-bold d-block mb-2">
                                                                <i class="bx bx-wallet me-1"></i> Cuentas
                                                            </small>
                                                            <ul class="list-group list-group-flush">
                                                                <li class="list-group-item px-0 py-1"><a href="cuentas.php"><i class="bx bx-credit-card me-2"></i> Cuentas</a></li>
                                                            </ul>
                                                        </div>
                                                        <!-- Movimientos -->
                                                        <div class="mb-3">
                                                            <small class="text-uppercase text-muted fw-bold d-block mb-2">
                                                                <i class="bx bx-transfer me-1"></i> Movimientos
                                                            </small>
                                                            <ul class="list-group list-group-flush">
                                                                <li class="list-group-item px-0 py-1"><a href="movimientos.php"><i class="bx bx-transfer-alt me-2"></i> Movimientos</a></li>
                                                            </ul>
                                                        </div>
                                                    </div>
                                                </div>

                                                <!-- Resultados de búsqueda -->
                                                <ul id="modalSearchResults" class="list-group mb-3"></ul>

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

</body>

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.1/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
    $(document).ready(function() {
        $('#tablaCuentas').DataTable({
            paging: true,
            searching: true,
            ordering: false,
            search: {
                smart: false
            },
            language: {
                paginate: {
                    previous: '<i class="fas fa-chevron-left"></i>',
                    next: '<i class="fas fa-chevron-right"></i>'
                },
                url: "https://cdn.datatables.net/plug-ins/1.13.1/i18n/es-ES.json"
            },
        });
    });
</script>
<script>
    const rutas = <?= json_encode(array_column($data, 'coordenadas_rutas', 'id_ruta')) ?>;
    const ubicaciones = <?= json_encode(array_column($data, 'ubicaciones', 'id_ruta')) ?>;
    const pedidosJS = <?= json_encode(array_column($data, 'pedidos', 'id_ruta')) ?>;
    const almacenes = <?= json_encode(array_column($data, 'almacen', 'id_ruta')) ?>;
    const statRep = <?= json_encode(array_column($data, 'stat_rep', 'id_ruta')) ?>;

    // Iconos
    const carIcon = L.icon({
        iconUrl: "../img/fleet-car.png",
        iconSize: [26, 48],
        iconAnchor: [16, 16],
        popupAnchor: [0, -16]
    });

    const iconAlmacen = L.icon({
        iconUrl: "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-blue.png",
        shadowUrl: "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png",
        iconSize: [25, 41],
        iconAnchor: [12, 41],
        popupAnchor: [1, -34],
        shadowSize: [41, 41]
    });

    const iconPedido = L.icon({
        iconUrl: "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-red.png",
        shadowUrl: "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png",
        iconSize: [25, 41],
        iconAnchor: [12, 41],
        popupAnchor: [1, -34],
        shadowSize: [41, 41]
    });

    // Variables globales
    let mapas = {};
    let markers = {};

    // Inicialización de mapas por modal
    document.querySelectorAll('.modal').forEach(modal => {
        modal.addEventListener('shown.bs.modal', function() {
            const id = modal.id.replace('modal', '');
            const mapDiv = document.getElementById('map' + id);

            if (!mapDiv) return; // <-- Agregado para prevenir el error
            if (!mapDiv.dataset.init) {
                mapDiv.dataset.init = true;

                const coordsRuta = rutas[id] || [];
                const coordsUbic = ubicaciones[id] || [];
                const pedidosRuta = pedidosJS[id] || [];
                const almacen = almacenes[id] || null;

                if (coordsRuta.length === 0 && !almacen) return;

                const map = L.map(mapDiv).setView(
                    [coordsRuta[0]?.lat || almacen.lat, coordsRuta[0]?.lon || almacen.lon],
                    13
                );
                mapas[id] = map;
                markers[id] = [];

                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    maxZoom: 19
                }).addTo(map);

                // Marcador del almacén (solo si STAT_REP != 'A')
                if (almacen && almacen.lat && almacen.lon && statRep[id] !== 'A') {
                    L.marker([almacen.lat, almacen.lon], {
                            icon: iconAlmacen
                        })
                        .addTo(map)
                        .bindPopup("<b>Almacén</b>");
                }

                // Marcadores de pedidos (solo si no están entregados)
                coordsRuta.forEach((c, index) => {
                    if (pedidosRuta[index]?.status === 'E') return; // ❌ Saltar entregados

                    const marker = L.marker([c.lat, c.lon], {
                            icon: iconPedido
                        })
                        .addTo(map)
                        .bindPopup(`<b>${pedidosRuta[index]?.direccion || 'Ruta'}</b>`);

                    markers[id].push({
                        direccion: pedidosRuta[index]?.direccion,
                        marker
                    });
                });

                // Ajustar vista del mapa
                let allCoords = coordsRuta.concat(coordsUbic);
                if (almacen) allCoords.push({
                    lat: almacen.lat,
                    lon: almacen.lon
                });
                allCoords = allCoords.map(c => [c.lat, c.lon]);
                if (allCoords.length > 0) map.fitBounds(allCoords);
            }
        });
    });

    // Función para enfocar marcador
    function focusMarker(rutaId, direccion) {
        const markerData = markers[rutaId]?.find(m => m.direccion === direccion);
        if (markerData) {
            mapas[rutaId].setView(markerData.marker.getLatLng(), 16);
            markerData.marker.openPopup();
        }
    }

    // Función para actualizar infoBox
    function actualizarInfoBoxPorOrden(id) {
        const infoText = document.getElementById(`infoText${id}`);
        if (!infoText) return;

        const pedidosRuta = pedidosJS[id] || [];
        const estadoRepartidor = statRep[id] || '';

        if (estadoRepartidor === 'O') {
            infoText.innerText = "Se dirige al almacén";
            return;
        }

        if (estadoRepartidor === 'A') {
            const siguiente = pedidosRuta.find(p => p.status !== 'E');
            infoText.innerText = siguiente ?
                `Se dirige hacia ${siguiente.direccion}` :
                "Todos los pedidos han sido entregados";
        }
    }

    // Llamar a infoBox cuando se abre el modal
    document.querySelectorAll('.modal').forEach(modal => {
        modal.addEventListener('shown.bs.modal', function() {
            const id = modal.id.replace('modal', '');
            actualizarInfoBoxPorOrden(id);
        });
    });
</script>

<script>
    // Función para actualizar la ubicación de un solo repartidor
    function actualizarUbicacionRuta(id_ruta) {
        const trackerId = <?= json_encode(array_column($data, 'traker_id', 'id_ruta')) ?>[id_ruta];
        if (!trackerId) return;

        fetch('get_ubicaciones.php')
            .then(res => res.json())
            .then(data => {
                // Filtrar solo la ubicación del tracker de esta ruta
                const ubic = data.find(d => d.nombre === trackerId);
                if (!ubic) return;

                const mapa = mapas[id_ruta];
                if (!mapa) return;

                // Revisar si ya existe el marcador de vehículo
                let vehMarker = markers[id_ruta]?.find(m => m.direccion === trackerId);
                if (vehMarker) {
                    // Actualizar posición
                    vehMarker.marker.setLatLng([parseFloat(ubic.lat), parseFloat(ubic.lon)]);
                } else {
                    // Crear nuevo marcador si no existe
                    const newMarker = L.marker([parseFloat(ubic.lat), parseFloat(ubic.lon)], {
                            icon: carIcon
                        }).addTo(mapa)
                        .bindPopup(`Ubicación tiempo real: ${trackerId}`);

                    if (!markers[id_ruta]) markers[id_ruta] = [];
                    markers[id_ruta].push({
                        direccion: trackerId,
                        marker: newMarker
                    });
                }
            })
            .catch(err => console.error("Error al obtener ubicación:", err));
    }

    // Ejecutar actualización periódica solo para modales abiertos
    setInterval(() => {
        document.querySelectorAll('.modal.show').forEach(modal => {
            const id = modal.id.replace('modal', '');
            actualizarUbicacionRuta(id);
        });
    }, 1000);
</script>


<script>
    function togglePedidoDetail(id) {
        const el = document.getElementById(id);
        if (el.style.display === 'none' || el.style.display === '') {
            el.style.display = 'block';
        } else {
            el.style.display = 'none';
        }
    }
</script>

<!-- js para cambiear entre modales -->
<script>
    // Abrir modal de detalles
    function abrirDetalle(idRuta) {
        const modalPrincipalEl = document.getElementById('modal' + idRuta);
        const detalleModalEl = document.getElementById('detalleUnidad' + idRuta);

        const modalPrincipal = bootstrap.Modal.getOrCreateInstance(modalPrincipalEl);
        const detalleModal = bootstrap.Modal.getOrCreateInstance(detalleModalEl);

        // Escuchar cuando el modal principal se cierre
        modalPrincipalEl.addEventListener('hidden.bs.modal', function handler() {
            modalPrincipalEl.removeEventListener('hidden.bs.modal', handler);

            // Eliminar backdrop sobrante
            document.querySelectorAll('.modal-backdrop').forEach(b => b.remove());

            // Abrir modal de detalle
            detalleModal.show();
        }, {
            once: true
        });

        // Cerrar modal principal
        modalPrincipal.hide();
    }

    // Regresar al modal principal
    function regresarDatosGenerales(idRuta) {
        const detalleModalEl = document.getElementById('detalleUnidad' + idRuta);
        const modalPrincipalEl = document.getElementById('modal' + idRuta);

        const detalleModal = bootstrap.Modal.getOrCreateInstance(detalleModalEl);
        const modalPrincipal = bootstrap.Modal.getOrCreateInstance(modalPrincipalEl);

        detalleModalEl.addEventListener('hidden.bs.modal', function handler() {
            detalleModalEl.removeEventListener('hidden.bs.modal', handler);

            // Eliminar backdrop sobrante
            document.querySelectorAll('.modal-backdrop').forEach(b => b.remove());

            // Volver a abrir modal principal
            modalPrincipal.show();
        }, {
            once: true
        });

        // Cerrar modal de detalle
        detalleModal.hide();
    }
</script>

<script>
    function togglePedidoDetailAnimated(id) {
        const el = document.getElementById(id);
        if (el.style.maxHeight && el.style.maxHeight !== '0px') {
            // Cerrar
            el.style.maxHeight = '0';
        } else {
            // Abrir: calculamos la altura del contenido
            el.style.maxHeight = el.scrollHeight + "px";
        }
    }
</script>

<script>
    document.getElementById("modalSearchInput").addEventListener("input", function() {
        const query = this.value.trim();
        const results = document.getElementById("modalSearchResults");
        const modulos = document.getElementById("modulosEstaticos");

        results.innerHTML = "";

        if (query.length < 2) {
            // Mostrar módulos estáticos y ocultar resultados
            modulos.style.display = "flex"; // o "block" si prefieres
            results.style.display = "none";
            return;
        }

        // Ocultar módulos estáticos y mostrar resultados
        modulos.style.display = "none";
        results.style.display = "block";

        fetch("buscar_archivos.php?q=" + encodeURIComponent(query))
            .then(response => response.json())
            .then(data => {
                if (data.length === 0) {
                    results.innerHTML = `<li class="list-group-item text-muted">No se encontraron resultados</li>`;
                    return;
                }

                data.forEach(item => {
                    const li = document.createElement("li");
                    li.className = "list-group-item list-group-item-action";
                    li.innerHTML = `<i class="bx bx-link-alt me-2"></i> ${item.titulo}`;
                    li.addEventListener("click", () => {
                        window.location.href = item.archivo;
                    });
                    results.appendChild(li);
                });
            })
            .catch(error => {
                console.error("Error al buscar:", error);
            });
    });
</script>

</html>