<?php
declare(strict_types=1);
require_once dirname(__DIR__, 2).'/config/functions.php';
require_role(['Admin','Ops']);

$cid = current_user()['company_id'] ?? null; if (!$cid) redirect(url_public('index.php'));

$stmt = db()->prepare("
  SELECT id, reg_no, type, make_model, capacity, current_status, last_service_date
  FROM vehicles
  WHERE company_id = :cid
  ORDER BY reg_no
");
$stmt->execute([':cid'=>$cid]);
$vehicles = $stmt->fetchAll();

include dirname(__DIR__, 2).'/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Vehicles</h1>
  <a href="add.php" class="btn btn-dark">Add Vehicle</a>
</div>

<div class="card shadow-sm">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead class="table-light">
        <tr>
          <th>Reg No</th><th>Type</th><th>Make/Model</th><th>Capacity</th><th>Status</th><th>Last Service</th><th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($vehicles as $v):
        $due = $v['last_service_date'] && (strtotime($v['last_service_date']) <= strtotime('-'.VEHICLE_SERVICE_INTERVAL_DAYS.' days'));
      ?>
        <tr>
          <td><?= e($v['reg_no']) ?></td>
          <td><?= e($v['type']) ?></td>
          <td><?= e($v['make_model']) ?></td>
          <td><?= e($v['capacity']) ?></td>
          <td>
            <?php if ($v['current_status']==='available'): ?>
              <span class="badge text-bg-success">Available</span>
            <?php elseif ($v['current_status']==='rented'): ?>
              <span class="badge text-bg-warning">Rented</span>
            <?php else: ?>
              <span class="badge text-bg-secondary">Maintenance</span>
            <?php endif; ?>
          </td>
          <td><?= $v['last_service_date'] ? e($v['last_service_date']) : '—' ?> <?= $due ? '<span class="badge text-bg-danger ms-2">Due</span>' : '' ?></td>
          <td class="text-end">
            <a class="btn btn-sm btn-outline-primary" href="edit.php?id=<?= (int)$v['id'] ?>">Edit</a>
            <form method="post" action="delete.php" class="d-inline">
              <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
              <input type="hidden" name="id" value="<?= (int)$v['id'] ?>">
              <button class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this vehicle?')">Delete</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if (!$vehicles): ?>
        <tr><td colspan="7" class="text-center text-muted py-4">No vehicles found.</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include dirname(__DIR__, 2).'/includes/footer.php'; ?>
