<?php
session_start();
require __DIR__ . '/includes/admin_lib.php';
if (($_SESSION['role'] ?? '') !== 'admin') { http_response_code(403); die('<h1>Access Denied</h1><p>Admins only.</p>'); }
$usersFile = 'C:/inetpub/Authentication/thunder/users.json';
function thunder_users_load(string $usersFile): array { if (!file_exists($usersFile)) return []; $decoded = json_decode((string)file_get_contents($usersFile), true); if (!is_array($decoded)) return []; $rows = $decoded['users'] ?? $decoded; $out = []; foreach ((array)$rows as $row) { if (!is_array($row)) continue; $u = trim((string)($row['username'] ?? '')); if ($u === '') continue; $out[] = ['u'=>$u,'p'=>(string)($row['password'] ?? ''),'role'=>((string)($row['role'] ?? 'viewer') === 'admin') ? 'admin' : 'viewer','perm'=>(string)($row['permissions'] ?? ''),'display_name'=>(string)($row['display_name'] ?? '')]; } return $out; }
function thunder_users_save(string $usersFile, array $rows): bool { $out = ['users' => []]; foreach ($rows as $r) { if (!is_array($r)) continue; $out['users'][] = ['username' => (string)($r['u'] ?? ''),'password' => (string)($r['p'] ?? ''),'role' => ((string)($r['role'] ?? 'viewer') === 'admin') ? 'admin' : 'viewer','permissions' => (string)($r['perm'] ?? ''),'display_name' => (string)($r['display_name'] ?? ($r['u'] ?? ''))]; } $dir = dirname($usersFile); if (!is_dir($dir)) @mkdir($dir, 0775, true); return @file_put_contents($usersFile, json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) !== false; }
$users = thunder_users_load($usersFile); $externalWriteOk = is_file($usersFile) ? is_writable($usersFile) : is_writable(dirname($usersFile));
$permissionMap = [
    'pages' => 'Page Builder',
    'newsreel_admin' => 'News',
    'events' => 'Events',
    'top50' => 'Top 50',
    'schedule' => 'Schedule',
    'about' => 'About',
    'media' => 'Media Library',
    'navigation' => 'Navigation',
    'djs' => 'DJs',
    'friends' => 'Friends',
    'fans' => 'Fans',
    'contact' => 'Contact Messages',
    'applications' => 'Join the Team',
    'requests' => 'Requests',
    'comments' => 'Comments',
    'chat' => 'Live Chat',
    'player' => 'Popout Player',
    'radiostats' => 'Radio Stats',
    'backup' => 'Backup / Restore',
    'poll' => 'Poll Manager',
    'admin-webstats' => 'Web Stats',
];
$grantPages = array_keys($permissionMap);
$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); thunder_users_save($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((string)($_POST['username'] ?? '')); $p = trim((string)($_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,'display_name'=>(string)($users[$editIndex]['display_name'] ?? $u)]; } else { if ($p === '') { smurf_redirect_self(['err'=>'password'], ['action','i']); } $users[] = ['u'=>$u,'p'=>$p,'role'=>$role,'perm'=>$perm,'display_name'=>$u]; } thunder_users_save($usersFile, $users); smurf_redirect_self(['saved'=>1], ['action','i']); } }
include __DIR__ . '/includes/admin_header.php'; ?>
<section class="content-card"><h1 class="admin-title">👤 User Management</h1><p style="opacity:.8;">Users are stored in <code><?= smurf_h($usersFile) ?></code>.</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 admin-users-layout" 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 viewer may edit/view.</div><div class="grid-2"><?php foreach ($grantPages as $p): ?><label style="display:flex;gap:8px;align-items:center;"><input type="checkbox" name="permissions[]" value="<?= smurf_h($p) ?>" <?= in_array($p, $editPerms, true) ? 'checked' : '' ?>><span><?= smurf_h($permissionMap[$p] ?? ucwords(str_replace(['-','_'], ' ', $p))) ?></span></label><?php endforeach; ?><?php foreach ($customPages as $cp): $slug = trim((string)($cp['slug'] ?? '')); if ($slug === '') continue; ?><label style="display:flex;gap:8px;align-items:center;"><input type="checkbox" disabled><span><?= smurf_h(ucwords(str_replace(['-','_'], ' ', $slug))) ?> <small style="opacity:.7;">(custom page)</small></span></label><?php endforeach; ?></div><p style="opacity:.75;margin-top:10px;">Admins always get full access automatically.</p></div><button class="admin-btn primary" type="submit" style="margin-top:14px;"><?= ($action === 'edit') ? 'Update User' : 'Create User' ?></button></form></section>
<section class="content-card" style="text-align:left;"><h3 style="margin-top:0;">Existing Users</h3><?php if (!$externalWriteOk): ?><div class="msg error">Users file is not writable right now: <code><?= smurf_h($usersFile) ?></code></div><?php endif; ?><div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>Username</th><th>Role</th><th>Permissions</th><th style="width:170px;">Actions</th></tr></thead><tbody><?php if (!$users): ?><tr><td colspan="4">No users yet.</td></tr><?php else: foreach ($users as $idx => $row): ?><tr><td><?= smurf_h($row['u']) ?></td><td><?= smurf_h($row['role']) ?></td><td><?php if (($row['perm'] ?? '') === 'all'): ?><span class="badge">All access</span><?php else: ?><div class="perm-badges"><?php foreach (array_filter(array_map('trim', explode(',', (string)($row['perm'] ?? '')))) as $permKey): ?><span class="badge"><?= smurf_h($permissionMap[$permKey] ?? ucwords(str_replace(['-','_'], ' ', $permKey))) ?></span><?php endforeach; ?></div><?php endif; ?></td><td class="actions-cell"><a class="admin-btn" href="?action=edit&i=<?= (int)$idx ?>">Edit</a><a class="admin-btn danger" href="?action=delete&i=<?= (int)$idx ?>" onclick="return confirm('Delete this user?')">Delete</a></td></tr><?php endforeach; endif; ?></tbody></table></div></section></div></section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
