<?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','ops']);

$rows = $pdo->query("
  SELECT v.*,
    (SELECT COUNT(*) FROM vehicle_photos p WHERE p.vehicle_id=v.id) AS photos_cnt,
    (SELECT COUNT(*) FROM documents d WHERE d.vehicle_id=v.id) AS docs_cnt
  FROM vehicles v
  ORDER BY v.entry_date DESC, v.id DESC
  LIMIT 300
")->fetchAll();

render_header($config, 'Viaturas');
?>
  <div class="card">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
      <h1 style="margin:0">Viaturas</h1>
      <a class="btn" href="vehicle_edit.php">+ Nova viatura</a>
    </div>
    <table>
      <thead><tr><th>Código</th><th>Entrada</th><th>Origem</th><th>Proprietário</th><th>Viatura</th><th>Matrícula</th><th>Estado</th><th>Imagens</th><th>Documentos</th><th>Abrir</th></tr></thead>
      <tbody>
      <?php foreach ($rows as $r): ?>
        <tr>
          <td><?= e($r['internal_code']) ?></td>
          <td><?= e((string)$r['entry_date']) ?></td>
          <td><span class="badge"><?= e((string)$r['source']) ?></span></td>
          <td><?= e(trim((string)($r['owner_type'] ?? '').' '.(string)($r['owner_name'] ?? ''))) ?></td>
          <td><?= e(trim($r['brand'].' '.$r['model'].' '.$r['version'])) ?></td>
          <td><?= e((string)$r['plate']) ?></td>
          <td><?= '<span class="badge">'.e($r['status']).'</span>' ?></td>
          <td><span class="badge"><?= (int)$r['photos_cnt'] ?></span></td>
          <td><span class="badge"><?= (int)$r['docs_cnt'] ?></span></td>
          <td><a href="vehicle_view.php?id=<?= (int)$r['id'] ?>">Ver</a> · <a href="vehicle_edit.php?id=<?= (int)$r['id'] ?>">Editar</a></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
<?php render_footer(); ?>
