<?php
include(__DIR__ . '/../includes/auth.php');
requireRole(['master','admin']);
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') {
  $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">Set each viewer account to only the admin pages you want them to see. Admin users still get full access automatically.</p>
</section>

<section class="admin-users-layout">
  <div class="content-card">
    <h2 class="text-warning">➕ Create User</h2>
    <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>
  </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">
                <button type="submit" class="admin-btn">Save Changes</button>
                <?php if (($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'; ?>
