<?php
require_once __DIR__ . '/../config/database.php';
requireLogin();
requireAnyRole(['admin','super_admin']);
$db = Database::getInstance();

$roles = $db->getAll("SELECT * FROM roles ORDER BY role");
$pageTitle = 'Roles & Permissions';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Roles</h1>
    <p class="text-muted mb-0">Manage role default permissions</p>
  </div>
  <div>
    <a href="roles_edit.php" class="btn btn-primary">New Role</a>
  </div>
</div>

<div class="card">
  <div class="card-body">
    <?php if (empty($roles)): ?>
      <p class="text-muted">No roles defined.</p>
    <?php else: ?>
      <table class="table table-striped">
        <thead><tr><th>Role</th><th>Permissions</th><th>Action</th></tr></thead>
        <tbody>
          <?php foreach ($roles as $r): ?>
            <tr>
              <td><?php echo htmlspecialchars($r['role']); ?></td>
              <td><small><?php echo htmlspecialchars(is_string($r['permissions']) ? substr($r['permissions'], 0, 120) : ''); ?></small></td>
              <td>
                <a href="roles_edit.php?id=<?php echo (int)$r['id']; ?>" class="btn btn-sm btn-outline-secondary">Edit</a>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
