<?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 s.*, v.internal_code, v.brand, v.model, v.plate, c.name AS customer_name FROM sales s JOIN vehicles v ON v.id=s.vehicle_id JOIN customers c ON c.id=s.customer_id ORDER BY s.sale_date DESC, s.id DESC LIMIT 300")->fetchAll();

render_header($config, 'Vendas');
?>
  <div class="card">
    <h1 style="margin-top:0">Vendas</h1>
    <table>
      <thead><tr><th>Data</th><th>Viatura</th><th>Matrícula</th><th>Cliente</th><th>Valor</th></tr></thead>
      <tbody>
      <?php foreach ($rows as $r): ?>
        <tr>
          <td><?= e($r['sale_date']) ?></td><td><?= e(trim($r['internal_code'].' '.$r['brand'].' '.$r['model'])) ?></td><td><?= e((string)$r['plate']) ?></td><td><?= e((string)$r['customer_name']) ?></td><td><?= e(money($r['sale_price'])) ?></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
<?php render_footer(); ?>
