<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

$pageTitle = 'Consulta de Recaudos';
$activeMenu = 'consultas';
$activePage = 'recaudos';
$basePath = '..';

$conn = db();
$vendedores = $conn->query('SELECT cod_vendedor, nombre FROM vendedores ORDER BY nombre');

require __DIR__ . '/../includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h4 class="mb-0"><i class="bi bi-wallet2"></i> Recaudos</h4>
  <button id="btnExportar" class="btn btn-outline-success btn-sm">
    <i class="bi bi-file-earmark-excel"></i> Exportar a Excel
  </button>
</div>

<div class="card shadow-sm mb-3">
  <div class="card-body">
    <div class="row g-3">
      <div class="col-md-2">
        <label class="form-label">Desde</label>
        <input type="date" id="fDesde" class="form-control form-control-sm">
      </div>
      <div class="col-md-2">
        <label class="form-label">Hasta</label>
        <input type="date" id="fHasta" class="form-control form-control-sm">
      </div>
      <div class="col-md-3">
        <label class="form-label">Vendedor</label>
        <select id="fVendedor" class="form-select form-select-sm">
          <option value="">Todos</option>
          <?php while ($v = $vendedores->fetch_assoc()): ?>
          <option value="<?= h($v['cod_vendedor']) ?>"><?= h($v['nombre']) ?></option>
          <?php endwhile; ?>
        </select>
      </div>
      <div class="col-md-2 d-flex align-items-end">
        <button id="btnFiltrar" class="btn btn-sm btn-primary w-100"><i class="bi bi-funnel"></i> Filtrar</button>
      </div>
    </div>
  </div>
</div>

<div class="card shadow-sm">
  <div class="card-body">
    <table id="tblRecaudos" class="table table-striped table-hover align-middle w-100">
      <thead>
        <tr><th>Fecha</th><th>Cliente</th><th>Vendedor</th><th>Factura</th><th>Valor recaudo</th><th>Tipo pago</th></tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>
</div>

<?php
$extraScripts = <<<HTML
<script>
let table = initServerTable('#tblRecaudos', '../api/datatable_recaudos.php', [
  {data: 0}, {data: 1}, {data: 2}, {data: 3}, {data: 4}, {data: 5}
], function () {
  return {
    desde: document.getElementById('fDesde').value,
    hasta: document.getElementById('fHasta').value,
    cod_vendedor: document.getElementById('fVendedor').value,
  };
});
document.getElementById('btnFiltrar').addEventListener('click', function () { table.ajax.reload(); });

document.getElementById('btnExportar').addEventListener('click', function () {
  const params = new URLSearchParams({
    desde: document.getElementById('fDesde').value,
    hasta: document.getElementById('fHasta').value,
    cod_vendedor: document.getElementById('fVendedor').value,
  });
  window.location.href = '../api/exportar_recaudos.php?' + params.toString();
});
</script>
HTML;
require __DIR__ . '/../includes/footer.php';
?>
