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

$pageTitle = 'Consulta de Productos';
$activeMenu = 'consultas';
$activePage = 'productos';
$basePath = '..';

$conn = db();
$categorias = $conn->query('SELECT DISTINCT categoria FROM productos WHERE categoria IS NOT NULL ORDER BY categoria');
$marcas = $conn->query('SELECT DISTINCT marca FROM productos WHERE marca IS NOT NULL ORDER BY marca');

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-box-seam"></i> Productos</h4>
</div>

<div class="card shadow-sm mb-3">
  <div class="card-body">
    <div class="row g-3">
      <div class="col-md-4">
        <label class="form-label">Categoría</label>
        <select id="fCategoria" class="form-select form-select-sm">
          <option value="">Todas</option>
          <?php while ($c = $categorias->fetch_assoc()): ?>
          <option value="<?= h($c['categoria']) ?>"><?= h($c['categoria']) ?></option>
          <?php endwhile; ?>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">Marca</label>
        <select id="fMarca" class="form-select form-select-sm">
          <option value="">Todas</option>
          <?php while ($m = $marcas->fetch_assoc()): ?>
          <option value="<?= h($m['marca']) ?>"><?= h($m['marca']) ?></option>
          <?php endwhile; ?>
        </select>
      </div>
    </div>
  </div>
</div>

<div class="card shadow-sm">
  <div class="card-body">
    <table id="tblProductos" class="table table-striped table-hover align-middle w-100">
      <thead>
        <tr><th>Código</th><th>Título</th><th>Categoría</th><th>Subcategoría</th><th>Marca</th><th>Unidad</th><th>IVA</th><th>Gramaje</th></tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>
</div>

<?php
$extraScripts = <<<HTML
<script>
let table = initServerTable('#tblProductos', '../api/datatable_productos.php', [
  {data: 0}, {data: 1}, {data: 2}, {data: 3}, {data: 4}, {data: 5}, {data: 6}, {data: 7}
], function () {
  return {
    categoria: document.getElementById('fCategoria').value,
    marca: document.getElementById('fMarca').value,
  };
});
['fCategoria', 'fMarca'].forEach(function (id) {
  document.getElementById(id).addEventListener('change', function () { table.ajax.reload(); });
});
</script>
HTML;
require __DIR__ . '/../includes/footer.php';
?>
