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

$pageTitle = 'Consulta de Vendedores';
$activeMenu = 'consultas';
$activePage = 'vendedores';
$basePath = '..';

$conn = db();
$sql = "SELECT v.cod_vendedor, v.nombre, v.telefono, v.canal, v.cod_regional,
               (SELECT COUNT(*) FROM clientes c WHERE c.cod_vendedor = v.cod_vendedor) AS num_clientes,
               (SELECT COALESCE(SUM(car.saldo),0) FROM cartera car WHERE car.cod_vendedor = v.cod_vendedor) AS saldo_cartera
        FROM vendedores v
        ORDER BY v.nombre";
$result = $conn->query($sql);

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-person-badge"></i> Vendedores</h4>
</div>

<div class="card shadow-sm">
  <div class="card-body">
    <table id="tblVendedores" class="table table-striped table-hover align-middle w-100">
      <thead>
        <tr><th>Código</th><th>Nombre</th><th>Teléfono</th><th>Canal</th><th>Regional</th><th>Clientes</th><th>Cartera pendiente</th></tr>
      </thead>
      <tbody>
        <?php while ($r = $result->fetch_assoc()): ?>
        <tr>
          <td><?= h($r['cod_vendedor']) ?></td>
          <td><?= h($r['nombre']) ?></td>
          <td><?= h($r['telefono']) ?></td>
          <td><?= h($r['canal']) ?></td>
          <td><?= h($r['cod_regional']) ?></td>
          <td><?= (int) $r['num_clientes'] ?></td>
          <td><?= money((float) $r['saldo_cartera']) ?></td>
        </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div>
</div>

<?php
$extraScripts = <<<HTML
<script>
new DataTable('#tblVendedores', {
  language: { url: 'https://cdn.datatables.net/plug-ins/1.13.11/i18n/es-ES.json' },
  pageLength: 25,
});
</script>
HTML;
require __DIR__ . '/../includes/footer.php';
?>
