<?php
require_once '../classes/Auth.php';
require_once '../classes/UserModel.php';
$auth = new Auth();
$user = $auth->guard();
if (!$user || $user['role'] !== 'admin') { http_response_code(403); die('Access denied'); }
$um = new UserModel();
$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $um->createUser($_POST['username'], $_POST['name'], $_POST['password'], $_POST['role']);
  $msg = 'User added successfully.';
}
if (isset($_GET['delete'])) {
  $um->deleteUser($_GET['delete']);
  $msg = 'User deleted.';
}
$users = $um->listUsers();
include 'partials/header.php';
include 'partials/sidebar.php';
?>
<div class="container-fluid">
  <h1 class="h3 mb-4 text-gray-800">Manage Users</h1>
  <?php if($msg): ?><div class="alert alert-success"><?= $msg ?></div><?php endif; ?>
  <div class="card shadow mb-4">
    <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Add User</h6></div>
    <div class="card-body">
      <form class="row g-3" method="POST">
        <div class="col-md-3"><input name="username" class="form-control" placeholder="username" required></div>
        <div class="col-md-3"><input name="name" class="form-control" placeholder="Full Name" required></div>
        <div class="col-md-2"><input name="password" class="form-control" placeholder="Password" required></div>
        <div class="col-md-2">
          <select name="role" class="form-select"><option value="staff">Staff</option><option value="admin">Admin</option><option value="viewer">Viewer</option></select>
        </div>
        <div class="col-md-2"><button class="btn btn-primary w-100">Add</button></div>
      </form>
    </div>
  </div>
  <div class="card shadow mb-4">
    <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">User List</h6></div>
    <div class="card-body">
      <div class="table-responsive"><table class="table table-bordered">
      <thead><tr><th>ID</th><th>Name</th><th>User Name</th><th>Role</th><th>Created</th><th></th></tr></thead>
      <tbody><?php foreach($users as $u): ?><tr><td><?= $u['id'] ?></td><td><?= htmlspecialchars($u['name']) ?></td><td><?= htmlspecialchars($u['username']) ?></td><td><?= htmlspecialchars($u['role']) ?></td><td><?= htmlspecialchars($u['created_at']) ?></td><td><a href="?delete=<?= $u['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete user?')"><i class="fas fa-trash"></i></a></td></tr><?php endforeach; ?></tbody>
      </table></div>
    </div>
  </div>
</div>
<?php include 'partials/footer.php'; ?>