<?php
require_once __DIR__ . '/config/config.php';
require_role(['admin']); // superadmin always passes

$permissions = all_permissions();
$roles = assignable_roles();

$selectedRole = $_GET['role'] ?? $roles[0];
if (!in_array($selectedRole, $roles)) $selectedRole = $roles[0];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $role = $_POST['role'];
    if (!in_array($role, $roles)) { flash('error', 'Invalid role.'); redirect('role_permissions.php'); }

    $checked = $_POST['permissions'] ?? [];
    $pdo->prepare("DELETE FROM role_permissions WHERE role = ?")->execute([$role]);
    $ins = $pdo->prepare("INSERT INTO role_permissions (role, permission_code) VALUES (?,?)");
    foreach ($checked as $code) {
        if (isset($permissions[$code])) $ins->execute([$role, $code]);
    }
    flash('success', "Default permissions updated for the \"$role\" role.");
    redirect('role_permissions.php?role=' . $role);
}

$currentCodes = get_role_permission_codes($pdo, $selectedRole);
$byCategory = [];
foreach ($permissions as $code => $p) { $byCategory[$p['category']][$code] = $p; }

$pageTitle = 'Role Permissions';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-2">Role Permissions</h1>
<p class="text-slate-500 text-sm mb-6 max-w-2xl">
  These are the <strong>defaults</strong> everyone with a given role gets, unless a specific person is
  overridden on the <a href="permissions.php" class="text-blue-600 hover:underline">Permissions</a> page.
  <code>superadmin</code> isn't listed — it always has everything. <code>admin</code> can be adjusted too,
  but be careful not to lock yourself out of a page you still need.
</p>

<div class="grid grid-cols-1 md:grid-cols-4 gap-6">
  <div class="md:col-span-1 bg-white rounded-xl shadow-sm border border-slate-200 p-4 h-fit">
    <h2 class="font-semibold text-sm mb-3">Select a role</h2>
    <ul class="space-y-1">
      <?php foreach ($roles as $r): ?>
        <li>
          <a href="?role=<?= $r ?>"
             class="block px-3 py-2 rounded-lg text-sm capitalize <?= $r===$selectedRole ? 'bg-blue-700 text-white' : 'hover:bg-slate-100 text-slate-700' ?>">
            <?= e($r) ?>
          </a>
        </li>
      <?php endforeach; ?>
    </ul>
  </div>

  <div class="md:col-span-3 bg-white rounded-xl shadow-sm border border-slate-200 p-6">
    <h2 class="font-semibold mb-5 capitalize">Default permissions for: <?= e($selectedRole) ?></h2>
    <form method="POST" class="space-y-6">
      <input type="hidden" name="role" value="<?= e($selectedRole) ?>">
      <?php foreach ($byCategory as $category => $perms): ?>
        <div>
          <h3 class="text-xs font-semibold uppercase tracking-wide text-slate-400 mb-2"><?= e($category) ?></h3>
          <div class="space-y-2">
            <?php foreach ($perms as $code => $p): ?>
              <label class="flex items-center gap-2 text-sm text-slate-700">
                <input type="checkbox" name="permissions[]" value="<?= $code ?>" <?= in_array($code, $currentCodes) ? 'checked' : '' ?>>
                <?= e($p['label']) ?>
              </label>
            <?php endforeach; ?>
          </div>
        </div>
      <?php endforeach; ?>
      <button class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-5 py-2.5 rounded-lg">Save Defaults for This Role</button>
    </form>
  </div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
