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

$pageTitle = 'Utilidad por Ventas';
$activeMenu = 'informes';
$activePage = 'utilidad_ventas';
$basePath = '..';

$conn = db();
$vendedores = $conn->query('SELECT cod_vendedor, nombre FROM vendedores ORDER BY nombre');
$regionales = $conn->query('SELECT DISTINCT cod_regional FROM vendedores WHERE cod_regional IS NOT NULL ORDER BY cod_regional');
$ciudades = $conn->query('SELECT DISTINCT ciudad FROM clientes WHERE ciudad IS NOT NULL ORDER BY ciudad');

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-graph-up"></i> Utilidad por Ventas</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">Fecha inicial</label>
        <input type="date" id="fDesde" class="form-control form-control-sm">
      </div>
      <div class="col-md-2">
        <label class="form-label">Fecha final</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">
        <label class="form-label">Cod. zona</label>
        <select id="fRegional" class="form-select form-select-sm">
          <option value="">Todas</option>
          <?php while ($r = $regionales->fetch_assoc()): ?>
          <option value="<?= h($r['cod_regional']) ?>"><?= h($r['cod_regional']) ?></option>
          <?php endwhile; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">Ciudad</label>
        <select id="fCiudad" class="form-select form-select-sm">
          <option value="">Todas</option>
          <?php while ($c = $ciudades->fetch_assoc()): ?>
          <option value="<?= h($c['ciudad']) ?>"><?= h($c['ciudad']) ?></option>
          <?php endwhile; ?>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Estado factura</label>
        <select id="fEstado" class="form-select form-select-sm">
          <option value="">Todos</option>
          <option value="CANCELADA">Cancelada</option>
          <option value="PENDIENTE">Pendiente</option>
        </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="leyenda-origen small text-muted mb-2">
  <span style="background-color:#fff3b0"></span>Vendedores
  <span style="background-color:#ffd8a8" class="ms-3"></span>Clientes
  <span style="background-color:#b2f2bb" class="ms-3"></span>Productos
  <span style="background-color:#a5d8ff" class="ms-3"></span>Ventas (detalle)
  <span style="background-color:#dee2e6" class="ms-3"></span>Estado de factura (según saldo en cartera)
</div>

<div class="card shadow-sm">
  <div class="card-body">
    <table id="tblUtilidad" class="table table-striped table-hover align-middle w-100">
      <thead>
        <tr>
          <th class="col-ventas">Fecha</th>
          <th class="col-vendedores">Cod Regional</th>
          <th class="col-vendedores">Vendedor</th>
          <th class="col-clientes">Ciudad</th>
          <th class="col-clientes">Ruta</th>
          <th class="col-clientes">Barrio</th>
          <th class="col-productos">Categoría</th>
          <th class="col-productos">Subcategoría</th>
          <th class="col-productos">Marca</th>
          <th class="col-ventas">Cantidad</th>
          <th class="col-ventas">Valor neto</th>
          <th class="col-clientes">Cliente</th>
          <th class="col-clientes">Tipología</th>
          <th class="col-clientes">Negocio</th>
          <th class="col-productos">Nombre</th>
          <th class="col-ventas">Valor IVA</th>
          <th class="col-ventas">Factura</th>
          <th class="col-estado">Estado factura</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>
</div>

<?php
$extraScripts = <<<HTML
<script>
let table = new DataTable('#tblUtilidad', {
  processing: true,
  serverSide: true,
  scrollX: true,
  ajax: {
    url: '../api/datatable_utilidad_ventas.php',
    data: function (d) {
      Object.assign(d, {
        desde: document.getElementById('fDesde').value,
        hasta: document.getElementById('fHasta').value,
        cod_vendedor: document.getElementById('fVendedor').value,
        cod_regional: document.getElementById('fRegional').value,
        ciudad: document.getElementById('fCiudad').value,
        estado: document.getElementById('fEstado').value,
      });
    },
  },
  columns: [
    {data: 0}, {data: 1}, {data: 2}, {data: 3}, {data: 4}, {data: 5}, {data: 6}, {data: 7},
    {data: 8}, {data: 9}, {data: 10}, {data: 11}, {data: 12}, {data: 13}, {data: 14}, {data: 15}, {data: 16}, {data: 17},
  ],
  language: { url: 'https://cdn.datatables.net/plug-ins/1.13.11/i18n/es-ES.json' },
  pageLength: 25,
  lengthMenu: [10, 25, 50, 100],
});

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,
    cod_regional: document.getElementById('fRegional').value,
    ciudad: document.getElementById('fCiudad').value,
    estado: document.getElementById('fEstado').value,
  });
  window.location.href = '../api/exportar_utilidad_ventas.php?' + params.toString();
});
</script>
HTML;
require __DIR__ . '/../includes/footer.php';
?>
