<!DOCTYPE html>
<html lang="en" class="light-style layout-menu-fixed" dir="ltr" data-theme="theme-default" data-assets-path="../assets/" data-template="vertical-menu-template-free">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
    <title>Facturas</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">
    <link rel="stylesheet" href="../css/estilos.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>
</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
                                width="25"
                                viewBox="0 0 25 42"
                                version="1.1"
                                xmlns="http://www.w3.org/2000/svg"
                                xmlns:xlink="http://www.w3.org/1999/xlink">
                                <defs>
                                    <path
                                        d="M13.7918663,0.358365126 L3.39788168,7.44174259 C0.566865006,9.69408886 -0.379795268,12.4788597 0.557900856,15.7960551 C0.68998853,16.2305145 1.09562888,17.7872135 3.12357076,19.2293357 C3.8146334,19.7207684 5.32369333,20.3834223 7.65075054,21.2172976 L7.59773219,21.2525164 L2.63468769,24.5493413 C0.445452254,26.3002124 0.0884951797,28.5083815 1.56381646,31.1738486 C2.83770406,32.8170431 5.20850219,33.2640127 7.09180128,32.5391577 C8.347334,32.0559211 11.4559176,30.0011079 16.4175519,26.3747182 C18.0338572,24.4997857 18.6973423,22.4544883 18.4080071,20.2388261 C17.963753,17.5346866 16.1776345,15.5799961 13.0496516,14.3747546 L10.9194936,13.4715819 L18.6192054,7.984237 L13.7918663,0.358365126 Z"
                                        id="path-1"></path>
                                    <path
                                        d="M5.47320593,6.00457225 C4.05321814,8.216144 4.36334763,10.0722806 6.40359441,11.5729822 C8.61520715,12.571656 10.0999176,13.2171421 10.8577257,13.5094407 L15.5088241,14.433041 L18.6192054,7.984237 C15.5364148,3.11535317 13.9273018,0.573395879 13.7918663,0.358365126 C13.5790555,0.511491653 10.8061687,2.3935607 5.47320593,6.00457225 Z"
                                        id="path-3"></path>
                                    <path
                                        d="M7.50063644,21.2294429 L12.3234468,23.3159332 C14.1688022,24.7579751 14.397098,26.4880487 13.008334,28.506154 C11.6195701,30.5242593 10.3099883,31.790241 9.07958868,32.3040991 C5.78142938,33.4346997 4.13234973,34 4.13234973,34 C4.13234973,34 2.75489982,33.0538207 2.37032616e-14,31.1614621 C-0.55822714,27.8186216 -0.55822714,26.0572515 -4.05231404e-15,25.8773518 C0.83734071,25.6075023 2.77988457,22.8248993 3.3049379,22.52991 C3.65497346,22.3332504 5.05353963,21.8997614 7.50063644,21.2294429 Z"
                                        id="path-4"></path>
                                    <path
                                        d="M20.6,7.13333333 L25.6,13.8 C26.2627417,14.6836556 26.0836556,15.9372583 25.2,16.6 C24.8538077,16.8596443 24.4327404,17 24,17 L14,17 C12.8954305,17 12,16.1045695 12,15 C12,14.5672596 12.1403557,14.1461923 12.4,13.8 L17.4,7.13333333 C18.0627417,6.24967773 19.3163444,6.07059163 20.2,6.73333333 C20.3516113,6.84704183 20.4862915,6.981722 20.6,7.13333333 Z"
                                        id="path-5"></path>
                                </defs>
                                <g id="g-app-brand" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                    <g id="Brand-Logo" transform="translate(-27.000000, -15.000000)">
                                        <g id="Icon" transform="translate(27.000000, 15.000000)">
                                            <g id="Mask" transform="translate(0.000000, 8.000000)">
                                                <mask id="mask-2" fill="white">
                                                    <use xlink:href="#path-1"></use>
                                                </mask>
                                                <use fill="#696cff" xlink:href="#path-1"></use>
                                                <g id="Path-3" mask="url(#mask-2)">
                                                    <use fill="#696cff" xlink:href="#path-3"></use>
                                                    <use fill-opacity="0.2" fill="#FFFFFF" xlink:href="#path-3"></use>
                                                </g>
                                                <g id="Path-4" mask="url(#mask-2)">
                                                    <use fill="#696cff" xlink:href="#path-4"></use>
                                                    <use fill-opacity="0.2" fill="#FFFFFF" xlink:href="#path-4"></use>
                                                </g>
                                            </g>
                                            <g
                                                id="Triangle"
                                                transform="translate(19.000000, 11.000000) rotate(-300.000000) translate(-19.000000, -11.000000) ">
                                                <use fill="#696cff" xlink:href="#path-5"></use>
                                                <use fill-opacity="0.2" fill="#FFFFFF" xlink:href="#path-5"></use>
                                            </g>
                                        </g>
                                    </g>
                                </g>
                            </svg>
                        </span>
                        <span class="app-brand-text demo menu-text fw-bolder ms-2">Sneat</span>
                    </a>

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

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

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

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

                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="tablero.php" class="menu-link">
                                    <div data-i18n="Without menu">Tablero</div>
                                </a>
                            </li>

                        </ul>
                    </li>

                    <li class="menu-header small text-uppercase">
                        <span class="menu-header-text">Aspel SAE</span>
                    </li>
                    <li class="menu-item active open">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-dock-top"></i>
                            <div data-i18n="Account Settings">Ventas</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item active">
                                <a href="facturas.php" class="menu-link">
                                    <div data-i18n="Account">Facturas</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="facturasxcobrar.php" class="menu-link">
                                    <div data-i18n="Notifications">Facturasxcobrar</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="estadisticas.php" class="menu-link">
                                    <div data-i18n="Connections">Estadisticas</div>
                                </a>
                            </li>
-->
                        </ul>
                    </li>

                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-lock-open-alt"></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>
                            <!--      <li class="menu-item">
                                <a href="estadisticascli.php" class="menu-link">
                                    <div data-i18n="Basic"> Estadisticas Clientes</div>
                                </a>
                            </li>     
-->
                        </ul>
                    </li>
                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-cube-alt"></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>
                        </ul>
                    </li>


                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-cube-alt"></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="ordenes.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Ordenes</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-cube-alt"></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="estadisticasprov.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Estadisticas Proveedores</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</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>
                        </ul>
                    </li>


                </ul>
            </aside>

            <!-- / Menu -->
            <div class="layout-page ">
                <nav class="barrra layout-navbar navbar navbar-expand-xl navbar-detached 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="Search..."
                                    aria-label="Search..." />
                            </div>
                        </div>
                        <!-- /Search -->

                        <ul class="navbar-nav flex-row align-items-center ms-auto">
                            <!-- Place this tag where you want the button to render. -->
                            <li class="nav-item lh-1 me-3">
                                <a
                                    class="github-button"
                                    href="https://github.com/themeselection/sneat-html-admin-template-free"
                                    data-icon="octicon-star"
                                    data-size="large"
                                    data-show-count="true"
                                    aria-label="Star themeselection/sneat-html-admin-template-free on GitHub">Star</a>
                            </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">
                                        <img src="../assets/img/avatars/1.png" alt class="w-px-40 h-auto rounded-circle" />
                                    </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">
                                                        <img src="../assets/img/avatars/1.png" alt class="w-px-40 h-auto rounded-circle" />
                                                    </div>
                                                </div>
                                                <div class="flex-grow-1">
                                                    <span class="fw-semibold d-block">John Doe</span>
                                                    <small class="text-muted">Admin</small>
                                                </div>
                                            </div>
                                        </a>
                                    </li>
                                    <li>
                                        <div class="dropdown-divider"></div>
                                    </li>



                                    <li>
                                        <a class="dropdown-item" href="auth-login-basic.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 -->


                    <!-- Contenedor Principal -->
                    <div class="content ">
                        <h1 class="mb-4">Te damos la bienvenida. ¿Qué deseas hacer?</h1>

                        <!-- Fila de Tarjetas -->
                        <div class="row tarjetas">
                            <div class="col-md-3">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="avatar">
                                            <img src="../assets/img/icons/unicons/paypal.png" alt="Credit Card" class="rounded" />
                                        </div>
                                        <span class="mb-1">Payments</span>
                                        <h3 class="card-title text-nowrap mb-2">$2,456</h3>
                                        <small class="text-danger fw-semibold">-14.82%</small>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-3">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="avatar">
                                            <img src="../assets/img/icons/unicons/cc-primary.png" alt="Credit Card" class="rounded" />
                                        </div>
                                        <span class="fw-semibold d-block mb-1">Tarjeta</span>
                                        <h3 class="card-title mb-2">$14,857</h3>
                                        <small class="text-success fw-semibold">+28.14%</small>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-3">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="avatar">
                                            <img src="../assets/img/icons/unicons/cc-primary.png" alt="Credit Card" class="rounded" />
                                        </div>
                                        <span class="fw-semibold d-block mb-1">Tarjeta</span>
                                        <h3 class="card-title mb-2">$14,857</h3>
                                        <small class="text-success fw-semibold">+28.14%</small>
                                    </div>
                                </div>
                            </div>


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



                    <!-- Basic Bootstrap Table -->
                    <div class="card tablas">
                        <!-- <h5 class="card-header">Compras</h5> -->
                        <div class="table-responsive text-nowrap"></div>

                        <?php
                        $serverName = "DESKTOP-BJI9NAO\NATIONALSOFT";
                        $database = "softrestaurant11";
                        $username = "sa";
                        $password = "National09";

                        // Obtenemos el filtro actual desde los parámetros GET
                        $filtro = isset($_GET['filtro']) ? $_GET['filtro'] : '';

                        try {
                            $dbh = new PDO("sqlsrv:Server=$serverName;Database=$database", $username, $password);
                            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                            $sql = "SELECT f.*, c.*
        FROM dbo.facturas f
        INNER JOIN dbo.clientes c ON f.idcliente = c.idcliente";
                            $stmt = $dbh->query($sql);


                            $stmt = $dbh->query($sql);
                            $stmt->execute();
                            echo "<div class='container mt-5'>";
                            echo "<div class='d-flex justify-content-between align-items-center mb-4'>";
                            echo "<h1>Facturas</h1>";

                            echo "<div class='export-container'>";
                            echo "<button id='exportBtn' class='export-button'>";
                            echo "<i class='fa fal fa-upload'></i> Exportar <i class='fa  fa-chevron-down'></i>";
                            echo "</button>";
                            echo "<div id='exportMenu' class='export-menu'>";
                            echo "<a href='#' id='printOption'><i class='fa fa-print'></i> Imprimir</a>";
                            echo "<a href='#' id='excelOption'><i class='fa fa-file-excel'></i> Excel</a>";
                            echo "<a href='#' id='pdfOption'><i class='fa fa-file-pdf'></i> PDF</a>";
                            echo "<a href='#' id='copyOption'><i class='fa fa-copy'></i> Copiar</a>";
                            echo "</div>";
                            echo "</div>";
                            echo "</div>";

                            echo "<div class='d-flex justify-content-between align-items-center mb-3'>";
                            echo "<div class='btn-group' role='group'>";
                            echo "<button class='btn custom-filter date-filter' data-filter='today'>Hoy</button>";
                            echo "<button class='btn custom-filter date-filter' data-filter='this-month'>Este mes</button>";
                            echo "<button class='btn custom-filter date-filter' data-filter='last-month'>Mes anterior</button>";
                            echo "<button class='btn custom-filter date-filter' data-filter='all'>Todas</button>";
                            echo "</div>";

                            echo "<div>";
                            echo "<button class='btn custom-date-filter' data-toggle='modal' data-target='#dateFilterModal'>Filtrar por Fecha</button>";
                            echo "<button class='btn custom-action' id='clearFilters'>Borrar Filtros</button>";
                            echo "</div>";
                            echo "</div>";

                            echo "<table id='clientesTable' class='table table-hover'>";
                            echo "<thead class='thead-dark'><tr><th>Factura</th><th>Cliente</th><th>Nota</th><th>Concepto</th><th>Estado</th><th>Total</th><th>Fecha</th><tbody>";

                            // Convertir 1 → "Cancelada" y 0 → "Emitida"

                            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                echo "<tr>";
                                echo "<td>" . $row['idfactura'] . "</td>";
                                echo "<td>" . $row['nombre'] . "</td>";
                                echo "<td>" . $row['nota'] . "</td>";
                                echo "<td>" . $row['concepto'] . "</td>";
                                if ($row['cancelada'] == 1) {
                                    echo "<td>Cancelada</td>";
                                } else {
                                    echo "<td>Emitida</td>";
                                }
                                echo "<td>" . $row['total'] . "</td>";
                                echo "<td>" . date('d/m/Y', strtotime($row['fecha'])) . "</td>";
                                echo "</tr>";
                            }

                            echo "</tbody></table>";
                            echo "</div>";
                            echo "</div>";
                        } catch (PDOException $e) {
                            echo "<div class='container mt-5'><h2>AUN NO HAY CONEXION:</h2>";
                            echo "<p>" . $e->getMessage() . "</p></div>";
                        }
                        ?>
                    </div>
                    <!-- / Content -->



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


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



        <!-- 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>
    <!-- Modal para el filtro por fecha -->
    <div class="modal fade" id="dateFilterModal" tabindex="-1" role="dialog" aria-labelledby="dateFilterModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="dateFilterModalLabel">Filtrar por Fecha</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form method="POST" action="">
                        <div class="form-group">
                            <label for="start_date">Fecha Inicial</label>
                            <input type="date" class="form-control" id="start_date" name="start_date" required>
                        </div>
                        <div class="form-group">
                            <label for="end_date">Fecha Final</label>
                            <input type="date" class="form-control" id="end_date" name="end_date" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Filtrar</button>
                    </form>
                </div>
            </div>
        </div>
    </div>



</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>
                        // Datos de los productos desde PHP
                        var productLabels = <?php echo json_encode($productos); ?>;
                        var productValues = <?php echo json_encode($cantidades); ?>;

                        // Configuración de la gráfica para Top 10 Productos
                        var topProductsChartData = {
                            labels: productLabels,
                            datasets: [{
                                label: 'Top 10 Productos',
                                data: productValues,
                                backgroundColor: [
                                    '#009DFF', '#007ECC', '#00C49A', '#FFC107', '#FF7A48', '#B0BEC5',
                                    '#007ACC', '#0088FF', '#004C99', '#FFA500'
                                ],
                                hoverBackgroundColor: [
                                    '#007ECC', '#009DFF', '#00B58A', '#FFB206', '#FF6A38', '#90A4AE',
                                    '#005F99', '#0070CC', '#003366', '#CC8400'
                                ],
                                borderColor: 'rgb(255, 255, 255)', // Bordes blancos
                                borderWidth: 2,
                                hoverOffset: 10 // Offset para mantener el efecto de hover
                            }]
                        };

                        // Crear la gráfica
                        var ctx = document.getElementById('topProductsChart').getContext('2d');
                        var topProductsChart = new Chart(ctx, {
                            type: 'doughnut',
                            data: topProductsChartData,
                            options: {
                                plugins: {
                                    legend: {
                                        display: true,
                                        position: 'bottom',
                                        labels: {
                                            boxWidth: 10,
                                            padding: 15,
                                            font: {
                                                family: 'Arial',
                                                size: 14,
                                                weight: 'bold'
                                            },
                                            color: '#333' // Color de texto
                                        }
                                    }
                                },
                                animation: {
                                    animateScale: true,
                                    animateRotate: true
                                },
                                responsive: true,
                                maintainAspectRatio: false,
                                layout: {
                                    padding: {
                                        bottom: 30
                                    }
                                },
                                tooltips: {
                                    callbacks: {
                                        label: function(tooltipItem, data) {
                                            var label = data.labels[tooltipItem.index] || '';
                                            var value = data.datasets[0].data[tooltipItem.index] || 0;
                                            return label + ': ' + value.toLocaleString('es-ES');
                                        }
                                    }
                                }
                            }
                        });
                    </script>



                    <script>
                        var topProductsData = <?php echo json_encode(array_map(function ($producto, $cantidad) {
                                                    return [
                                                        "nombre" => $producto,
                                                        "cantidad" => $cantidad
                                                    ];
                                                }, $productos, $cantidades)); ?>;

                        function renderProductList(data) {
                            var listContainer = document.querySelector('#productList');
                            listContainer.innerHTML = ''; // Limpiar contenido previo

                            data.forEach((product, index) => {
                                // Generar un cambio porcentual aleatorio para el ejemplo
                                var randomChange = (Math.random() * 20 - 10).toFixed(2); // Rango de -10% a +10%
                                var changeClass = randomChange >= 0 ? 'positive' : 'negative';

                                var listItem = `
                <li class="list-group-item-custom">
                    <div class="product-info d-flex align-items-center">
                        <div class="product-icon">
                            <i class="bi bi-box-seam"></i> <!-- Ícono para el producto -->
                        </div>
                        <div class="ml-2">
                            <div class="product-name">${product.nombre}</div>
                            <div class="product-stats">
                        ${parseInt(product.cantidad).toLocaleString('es-ES')}
                        
                    </div>
                        </div>
                    </div>
                    <div class="product-stats">
                        <span class="sales-change ${changeClass}">
                            ${randomChange}%
                        </span>
                    </div>
                </li>`;
                                listContainer.innerHTML += listItem;
                            });
                        }

                        // Llamar a la función para renderizar la lista
                        renderProductList(topProductsData);
                    </script>


                    <!-- Script para la lista de agentes -->
                    <script>
                        var topAgentsData = <?php echo $topAgentsData; ?>;

                        function renderAgentesList(data) {
                            var listContainer = document.querySelector('#agentesList');
                            listContainer.innerHTML = ''; // Limpiar contenido previo

                            data.forEach(agent => {
                                // Generar un cambio porcentual aleatorio para el ejemplo
                                var randomChange = (Math.random() * 20 - 10).toFixed(2); // Rango de -10% a +10%
                                var changeClass = randomChange >= 0 ? 'positive' : 'negative';

                                var listItem = `
                <li class="list-group-item-custom">
                    <div class="agent-info">
                        <div class="agent-icon">
                            <!-- Aquí puedes añadir un ícono o imagen representativa -->
                            <i class="bi bi-person"></i>
                        </div>
                        <div>
                            <div class="agent-name">${agent.agente}</div>
                            $${parseFloat(agent.total_ventas).toLocaleString('es-ES')}
                        </div>
                    </div>
                    <div class="agent-sales">
                        <span class="sales-change ${changeClass}">
                            ${randomChange}%
                        </span>
                    </div>
                </li>`;
                                listContainer.innerHTML += listItem;
                            });
                        }
                        renderAgentesList(topAgentsData);
                    </script>


                    <script>
                        // Datos de los agentes desde PHP o JSON
                        var agentLabels = topAgentsData.map(agent => agent.agente);
                        var agentValues = topAgentsData.map(agent => agent.total_ventas);

                        var topAgentsChartData = {
                            labels: agentLabels,
                            datasets: [{
                                label: 'Top 10 Agentes',
                                data: agentValues,
                                backgroundColor: [
                                    '#009DFF', '#007ECC', '#00C49A', '#FFC107', '#FF7A48', '#B0BEC5',
                                    '#007ACC', '#0088FF', '#004C99', '#FFA500'
                                ],
                                hoverBackgroundColor: [
                                    '#007ECC', '#009DFF', '#00B58A', '#FFB206', '#FF6A38', '#90A4AE',
                                    '#005F99', '#0070CC', '#003366', '#CC8400'
                                ],
                                borderColor: 'rgb(255, 255, 255)', // Bordes blancos
                                borderWidth: 2,
                                hoverOffset: 10 // Efecto de desplazamiento al pasar el mouse
                            }]
                        };

                        // Crear la gráfica
                        var topAgentsChart = new Chart(document.getElementById('topAgentsChart'), {
                            type: 'doughnut',
                            data: topAgentsChartData,
                            options: {
                                plugins: {
                                    legend: {
                                        display: true,
                                        position: 'bottom',
                                        labels: {
                                            boxWidth: 10,
                                            padding: 15,
                                            font: {
                                                family: 'Arial',
                                                size: 14,
                                                weight: 'bold'
                                            },
                                            color: '#333' // Color del texto
                                        }
                                    }
                                },
                                animation: {
                                    animateScale: true,
                                    animateRotate: true
                                },
                                responsive: true,
                                maintainAspectRatio: false,
                                layout: {
                                    padding: {
                                        bottom: 30
                                    }
                                },
                                tooltips: {
                                    callbacks: {
                                        label: function(tooltipItem, data) {
                                            var label = data.labels[tooltipItem.index] || '';
                                            var value = data.datasets[0].data[tooltipItem.index] || 0;
                                            return label + ': ' + value.toLocaleString('es-ES');
                                        }
                                    }
                                }
                            }
                        });
                    </script>


                    <script>
                        // Datos generados desde PHP
                        let clientesData = <?php echo json_encode(array_map(function ($nombre, $monto, $montoFormateado) {
                                                return ['nombre' => $nombre, 'monto' => $monto, 'montoFormateado' => $montoFormateado];
                                            }, $clientes, $montos, $montosFormateados)); ?>;

                        // Sumar todos los montos para calcular los porcentajes
                        let totalMontos = clientesData.reduce((acc, cliente) => acc + parseFloat(cliente.monto), 0);

                        // Función para renderizar la lista de clientes
                        function renderClientesList(data) {
                            let listContainer = document.querySelector('#listaClientes');
                            listContainer.innerHTML = ''; // Limpiar contenido previo

                            data.forEach((cliente, index) => {
                                let porcentaje = (parseFloat(cliente.monto) / totalMontos * 100).toFixed(2); // Calcular porcentaje
                                let changeClass = (porcentaje >= 0) ? 'positive' : 'negative'; // Clase para el cambio

                                let listItem = `
                <li class="list-group-item-custom">
                    <div class="agent-info">
                        <div class="agent-icon">
                            <i class="bi bi-person"></i> <!-- Icono para el cliente -->
                        </div>
                        <div>
                            <div class="agent-name">${index + 1}. ${cliente.nombre}</div>
                            <div class="agent-company"> $${cliente.montoFormateado}</div>
                        </div>
                    </div>
                    <div class="agent-sales">
                        <span class="sales-change ${changeClass}">
                            ${porcentaje}%
                        </span>
                    </div>
                </li>`;
                                listContainer.innerHTML += listItem;
                            });
                        }

                        // Función para actualizar el gráfico y la lista
                        function actualizarTopClientes(cantidad) {
                            // Filtrar los clientes según la cantidad seleccionada
                            let clientesFiltrados = clientesData.slice(0, cantidad);

                            // Renderizar la lista de clientes
                            renderClientesList(clientesFiltrados);

                            // Actualizar el gráfico
                            let chartCanvas = document.getElementById('TopClientesChart').getContext('2d');
                            if (window.myBarChart) {
                                window.myBarChart.destroy(); // Destruir el gráfico anterior
                            }

                            // Colores sólidos actualizados para las barras
                            const barColors = [
                                '#009DFF', '#007ECC', '#00C49A', '#FFC107', '#FF7A48',
                                '#B0BEC5', '#009DFF', '#007ECC', '#00C49A', '#FFC107'
                            ];

                            window.myBarChart = new Chart(chartCanvas, {
                                type: 'bar',
                                data: {
                                    labels: clientesFiltrados.map(cliente => cliente.nombre),
                                    datasets: [{
                                        label: 'Monto de compras',
                                        data: clientesFiltrados.map(cliente => parseFloat(cliente.monto)), // Usar montos sin formatear
                                        backgroundColor: barColors.slice(0, clientesFiltrados.length),
                                        borderColor: '#fff',
                                        borderWidth: 1,
                                        borderRadius: 5, // Bordes redondeados
                                        hoverBackgroundColor: '#007ECC',
                                        hoverBorderColor: '#005B99',
                                    }]
                                },
                                options: {
                                    scales: {
                                        x: {
                                            grid: {
                                                display: false
                                            },
                                            ticks: {
                                                color: '#444',
                                                font: {
                                                    size: 12,
                                                    family: 'Arial'
                                                }
                                            }
                                        },
                                        y: {
                                            grid: {
                                                color: 'rgba(0, 0, 0, 0.1)',
                                                drawBorder: false
                                            },
                                            ticks: {
                                                color: '#444',
                                                font: {
                                                    size: 12,
                                                    family: 'Arial'
                                                },
                                                callback: value => `$${value}` // Formato de moneda en el eje Y
                                            },
                                            beginAtZero: true
                                        }
                                    },
                                    plugins: {
                                        legend: {
                                            display: false
                                        },
                                        tooltip: {
                                            backgroundColor: '#007ECC',
                                            borderColor: '#005B99',
                                            borderWidth: 1,
                                            callbacks: {
                                                label: tooltipItem => `Monto: $${tooltipItem.raw}`
                                            }
                                        }
                                    }
                                }
                            });
                        }

                        // Evento cuando se cambia la cantidad en el menú desplegable
                        document.getElementById('numClients').addEventListener('change', function() {
                            let cantidadSeleccionada = parseInt(this.value);
                            actualizarTopClientes(cantidadSeleccionada);
                        });

                        // Llamar a la función inicialmente con la cantidad seleccionada desde PHP
                        actualizarTopClientes(<?php echo $numClients; ?>); // Usar el valor por defecto de PHP
                    </script>





</html>