<?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'];


        function obtenerIniciales($nombreCompleto)
        {
            $partes = explode(' ', $nombreCompleto);
            $iniciales = '';

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


        $inicialesUsuario = obtenerIniciales($nombre);
    } else {
        $nombre = "Usuario";
        $rol = "Usuario";
        $inicialesUsuario = "US";
    }

    $conn->close();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="es" class="layout-navbar-fixed layout-compact layout-menu-fixed" dir="ltr" data-theme="theme-default" data-assets-path="../assets/" data-template="vertical-menu-template">

<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>Cuentas</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://stackpath.bootstrapcdn.com/bootstrap/4.5.2/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" />



    <!-- 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;
        }

        .badge-dia {
            display: inline-block;
            min-width: 17ch;
            /* ajusta según lo más largo que haya */
            text-align: center;
            white-space: nowrap;
            font-size: 1rem;
            padding: 0.5rem 1rem;
        }

        #expBtn {
            display: inline-flex;
            /* Ícono, texto y flecha en línea */
            align-items: center;
            /* Alinea verticalmente */
            gap: 0.5rem;
            /* Espacio entre ícono y texto */
        }

        #expBtn.dropdown-toggle::after {
            margin-left: 0.5rem;
            /* Separa la flecha del texto */
            vertical-align: middle;
            /* Centra verticalmente la flecha */
        }
    </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">

                    <!-- 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>

                        </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>
                            <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="cuentasxcobrar.php" class="menu-link">
                                    <div data-i18n="Basic">Cuentas X Cobrar</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 active">
                                <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>

                </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>
                        <style>
                            /* 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;
                            }
                        </style>

                        <!-- /Search -->

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



                            <!-- icono de idioma  -->
                            <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>


                            <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 ps--active-y">
                                        <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 -->


                <?php
                $host = 'localhost';
                $database = 'C:\Program Files (x86)\Common Files\Aspel\Sistemas Aspel\COI10.00\Ejemplos\EJEMPLOS.FDB';
                $username = 'SYSDBA';
                $password = 'masterkey';

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

                    // Buscar tablas CUENTASXX
                    $sqlTablas = "SELECT TRIM(RDB\$RELATION_NAME) AS TABLE_NAME
                  FROM RDB\$RELATIONS
                  WHERE RDB\$SYSTEM_FLAG = 0
                    AND RDB\$VIEW_BLR IS NULL
                    AND RDB\$RELATION_NAME LIKE '%CUENTAS%'";
                    $stmtTablas = $dbh->query($sqlTablas);
                    $tablas = $stmtTablas->fetchAll(PDO::FETCH_ASSOC);
                } catch (PDOException $e) {
                    echo "<div class='container mt-5'><h2>AUN NO HAY CONEXION:</h2>";
                    echo "<p>" . $e->getMessage() . "</p></div>";
                    exit;
                }
                ?>


                <!-- Content wrapper -->
                <div class="content-wrapper">
                    <!-- Content -->
                    <div class="container-xxl flex-grow-1 container-p-y">
                        <!-- <div class="row">
                            <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>
                                                        <h4 class="mb-1" id="total-registros"></h4>
                                                    </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>Facturas Emitidas</small>
                                                        <h4 class="mb-1" id="facturas-emitidas"></h4>
                                                    </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>Facturas Canceladas</small>
                                                        <h4 class="mb-1" id="facturas-canceladas"></h4>
                                                    </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>
                        </div> -->



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

                            <!-- Encabezado  -->
                            <div class="card-datatable text-nowrap">
                                <div class="dt-container dt-bootstrap5 dt-empty-footer">
                                    <div class="row card-header flex-column flex-md-row pb-0">
                                        <div class="d-md-flex justify-content-between align-items-center dt-layout-start col-md-auto me-auto mt-0">
                                            <h5 class="card-title mb-0 text-md-start text-center">Cuentas</h5>
                                        </div>
                                        <div class="d-md-flex justify-content-between align-items-center dt-layout-end col-md-auto ms-auto mt-0">
                                            <div class="dt-buttons btn-group flex-wrap mb-0">

                                                <div class="btn-group">
                                                    <button id="expBtn" type="button" class="btn btn-label-primary dropdown-toggle  " data-bs-toggle="dropdown" aria-expanded="false">
                                                        <span>
                                                            <span class="d-flex align-items-center gap-2">
                                                                <i class="icon-base bx bx-export me-sm-1"></i>
                                                                <span class="d-none d-sm-inline-block">Exportar</span>
                                                            </span>
                                                        </span>
                                                    </button>
                                                    <ul class="dropdown-menu">
                                                        <li><a id="printOption" class="dropdown-item" href="javascript:void(0);">
                                                                <span>
                                                                    <span class="d-flex align-items-center">
                                                                        <i class="icon-base bx bx-printer me-1"></i>Imprimir
                                                                    </span>
                                                                </span>
                                                            </a></li>
                                                        <li><a class="dropdown-item" href="javascript:void(0);">
                                                                <span>
                                                                    <span class="d-flex align-items-center">
                                                                        <i class="icon-base bx bx-file me-1"></i>Csv
                                                                    </span>
                                                                </span>
                                                            </a></li>
                                                        <li><a id="excelOption" class="dropdown-item" href="javascript:void(0);">
                                                                <span>
                                                                    <span class="d-flex align-items-center">
                                                                        <i class="icon-base bx bxs-file-export me-1"></i>Excel
                                                                    </span>
                                                                </span>
                                                            </a></li>
                                                        <li><a id="pdfOption" class="dropdown-item" href="javascript:void(0);">
                                                                <span>
                                                                    <span class="d-flex align-items-center">
                                                                        <i class="icon-base bx bxs-file-pdf me-1"></i>Pdf
                                                                    </span>
                                                                </span>
                                                            </a></li>
                                                        <li><a id="copyOption" class="dropdown-item" href="javascript:void(0);">
                                                                <span>
                                                                    <i class="icon-base bx bx-copy me-1"></i>Copiar
                                                                </span>
                                                            </a>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row m-3 my-0 justify-content-between">
                                        <div class="d-md-flex justify-content-between align-items-center dt-layout-start col-md-auto me-auto mt-0">
                                            <div class="mt-4">
                                                <div class="btn-group" role="group" aria-label="Basic example">

                                                </div>
                                            </div>
                                        </div>
                                        <div class="d-md-flex justify-content-between align-items-center dt-layout-end col-md-auto ms-auto mt-0">
                                            <div class="demo-inline-spacing">
                                                <button type="button" class="btn btn-label-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                                                    <?= $tablaSeleccionada ? htmlspecialchars($tablaSeleccionada, ENT_QUOTES, 'UTF-8') : 'Periodo' ?>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <?php foreach ($tablas as $t): ?>
                                                        <li>
                                                            <a class="dropdown-item <?= ($t['TABLE_NAME'] === $tablaSeleccionada) ? 'active' : '' ?>"
                                                                href="?tabla=<?= htmlspecialchars($t['TABLE_NAME'], ENT_QUOTES, 'UTF-8') ?>&cargar=1">
                                                                <?= htmlspecialchars($t['TABLE_NAME'], ENT_QUOTES, 'UTF-8') ?>
                                                            </a>
                                                        </li>
                                                    <?php endforeach; ?>
                                                </ul>


                                                <button id="clearFilters" type="button" class="btn btn-primary custom-action">
                                                    <span class="icon-base bx bx-trash icon-sm me-2"></span>Borrar Filtros
                                                </button>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="justify-content-between dt-layout-table">
                                        <div class="d-md-flex justify-content-between align-items-center col-12 dt-layout-full col-md">

                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- /Fin Encabezado -->

                            <!-- conexion tabla -->
                            <?php
                            $datos = [];
                            $tablaSeleccionada = '';

                            if (isset($_GET['cargar']) && !empty($_GET['tabla'])) {
                                $tablaSeleccionada = preg_replace('/[^A-Z0-9_]/i', '', $_GET['tabla']);
                            } else {
                                if (!empty($tablas)) {
                                    $tablaSeleccionada = trim($tablas[0]['TABLE_NAME']);
                                }
                            }

                            if (!empty($tablaSeleccionada)) {
                                $available = array_map('trim', array_column($tablas, 'TABLE_NAME'));
                                if (!in_array($tablaSeleccionada, $available)) {
                                    $tablaSeleccionada = !empty($available) ? $available[0] : $tablaSeleccionada;
                                }

                                $periodo = preg_replace('/[^0-9]/', '', $tablaSeleccionada);
                                $tablaSaldos = "SALDOS" . $periodo;

                                try {
                                    $sql = "SELECT c.NUM_CTA, c.NOMBRE, s.INICIAL, c.TIPO
                FROM $tablaSeleccionada c
                LEFT JOIN $tablaSaldos s ON c.NUM_CTA = s.NUM_CTA
                ORDER BY c.NUM_CTA";
                                    $stmt = $dbh->query($sql);
                                    $stmt->execute();
                                    $datos = $stmt->fetchAll(PDO::FETCH_ASSOC);

                                    // Agrupar por nivel y padre
                                    $nodes = [];
                                    $levels = [];
                                    foreach ($datos as $r) {
                                        $num = trim($r['NUM_CTA']);
                                        $nivel = intval(substr($num, -1));
                                        if ($nivel < 1) $nivel = 1;

                                        $nodes[$num] = [
                                            'NUM_CTA' => $num,
                                            'NOMBRE'  => $r['NOMBRE'],
                                            'INICIAL' => $r['INICIAL'],
                                            'TIPO'    => $r['TIPO'],  
                                            'NIVEL'   => $nivel,
                                            'PADRE'   => null
                                        ];
                                        $levels[$nivel][] = $num;
                                    }

                                    function common_prefix_len($a, $b)
                                    {
                                        $len = min(strlen($a), strlen($b));
                                        $i = 0;
                                        for (; $i < $len; $i++) {
                                            if ($a[$i] !== $b[$i]) break;
                                        }
                                        return $i;
                                    }

                                    if (!empty($levels)) {
                                        $maxLevel = max(array_keys($levels));
                                        for ($lvl = 2; $lvl <= $maxLevel; $lvl++) {
                                            if (!isset($levels[$lvl])) continue;
                                            if (!isset($levels[$lvl - 1])) continue;
                                            foreach ($levels[$lvl] as $childNum) {
                                                $bestParent = null;
                                                $bestLen = -1;
                                                foreach ($levels[$lvl - 1] as $candNum) {
                                                    $cpl = common_prefix_len($childNum, $candNum);
                                                    if ($cpl > $bestLen) {
                                                        $bestLen = $cpl;
                                                        $bestParent = $candNum;
                                                    }
                                                }
                                                if ($bestParent !== null) {
                                                    $nodes[$childNum]['PADRE'] = $bestParent;
                                                }
                                            }
                                        }
                                    }

                                    // Mapear hijos
                                    $children = [];
                                    foreach ($nodes as $num => $nd) {
                                        if (!empty($nd['PADRE'])) {
                                            $children[$nd['PADRE']][] = $num;
                                        }
                                    }

                                    echo "<div class='container mt-5'>";
                                    echo "<div class='table-container'>";
                                    echo "<table id='clientesTable' class='table table-hover table-responsive text-nowrap'>";
                                    echo "<thead class='thead-dark'><tr>
                <th>Cuenta</th>
                <th>Nombre</th>
                <th>Saldo Inicial</th>
                <th>Tipo</th>
              </tr></thead><tbody>";

                                    $renderNode = function ($num, $nodes, $children, $level = 1) use (&$renderNode) {
                                        $nd = $nodes[$num];
                                        $hasChildren = isset($children[$num]) && count($children[$num]) > 0;
                                        $icon = $hasChildren ? "<i class='fas fa-chevron-right toggle-detalles' style='cursor:pointer; margin-right:8px;'></i>"
                                            : "<span style='display:inline-block;width:16px;margin-right:8px;'></span>";

                                        $hiddenClass = ($nd['NIVEL'] == 1) ? "principal-row" : "subcuenta-row d-none";
                                        echo "<tr class='{$hiddenClass}' data-id='" . htmlspecialchars($nd['NUM_CTA'], ENT_QUOTES) . "' data-nivel='" . intval($nd['NIVEL']) . "'";
                                        if (!empty($nd['PADRE'])) {
                                            echo " data-parent='" . htmlspecialchars($nd['PADRE'], ENT_QUOTES) . "'";
                                        }
                                        echo ">";

                                        echo "<td>" . $icon . htmlspecialchars($nd['NUM_CTA']) . "</td>";
                                        echo "<td>" . htmlspecialchars($nd['NOMBRE']) . "</td>";
                                        echo "<td>" . number_format(floatval($nd['INICIAL']), 2, '.', ',') . "</td>";

                                        $tipo = ($nd['TIPO'] === 'A') ? 'Acreditada' : (($nd['TIPO'] === 'D') ? 'Deudora' : '---');
                                        echo "<td>" . htmlspecialchars($tipo) . "</td>";

                                        echo "</tr>";

                                        if ($hasChildren) {
                                            foreach ($children[$num] as $childNum) {
                                                $renderNode($childNum, $nodes, $children, $nodes[$childNum]['NIVEL']);
                                            }
                                        }
                                    };

                                    if (isset($levels[1])) {
                                        foreach ($levels[1] as $topNum) {
                                            if (isset($nodes[$topNum])) {
                                                $renderNode($topNum, $nodes, $children, 1);
                                            }
                                        }
                                    }

                                    echo "</tbody></table>";
                                    echo "</div></div>";
                                } catch (PDOException $e) {
                                    echo "<div class='container mt-5'><h2>Error en consulta:</h2>";
                                    echo "<p>" . $e->getMessage() . "</p></div>";
                                }
                            }
                            ?>

                            <!-- /fin tabla -->
                        </div>
                    </div>
                    <!-- Content wrapper -->
                </div>
            </div>
        </div>
        <!-- / Layout wrapper -->
    </div>


    <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="close" data-dismiss="modal" aria-label="Cerrar">
                        <span aria-hidden="true">&times;</span>
                    </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>

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

</body>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.21/i18n/Spanish.json"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.25/sorting/natural.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.13/jspdf.plugin.autotable.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.3.0/exceljs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/countup.js/2.0.8/countUp.min.js"></script>

<!-- Script para orden numérico con coma + inicialización de DataTable -->
<script>
    $(document).ready(function() {
        // 1) Orden personalizado para números con coma
        $.fn.dataTable.ext.type.order['numeric-comma-asc'] = function(data) {
            return parseFloat(data.replace(/[^0-9.-]/g, '')) || 0;
        };
        $.fn.dataTable.ext.type.order['numeric-comma-desc'] = function(data) {
            return -parseFloat(data.replace(/[^0-9.-]/g, '')) || 0;
        };

        // 2) Asegúrate de destruir instancia previa si existe
        if ($.fn.DataTable.isDataTable('#clientesTable')) {
            $('#clientesTable').DataTable().destroy();
        }

        // 3) Construir mapa de hijos a partir de las TR.subcuenta-row
        var childrenMap = {};
        $('#clientesTable tbody tr.subcuenta-row').each(function() {
            var $tr = $(this);
            var parent = $tr.data('parent') + '';
            var id = $tr.data('id') + '';
            var nivel = $tr.data('nivel') || '';
            var tds = $tr.children('td');
            var cuenta = tds.eq(0).text().trim();
            var nombre = tds.eq(1).text().trim();
            var saldo = tds.eq(2).text().trim();
            var tipo  = tds.eq(3).text().trim();  // 👈 Capturamos la columna TIPO

            if (!childrenMap[parent]) childrenMap[parent] = [];
            childrenMap[parent].push({
                id: id,
                cuenta: cuenta,
                nombre: nombre,
                saldo: saldo,
                tipo: tipo,   // 👈 Guardamos el tipo
                nivel: nivel
            });
        });

        // 4) Eliminar las filas de subcuentas del DOM
        $('#clientesTable tbody tr.subcuenta-row').remove();

        // 5) Inicializar DataTable sobre las filas principales
        var table = $('#clientesTable').DataTable({
            language: {
                url: '../json/Spanish.json'
            },
            pageLength: 10,
            lengthMenu: [
                [10, 25, 50, -1],
                [10, 25, 50, "Todos"]
            ],
            columnDefs: [{
                targets: 2,
                type: 'numeric-comma'
            }],
            order: [
                [2, 'asc']
            ]
        });

        // 6) Función para construir tabla hija
        function buildChildrenHtml(parentId) {
            var children = childrenMap[parentId];
            if (!children || children.length === 0) return '';

            var html = "<table class='table table-hover table-responsive text-nowrap'><tbody>";
            children.forEach(function(c) {
                var hasGrand = !!childrenMap[c.id];
                var iconHtml = hasGrand ?
                    "<i class='fas fa-chevron-right child-toggle' style='cursor:pointer; margin-right:8px;'></i>" :
                    "<span style='display:inline-block;width:16px;margin-right:8px;'></span>";

                html += "<tr class='child-row' data-id='" + c.id + "' data-parent='" + parentId + "' data-nivel='" + c.nivel + "'>";
                html += "<td>" + iconHtml + $("<div>").text(c.cuenta).html() + "</td>";
                html += "<td>" + $("<div>").text(c.nombre).html() + "</td>";
                html += "<td>" + $("<div>").text(c.saldo).html() + "</td>";
                html += "<td>" + $("<div>").text(c.tipo).html() + "</td>";  // 👈 Mostramos el tipo
                html += "</tr>";

                if (hasGrand) {
                    html += "<tr class='grandchildren-container d-none' data-parent-container='" + c.id + "'>";
                    html += "<td colspan='4'></td>";  // 👈 Ajustado a 4 columnas
                    html += "</tr>";
                }
            });
            html += "</tbody></table>";
            return html;
        }

        // 7) Toggle en filas principales
        $(document).on('click', 'i.fas.fa-chevron-right.toggle-detalles, i.fas.fa-chevron-down.toggle-detalles', function(e) {
            e.stopPropagation();
            var $icon = $(this);
            var $tr = $icon.closest('tr');
            var parentId = $tr.data('id') + '';
            var row = table.row($tr);

            if (row.child.isShown()) {
                row.child.hide();
                $icon.removeClass('fa-chevron-down').addClass('fa-chevron-right');
            } else {
                var childHtml = buildChildrenHtml(parentId);
                row.child("<div>" + childHtml + "</div>").show();
                $icon.removeClass('fa-chevron-right').addClass('fa-chevron-down');
            }
        });

        // 8) Toggle en subcuentas con nietos
        $(document).on('click', '#clientesTable .child-toggle', function(e) {
            e.stopPropagation();
            var $icon = $(this);
            var $childRow = $icon.closest('tr');
            var childId = $childRow.data('id') + '';

            var $gcRow = $childRow.nextAll("tr.grandchildren-container[data-parent-container='" + childId + "']").first();
            if (!$gcRow.length) return;

            if ($gcRow.hasClass('d-none')) {
                var grandHtml = buildChildrenHtml(childId);
                $gcRow.find('td').first().html(grandHtml);
                $gcRow.removeClass('d-none').hide().slideDown(150);
                $icon.removeClass('fa-chevron-right').addClass('fa-chevron-down');
            } else {
                $gcRow.slideUp(150, function() {
                    $gcRow.addClass('d-none');
                    $gcRow.find('td').first().empty();
                });
                $icon.removeClass('fa-chevron-down').addClass('fa-chevron-right');
            }
        });

        // 9) Click en fila principal = toggle
        $(document).on('click', '#clientesTable tbody tr.principal-row', function(e) {
            var $tr = $(this);
            var $icon = $tr.find('i.toggle-detalles').first();
            if ($icon.length) $icon.trigger('click');
        });

    });
</script>




<!-- Script: Limpiar filtros -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('clearFilters').addEventListener('click', function() {
            // Quitar clase 'active' de botones de filtros
            document.querySelectorAll('.custom-filter').forEach(btn => btn.classList.remove('active'));

            const dateFilter = document.querySelector('.custom-date-filter');
            if (dateFilter) dateFilter.classList.remove('active');

            document.querySelectorAll('input[type="text"], input[type="date"], select').forEach(input => {
                input.value = '';
            });

            // Reiniciar DataTable sin filtros personalizados
            $.fn.dataTable.ext.search = [];
            $('#clientesTable').DataTable().search('').columns().search('').draw();

            // Recargar tarjetas sin filtros (valores generales)
            fetch('get_card_data.php')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('total-registros').textContent = data.totalRegistros || '0';
                    document.getElementById('facturas-emitidas').textContent = data.totalEmitidas || '0';
                    document.getElementById('facturas-canceladas').textContent = data.totalCanceladas || '0';
                })
                .catch(error => console.error('Error al actualizar tarjetas después de limpiar filtros:', error));
        });
    });
</script>






<script>
    $(document).ready(function() {
        $('body').css('overflow', 'auto');
    });
</script>


<!-- SCRIPT PARA BOTON "EXPORTAR" -->
<script>
    document.getElementById("exportBtn").addEventListener("click", function() {
        var menu = document.getElementById("exportMenu");
        menu.style.display = menu.style.display === "block" ? "none" : "block";
    });
    window.onclick = function(event) {
        if (!event.target.matches('.export-button')) {
            var dropdowns = document.getElementsByClassName("export-menu");
            for (var i = 0; i < dropdowns.length; i++) {
                var openDropdown = dropdowns[i];
                if (openDropdown.style.display === "block") {
                    openDropdown.style.display = "none";
                }
            }
        }
    };
</script>

<!-- SCRIPT PARA  "IMPRIMIR" -->
<script>
    $('#printOption').click(function() {
        const nombreEmpresa = 'Empresa Inválida S.A. de C.V.';
        const logoSrc = 'img/siigo-aspel.svg';
        const printWindow = window.open('', '', 'height=600,width=800');

        // Clonar el encabezado de la tabla principal
        const tableHeader = document.querySelector('#clientesTable thead').cloneNode(true);

        // Buscar la columna "Acción" y eliminarla tanto del encabezado como de las filas
        const actionIndex = Array.from(tableHeader.querySelectorAll('th')).findIndex(th => th.innerText.trim() === 'Acción');
        if (actionIndex >= 0) {
            tableHeader.querySelectorAll('th')[actionIndex].remove();
        }

        const addPageHeader = () => {
            return `
                <div class="page-header" style="text-align: center; page-break-before: always;">
                    <img src="${logoSrc}" alt="Logo" class="logo" style="max-width: 280px; margin-bottom: 18px;">
                    <h1 style="font-size: 24px; font-weight: bold; margin-top: 40px;">${nombreEmpresa}</h1>
                    <h2 style="font-size: 20px; font-weight: normal; margin-bottom: 20px;">Facturas</h2>
                </div>
                
            `;
        };

        // Crear el contenido HTML para la impresión
        let printContent = '<html><head><title>Imprimir</title>';
        printContent += '<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">';
        printContent += '<style>';
        printContent += 'body { text-align: center; margin: 20px; }';
        printContent += 'h1 { font-size: 24px; font-weight: bold; margin-top: 40px; }';
        printContent += 'h2 { font-size: 20px; font-weight: normal; margin-bottom: 20px; }';
        printContent += 'img.logo { max-width: 280px; margin-bottom: 18px; }';
        printContent += 'table { width: 100%; border-collapse: collapse; }';
        printContent += 'th, td { padding: 8px; text-align: left; border: none; }';
        printContent += 'th { background-color: #f8f9fa; }';
        printContent += '.col-partida { width: 10%; }';
        printContent += '.col-cantidad { width: 10%; }';
        printContent += '.col-clave { width: 15%; }';
        printContent += '.col-precio { width: 15%; }';
        printContent += '.col-subtotal { width: 15%; }';
        printContent += '.col-observaciones { width: 25%; word-wrap: break-word; }';
        printContent += '.page-header { page-break-before: always; }';
        printContent += '</style>';
        printContent += '</head><body>';

        // Generar el contenido para cada fila expandida o todas las filas si no hay filas expandidas
        const expandedRows = $('#clientesTable tbody').find('i.toggle-detalles.down').closest('tr');

        if (expandedRows.length > 0) {
            expandedRows.each(function() {
                // Añadir encabezado antes de cada partida expandida para asegurarlo en cada página
                printContent += addPageHeader();

                // Generar la tabla con la fila expandida
                printContent += '<table class="table table-hover">';
                printContent += '<thead>' + tableHeader.innerHTML + '</thead><tbody>';

                // Clonar y eliminar la columna "Acción"
                const expandedRow = $(this).clone()[0];
                expandedRow.querySelectorAll('td')[actionIndex]?.remove();
                printContent += '<tr>' + expandedRow.innerHTML + '</tr>';

                // Clonar y añadir la fila de detalles
                const detalleRow = $(this).next('tr').clone()[0];
                if (detalleRow) {
                    detalleRow.querySelectorAll('td')[actionIndex]?.remove();
                    printContent += '<tr>' + detalleRow.innerHTML + '</tr>';
                }

                printContent += '</tbody></table>';
            });
        } else {
            // Si no hay filas expandidas, imprimimos todas las partidas con encabezado en la primera página
            printContent += addPageHeader();
            printContent += '<table class="table table-hover">';
            printContent += '<thead>' + tableHeader.innerHTML + '</thead><tbody>';

            $('#clientesTable tbody tr').each(function() {
                const row = $(this).clone()[0];
                row.querySelectorAll('td')[actionIndex]?.remove();
                printContent += '<tr>' + row.innerHTML + '</tr>';
            });

            printContent += '</tbody></table>';
        }

        printContent += '</body></html>';

        // Escribir el contenido en la ventana de impresión
        printWindow.document.write(printContent);
        printWindow.document.close();
        printWindow.focus();
        printWindow.print();
    });
</script>


<!-- SCRIPT PARA EXCEL -->
<script>
    $(document).ready(function() {
        $('#excelOption').click(async function() {
            const workbook = new ExcelJS.Workbook();
            const worksheet = workbook.addWorksheet('Facturas');
            const nombreEmpresa = 'Empresa Inválida S.A. de C.V.';

            // Encabezados para la parte superior
            const headersDocumento = ['Tipo', 'Clave', 'Cliente', 'Nombre', 'Estatus', 'Fecha', 'Total'];
            const headersPartida = ['Partida', 'Cantidad', 'Clave', 'Prec. Unit', 'Subtotal', 'Observaciones'];

            // Buscar todas las filas que están expandidas
            let expandedRows = $('#clientesTable tbody').find('i.toggle-detalles.down').closest('tr');

            // Si no hay filas expandidas, selecciona todas las filas de la tabla
            if (expandedRows.length === 0) {
                expandedRows = $('#clientesTable tbody tr');
            }

            // Agregar el nombre de la empresa y título
            worksheet.mergeCells('A1:G1');
            worksheet.getCell('A1').value = nombreEmpresa;
            worksheet.getCell('A1').font = {
                bold: true,
                size: 14
            };
            worksheet.getCell('A1').alignment = {
                horizontal: 'center'
            };

            worksheet.mergeCells('A2:G2');
            worksheet.getCell('A2').value = 'Detalle de Facturas';
            worksheet.getCell('A2').font = {
                bold: true,
                size: 12
            };
            worksheet.getCell('A2').alignment = {
                horizontal: 'center'
            };

            expandedRows.each(function(index, row) {
                // Obtener los datos generales del documento
                const datosDocumento = Array.from($(row).find('td')).slice(0, 7).map(td => $(td).text().trim());

                // Añadir encabezados de documento
                const headerRowDoc = worksheet.addRow(headersDocumento);
                headerRowDoc.font = {
                    bold: true
                };
                headerRowDoc.eachCell((cell) => {
                    cell.fill = {
                        type: 'pattern',
                        pattern: 'solid',
                        fgColor: {
                            argb: '009DFF'
                        }
                    };
                    cell.font = {
                        color: {
                            argb: 'FFFFFF'
                        },
                        bold: true
                    };
                    cell.alignment = {
                        horizontal: 'center'
                    };
                });

                // Añadir datos generales del documento
                worksheet.addRow(datosDocumento);

                // Obtener los detalles de la partida
                const detallesPartidaRow = $(row).next();
                const detallesPartida = [];

                // Recopilar los datos de las partidas
                detallesPartidaRow.find('tr').each(function() {
                    const fila = [];
                    $(this).find('td').each(function() {
                        fila.push($(this).text().trim());
                    });
                    detallesPartida.push(fila);
                });

                // Añadir encabezados de la partida
                if (detallesPartida.length > 0) {
                    const partidaHeaderRow = worksheet.addRow(headersPartida);
                    partidaHeaderRow.font = {
                        bold: true
                    };
                    partidaHeaderRow.eachCell((cell) => {
                        cell.fill = {
                            type: 'pattern',
                            pattern: 'solid',
                            fgColor: {
                                argb: '007ecc'
                            }
                        };
                        cell.font = {
                            color: {
                                argb: 'FFFFFF'
                            },
                            bold: true
                        };
                        cell.alignment = {
                            horizontal: 'center'
                        };
                    });

                    // Añadir datos de cada partida inmediatamente después de los encabezados
                    detallesPartida.forEach(partidaData => {
                        if (partidaData.some(data => data !== "")) { // Evitar filas completamente vacías
                            worksheet.addRow(partidaData);
                        }
                    });
                }
            });

            // Ajustar el ancho para las columnas de encabezados de las partidas
            headersPartida.forEach((header, index) => {
                const colIndex = index + 1; // Ajusta a partir de la columna 1 para las partidas
                worksheet.getColumn(colIndex).width = header.length + 2; // +2 para un poco de espacio adicional
            });

            // Descargar el archivo de Excel
            const buffer = await workbook.xlsx.writeBuffer();
            const blob = new Blob([buffer], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            });
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = 'facturas.xlsx';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });
    });
</script>

<!-- SCRIPT PARA PDF -->
<script>
    $(document).ready(function() {
        $('#pdfOption').click(async function() {
            const {
                jsPDF
            } = window.jspdf;
            const doc = new jsPDF();
            const nombreEmpresa = 'Empresa Inválida S.A. de C.V.';

            // Ruta del logo SVG
            const svgPath = 'img/siigo-aspel.svg';

            // Función para cargar y convertir el SVG a base64 en formato PNG
            async function convertSvgToBase64(url) {
                return new Promise((resolve) => {
                    fetch(url)
                        .then(response => response.text())
                        .then(svgText => {
                            const svg = new Blob([svgText], {
                                type: 'image/svg+xml;charset=utf-8'
                            });
                            const DOMURL = window.URL || window.webkitURL || window;
                            const url = DOMURL.createObjectURL(svg);
                            const img = new Image();
                            img.onload = function() {
                                const canvas = document.createElement('canvas');
                                canvas.width = img.width;
                                canvas.height = img.height;
                                const ctx = canvas.getContext('2d');
                                ctx.drawImage(img, 0, 0);
                                DOMURL.revokeObjectURL(url);
                                resolve(canvas.toDataURL('image/png'));
                            };
                            img.src = url;
                        });
                });
            }

            // Convertir el SVG a base64
            const logoBase64 = await convertSvgToBase64(svgPath);

            // Encabezados para la parte superior
            const headersDocumento = ['Tipo', 'Clave', 'Cliente', 'Nombre', 'Estatus', 'Fecha', 'Total'];
            // Encabezados para los detalles de la partida
            const headersPartida = ['Partida', 'Cantidad', 'Clave', 'Prec. Unit', 'Subtotal', 'Observaciones'];

            // Buscar todas las filas que están expandidas
            let expandedRows = $('#clientesTable tbody').find('i.toggle-detalles.down').closest('tr');

            if (expandedRows.length === 0) {
                // Si no hay partidas seleccionadas, exportar toda la tabla en un formato general
                const headers = Array.from($('#clientesTable thead th')).map(th => $(th).text().trim()).filter(h => h !== 'Acción');
                const rows = Array.from($('#clientesTable tbody tr')).map(row =>
                    Array.from($(row).find('td')).map(td => $(td).text().trim())
                );

                // Insertar el logo en la parte superior
                doc.addImage(logoBase64, 'PNG', 15, 10, 30, 18); // Tamaño más pequeño

                // Título de la empresa y encabezados generales
                doc.setFontSize(12); // Tamaño de fuente reducido
                doc.text(nombreEmpresa, 105, 20, {
                    align: 'center'
                });
                doc.setFontSize(10); // Tamaño de fuente reducido
                doc.text('Resumen de Facturas', 105, 30, {
                    align: 'center'
                });

                // Tabla general
                doc.autoTable({
                    startY: 40,
                    head: [headers],
                    body: rows,
                    headStyles: {
                        fillColor: '#009DFF',
                        textColor: '#FFFFFF',
                        halign: 'center'
                    },
                    bodyStyles: {
                        halign: 'center'
                    },
                    styles: {
                        fontSize: 8,
                        cellPadding: 2
                    }, // Tamaño de fuente y padding reducidos
                    theme: 'striped'
                });
            } else {
                // Si hay partidas seleccionadas, usar el diseño de partidas detalladas
                expandedRows.each(function(index, row) {
                    if (index > 0) {
                        doc.addPage(); // Crear nueva página para cada partida expandida
                    }

                    // Obtener los datos generales del documento de esa partida
                    const datosDocumento = Array.from($(row).find('td')).slice(0, 7).map(td => $(td).text().trim());

                    // Obtener los detalles de la partida expandida (asumiendo que están en la fila siguiente)
                    const detallesPartidaRow = $(row).next();
                    const detallesPartida = [];

                    // Construir la fila de detalles de la partida en un formato adecuado
                    detallesPartidaRow.find('tr').each(function() {
                        const fila = [];
                        $(this).find('td').each(function() {
                            fila.push($(this).text().trim());
                        });
                        detallesPartida.push(fila); // Añadir cada fila como un array separado en `detallesPartida`
                    });

                    // Insertar el logo en la parte superior
                    doc.addImage(logoBase64, 'PNG', 15, 10, 30, 18); // Tamaño más pequeño

                    // Título de la empresa y encabezados generales
                    doc.setFontSize(12); // Tamaño de fuente reducido
                    doc.text(nombreEmpresa, 105, 20, {
                        align: 'center'
                    });
                    doc.setFontSize(10); // Tamaño de fuente reducido
                    doc.text('Detalle de Facturas', 105, 30, {
                        align: 'center'
                    });

                    // Tabla de datos generales del documento
                    doc.autoTable({
                        startY: 40,
                        head: [headersDocumento],
                        body: [datosDocumento],
                        headStyles: {
                            fillColor: '#009DFF',
                            textColor: '#FFFFFF',
                            halign: 'center'
                        },
                        bodyStyles: {
                            halign: 'center'
                        },
                        styles: {
                            fontSize: 8,
                            cellPadding: 2
                        }, // Tamaño de fuente y padding reducidos
                        theme: 'plain'
                    });

                    // Espacio entre tablas
                    const tableY = doc.lastAutoTable.finalY + 5; // Espacio reducido

                    // Tabla de detalles de la partida
                    doc.autoTable({
                        startY: tableY,
                        head: [headersPartida],
                        body: detallesPartida,
                        headStyles: {
                            fillColor: '#009DFF',
                            textColor: '#FFFFFF',
                            halign: 'center'
                        },
                        bodyStyles: {
                            halign: 'center'
                        },
                        styles: {
                            fontSize: 8,
                            cellPadding: 2
                        }, // Tamaño de fuente y padding reducidos
                        theme: 'plain',
                    });
                });
            }

            // Descargar el PDF
            doc.save('facturas.pdf');
        });
    });
</script>
<script>
    $(document).ready(function() {
        $('#copyOption').click(function() {
            let textToCopy = "";
            const table = document.getElementById('clientesTable');

            // Obtener los encabezados de la tabla (solo una vez)
            const headerCells = table.querySelectorAll('thead th');
            const headers = Array.from(headerCells).slice(0, -1).map(cell => cell.innerText).join("\t");
            textToCopy = headers + "\n"; // Agregar encabezados al inicio solo una vez

            // Recorrer todas las filas del tbody, asegurando que no se dupliquen
            $('#clientesTable tbody tr').each(function() {
                const row = $(this);
                const cells = row.find('td, th');

                // Verificar si la fila es de detalle (expandida)
                if (row.hasClass('detalle')) {
                    // Solo copiar si la fila de detalle está visible
                    if (row.css('display') !== 'none') {
                        // Copiar los datos de la fila de detalle
                        const detailText = Array.from(cells).map(cell => cell.innerText).join("\t");
                        textToCopy += detailText + "\n"; // Agregar detalle al texto
                    }
                } else {
                    // Si es una fila principal (partida), copiarla
                    const rowText = Array.from(cells).slice(0, -1).map(cell => cell.innerText).join("\t");
                    textToCopy += rowText + "\n"; // Agregar la fila principal al texto
                }
            });

            // Copiar el texto al portapapeles
            navigator.clipboard.writeText(textToCopy).then(() => {
                $('#copyAlert').fadeIn().css('display', 'flex');
                setTimeout(function() {
                    $('#copyAlert').fadeOut();
                }, 3000);
            }).catch(err => {
                console.error('Error al copiar: ', err);
            });
        });
    });
</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>