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

$companyId = current_user()['company_id'] ?? null;
if (!$companyId) redirect('../../public/index.php');

$stmt = db()->prepare("
  SELECT u.id, u.name, u.email, u.last_login, r.name AS role_name
  FROM users u
  JOIN roles r ON r.id = u.role_id
  WHERE u.company_id = :cid
  ORDER BY u.name
");
$stmt->execute([':cid' => $companyId]);
$users = $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">Users</h1>
  <a href="add.php" class="btn btn-dark">Add User</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>Role</th>
          <th>Last Login</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($users as $u): ?>
          <tr>
            <td><?= e($u['name']) ?></td>
            <td><?= e($u['email']) ?></td>
            <td><span class="badge text-bg-secondary"><?= e($u['role_name']) ?></span></td>
            <td><?= $u['last_login'] ? e($u['last_login']) : '—' ?></td>
            <td class="text-end">
              <a href="edit.php?id=<?= (int)$u['id'] ?>" class="btn btn-sm btn-outline-primary">Edit</a>
              <?php if ((int)$u['id'] !== (int)current_user()['id']): ?>
              <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)$u['id'] ?>">
                <button class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this user? This cannot be undone.')">Delete</button>
              </form>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if (!$users): ?>
          <tr><td colspan="5" class="text-center text-muted py-4">No users found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include dirname(__DIR__, 2) . '/includes/footer.php'; ?>
