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

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

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

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

  $usuario = $_SESSION['usuario'];

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

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

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

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

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

  $conn->close();
} catch (Exception $e) {
  echo "Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="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>Clientes</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">

  <!-- Bootstrap (si no lo tienes) -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

  <!-- Boxicons -->
  <link href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet">

  <!-- Select2 -->
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

  <!-- QuillJS (para el editor) -->
  <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">

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

    .submenu {
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.3s ease-out;
    }


    .app-email-view-content {
      padding-bottom: 0 !important;
    }

    .card.email-card-prev,
    .card.email-card-prev .card-body {
      margin-bottom: 0 !important;
      padding-bottom: 1rem !important;
      /* Ajusta a lo que quieras */
    }
  </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>

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

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

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

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

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

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

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

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


          <li class="menu-item active open">
            <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 active">
                <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>
              <li class="menu-item">
                <a href="clientespoliza.php" class="menu-link">
                  <div data-i18n="Basic">Clientes con Póliza</div>
                </a>
              </li>

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

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


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


          <li class="menu-item">
            <a href="#" class="menu-link menu-toggle">
              <i class="menu-icon tf-icons bx bx-shopping-bag"></i>
              <div data-i18n="Misc">Compras</div>
            </a>
            <ul class="menu-sub">
              <li class="menu-item">
                <a href="compras.php" class="menu-link">
                  <div data-i18n="Error">Compras</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="recepciones.php" class="menu-link">
                  <div data-i18n="Under Maintenance">Recepciones</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="ordenes.php" class="menu-link">
                  <div data-i18n="Under Maintenance">Ordenes</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="requisiciones.php" class="menu-link">
                  <div data-i18n="Under Maintenance">Requisiciones</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="devolucionescom.php" class="menu-link">
                  <div data-i18n="Under Maintenance">Devoluciones</div>
                </a>
              </li>
            </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">
            <a href="#" class="menu-link menu-toggle">
              <i class="menu-icon tf-icons bx bx-copy"></i>
              <div data-i18n="Extended UI">Cuentas y Pólizas</div>
            </a>
            <ul class="menu-sub">
              <li class="menu-item">
                <a href="cuentas.php" class="menu-link">
                  <div data-i18n="Perfect Scrollbar">Cuentas</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="polizas.php" class="menu-link">
                  <div data-i18n="Text Divider">Pólizas</div>
                </a>
              </li>
              <li class="menu-item ">
                <a href="activos.php" class="menu-link">
                  <div data-i18n="Text Divider">Activos</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="auxiliares.php" class="menu-link">
                  <div data-i18n="Text Divider">Auxiliares</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="presupuestos.php" class="menu-link">
                  <div data-i18n="Text Divider">Presupuestos</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="presupuestosPD.php" class="menu-link">
                  <div data-i18n="Text Divider">Presupuestos DP</div>
                </a>
              </li>
              <li class="menu-item ">
                <a href="monedas.php" class="menu-link">
                  <div data-i18n="Text Divider">Monedas</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="departamentos.php" class="menu-link">
                  <div data-i18n="Text Divider">Departamentos</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="otrosimpuestos.php" class="menu-link">
                  <div data-i18n="Text Divider">Otros Impuestos</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="activosgenerales.php" class="menu-link">
                  <div data-i18n="Text Divider">Activos Generales</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="saldos.php" class="menu-link">
                  <div data-i18n="Text Divider">Saldos</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="saldosDP.php" class="menu-link">
                  <div data-i18n="Text Divider">Saldos DP</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="rubros.php" class="menu-link">
                  <div data-i18n="Text Divider">Rubros</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="ccostos.php" class="menu-link">
                  <div data-i18n="Text Divider">Centro de Costos</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="concepto.php" class="menu-link">
                  <div data-i18n="Text Divider">Conceptos</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="regpol.php" class="menu-link">
                  <div data-i18n="Text Divider">Registro de Pólizas</div>
                </a>
              </li>
              <li class="menu-item">
                <a href="impuestos.php" class="menu-link">
                  <div data-i18n="Text Divider">Impuestos</div>
                </a>
              </li>
              <li class="menu-item ">
                <a href="timbres.php" class="menu-link">
                  <div data-i18n="Text Divider">Timbres</div>
                </a>
              </li>
            </ul>
          </li>

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

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

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

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

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

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

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

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

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

              </li>
            </ul>
          </li>
        </ul>
      </aside>
      <!-- / Menu -->

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

              .search-dropdown li {
                cursor: pointer;
              }

              .search-dropdown li:hover {
                background-color: #f0f0f0;
              }
            </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>Light
                      </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>Dark
                      </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>System
                      </span>
                    </button>
                  </li>

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


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

              </li>

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

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


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

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

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

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


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


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

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



            <div class="app-email card">
              <div class="row g-0">
                <!-- Email Sidebar -->
                <div class="col app-email-sidebar border-end flex-grow-0" id="app-email-sidebar">
                  <div class="btn-compost-wrapper d-grid">
                    <button class="btn btn-primary btn-compose" data-bs-toggle="modal" data-bs-target="#emailComposeSidebar" id="emailComposeSidebarLabel">Redactar</button>
                  </div>

                  <div class="email-filters pt-4 pb-2">
                    <div class="email-filters pt-2 pb-2 px-3">
                      <ul class="email-filter-folders list-unstyled">
                        <li class="active mb-3" data-target="inbox">
                          <a href="javascript:void(0);" id="btnInbox" class="d-flex align-items-center">
                            <i class="icon-base bx bx-envelope"></i>
                            <span class="ms-2">Bandeja</span>
                          </a>
                        </li>
                        <li class="mb-3" data-target="sent">
                          <a href="javascript:void(0);" class="d-flex align-items-center">
                            <i class="icon-base bx bx-send"></i>
                            <span class="ms-2">Enviado</span>
                          </a>
                        </li>
                        <li class="mb-3" data-target="archived">
                          <a href="javascript:void(0);" id="btnArchived" class="d-flex align-items-center">
                            <i class="icon-base bx bx-archive"></i>
                            <span class="ms-2">Archivados</span>
                          </a>
                        </li>
                        <li class="mb-3" data-target="starred">
                          <a href="javascript:void(0);" id="btnStarred" class="d-flex align-items-center">
                            <i class="icon-base bx bx-star"></i>
                            <span class="ms-2">Destacados</span>
                          </a>
                        </li>


                        <li class="mb-3" data-target="trash">
                          <a href="javascript:void(0);" id="btnTrash" class="d-flex align-items-center">
                            <i class="icon-base bx bx-trash"></i>
                            <span class="ms-2">papeleria</span>
                          </a>
                        </li>

                      </ul>
                    </div>
                  </div>
                </div>
                <!--/ Email Sidebar -->

                <!-- Emails List -->
                <div class="col app-emails-list">
                  <div class="card shadow-none border-0 rounded-0">
                    <div class="card-body emails-list-header p-3 py-2">
                      <!-- Email List: Search -->
                      <div class="d-flex justify-content-between align-items-center px-3 mt-2">
                        <div class="d-flex align-items-center w-100">
                          <i class="icon-base bx bx-menu icon-lg cursor-pointer d-block d-lg-none me-4 mb-4" data-bs-toggle="sidebar" data-target="#app-email-sidebar" data-overlay></i>
                          <div class="mb-4 w-100">
                            <div class="input-group input-group-merge shadow-none">
                              <span class="input-group-text border-0 p-0 pe-4" id="email-search">
                                <i class="icon-base bx bx-search icon-md text-body"></i>
                              </span>
                              <input type="text" class="form-control email-search-input border-0 py-0" placeholder="Search mail" aria-label="Search mail" aria-describedby="email-search" />
                            </div>
                          </div>
                        </div>
                      </div>
                      <hr class="mx-n3 emails-list-header-hr mb-2" />
                      <!-- Email List: Actions -->
                      <div class="d-flex justify-content-between align-items-center ps-1">
                        <div class="d-flex align-items-center">
                          <div class="form-check mb-0 ms-2">
                            <input class="form-check-input" type="checkbox" id="email-select-all" />
                            <label class="form-check-label" for="email-select-all"></label>
                          </div>
                          <div class="btn btn-icon me-1"><i class="icon-base bx bx-trash icon-md email-list-delete cursor-pointer"></i></div>
                          <div class="dropdown me-1">
                            <button class="btn btn-icon p-0" type="button" id="dropdownMenuFolderOne" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                              <i class="icon-base bx bx-label icon-md"></i>
                            </button>
                            <div class="dropdown-menu dropdown-menu-end" aria-labelledby="dropdownMenuFolderOne">
                              <a class="dropdown-item" href="javascript:void(0)">
                                <i class="icon-base bx bx-envelope"></i>
                                <span class="align-middle">bandeja</span>
                              </a>
                              <a class="dropdown-item" href="javascript:void(0)">
                                <i class="icon-base bx bx-folder icon-md"></i>
                                <span class="align-middle">archivado</span>
                              </a>
                              <a class="dropdown-item" href="javascript:void(0)">
                                <i class="icon-base bx bx-trash icon-sm me-1"></i>
                                <span class="align-middle">papeleria</span>
                              </a>
                            </div>
                          </div>

                        </div>
                        <div class="d-flex align-items-center">
                          <span class="btn btn-icon me-1">
                            <i class="icon-base bx bx-refresh icon-md scaleX-n1-rtl cursor-pointer email-refresh"></i>
                          </span>
                          <div class="dropdown">
                            <button class="btn btn-icon p-0" type="button" id="emailsActions" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                              <i class="icon-base bx bx-dots-vertical-rounded icon-md"></i>
                            </button>
                            <div class="dropdown-menu dropdown-menu-end" aria-labelledby="emailsActions">
                              <a class="dropdown-item" href="javascript:void(0)">Marca Como Leido</a>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <hr class="container-m-nx m-0" />
                    <!-- Email List: Items -->

                    <!-- Contenedor de listas -->
                    <div class="col app-emails-list">
                      <div class="card shadow-none border-0 rounded-0">

                        <!-- Bandeja: Entrada -->
                        <div class="email-list pt-0" id="emailListInbox">
                          <ul class="list-unstyled m-0" id="inboxList">



                          </ul>
                        </div>

                        <!-- Bandeja: Archivados -->
                        <div class="email-list pt-0 d-none" id="emailListArchived">
                          <ul class="list-unstyled m-0" id="archivedList">
                            <li class="text-muted text-center">Aquí aparecerán los archivados</li>
                          </ul>
                        </div>

                        <div class="email-list pt-0 d-none" id="emailListDestacado">
                          <ul class="list-unstyled m-0" id="starredList">
                            <li class="text-muted text-center">Aquí aparecerán los destacados</li>
                          </ul>
                        </div>

                        <div class="email-list pt-0 d-none" id="emailListTrash">
                          <ul class="list-unstyled m-0" id="trashList">
                            <li class="text-muted text-center" id="trashEmptyMsg">Aquí aparecerán los borrados</li>
                          </ul>
                        </div>

                      </div>

                    </div>
                    <div class="app-overlay"></div>
                  </div>
                  <!-- /Emails List -->


                  <!-- MODAL <!-- MODAL CORREGIDO -->
                  <div class="modal fade" id="emailComposeSidebar" tabindex="-1" aria-labelledby="emailComposeSidebarLabel" aria-hidden="true">
                    <div class="modal-dialog" style="position: fixed; bottom: 20px; right: 20px; width: 900px; max-width: 95%;">
                      <div class="modal-content shadow-lg">
                        <div class="modal-header py-2 px-3">
                          <h5 class="modal-title text-body fs-6">Redactar Correo</h5>
                          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                        </div>

                        <div class="modal-body p-3">
                          <form id="formEnviarCorreo" enctype="multipart/form-data">
                            <div class="row">

                              <!-- DE (remitente) -->
                              <div class="d-flex align-items-center mb-3">
                                <label for="correo" class="fw-medium text-body-secondary me-2" style="width: 50px;">De:</label>
                                <input type="email" id="correo-de" name="correo_de" class="form-control form-control-sm flex-grow-1" placeholder="ejemplo@gmail.com" required>
                              </div>

                              <!-- A (destinatario) con búsqueda -->
                              <div class="d-flex align-items-center mb-3">
                                <label for="email-to" class="fw-medium text-body-secondary me-2" style="width: 50px;">Para:</label>
                                <div class="input-group flex-grow-1">
                                  <input type="email" id="email-to" name="correo_para" class="form-control form-control-sm" placeholder="cliente@ejemplo.com" required>
                                  <button type="button" class="btn btn-outline-secondary btn-sm" id="btnBuscarCliente" data-bs-toggle="modal" data-bs-target="#modalBuscarCliente">
                                    <i class="bx bx-search"></i>
                                  </button>
                                </div>
                              </div>

                              <!-- Asunto -->
                              <div class="mb-3">
                                <label for="email-subject" class="fw-medium text-body-secondary mb-1 d-block">Asunto :</label>
                                <input id="email-subject" name="asunto" class="form-control" placeholder="Asunto del correo" required />
                              </div>

                              <!-- Mensaje -->
                              <div class="mb-3">
                                <label for="mensaje" class="fw-medium text-body-secondary mb-1 d-block">Mensaje:</label>
                                <textarea id="mensaje" name="mensaje" class="form-control" rows="6" placeholder="Escribe tu mensaje aquí..." required></textarea>
                              </div>

                              <!-- Botones de acción -->
                              <div class="d-flex justify-content-between align-items-center">
                                <button type="submit" class="btn btn-primary btn-sm">
                                  Enviar <i class="bx bx-paper-plane ms-1"></i>
                                </button>

                                <!-- Adjuntar archivo -->
                                <div class="d-flex gap-2 align-items-center">
                                  <label for="attach-file" class="btn btn-light btn-sm btn-icon mb-0" title="Adjuntar archivo">
                                    <i class="bx bx-paperclip"></i>
                                  </label>
                                  <input type="file" name="archivo" id="attach-file" class="d-none" />
                                  <span id="archivo-nombre" class="text-muted small"></span>
                                </div>
                              </div>

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

                </div>



                <!-- Modal Buscar Cliente -->
                <div class="modal fade" id="modalBuscarCliente" tabindex="-1" aria-labelledby="modalBuscarClienteLabel" aria-hidden="true">
                  <div class="modal-dialog modal-dialog-centered modal-lg">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title" id="modalBuscarClienteLabel">Buscar Cliente</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                      </div>
                      <div class="modal-body">
                        <input type="text" id="busquedaCliente" class="form-control mb-3" placeholder="Buscar por nombre o correo...">

                        <ul class="list-group" id="listaClientes">
                          <!-- Aquí se llenan dinámicamente los clientes encontrados -->
                        </ul>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- Modal para ver correo -->
                <div class="modal fade" id="emailDetailModal" tabindex="-1" aria-labelledby="emailDetailLabel" aria-hidden="true">
                  <div class="modal-dialog modal-dialog-scrollable custom-email-modal">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title" id="emailDetailLabel">Detalle del Correo</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                      </div>
                      <div class="modal-body" id="emailDetailBody">
                        <!-- Aquí se inyecta el contenido dinámico del correo -->
                      </div>
                    </div>
                  </div>
                </div>



                <!-- /Compose Email -->
                <!-- / Content -->
                <div class="content-backdrop fade"></div>
              </div>
              <!-- Content wrapper -->
            </div>

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

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


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

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

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

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

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

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




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

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

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

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

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

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

          <style>
            /* Ocultar resultados inicialmente */
            #modalSearchResults {
              display: none;
              max-height: 300px;
              overflow-y: auto;
            }
          </style>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<script src="https://code.jquery.com/jquery-3.5.1.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.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<!-- Bootstrap Bundle (incluye Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>



<!-- QuillJS -->
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>

<script>
  document.addEventListener('DOMContentLoaded', () => {
    const inboxList = document.getElementById('inboxList');
    const form = document.getElementById('formEnviarCorreo'); // ✅ Asegúrate que tu <form> tenga este ID
    const archivoNombre = document.getElementById('archivo-nombre');
    const inputArchivo = document.getElementById('attach-file');

    // Crear cada <li> con la info del correo
    function crearItemCorreo(correo) {
      const li = document.createElement('li');
      li.className = "email-list-item d-flex align-items-center";
      li.style.cursor = 'pointer';

      // Formatear fecha
      const fecha = new Date(correo.FECHA_ENVIO || new Date());
      const hora = fecha.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });

      li.innerHTML = `
        <div class="d-flex align-items-center w-100">
          <div class="form-check mb-0 ms-2">
            <input class="form-check-input email-list-item-input" type="checkbox" />
          </div>
          <span class="ms-sm-3 me-4 d-sm-inline-block d-none">
            <i class="email-list-item-bookmark icon-base bx bx-star icon-md cursor-pointer ms-1"></i>
          </span>
          <img src="../../assets/img/avatars/1.png" alt="user-avatar" class="rounded-circle me-sm-2 me-0" height="32" width="32" />
          <div class="email-list-item-content ms-2 ms-sm-0 me-2">
            <span class="email-list-item-username me-2 text-heading">${correo.REMITENTE}</span>
            <small class="email-list-item-subject">${correo.ASUNTO}</small>
          </div>
          <div class="email-list-item-meta ms-auto d-flex align-items-center">
            <small class="email-list-item-time text-body-secondary">${hora}</small>
            <ul class="list-inline email-list-item-actions">
              <li class="list-inline-item email-delete btn btn-icon">
                <i class="icon-base bx bx-trash icon-md"></i>
              </li>
            </ul>
          </div>
        </div>
      `;

      li.querySelector('.email-list-item-username').addEventListener('click', (e) => {
        e.stopPropagation();
        abrirModalCorreo(correo);
      });

      return li;
    }

    // Modal de detalle de correo
    function abrirModalCorreo(correo) {
      const fecha = new Date(correo.FECHA_ENVIO || new Date());
      const fechaStr = fecha.toLocaleDateString() + ', ' + fecha.toLocaleTimeString();

      const contenidoEmail = `
        <div class="header">
          <h2>Dahs S.A de C.V.</h2>
        </div>
        <div>
          <div class="card-header d-flex justify-content-between align-items-center flex-wrap border-bottom">
            <div class="d-flex align-items-center mb-sm-0 mb-3">
              <img src="../../assets/img/avatars/2.png" alt="user-avatar" class="flex-shrink-0 rounded-circle me-4" height="38" width="38" />
              <div class="flex-grow-1 ms-1">
                <h6 class="m-0 fw-normal">${correo.REMITENTE}</h6>
                <small class="text-body">${correo.REMITENTE}</small>
              </div>
            </div>
            <div class="d-flex align-items-center">
              <p class="mb-0 me-4 text-body-secondary">${fechaStr}</p>
            </div>
          </div>
          <div class="card-body">
            <p class="fw-medium">Asunto: ${correo.ASUNTO}</p>
            <p>${correo.MENSAJE}</p>
          </div>
        </div>
      `;

      document.getElementById('emailDetailBody').innerHTML = contenidoEmail;
      new bootstrap.Modal(document.getElementById('emailDetailModal')).show();
    }

    // ✅ Cargar correos desde PHP
    fetch('cargar_correos.php')
      .then(res => res.json())
      .then(data => {
        if (!data.success) {
          console.error('Error al cargar correos:', data.message);
          return;
        }
        inboxList.innerHTML = '';
        data.correos.forEach(correo => inboxList.appendChild(crearItemCorreo(correo)));
      })
      .catch(err => {
        console.error('Error al cargar correos:', err);
        inboxList.innerHTML = '<li class="text-danger text-center">Error al cargar correos</li>';
      });

    // ✅ Evento enviar correo
    form.addEventListener('submit', e => {
      e.preventDefault();

      const formData = new FormData(form);
      console.log("📤 Enviando correo...");

      fetch('enviar_correo.php', {
        method: 'POST',
        body: formData
      })
      .then(res => res.text())
      .then(text => {
        console.log("=== RESPUESTA RAW ===");
        console.log(text);
        console.log("=== FIN RESPUESTA ===");

        let data;
        try {
          data = JSON.parse(text);
        } catch (err) {
          console.error('❌ Error parseando JSON:', err);
          mostrarToast('Error en la respuesta del servidor', 'danger');
          return;
        }

        if (data.success) {
          mostrarToast('✅ Correo enviado correctamente', 'success');

          if (data.correo) {
            const nuevoCorreo = {
              REMITENTE: data.correo.remitente,
              ASUNTO: data.correo.asunto,
              MENSAJE: data.correo.mensaje,
              FECHA_ENVIO: new Date().toISOString()
            };
            inboxList.prepend(crearItemCorreo(nuevoCorreo));
          }

          form.reset();
          archivoNombre.textContent = '';

          const modalEl = document.getElementById('emailComposeSidebar');
          const modal = bootstrap.Modal.getInstance(modalEl);
          if (modal) modal.hide();

          setTimeout(() => {
            document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
            document.body.classList.remove('modal-open');
            document.body.style.paddingRight = '';
          }, 500);

        } else {
          mostrarToast('❌ Error al enviar: ' + (data.message || 'Sin detalles'), 'danger');
        }
      })
      .catch(error => {
        console.error('⚠️ Error en Fetch:', error);
        mostrarToast('Algo falló. Intenta de nuevo.', 'danger');
      });
    });

    // ✅ Mostrar nombre del archivo seleccionado
    inputArchivo.addEventListener('change', function() {
      const nombre = this.files[0]?.name || '';
      archivoNombre.textContent = nombre;
    });

    // ✅ Función para mostrar Toast (Bootstrap 5)
    function mostrarToast(mensaje, tipo = 'info') {
      const toastId = 'toast-' + Date.now();
      const toastHTML = `
        <div id="${toastId}" class="toast align-items-center text-bg-${tipo} border-0 position-fixed bottom-0 end-0 m-3" role="alert" aria-live="assertive" aria-atomic="true">
          <div class="d-flex">
            <div class="toast-body">${mensaje}</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
          </div>
        </div>
      `;
      document.body.insertAdjacentHTML('beforeend', toastHTML);
      const toastEl = document.getElementById(toastId);
      const toast = new bootstrap.Toast(toastEl);
      toast.show();
      setTimeout(() => toastEl.remove(), 4000);
    }
  });
</script>


<script>
  // Función para abrir modal con contenido estilizado
  function abrirModalCorreo(nombre, fecha, asunto, mensaje) {
    const fechaFormateada = new Date(fecha).toLocaleDateString('es-MX');

    const htmlContenido = `
      <div style="padding: 20px;">
        <div style="text-align: center; background-color: #9c0529; color: white; padding: 10px;">
          <h2>Dahs S.A de C.V.</h2>
        </div>
        <div style="margin: 20px 0;">
          <h2>Estimado(a) ${nombre},</h2>
          <p><strong>Fecha de correo:</strong> ${fechaFormateada}</p>
          <p><strong>Asunto:</strong> ${asunto}</p>
          <p><strong>Mensaje:</strong></p>
          <p>${mensaje}</p>
        </div>
        <div style="margin-top: 30px; font-size: 12px; color: #888; text-align: center;">
          <p>Este correo fue generado automáticamente. Por favor no responda a este mensaje.</p>
        </div>
      </div>
    `;

    document.getElementById('detailMessage').innerHTML = htmlContenido;

    const emailModal = new bootstrap.Modal(document.getElementById('emailDetailModal'));
    emailModal.show();
  }
</script>



<script>
  // Mostrar nombre del archivo adjunto cuando se seleccione
  document.getElementById('attach-file').addEventListener('change', function() {
    const nombreArchivo = this.files[0]?.name || '';
    document.getElementById('archivo-nombre').textContent = nombreArchivo;
  });
</script>


<script>
  document.addEventListener("DOMContentLoaded", function() {
    let bandejaActual = "emailListInbox"; // Valor inicial al cargar

    // Refresca la bandeja activa y limpia los checkboxes
    function refrescarBandejaActual() {
      // Limpiar todos los checkboxes
      document.querySelectorAll('.email-list-item-input, #email-select-all').forEach(chk => {
        chk.checked = false;
      });

      // Refrescar contenido de bandeja actual si aplica
      if (bandejaActual === "emailListDestacado") {
        refrescarDestacados();
      } else if (bandejaActual === "emailListTrash") {
        refrescarTrash();
      } else if (bandejaActual === "emailListArchived") {
        // refrescarArchivados(); // si tienes implementado esto
      }

      // Volver a mostrar la bandeja activa
      mostrarBandeja(bandejaActual);
    }

    // Función para cambiar de bandeja y actualizar el valor actual
    function mostrarBandeja(idMostrar) {
      document.querySelectorAll(".email-list").forEach(div => div.classList.add("d-none"));
      document.getElementById(idMostrar).classList.remove("d-none");

      document.querySelectorAll(".email-filter-folders li").forEach(el => el.classList.remove("active"));
      const target = idMostrar.replace("emailList", "").toLowerCase();
      const menuItem = document.querySelector(`.email-filter-folders li[data-target="${target}"]`);
      if (menuItem) menuItem.classList.add("active");

      bandejaActual = idMostrar;
      sincronizarEstrellas();
    }

    // Ícono de recarga (actualizar bandeja)
    document.querySelector(".email-refresh")?.addEventListener("click", () => {
      refrescarBandejaActual();
    });

    // Exportar función si se usa en otros scripts
    window.mostrarBandeja = mostrarBandeja;
  });
</script>

<script>
  //acciones
  document.addEventListener("DOMContentLoaded", function() {
    const inboxList = document.getElementById("inboxList");
    const archivedList = document.getElementById("archivedList");
    const trashList = document.getElementById("trashList");
    const trashEmptyMsg = document.getElementById("trashEmptyMsg");

    function refrescarTrash() {
      const items = trashList.querySelectorAll(".email-list-item");
      trashEmptyMsg.style.display = items.length === 0 ? "block" : "none";
    }

    function moverCorreosSeleccionados(origenList, destinoList) {
      const seleccionados = origenList.querySelectorAll('.email-list-item-input:checked');
      seleccionados.forEach(checkbox => {
        const item = checkbox.closest('.email-list-item');
        if (item && destinoList) {
          destinoList.appendChild(item);
          checkbox.checked = false;
        }
      });

      refrescarTrash();
    }

    // 🗑 Borrar correos seleccionados
    document.querySelector(".email-list-delete")?.addEventListener("click", () => {
      moverCorreosSeleccionados(document, trashList);

      document.querySelectorAll('.email-list-item').forEach(item => {
        if (item.querySelector('.email-list-item-input:checked')) {
          item.classList.add("bg-light", "text-muted");
          item.setAttribute("data-trashed", "true");
        }
      });
    });

    // 📂 Mover a bandeja
    document.querySelector('.dropdown-menu .bx-envelope')?.closest("a")?.addEventListener("click", () => {
      moverCorreosSeleccionados(document, inboxList);
    });

    // 📁 Mover a archivado
    document.querySelector('.dropdown-menu .bx-folder')?.closest("a")?.addEventListener("click", () => {
      moverCorreosSeleccionados(document, archivedList);

      document.querySelectorAll('.email-list-item').forEach(item => {
        if (item.querySelector('.email-list-item-input:checked')) {
          item.setAttribute("data-archived", "true");
          item.classList.add("opacity-75"); // opcional: estilo de archivado
        }
      });
    });

    // 🗑 Mover desde dropdown a papelería
    document.querySelector('.dropdown-menu .bx-trash')?.closest("a")?.addEventListener("click", () => {
      moverCorreosSeleccionados(document, trashList);

      document.querySelectorAll('.email-list-item').forEach(item => {
        if (item.querySelector('.email-list-item-input:checked')) {
          item.classList.add("bg-light", "text-muted");
          item.setAttribute("data-trashed", "true");
        }
      });

      refrescarTrash();
    });

  });
</script>



<script>
  //check
  document.addEventListener("DOMContentLoaded", function() {
    const selectAllCheckbox = document.getElementById("email-select-all");

    // Escuchar cambios en el checkbox "Seleccionar todos"
    selectAllCheckbox.addEventListener("change", function() {
      const checkboxes = document.querySelectorAll(".email-list-item-input");
      checkboxes.forEach(cb => cb.checked = selectAllCheckbox.checked);
    });
  });
</script>

<script>
  //papeleria
  document.addEventListener("DOMContentLoaded", function() {
    const trashList = document.getElementById("trashList");
    const trashEmptyMsg = document.getElementById("trashEmptyMsg");

    // Refrescar estado de bandeja de borrado
    function refrescarTrash() {
      const items = trashList.querySelectorAll(".email-list-item");
      trashEmptyMsg.style.display = items.length === 0 ? "block" : "none";
    }

    // Delegación para clic en ícono de borrar
    document.addEventListener("click", function(e) {
      const trashIcon = e.target.closest(".email-trash-icon");
      if (trashIcon) {
        const emailItem = trashIcon.closest(".email-list-item");
        if (!emailItem) return;

        // Marcar como eliminado y mover al contenedor de borrados
        emailItem.setAttribute("data-trashed", "true");
        emailItem.classList.add("bg-light", "text-muted");

        // Si no estás en la papelera, muévelo y ocúltalo de la vista actual
        if (!emailItem.closest("#emailListTrash")) {
          trashList.appendChild(emailItem);
        }

        refrescarTrash();
      }
    });

    // Iniciar refresco por si ya hay elementos
    refrescarTrash();
  });
</script>


<script>
  document.addEventListener("click", function(e) {
    const starIcon = e.target.closest(".email-list-item-bookmark");
    if (!starIcon) return;

    const emailItem = starIcon.closest(".email-list-item");
    if (!emailItem) return;

    const isStarred = emailItem.getAttribute("data-starred") === "true";

    if (isStarred) {
      emailItem.setAttribute("data-starred", "false");
      starIcon.classList.remove("text-warning");
      starIcon.classList.replace("bxs-star", "bx-star"); // opcional
    } else {
      emailItem.setAttribute("data-starred", "true");
      starIcon.classList.add("text-warning");
      starIcon.classList.replace("bx-star", "bxs-star"); // opcional
    }
  });
</script>



<script>
  //destacado
  document.addEventListener("DOMContentLoaded", function() {
    // Elementos
    const inboxList = document.getElementById("inboxList");
    const starredList = document.getElementById("starredList");
    const trashList = document.getElementById("trashList");
    const trashEmptyMsg = document.getElementById("trashEmptyMsg");

    // Mostrar una bandeja por ID
    function mostrarBandeja(idMostrar) {
      document.querySelectorAll(".email-list").forEach(div => div.classList.add("d-none"));
      document.getElementById(idMostrar).classList.remove("d-none");

      // Marcar el botón activo
      document.querySelectorAll(".email-filter-folders li").forEach(el => el.classList.remove("active"));
      const target = idMostrar.replace("emailList", "").toLowerCase();
      document.querySelector(`.email-filter-folders li[data-target="${target}"]`)?.classList.add("active");

      // Sincronizar estrellas visuales
      sincronizarEstrellas();
    }

    // Mostrar destacados
    function mostrarDestacados() {
      starredList.innerHTML = "";
      const destacados = document.querySelectorAll('#inboxList .email-list-item[data-starred="true"]');

      if (destacados.length === 0) {
        starredList.innerHTML = `<li class="text-muted text-center">No hay correos destacados ⭐</li>`;
      } else {
        destacados.forEach(item => {
          const clone = item.cloneNode(true);
          starredList.appendChild(clone);
        });
      }

      mostrarBandeja("emailListDestacado");
    }

    // Actualiza mensaje vacío en papelera
    function refrescarTrash() {
      const items = trashList.querySelectorAll(".email-list-item");
      trashEmptyMsg.style.display = items.length === 0 ? "block" : "none";
    }

    // Sincroniza estado visual del ícono de estrella
    function sincronizarEstrellas() {
      document.querySelectorAll(".email-list-item").forEach(item => {
        const icon = item.querySelector(".email-list-item-bookmark");
        if (!icon) return;

        const isStarred = item.getAttribute("data-starred") === "true";

        if (isStarred) {
          icon.classList.add("text-warning");
          icon.classList.replace("bx-star", "bxs-star");
        } else {
          icon.classList.remove("text-warning");
          icon.classList.replace("bxs-star", "bx-star");
        }
      });
    }

    // Eventos de menú lateral
    document.getElementById("btnInbox")?.addEventListener("click", () => mostrarBandeja("emailListInbox"));
    document.getElementById("btnStarred")?.addEventListener("click", mostrarDestacados);
    document.getElementById("btnTrash")?.addEventListener("click", () => {
      refrescarTrash();
      mostrarBandeja("emailListTrash");
    });

    // Delegación global de clics para estrella y borrar
    document.addEventListener("click", function(e) {
      const starIcon = e.target.closest(".email-list-item-bookmark");
      if (starIcon) {
        const emailItem = starIcon.closest(".email-list-item");
        if (!emailItem) return;

        const isStarred = emailItem.getAttribute("data-starred") === "true";

        if (isStarred) {
          emailItem.setAttribute("data-starred", "false");
        } else {
          emailItem.setAttribute("data-starred", "true");
        }

        sincronizarEstrellas();
        return;
      }

      const deleteBtn = e.target.closest(".email-delete");
      if (deleteBtn) {
        const emailItem = deleteBtn.closest(".email-list-item");
        if (!emailItem) return;

        trashList.appendChild(emailItem);
        emailItem.classList.add("bg-light", "text-muted");
        refrescarTrash();
        sincronizarEstrellas();
      }
    });

    // Iniciar en bandeja
    mostrarBandeja("emailListInbox");
  });
</script>

<script>
  document.addEventListener("DOMContentLoaded", function() {
    // Contenedores de listas
    const inboxList = document.getElementById("inboxList");
    const archivedList = document.getElementById("archivedList");
    const starredList = document.getElementById("starredList");
    const trashList = document.getElementById("trashList");
    const trashEmptyMsg = document.getElementById("trashEmptyMsg");

    // Mostrar una bandeja
    function mostrarBandeja(idMostrar) {
      document.querySelectorAll(".email-list").forEach(div => div.classList.add("d-none"));
      document.getElementById(idMostrar).classList.remove("d-none");

      // Menú activo
      document.querySelectorAll(".email-filter-folders li").forEach(el => el.classList.remove("active"));
      const target = idMostrar.replace("emailList", "").toLowerCase();
      const menuItem = document.querySelector(`.email-filter-folders li[data-target="${target}"]`);
      if (menuItem) menuItem.classList.add("active");

      sincronizarEstrellas();
    }

    // Refrescar bandeja de destacados
    function refrescarDestacados() {
      starredList.innerHTML = "";
      const destacados = inboxList.querySelectorAll('.email-list-item[data-starred="true"]');
      if (destacados.length === 0) {
        starredList.innerHTML = `<li class="text-muted text-center">No hay correos destacados ⭐</li>`;
      } else {
        destacados.forEach((item, idx) => {
          const clone = item.cloneNode(true);
          clone.setAttribute("data-original-index", idx); // Referencia al original
          starredList.appendChild(clone);
        });
      }
      sincronizarEstrellas();
    }

    // Refrescar papelera
    function refrescarTrash() {
      const items = trashList.querySelectorAll(".email-list-item");
      trashEmptyMsg.style.display = items.length === 0 ? "block" : "none";
    }

    // Sincroniza íconos de estrella
    function sincronizarEstrellas() {
      document.querySelectorAll(".email-list-item").forEach(item => {
        const icon = item.querySelector(".email-list-item-bookmark");
        if (!icon) return;

        const isStarred = item.getAttribute("data-starred") === "true";

        icon.classList.remove("bxs-star", "bx-star", "text-warning");
        if (isStarred) {
          icon.classList.add("bxs-star", "text-warning");
        } else {
          icon.classList.add("bx-star");
        }
      });
    }

    // Navegación entre bandejas
    document.getElementById("btnInbox")?.addEventListener("click", () => mostrarBandeja("emailListInbox"));
    document.getElementById("btnArchived")?.addEventListener("click", () => mostrarBandeja("emailListArchived"));
    document.getElementById("btnStarred")?.addEventListener("click", () => {
      refrescarDestacados();
      mostrarBandeja("emailListDestacado");
    });
    document.getElementById("btnTrash")?.addEventListener("click", () => {
      refrescarTrash();
      mostrarBandeja("emailListTrash");
    });

    // Eliminar correo (mover a papelera)
    document.addEventListener("click", e => {
      const deleteBtn = e.target.closest(".email-delete");
      if (deleteBtn) {
        const emailItem = deleteBtn.closest(".email-list-item");
        if (!emailItem) return;

        trashList.appendChild(emailItem);
        emailItem.classList.add("bg-light", "text-muted");
        refrescarTrash();
        sincronizarEstrellas();
      }
    });

    // Toggle estrella
    document.addEventListener("click", e => {
      const starIcon = e.target.closest(".email-list-item-bookmark");
      if (starIcon) {
        const emailItem = starIcon.closest(".email-list-item");
        if (!emailItem) return;

        const isStarred = emailItem.getAttribute("data-starred") === "true";

        if (isStarred) {
          emailItem.setAttribute("data-starred", "false");
          starIcon.classList.remove("text-warning", "bxs-star");
          starIcon.classList.add("bx-star");
        } else {
          emailItem.setAttribute("data-starred", "true");
          starIcon.classList.add("text-warning", "bxs-star");
          starIcon.classList.remove("bx-star");
        }

        // 🔁 Si estamos en la vista de destacados, sincronizar original
        const originalIndex = emailItem.getAttribute("data-original-index");
        if (originalIndex !== null) {
          const original = inboxList.querySelectorAll('.email-list-item')[originalIndex];
          if (original) {
            original.setAttribute("data-starred", emailItem.getAttribute("data-starred"));
          }

          // Si se desmarcó desde destacados, actualizar vista
          if (emailItem.getAttribute("data-starred") === "false") {
            refrescarDestacados();
          }
        }
      }
    });

    // Mostrar inbox al iniciar
    mostrarBandeja("emailListInbox");
  });
</script>


<!-- MODALES -->
<script>
  let clientes = [];

  // Cargar clientes al abrir la modal de búsqueda
  document.getElementById('modalBuscarCliente')
    .addEventListener('shown.bs.modal', function() {
      const filtro = document.getElementById('busquedaCliente').value;
      if (clientes.length === 0) {
        fetch('obtener_correos.php')
          .then(r => r.json())
          .then(data => {
            clientes = data;
            mostrarClientes(filtro);
          })
          .catch(e => console.error('Error al obtener clientes:', e));
      } else {
        mostrarClientes(filtro);
      }
    });

  // Filtrar al escribir
  document.getElementById('busquedaCliente')
    .addEventListener('input', function() {
      mostrarClientes(this.value);
    });

  function mostrarClientes(filtro) {
    const lista = document.getElementById('listaClientes');
    lista.innerHTML = '';
    const encontrados = clientes.filter(c =>
      c.nombre.toLowerCase().includes(filtro.toLowerCase()) ||
      c.correo.toLowerCase().includes(filtro.toLowerCase())
    );
    if (!encontrados.length) {
      lista.innerHTML = '<li class="list-group-item text-muted">No se encontraron resultados</li>';
      return;
    }
    encontrados.forEach(cliente => {
      const li = document.createElement('li');
      li.className = 'list-group-item list-group-item-action';
      li.textContent = `${cliente.nombre} <${cliente.correo}>`;
      li.style.cursor = 'pointer';
      li.onclick = () => seleccionarCliente(cliente.correo);
      lista.appendChild(li);
    });
  }

  function seleccionarCliente(correo) {
    // 1) Poner email en el input
    const input = document.getElementById('email-to');
    input.value = correo;
    input.focus();

    // 2) Cerrar modal de búsqueda
    const modalBuscarEl = document.getElementById('modalBuscarCliente');
    const modalBuscar = bootstrap.Modal.getInstance(modalBuscarEl);
    modalBuscar.hide();

    // 3) Al cerrarse completamente, reabrir la modal de redacción
    modalBuscarEl.addEventListener('hidden.bs.modal', function handler() {
      modalBuscarEl.removeEventListener('hidden.bs.modal', handler);
      const modalRedaccionEl = document.getElementById('emailComposeSidebar');
      const modalRedaccion = new bootstrap.Modal(modalRedaccionEl);
      modalRedaccion.show();
    });
  }
</script>



</html>