<?php
declare(strict_types=1);

$config = require __DIR__ . '/app/config.php';
require __DIR__ . '/app/db.php';
require __DIR__ . '/app/auth.php';
require __DIR__ . '/app/helpers.php';
require __DIR__ . '/app/acl.php';
require __DIR__ . '/app/layout.php';

require_login($config);
require_role($config, ['admin','manager','finance','sales']);

$rows = $pdo->query("SELECT l.*, v.internal_code, v.brand, v.model FROM leads l LEFT JOIN vehicles v ON v.id=l.vehicle_id ORDER BY l.created_at DESC LIMIT 400")->fetchAll();

render_header($config, 'Leads');
?>
  <div class="card">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
      <h1 style="margin:0">Leads</h1>
      <a class="btn" href="lead_edit.php">+ Novo lead</a>
    </div>
    <table>
      <thead><tr><th>Data</th><th>Origem</th><th>Cliente</th><th>Viatura</th><th>Fase</th><th>Abrir</th></tr></thead>
      <tbody>
      <?php foreach ($rows as $r): ?>
        <tr>
          <td><?= e(substr($r['created_at'],0,10)) ?></td><td><?= e($r['source']) ?></td><td><?= e($r['name']) ?></td><td><?= e(trim(($r['internal_code']??'').' '.($r['brand']??'').' '.($r['model']??''))) ?></td><td><?= '<span class="badge">'.e($r['stage']).'</span>' ?></td>
          <td><a href="lead_edit.php?id=<?= (int)$r['id'] ?>">Ver</a></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
<?php render_footer(); ?>
