<?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, "");

$lines = file($usersFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$users = [];
foreach ($lines as $line) {
  $p = explode('|', $line);
  if (count($p) < 4) continue;
  $users[] = ['u'=>$p[0],'p'=>$p[1],'role'=>$p[2],'perm'=>$p[3]];
}

$action = $_GET['action'] ?? '';
$i = isset($_GET['i']) ? (int)$_GET['i'] : -1;

if ($action === 'delete' && $i >= 0 && isset($users[$i])) {
  array_splice($users, $i, 1);
  $out = array_map(fn($r)=>$r['u'].'|'.$r['p'].'|'.$r['role'].'|'.$r['perm'], $users);
  file_put_contents($usersFile, implode("\n",$out) . (count($out)? "\n":""));
  header("Location: /admin/users.php");
  exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $u = trim($_POST['username'] ?? '');
  $p = trim($_POST['password'] ?? '');
  $role = ($_POST['role'] ?? 'viewer') === 'admin' ? 'admin' : 'viewer';
  $perm = trim($_POST['permissions'] ?? '');

  if ($u !== '' && $p !== '') {
    $users[] = ['u'=>$u,'p'=>$p,'role'=>$role,'perm'=>$role==='admin'?'all':$perm];
    $out = array_map(fn($r)=>$r['u'].'|'.$r['p'].'|'.$r['role'].'|'.$r['perm'], $users);
    file_put_contents($usersFile, implode("\n",$out) . "\n");
    $added = true;
  }
}
?>
<section class="content-card">
  <h1 class="admin-title">👤 User Management</h1>
  <p style="opacity:.8;">Users are stored in <code>/admin/users.txt</code> using: <code>username|password|role|permissions</code></p>

  <?php if (!empty($added)): ?>
    <div class="msg success">User added.</div>
  <?php endif; ?>

  <div class="admin-wrap" style="margin-top:10px;">
    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Add User</h3>
      <form method="POST" class="form">
        <label>Username</label>
        <input class="input-field" name="username" required>

        <label>Password</label>
        <input class="input-field" name="password" required>

        <label>Role</label>
        <select class="input-field" name="role">
          <option value="viewer">Viewer</option>
          <option value="admin">Admin</option>
        </select>

        <label>Viewer permissions (comma-separated page names, without .php)</label>
        <input class="input-field" name="permissions" placeholder="about,news,requests">

        <button class="admin-btn primary" type="submit" style="margin-top:12px;">Add</button>
      </form>

      <div class="content-card" style="text-align:left;margin-top:14px;">
        <strong>Pages you can grant:</strong>
        <div style="opacity:.9;margin-top:6px;">
          about, news, schedule, djs, friends, requests, applications, contact, comments, poll, radiostats
        </div>
      </div>
    </section>

    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Existing Users</h3>
      <?php if (empty($users)): ?>
        <p>No users.</p>
      <?php else: ?>
        <?php foreach ($users as $idx => $u): ?>
          <div class="content-card" style="text-align:left;">
            <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;">
              <strong><?= smurf_h($u['u']) ?></strong>
              <a class="admin-btn" href="/admin/users.php?action=delete&i=<?= $idx ?>" onclick="return confirm('Delete this user?');">Delete</a>
            </div>
            <p style="margin:8px 0 0;opacity:.9;"><strong>Role:</strong> <?= smurf_h($u['role']) ?></p>
            <p style="margin:4px 0 0;opacity:.9;"><strong>Permissions:</strong> <?= smurf_h($u['perm']) ?></p>
            <p style="margin:4px 0 0;opacity:.75;"><strong>Password:</strong> <?= smurf_h($u['p']) ?></p>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </section>
  </div>
</section>

<?php include __DIR__ . '/includes/admin_footer.php'; ?>
