<?php
include(__DIR__ . '/../includes/auth.php');
$role = strtolower((string)($_SESSION['role'] ?? 'guest'));
$permissions = is_array($_SESSION['permissions'] ?? null) ? $_SESSION['permissions'] : [];
$CAN_VIEW = ah_user_can_access_page($role, $permissions, 'users');
$CAN_EDIT = ah_user_can_edit_page($role, $permissions, 'users');
if (!$CAN_VIEW) { header('Location: /login/index.php'); exit; }
require_once __DIR__ . '/../includes/auth_paths.php';
require_once __DIR__ . '/includes/admin_lib.php';

$users = ah_load_users();
if (!is_array($users)) $users = [];

$permissionMap = ah_permission_map();
$grantPages = array_keys($permissionMap);
$customPages = smurf_read_json(__DIR__ . '/../data/pages.json', []);
if (!is_array($customPages)) $customPages = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) { http_response_code(403); die('View only.'); }
  $action = $_POST['action'] ?? 'create';
  $username = trim((string)($_POST['username'] ?? ''));

  $selectedPermissions = [];
  foreach ((array)($_POST['permissions'] ?? []) as $perm) {
    $perm = ah_normalize_permission_key((string)$perm);
    if (in_array($perm, $grantPages, true)) {
      $selectedPermissions[$perm] = 'view';
    }
  }

  if ($action === 'create') {
    $password = (string)($_POST['password'] ?? '');
    $role = (($_POST['role'] ?? 'viewer') === 'admin') ? 'admin' : 'viewer';

    foreach ($users as $u) {
      if (($u['username'] ?? '') === $username) {
        die('Username already exists.');
      }
    }

    $users[] = [
      'username' => $username,
      'password' => password_hash($password, PASSWORD_DEFAULT),
      'role' => $role,
      'permissions' => $role === 'admin' ? [] : $selectedPermissions,
    ];
  }

  if ($action === 'update') {
    foreach ($users as &$u) {
      $u = ah_normalize_user_record(is_array($u) ? $u : []);
      if (($u['username'] ?? '') === $username) {
        if (!empty($_POST['password'])) {
          $u['password'] = password_hash((string)$_POST['password'], PASSWORD_DEFAULT);
        }
        if (($u['username'] ?? '') !== 'master') {
          $u['role'] = (($_POST['role'] ?? 'viewer') === 'admin') ? 'admin' : 'viewer';
        }
        if (($u['role'] ?? 'viewer') === 'viewer') {
          $u['permissions'] = $selectedPermissions;
        } else {
          $u['permissions'] = [];
        }
      }
    }
    unset($u);
  }

  if ($action === 'delete') {
    if ($username === 'master') {
      die('Master admin cannot be removed.');
    }
    $users = array_values(array_filter($users, fn($u) => ($u['username'] ?? '') !== $username));
  }

  ah_save_users($users);
  header('Location: manage_users.php');
  exit;
}

$pageTitle = 'User Manager';
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">👥 User Manager</h1>
  <p class="content-muted">All staff can open admin pages. Use the permissions below to choose which pages each non-admin user may control.</p>
  <?php if (!$CAN_EDIT): ?><div class="msg error">View-only mode — you can see this page, but only authorised users can change accounts or permissions.</div><?php endif; ?>
</section>

<section class="admin-users-layout">
  <div class="content-card">
    <h2 class="text-warning">➕ Create User</h2>
    <?php if ($CAN_EDIT): ?><form method="post" class="admin-form">
      <input type="hidden" name="action" value="create">
      <div class="admin-form-grid">
        <div>
          <label>Username</label>
          <input type="text" name="username" class="admin-input mb-2" placeholder="Username" required>
        </div>
        <div>
          <label>Password</label>
          <input type="password" name="password" class="admin-input mb-2" placeholder="Password" required>
        </div>
      </div>

      <label>Role</label>
      <select name="role" id="create-role" class="admin-select mb-3" onchange="togglePermissions(this.value, 'create-permissions')">
        <option value="admin">Admin (Full Access)</option>
        <option value="viewer">Viewer (Choose Pages)</option>
      </select>

      <div id="create-permissions" style="display:none;" class="mb-3">
        <label class="text-muted">Viewer page access</label>
        <div class="perm-grid perm-grid-checks">
          <?php foreach ($permissionMap as $key => $label): ?>
            <label class="perm-item perm-item-check">
              <input type="checkbox" name="permissions[]" value="<?= htmlspecialchars($key) ?>">
              <span><?= htmlspecialchars($label) ?></span>
            </label>
          <?php endforeach; ?>
        </div>
      </div>

      <button type="submit" class="admin-btn">Create User</button>
    </form><?php else: ?><p class="content-muted">User management controls are locked for your account.</p><?php endif; ?>
  </div>

  <div class="content-card">
    <h2 class="text-warning">📜 Existing Users</h2>
    <div class="users-list">
      <?php foreach ($users as $u): $u = ah_normalize_user_record(is_array($u) ? $u : []); $editPerms = array_keys($u['permissions'] ?? []); ?>
        <div class="user-row-card">
          <div>
            <h3><?= htmlspecialchars($u['username'] ?? '') ?> <span class="content-muted">(<?= htmlspecialchars($u['role']) ?>)</span></h3>
            <div class="user-row-meta">
              <?php if (($u['role'] ?? 'viewer') === 'viewer' && !empty($u['permissions'])): ?>
                <?php foreach ($u['permissions'] as $perm => $level): ?>
                  <span class="preview-badge"><?= htmlspecialchars($permissionMap[$perm] ?? $perm) ?></span>
                <?php endforeach; ?>
              <?php elseif (($u['role'] ?? '') === 'viewer'): ?>
                No page access selected yet.
              <?php else: ?>
                Full admin access.
              <?php endif; ?>
            </div>

            <form method="post" class="admin-form" style="margin-top:14px;">
              <input type="hidden" name="action" value="update">
              <input type="hidden" name="username" value="<?= htmlspecialchars($u['username'] ?? '') ?>">
              <div class="admin-form-grid">
                <div>
                  <label>Change password</label>
                  <input type="password" name="password" class="admin-input mb-2" placeholder="Leave blank to keep current">
                </div>
                <div>
                  <?php if (($u['username'] ?? '') !== 'master'): ?>
                    <label>Role</label>
                    <select name="role" class="admin-select mb-2" onchange="togglePermissions(this.value, 'perm-<?= htmlspecialchars($u['username'] ?? '') ?>')">
                      <option value="admin" <?= $u['role'] === 'admin' ? 'selected' : '' ?>>Admin</option>
                      <option value="viewer" <?= $u['role'] === 'viewer' ? 'selected' : '' ?>>Viewer</option>
                    </select>
                  <?php else: ?>
                    <label>Role</label>
                    <input type="text" class="admin-input mb-2" value="master" disabled>
                  <?php endif; ?>
                </div>
              </div>

              <div id="perm-<?= htmlspecialchars($u['username'] ?? '') ?>" style="display:<?= $u['role'] === 'viewer' ? 'block' : 'none' ?>;" class="mb-3">
                <label class="text-muted">Viewer page access</label>
                <div class="perm-grid perm-grid-checks">
                  <?php foreach ($permissionMap as $key => $label): ?>
                    <label class="perm-item perm-item-check">
                      <input type="checkbox" name="permissions[]" value="<?= htmlspecialchars($key) ?>" <?= in_array($key, $editPerms, true) ? 'checked' : '' ?>>
                      <span><?= htmlspecialchars($label) ?></span>
                    </label>
                  <?php endforeach; ?>
                </div>
              </div>

              <div class="user-row-actions">
                <?php if ($CAN_EDIT): ?><button type="submit" class="admin-btn">Save Changes</button><?php endif; ?>
                <?php if ($CAN_EDIT && ($u['username'] ?? '') !== 'master'): ?>
                  <button type="submit" formaction="manage_users.php" formmethod="post" class="admin-btn ghost" name="action" value="delete" onclick="return confirm('Delete this user?')">Delete User</button>
                <?php endif; ?>
              </div>
            </form>
          </div>
        </div>
      <?php endforeach; ?>
    </div>

    <?php if (!empty($customPages)): ?>
      <div class="content-card" style="margin-top:16px;">
        <strong>Custom pages on site:</strong>
        <div class="content-muted" style="margin-top:6px;">These stay managed through the Pages admin tool and are not separate admin permissions.</div>
      </div>
    <?php endif; ?>
  </div>
</section>

<script>
function togglePermissions(role, targetId) {
  var el = document.getElementById(targetId);
  if (!el) return;
  el.style.display = role === 'viewer' ? 'block' : 'none';
}
</script>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
