<?php
session_start();
require __DIR__ . '/includes/admin_lib.php';
include __DIR__ . '/includes/admin_header.php';

if (($_SESSION['role'] ?? '') !== 'admin') {
  http_response_code(403);
  die('<h1>Access Denied</h1><p>Admins only.</p>');
}

$usersFile = __DIR__ . '/users.txt';
if (!file_exists($usersFile)) file_put_contents($usersFile, '');

function load_users_rows(string $usersFile): array {
  $lines = file($usersFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
  $rows = [];
  foreach ($lines as $line) {
    $p = explode('|', $line);
    if (count($p) < 4) continue;
    $rows[] = ['u'=>$p[0],'p'=>$p[1],'role'=>$p[2],'perm'=>$p[3]];
  }
  return $rows;
}
function save_users_rows(string $usersFile, array $rows): void {
  $out = array_map(fn($r)=>$r['u'].'|'.$r['p'].'|'.$r['role'].'|'.$r['perm'], $rows);
  file_put_contents($usersFile, implode("\n", $out) . (count($out)?"\n":""));
}

$users = load_users_rows($usersFile);
$allAdminPages = array_map(fn($f)=>basename($f, '.php'), glob(__DIR__ . '/*.php'));
$skip = ['auth','login','logout','index','users'];
$grantPages = array_values(array_filter($allAdminPages, fn($p)=>!in_array($p, $skip, true)));
sort($grantPages);
$customPages = smurf_read_json(__DIR__ . '/../data/pages.json', []);
if (!is_array($customPages)) $customPages = [];

$action = $_GET['action'] ?? '';
$i = isset($_GET['i']) ? (int)$_GET['i'] : -1;
$editUser = ($action === 'edit' && $i >= 0 && isset($users[$i])) ? $users[$i] : ['u'=>'','p'=>'','role'=>'viewer','perm'=>''];
$editPerms = ($editUser['perm'] ?? '') === 'all' ? $grantPages : array_values(array_filter(array_map('trim', explode(',', (string)($editUser['perm'] ?? '')))));

if ($action === 'delete' && $i >= 0 && isset($users[$i])) {
  array_splice($users, $i, 1);
  save_users_rows($usersFile, $users);
  smurf_redirect_self(['deleted'=>1], ['action','i']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $mode = $_POST['mode'] ?? 'create';
  $editIndex = (int)($_POST['edit_index'] ?? -1);
  $u = trim($_POST['username'] ?? '');
  $p = trim($_POST['password'] ?? '');
  $role = ($_POST['role'] ?? 'viewer') === 'admin' ? 'admin' : 'viewer';
  $permArr = $_POST['permissions'] ?? [];
  if (!is_array($permArr)) $permArr = [];
  $permArr = array_values(array_intersect($grantPages, array_map('trim', $permArr)));
  $perm = $role === 'admin' ? 'all' : implode(',', $permArr);
  if ($u !== '') {
    if ($mode === 'update' && isset($users[$editIndex])) {
      if ($p === '') $p = (string)($users[$editIndex]['p'] ?? '');
      $users[$editIndex] = ['u'=>$u,'p'=>$p,'role'=>$role,'perm'=>$perm];
    } else {
      if ($p === '') {
        smurf_redirect_self(['err'=>'password'], ['action','i']);
      }
      $users[] = ['u'=>$u,'p'=>$p,'role'=>$role,'perm'=>$perm];
    }
    save_users_rows($usersFile, $users);
    smurf_redirect_self(['saved'=>1], ['action','i']);
  }
}
?>
<section class="content-card">
  <h1 class="admin-title">👤 User Management</h1>
  <p style="opacity:.8;">Permissions auto-update from real admin pages, including Events, Media Library, Backup/Restore and any new admin tools you add later. Use Edit User to update existing accounts when new pages appear.</p>
  <?php if ($action === 'edit'): ?><div class="msg success">Editing user: <strong><?= smurf_h($editUser['u'] ?? '') ?></strong></div><?php endif; ?>
  <?php if (!empty($_GET['saved'])): ?><div class="msg success">Saved.</div><?php endif; ?>
  <?php if (!empty($_GET['deleted'])): ?><div class="msg success">Deleted.</div><?php endif; ?>
  <?php if (($_GET['err'] ?? '') === 'password'): ?><div class="msg error">Password is required when creating a new user.</div><?php endif; ?>

  <div class="admin-wrap" style="margin-top:10px;">
    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;"><?= ($action === 'edit') ? 'Edit User' : 'Add User' ?></h3>
      <form method="POST" class="form">
        <input type="hidden" name="mode" value="<?= ($action === 'edit') ? 'update' : 'create' ?>">
        <input type="hidden" name="edit_index" value="<?= (int)$i ?>">

        <label>Username</label>
        <input class="input-field" name="username" required value="<?= smurf_h($editUser['u'] ?? '') ?>">

        <label>Password <?= ($action === 'edit') ? '<small style="opacity:.75;">(leave blank to keep current password)</small>' : '' ?></label>
        <input class="input-field" name="password" <?= ($action === 'edit') ? '' : 'required' ?> value="">

        <label>Role</label>
        <select class="input-field" name="role">
          <option value="viewer" <?= (($editUser['role'] ?? '') === 'viewer') ? 'selected' : '' ?>>Viewer</option>
          <option value="admin" <?= (($editUser['role'] ?? '') === 'admin') ? 'selected' : '' ?>>Admin</option>
        </select>

        <label>Viewer permissions</label>
        <div class="content-card" style="text-align:left;">
          <div style="opacity:.85;margin-bottom:10px;">Tick which admin pages this user can edit. Admin users automatically get everything.</div>
          <div class="perm-grid">
            <?php foreach ($grantPages as $gp): ?>
              <label class="perm-item">
                <input type="checkbox" name="permissions[]" value="<?= smurf_h($gp) ?>" <?= in_array($gp, $editPerms, true) ? 'checked' : '' ?>>
                <span><?= smurf_h(ucwords(str_replace(['_','-'],' ', $gp))) ?></span>
              </label>
            <?php endforeach; ?>
          </div>
        </div>

        <button class="admin-btn primary" type="submit" style="margin-top:12px;"><?= ($action === 'edit') ? 'Save User' : 'Add User' ?></button>
        <?php if ($action === 'edit'): ?><a class="admin-btn" href="/admin/users.php" style="margin-left:8px;">Cancel</a><?php endif; ?>
      </form>

      <div class="content-card" style="text-align:left;margin-top:14px;">
        <strong>Admin pages you can grant:</strong>
        <div style="opacity:.9;margin-top:6px;"><?= smurf_h(implode(', ', $grantPages)) ?></div>
        <?php if (!empty($customPages)): ?>
          <div style="opacity:.85;margin-top:12px;"><strong>Custom pages currently on site:</strong> <?= smurf_h(implode(', ', array_keys($customPages))) ?><br><small>These are managed through the <code>Pages</code> admin tool.</small></div>
        <?php endif; ?>
      </div>
    </section>

    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Existing Users</h3>
      <p style="opacity:.8; margin-top:0;">Use the Edit button to change permissions for an existing user, including newly added admin pages.</p>
      <?php if (empty($users)): ?>
        <p>No users.</p>
      <?php else: ?>
        <div class="users-list">
          <?php foreach ($users as $idx => $u): ?>
            <div class="user-row-card">
              <div class="user-row-main">
                <div class="user-row-name"><strong><?= smurf_h($u['u']) ?></strong></div>
                <div class="user-row-meta"><strong>Role:</strong> <?= smurf_h($u['role']) ?></div>
                <div class="user-row-meta"><strong>Permissions:</strong> <?= smurf_h($u['perm']) ?></div>
                <div class="user-row-meta"><strong>Password:</strong> <?= smurf_h($u['p']) ?></div>
              </div>
              <div class="user-row-actions">
                <a class="admin-btn primary" href="/admin/users.php?action=edit&i=<?= $idx ?>">✏ Edit User</a>
                <a class="admin-btn" href="/admin/users.php?action=delete&i=<?= $idx ?>" onclick="return confirm('Delete this user?');">Delete</a>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </section>
    </section>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>