<?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 d.id, d.name, d.email, d.phone, d.is_active,
         d.own_vehicle_reg_no,
         (SELECT COUNT(*) FROM driver_documents dd WHERE dd.driver_id = d.id) AS doc_count
  FROM drivers d
  WHERE d.company_id = :cid
  ORDER BY d.name
");
$stmt->execute([':cid'=>$cid]);
$drivers = $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">Drivers</h1>
  <a href="add.php" class="btn btn-dark">Add Driver</a>
</div>

<div class="card shadow-sm">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead class="table-light">
        <tr>
          <th>Name</th><th>Email</th><th>Phone</th><th>Own Reg</th><th>Docs</th><th>Status</th><th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($drivers as $d): ?>
        <tr>
          <td><?= e($d['name']) ?></td>
          <td><?= e($d['email']) ?></td>
          <td><?= e($d['phone']) ?></td>
          <td><?= e($d['own_vehicle_reg_no'] ?: '—') ?></td>
          <td><span class="badge text-bg-secondary"><?= (int)$d['doc_count'] ?></span></td>
          <td>
            <?= $d['is_active'] ? '<span class="badge text-bg-success">Active</span>'
                                : '<span class="badge text-bg-secondary">Inactive</span>' ?>
          </td>
          <td class="text-end">
            <a href="view.php?id=<?= (int)$d['id'] ?>" class="btn btn-sm btn-outline-secondary">View</a>
            <a href="edit.php?id=<?= (int)$d['id'] ?>" class="btn btn-sm btn-outline-primary">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)$d['id'] ?>">
              <button class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this driver?')">Delete</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if (!$drivers): ?>
        <tr><td colspan="7" class="text-center text-muted py-4">No drivers found.</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include dirname(__DIR__, 2) . '/includes/footer.php'; ?>
