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

$users = $pdo->query("SELECT id, username, role FROM users ORDER BY username")->fetchAll();
$permissions = all_permissions();

$selectedUserId = (int)($_GET['user_id'] ?? ($users[0]['id'] ?? 0));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = (int)$_POST['user_id'];
    $selections = $_POST['permissions'] ?? []; // code => 'inherit' | 'grant' | 'deny'

    $del = $pdo->prepare("DELETE FROM user_permissions WHERE user_id = ? AND permission_code = ?");
    $ins = $pdo->prepare("INSERT INTO user_permissions (user_id, permission_code, state, granted_by) VALUES (?,?,?,?)
                           ON DUPLICATE KEY UPDATE state = VALUES(state), granted_by = VALUES(granted_by)");

    foreach ($permissions as $code => $p) {
        $choice = $selections[$code] ?? 'inherit';
        if ($choice === 'grant' || $choice === 'deny') {
            $ins->execute([$userId, $code, $choice, current_user()['id']]);
        } else {
            $del->execute([$userId, $code]);
        }
    }
    flash('success', 'Permissions updated.');
    redirect('permissions.php?user_id=' . $userId);
}

$selectedUser = null;
foreach ($users as $usr) if ($usr['id'] == $selectedUserId) $selectedUser = $usr;
$overrides = $selectedUser ? get_user_permission_overrides($pdo, $selectedUser['id']) : [];

$byCategory = [];
foreach ($permissions as $code => $p) { $byCategory[$p['category']][$code] = $p; }

$pageTitle = 'Permissions';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-2">User Permissions</h1>
<p class="text-slate-500 text-sm mb-6 max-w-2xl">
  Each role's <strong>defaults</strong> are set on the
  <a href="role_permissions.php" class="text-blue-600 hover:underline">Role Permissions</a> page. Use this
  page to override a specific person on top of that: <strong>Allow</strong> grants it to them even if their
  role doesn't include it, and <strong>Deny</strong> takes it away even if their role does — for example, a
  manager who shouldn't see other departments' requisitions, or a supervisor who should be able to issue
  stock. superadmin is unaffected by any of this.
</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 user</h2>
    <ul class="space-y-1">
      <?php foreach ($users as $usr): ?>
        <li>
          <a href="?user_id=<?= $usr['id'] ?>"
             class="block px-3 py-2 rounded-lg text-sm <?= $usr['id']==$selectedUserId ? 'bg-blue-700 text-white' : 'hover:bg-slate-100 text-slate-700' ?>">
            <?= e($usr['username']) ?>
            <span class="block text-xs <?= $usr['id']==$selectedUserId ? 'text-blue-100' : 'text-slate-400' ?> capitalize"><?= e($usr['role']) ?></span>
          </a>
        </li>
      <?php endforeach; ?>
    </ul>
  </div>

  <div class="md:col-span-3 bg-white rounded-xl shadow-sm border border-slate-200 p-6">
    <?php if ($selectedUser): ?>
      <?php if ($selectedUser['role'] === 'superadmin'): ?>
        <div class="bg-blue-50 border border-blue-200 text-blue-700 text-sm px-4 py-2.5 rounded-lg mb-5">
          This user is a <strong>superadmin</strong> — they always have full access regardless of anything set here.
        </div>
      <?php endif; ?>
      <h2 class="font-semibold mb-1">Permissions for <?= e($selectedUser['username']) ?></h2>
      <p class="text-xs text-slate-500 mb-5">Role: <span class="capitalize font-medium"><?= e($selectedUser['role']) ?></span></p>

      <form method="POST" class="space-y-6">
        <input type="hidden" name="user_id" value="<?= $selectedUser['id'] ?>">
        <?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-3">
              <?php foreach ($perms as $code => $p):
                  $byRole = role_has_permission($pdo, $selectedUser['role'], $code);
                  $current = $overrides[$code] ?? 'inherit';
              ?>
                <div class="flex items-center justify-between gap-4 <?= $selectedUser['role']==='superadmin' ? 'opacity-40 pointer-events-none' : '' ?>">
                  <label class="text-sm text-slate-700 flex-1">
                    <?= e($p['label']) ?>
                    <span class="block text-xs text-slate-400">Default for <?= e(ucfirst($selectedUser['role'])) ?>: <?= $byRole ? 'Allowed' : 'Not allowed' ?></span>
                  </label>
                  <select name="permissions[<?= $code ?>]" class="border border-slate-300 rounded-lg px-2 py-1.5 text-sm">
                    <option value="inherit" <?= $current==='inherit'?'selected':'' ?>>Default (<?= $byRole ? 'Allowed' : 'Not allowed' ?>)</option>
                    <option value="grant" <?= $current==='grant'?'selected':'' ?>>Allow</option>
                    <option value="deny" <?= $current==='deny'?'selected':'' ?>>Deny</option>
                  </select>
                </div>
              <?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 Permissions</button>
      </form>
    <?php else: ?>
      <p class="text-slate-400 text-sm">Select a user from the left to manage their permissions.</p>
    <?php endif; ?>
  </div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
