<?php
$sales      = is_array($sales ?? null) ? $sales : [];
$filters    = is_array($filters ?? null) ? $filters : [];
$page       = max(1, (int) ($page ?? 1));
$pages      = max(1, (int) ($pages ?? 1));
$totalSales = (int) ($total ?? 0);
$perPage    = (int) ($per_page ?? 20);

$fechaDesde = trim((string) ($filters['fecha_desde'] ?? ''));
$fechaHasta = trim((string) ($filters['fecha_hasta'] ?? ''));

// Helper URL para paginación conservando filtros
$buildUrl = static function (int $p) use ($fechaDesde, $fechaHasta, $perPage): string {
    $q = http_build_query(array_filter([
        'fecha_desde' => $fechaDesde,
        'fecha_hasta' => $fechaHasta,
        'per_page'    => $perPage !== 20 ? $perPage : null,
        'page'        => $p > 1 ? $p : null,
    ]));
    return url('ventas') . ($q !== '' ? '?' . $q : '');
};

$branches = [];
$saleStatuses = [];

foreach ($sales as $saleRow) {
    $branchName = trim((string) ($saleRow['sucursal'] ?? ''));
    if ($branchName === '') {
        $branchName = 'Sin sucursal';
    }
    $branchKey = strtolower($branchName);
    $branches[$branchKey] = $branchName;

    $saleStatus = strtolower(trim((string) ($saleRow['estado'] ?? 'pendiente')));
    if ($saleStatus === '') {
        $saleStatus = 'pendiente';
    }
    $saleStatuses[$saleStatus] = ucfirst($saleStatus);
}

asort($branches);
ksort($saleStatuses);
?>

<div class="card border-0 shadow-sm">
    <div class="card-body">
        <h1 class="h5 mb-3">Historial de ventas</h1>

        <?php
        // Accesos rápidos de mes
        $mesesEs = [
            1 => 'Enero', 2 => 'Febrero', 3 => 'Marzo', 4 => 'Abril',
            5 => 'Mayo', 6 => 'Junio', 7 => 'Julio', 8 => 'Agosto',
            9 => 'Septiembre', 10 => 'Octubre', 11 => 'Noviembre', 12 => 'Diciembre',
        ];
        $quickMonths = [];
        for ($i = 0; $i < 6; $i++) {
            $ts    = strtotime("-{$i} month");
            $key   = date('Y-m', $ts);
            $mes   = (int) date('n', $ts);
            $anio  = date('Y', $ts);
            $label = ($mesesEs[$mes] ?? date('F', $ts)) . ' ' . $anio;
            $quickMonths[] = ['key' => $key, 'label' => $label];
        }
        $activeMes = substr($fechaDesde, 0, 7);
        ?>
        <form method="GET" action="<?= url('ventas') ?>" id="vxSalesDateForm" class="mb-4">
            <div class="card border-0 bg-light rounded-3 p-3">
                <div class="d-flex flex-wrap gap-3" style="align-items: flex-end;">

                    <div class="flex-grow-1" style="min-width:160px; max-width:220px;">
                        <label class="form-label fw-semibold mb-1" style="font-size:.75rem; text-transform:uppercase; letter-spacing:.04em; color:#6c757d;">
                            <i class="bx bx-calendar me-1"></i>Mes
                        </label>
                        <select class="form-select form-select-sm" id="vxMonthPicker">
                            <option value="">— Rango personalizado —</option>
                            <?php foreach ($quickMonths as $qm): ?>
                                <option value="<?= e($qm['key']) ?>" <?= $activeMes === $qm['key'] ? 'selected' : '' ?>>
                                    <?= e($qm['label']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div style="min-width:140px;">
                        <label class="form-label fw-semibold mb-1" style="font-size:.75rem; text-transform:uppercase; letter-spacing:.04em; color:#6c757d;">
                            Desde
                        </label>
                        <input type="date" name="fecha_desde" class="form-control form-control-sm" id="vxFechaDesde" value="<?= e($fechaDesde) ?>">
                    </div>

                    <div style="min-width:140px;">
                        <label class="form-label fw-semibold mb-1" style="font-size:.75rem; text-transform:uppercase; letter-spacing:.04em; color:#6c757d;">
                            Hasta
                        </label>
                        <input type="date" name="fecha_hasta" class="form-control form-control-sm" id="vxFechaHasta" value="<?= e($fechaHasta) ?>">
                    </div>

                    <div>
                        <div class="form-label mb-1" style="font-size:.75rem; visibility:hidden;">_</div>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-sm btn-primary px-3">
                                <i class="bx bx-search-alt me-1"></i>Buscar
                            </button>
                            <a href="<?= e(url('ventas') . '?' . http_build_query(array_filter([
                                'fecha_desde' => date('Y-m-d'),
                                'fecha_hasta' => date('Y-m-d'),
                                'per_page' => $perPage !== 20 ? $perPage : null,
                            ]))) ?>" class="btn btn-sm btn-outline-secondary px-3">
                                Hoy
                            </a>
                        </div>
                    </div>
                </div>
                <input type="hidden" name="per_page" value="<?= e((string) $perPage) ?>" id="vxPerPageHidden">

                <?php if ($fechaDesde !== '' || $fechaHasta !== ''): ?>
                <div class="mt-2 d-flex align-items-center gap-2">
                    <span class="badge text-bg-primary" style="font-size:.78rem; padding:.35em .7em;">
                        <i class="bx bx-calendar-check me-1"></i>
                        <?= e($fechaDesde ?: '…') ?> — <?= e($fechaHasta ?: '…') ?>
                    </span>
                    <span class="text-muted" style="font-size:.82rem;"><?= e(number_format($totalSales)) ?> venta(s)</span>
                </div>
                <?php endif; ?>
            </div>
        </form>
        <script>
        document.getElementById('vxMonthPicker')?.addEventListener('change', function () {
            const val = this.value;
            if (!val) return;
            const [y, m] = val.split('-');
            const last = new Date(+y, +m, 0).getDate();
            document.getElementById('vxFechaDesde').value = `${y}-${m}-01`;
            document.getElementById('vxFechaHasta').value = `${y}-${m}-${String(last).padStart(2, '0')}`;
            document.getElementById('vxSalesDateForm').submit();
        });
        // Si el usuario cambia manualmente las fechas, limpiar el selector de mes
        ['vxFechaDesde','vxFechaHasta'].forEach(id => {
            document.getElementById(id)?.addEventListener('change', () => {
                document.getElementById('vxMonthPicker').value = '';
            });
        });
        </script>

        <div class="vx-sales-filters mb-3" id="vxSalesFilters">
            <div class="vx-sales-toolbar-row">
                <div class="input-group input-group-sm vx-sales-search-group">
                    <span class="input-group-text bg-white"><i class="bx bx-search"></i></span>
                    <input
                        type="search"
                        class="form-control"
                        id="vxSalesSearchInput"
                        placeholder="Buscar en esta página: documento, cliente, cajero..."
                        autocomplete="off"
                    >
                </div>

                <select class="form-select form-select-sm vx-sales-filter-control" id="vxSalesSaleStatusFilter" title="Estado de venta">
                    <option value="">Venta: Todas</option>
                    <?php foreach ($saleStatuses as $statusValue => $statusLabel): ?>
                        <option value="<?= e($statusValue) ?>">Venta: <?= e($statusLabel) ?></option>
                    <?php endforeach; ?>
                </select>

                <select class="form-select form-select-sm vx-sales-filter-control" id="vxSalesBranchFilter" title="Sucursal">
                    <option value="">Sucursal: Todas</option>
                    <?php foreach ($branches as $branchValue => $branchLabel): ?>
                        <option value="<?= e($branchValue) ?>"><?= e($branchLabel) ?></option>
                    <?php endforeach; ?>
                </select>

                <button type="button" class="btn btn-sm btn-outline-dark" id="vxSalesClearFilters">
                    <i class="bx bx-eraser me-1"></i>Limpiar
                </button>

                <select class="form-select form-select-sm vx-sales-filter-control" id="vxSalesPerPage" title="Registros por página">
                    <?php foreach ([10, 20, 50, 100] as $pageSize): ?>
                        <option value="<?= e((string) $pageSize) ?>" <?= $perPage === $pageSize ? 'selected' : '' ?>>
                            <?= e((string) $pageSize) ?>/página
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <small class="text-muted d-block mt-2" id="vxSalesResultCount"></small>
        </div>
        <div class="table-responsive">
            <table class="table table-striped table-hover vx-sales-table" id="vxSalesTable">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Documento</th>
                    <th>Fecha</th>
                    <th>Cliente</th>
                    <th>Total</th>
                    <th>Estado</th>
                    <th class="text-end">Acciones</th>
                </tr>
                </thead>
                <tbody id="vxSalesTableBody">
                <?php foreach ($sales as $sale): ?>
                    <?php
                    $saleId = (int) ($sale['id'] ?? 0);
                    $documento = (string) ($sale['documento_numero'] ?? ('POS-' . (string) $saleId));
                    $fecha = (string) ($sale['fecha'] ?? '');
                    $sucursal = trim((string) ($sale['sucursal'] ?? 'Sin sucursal'));
                    $cliente = trim((string) ($sale['cliente'] ?? 'Consumidor final'));
                    $cajero = trim((string) ($sale['cajero'] ?? 'Sin cajero'));
                    $saleTotal = (float) ($sale['total'] ?? 0);
                    $pagado = (float) ($sale['pagado'] ?? 0);
                    $saldo = (float) ($sale['saldo'] ?? 0);
                    $estadoCobro = strtolower(trim((string) ($sale['estado_pago'] ?? 'pendiente')));
                    $estadoVenta = strtolower(trim((string) ($sale['estado'] ?? 'pendiente')));
                    $metodosPagoRaw = strtolower(trim((string) ($sale['metodos_pago'] ?? '')));
                    $metodosPagoList = array_values(array_filter(array_map(
                        static fn (string $method): string => trim($method),
                        explode(',', $metodosPagoRaw)
                    ), static fn (string $method): bool => $method !== ''));
                    $isCredibancoDataphone = false;
                    foreach ($metodosPagoList as $methodCode) {
                        if (in_array($methodCode, ['credibanco', 'credibanco_dataphone', 'credibanco_datafono'], true)) {
                            $isCredibancoDataphone = true;
                            break;
                        }
                    }
                    $printBlockedByWebhook = $isCredibancoDataphone && $estadoVenta !== 'pagada';
                    $isSaleCanceled = $estadoVenta === 'anulada';
                    $detailModalId = 'saleDetailModal' . (string) $saleId;

                    $estadoCobroClass = $estadoCobro === 'pagada'
                        ? 'text-bg-success'
                        : ($estadoCobro === 'parcial' ? 'text-bg-warning' : ($estadoCobro === 'anulada' ? 'text-bg-secondary' : 'text-bg-danger'));
                    $estadoVentaClass = $isSaleCanceled ? 'text-bg-secondary' : 'text-bg-primary';
                    $saleDateOnly = substr($fecha, 0, 10);
                    $searchText = strtolower(trim(
                        $documento . ' ' .
                        $fecha . ' ' .
                        $sucursal . ' ' .
                        $cliente . ' ' .
                        $cajero . ' ' .
                        (string) $saleId
                    ));
                    ?>
                    <tr
                        data-sale-row="1"
                        data-search="<?= e($searchText) ?>"
                        data-estado-cobro="<?= e($estadoCobro) ?>"
                        data-estado-venta="<?= e($estadoVenta) ?>"
                        data-sucursal="<?= e(strtolower($sucursal)) ?>"
                        data-fecha="<?= e($saleDateOnly) ?>"
                    >
                        <td><?= e((string) $saleId) ?></td>
                        <td class="fw-semibold"><?= e($documento) ?></td>
                        <td><?= e($fecha) ?></td>
                        <td>
                            <div class="fw-semibold"><?= e($cliente) ?></div>
                            <small class="text-muted d-block"><?= e($sucursal) ?> · <?= e($cajero) ?></small>
                        </td>
                        <td class="fw-semibold"><?= e(money($saleTotal)) ?></td>
                        <td>
                            <div class="d-flex flex-column gap-1">
                                <?php if ($isSaleCanceled): ?>
                                    <span class="badge text-bg-danger d-inline-block">Anulada</span>
                                <?php else: ?>
                                    <span class="badge <?= e($estadoCobroClass) ?> d-inline-block">Cobro: <?= e($estadoCobro) ?></span>
                                    <span class="badge <?= e($estadoVentaClass) ?> d-inline-block">Venta: <?= e($estadoVenta) ?></span>
                                    <?php if ($printBlockedByWebhook): ?>
                                        <small class="text-warning">Pendiente confirmación Credibanco</small>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td class="text-end">
                            <div class="vx-sales-actions">
                                <div class="vx-sales-primary-actions">
                                    <button
                                        class="btn btn-sm btn-outline-secondary vx-sales-action-btn"
                                        type="button"
                                        data-bs-toggle="modal"
                                        data-bs-target="#<?= e($detailModalId) ?>"
                                        title="Ver detalle"
                                        aria-label="Ver detalle de venta"
                                    >
                                        <i class="bx bx-info-circle"></i>
                                    </button>

                                    <?php if ($printBlockedByWebhook): ?>
                                        <button
                                            class="btn btn-sm btn-outline-secondary vx-sales-action-btn"
                                            type="button"
                                            disabled
                                            title="Disponible cuando Credibanco confirme el pago"
                                            aria-label="Impresión bloqueada hasta confirmación de Credibanco"
                                        >
                                            <i class="bx bx-file"></i>
                                        </button>
                                    <?php else: ?>
                                        <a
                                            class="btn btn-sm btn-outline-primary vx-sales-action-btn"
                                            href="<?= e(url('ventas/' . $saleId . '/factura/imprimir')) ?>"
                                            target="_blank"
                                            rel="noopener"
                                            title="Imprimir factura"
                                            aria-label="Imprimir factura"
                                        >
                                            <i class="bx bx-file"></i>
                                        </a>
                                    <?php endif; ?>

                                    <?php if ($printBlockedByWebhook): ?>
                                        <button
                                            class="btn btn-sm btn-outline-secondary vx-sales-action-btn"
                                            type="button"
                                            disabled
                                            title="Disponible cuando Credibanco confirme el pago"
                                            aria-label="Impresión de ticket bloqueada hasta confirmación de Credibanco"
                                        >
                                            <i class="bx bx-receipt"></i>
                                        </button>
                                    <?php else: ?>
                                        <a
                                            class="btn btn-sm btn-outline-dark vx-sales-action-btn"
                                            href="<?= e(url('ventas/' . $saleId . '/ticket/imprimir')) ?>"
                                            target="_blank"
                                            rel="noopener"
                                            title="Imprimir ticket"
                                            aria-label="Imprimir ticket"
                                        >
                                            <i class="bx bx-receipt"></i>
                                        </a>
                                    <?php endif; ?>
                                </div>

                                <div class="dropdown">
                                    <button
                                        class="btn btn-sm btn-outline-secondary vx-sales-action-btn"
                                        type="button"
                                        data-bs-toggle="dropdown"
                                        data-bs-auto-close="outside"
                                        title="Más acciones"
                                        aria-label="Más acciones"
                                    >
                                        <i class="bx bx-dots-vertical-rounded"></i>
                                    </button>
                                    <ul class="dropdown-menu dropdown-menu-end vx-sales-dropdown">
                                        <li>
                                            <button
                                                class="dropdown-item"
                                                type="button"
                                                data-bs-toggle="modal"
                                                data-bs-target="#<?= e($detailModalId) ?>"
                                            >
                                                <i class="bx bx-info-circle me-1"></i>Detalle
                                            </button>
                                        </li>
                                        <?php if ($printBlockedByWebhook): ?>
                                            <li><span class="dropdown-item text-muted"><i class="bx bx-time-five me-1"></i>Esperando webhook Credibanco</span></li>
                                        <?php else: ?>
                                            <li>
                                                <a
                                                    class="dropdown-item"
                                                    href="<?= e(url('ventas/' . $saleId . '/factura/imprimir')) ?>"
                                                    target="_blank"
                                                    rel="noopener"
                                                >
                                                    <i class="bx bx-file me-1"></i>Imprimir factura
                                                </a>
                                            </li>
                                            <li>
                                                <a
                                                    class="dropdown-item"
                                                    href="<?= e(url('ventas/' . $saleId . '/ticket/imprimir')) ?>"
                                                    target="_blank"
                                                    rel="noopener"
                                                >
                                                    <i class="bx bx-receipt me-1"></i>Imprimir ticket
                                                </a>
                                            </li>
                                        <?php endif; ?>
                                        <li><hr class="dropdown-divider"></li>
                                        <li>
                                            <a class="dropdown-item" href="<?= e(url('ventas/' . $saleId)) ?>">
                                                <i class="bx bx-git-branch me-1"></i>Trazabilidad
                                            </a>
                                        </li>
                                        <?php if ($printBlockedByWebhook): ?>
                                            <li><span class="dropdown-item text-muted"><i class="bx bx-download me-1"></i>PDF pendiente de aprobación</span></li>
                                        <?php else: ?>
                                            <li>
                                                <a
                                                    class="dropdown-item"
                                                    href="<?= e(url('ventas/' . $saleId . '/factura/pdf')) ?>"
                                                    target="_blank"
                                                    rel="noopener"
                                                >
                                                    <i class="bx bx-download me-1"></i>Descargar PDF
                                                </a>
                                            </li>
                                        <?php endif; ?>
                                        <?php if (!$isSaleCanceled): ?>
                                            <li><hr class="dropdown-divider"></li>
                                            <li>
                                                <form action="<?= e(url('ventas/' . $saleId . '/anular')) ?>" method="post">
                                                    <?= csrf_field() ?>
                                                    <button class="dropdown-item text-danger" type="submit">
                                                        <i class="bx bx-x-circle me-1"></i>Anular venta
                                                    </button>
                                                </form>
                                            </li>
                                        <?php endif; ?>
                                    </ul>
                                </div>
                            </div>

                            <div class="modal fade" id="<?= e($detailModalId) ?>" tabindex="-1" aria-labelledby="<?= e($detailModalId) ?>Label" aria-hidden="true">
                                <div class="modal-dialog modal-dialog-centered">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h2 class="h6 mb-0" id="<?= e($detailModalId) ?>Label">
                                                Venta #<?= e((string) $saleId) ?> · <?= e($documento) ?>
                                            </h2>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                                        </div>
                                        <div class="modal-body">
                                            <div class="vx-sale-detail-grid">
                                                <div class="vx-sale-detail-item">
                                                    <small>Fecha</small>
                                                    <strong><?= e($fecha) ?></strong>
                                                </div>
                                                <div class="vx-sale-detail-item">
                                                    <small>Sucursal</small>
                                                    <strong><?= e($sucursal) ?></strong>
                                                </div>
                                                <div class="vx-sale-detail-item">
                                                    <small>Cajero</small>
                                                    <strong><?= e($cajero) ?></strong>
                                                </div>
                                                <div class="vx-sale-detail-item">
                                                    <small>Cliente</small>
                                                    <strong><?= e($cliente) ?></strong>
                                                </div>
                                                <div class="vx-sale-detail-item">
                                                    <small>Total</small>
                                                    <strong><?= e(money($saleTotal)) ?></strong>
                                                </div>
                                                <div class="vx-sale-detail-item">
                                                    <small>Pagado</small>
                                                    <strong class="text-success"><?= e(money($pagado)) ?></strong>
                                                </div>
                                                <div class="vx-sale-detail-item">
                                                    <small>Saldo</small>
                                                    <strong class="text-danger"><?= e(money($saldo)) ?></strong>
                                                </div>
                                                <?php if ($isSaleCanceled): ?>
                                                <div class="vx-sale-detail-item">
                                                    <small>Estado</small>
                                                    <span class="badge text-bg-danger">Anulada</span>
                                                </div>
                                                <?php else: ?>
                                                <div class="vx-sale-detail-item">
                                                    <small>Estado cobro</small>
                                                    <span class="badge <?= e($estadoCobroClass) ?>"><?= e($estadoCobro) ?></span>
                                                </div>
                                                <div class="vx-sale-detail-item">
                                                    <small>Estado venta</small>
                                                    <span class="badge <?= e($estadoVentaClass) ?>"><?= e($estadoVenta) ?></span>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <a class="btn btn-sm btn-outline-secondary" href="<?= e(url('ventas/' . $saleId)) ?>">
                                                <i class="bx bx-git-branch me-1"></i>Trazabilidad
                                            </a>
                                            <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">Cerrar</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div class="alert alert-light border mt-3 mb-0 d-none" id="vxSalesNoResults">
            No se encontraron ventas con los filtros aplicados.
        </div>

        <?php if ($totalSales > 0): ?>
        <nav class="mt-4 d-flex flex-wrap align-items-center justify-content-between gap-3" aria-label="Paginación ventas">
            <small class="text-muted">
                <?php
                $desde_num = ($page - 1) * $perPage + 1;
                $hasta_num = min($page * $perPage, $totalSales);
                ?>
                Mostrando <strong><?= e(number_format($desde_num)) ?>–<?= e(number_format($hasta_num)) ?></strong>
                de <strong><?= e(number_format($totalSales)) ?></strong> ventas
                &nbsp;·&nbsp; Página <strong><?= e((string) $page) ?></strong> de <strong><?= e((string) $pages) ?></strong>
            </small>

            <?php if ($pages > 1): ?>
            <?php
            $visibleCount = 3;
            $start = max(1, min($page - 1, $pages - ($visibleCount - 1)));
            $end = min($pages, $start + ($visibleCount - 1));
            ?>
            <ul class="pagination vx-sales-pagination mb-0">
                <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                    <a class="page-link" href="<?= e($buildUrl(max(1, $page - 1))) ?>" aria-label="Página anterior" title="Página anterior">
                        <i class="bx bx-chevrons-left"></i>
                    </a>
                </li>
                <?php for ($i = $start; $i <= $end; $i++): ?>
                    <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                        <a class="page-link" href="<?= e($buildUrl($i)) ?>"><?= e((string) $i) ?></a>
                    </li>
                <?php endfor; ?>
                <li class="page-item <?= $page >= $pages ? 'disabled' : '' ?>">
                    <a class="page-link" href="<?= e($buildUrl(min($pages, $page + 1))) ?>" aria-label="Página siguiente" title="Página siguiente">
                        <i class="bx bx-chevrons-right"></i>
                    </a>
                </li>
            </ul>
            <?php endif; ?>
        </nav>
        <?php endif; ?>
    </div>
</div>

<script>
    window.addEventListener('DOMContentLoaded', () => {
        const searchInput = document.getElementById('vxSalesSearchInput');
        const saleFilter = document.getElementById('vxSalesSaleStatusFilter');
        const branchFilter = document.getElementById('vxSalesBranchFilter');
        const clearButton = document.getElementById('vxSalesClearFilters');
        const perPageSelect = document.getElementById('vxSalesPerPage');
        const perPageHidden = document.getElementById('vxPerPageHidden');
        const dateForm = document.getElementById('vxSalesDateForm');
        const tableBody = document.getElementById('vxSalesTableBody');
        const noResultsBox = document.getElementById('vxSalesNoResults');
        const resultCount = document.getElementById('vxSalesResultCount');

        if (!searchInput || !saleFilter || !branchFilter || !clearButton || !tableBody) {
            return;
        }

        const rows = Array.from(tableBody.querySelectorAll('tr[data-sale-row="1"]'));
        const totalRows = rows.length;

        const normalize = (value) => String(value || '')
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .toLowerCase()
            .trim();

        const updateResultText = (visibleRows) => {
            if (!resultCount) {
                return;
            }
            resultCount.textContent = `Mostrando ${visibleRows} de ${totalRows} ventas`;
        };

        const applyFilters = () => {
            const searchValue = normalize(searchInput.value);
            const saleValue = normalize(saleFilter.value);
            const branchValue = normalize(branchFilter.value);

            let visibleRows = 0;

            rows.forEach((row) => {
                const rowSearch = normalize(row.dataset.search || '');
                const rowSale = normalize(row.dataset.estadoVenta || '');
                const rowBranch = normalize(row.dataset.sucursal || '');

                const matchesSearch = searchValue === '' || rowSearch.includes(searchValue);
                const matchesSale = saleValue === '' || rowSale === saleValue;
                const matchesBranch = branchValue === '' || rowBranch === branchValue;

                const visible = matchesSearch && matchesSale && matchesBranch;
                row.classList.toggle('d-none', !visible);
                if (visible) {
                    visibleRows++;
                }
            });

            if (noResultsBox) {
                noResultsBox.classList.toggle('d-none', visibleRows > 0);
            }
            updateResultText(visibleRows);
        };

        [searchInput, saleFilter, branchFilter].forEach((element) => {
            element.addEventListener('input', applyFilters);
            element.addEventListener('change', applyFilters);
        });

        clearButton.addEventListener('click', () => {
            searchInput.value = '';
            saleFilter.value = '';
            branchFilter.value = '';
            applyFilters();
        });

        if (perPageSelect && perPageHidden && dateForm) {
            perPageSelect.addEventListener('change', () => {
                perPageHidden.value = String(perPageSelect.value || '20');
                dateForm.submit();
            });
        }

        applyFilters();
    });
</script>
