<?php require_once __DIR__ . '/includes/admin_bootstrap.php';
ugfx_require_permission('users');
$items = ugfx_admin_users();
$message = '';
$editing = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save';
    $current = ugfx_admin_current_user();
    if (ugfx_admin_role_rank((string)($current['role'] ?? '')) < 100) {
        $message = 'Only a Super Admin can manage admin users.';
    } elseif ($action === 'delete') {
        $username = (string)($_POST['username'] ?? '');
        foreach ($items as $existing) {
            if ((string)($existing['username'] ?? '') === $username && !empty($existing['super_admin_lock'])) {
                $message = 'Super Admin lock is enabled for that user.';
                $username = '';
                break;
            }
        }
        if ($username === ($current['username'] ?? '')) {
            $message = 'You cannot delete your own admin account while signed in.';
        } elseif ($username !== '') {
            $items = array_values(array_filter($items, fn($item) => (string)($item['username'] ?? '') !== $username));
            ugfx_write_json($ugfx['storage']['users'], $items);
            ugfx_admin_log('admin_user_deleted', ['username' => $username]);
            $message = 'Admin user deleted.';
        }
    } else {
        $username = trim((string)($_POST['username'] ?? ''));
        $password = (string)($_POST['password'] ?? '');
        $role = ugfx_normalize_role((string)($_POST['role'] ?? 'editor'));
        $permissions = array_values(array_intersect(array_keys(ugfx_admin_all_permissions()), (array)($_POST['permissions'] ?? [])));
        if ($username !== '') {
            $existingUser = null;
            foreach ($items as $it) if ((string)($it['username'] ?? '') === $username) { $existingUser = $it; break; }
            if (!empty($existingUser['super_admin_lock']) && ($current['username'] ?? '') !== $username && ugfx_admin_role_rank((string)($current['role'] ?? '')) < 100) {
                $message = 'Only a Super Admin can edit that locked account.';
            } else {
                if ($role === 'superadmin' && ($current['username'] ?? '') !== $username) {
                    $message = 'Create or upgrade Super Admin accounts only while signed in as that account owner.';
                } else {
                $entry = [
                    'username' => $username,
                    'password' => $password !== '' ? password_hash($password, PASSWORD_DEFAULT) : (string)($existingUser['password'] ?? ''),
                    'role' => $role,
                    'permissions' => $permissions ?: ugfx_admin_permission_defaults($role),
                    'temp_login' => isset($_POST['temp_login']) ? 1 : 0,
                    'super_admin_lock' => isset($_POST['super_admin_lock']) ? 1 : (!empty($existingUser['super_admin_lock']) ? 1 : 0),
                    'last_login' => (string)($existingUser['last_login'] ?? ''),
                    'last_seen' => (string)($existingUser['last_seen'] ?? ''),
                ];
                $updated = false;
                foreach ($items as &$item) {
                    if ((string)($item['username'] ?? '') === $username) {
                        $item = $entry;
                        $updated = true;
                        break;
                    }
                }
                unset($item);
                if (!$updated) $items[] = $entry;
                ugfx_write_json($ugfx['storage']['users'], $items);
                ugfx_admin_log($updated ? 'admin_user_updated' : 'admin_user_created', ['username' => $username, 'role' => $role]);
                $message = $updated ? 'Admin user updated.' : 'Admin user created.';
                }
            }
        }
    }
    $items = ugfx_admin_users();
}
$onlineUsers = ugfx_admin_online_users();
$editId = (string)($_GET['edit'] ?? '');
foreach ($items as $item) if ((string)($item['username'] ?? '') === $editId) { $editing = $item; break; }
$adminTitle='Users & Roles'; include __DIR__ . '/includes/admin_header.php'; ?>
<?php if ($message): ?><div class="ugfx-admin-alert"><?= htmlspecialchars($message) ?></div><?php endif; ?>
<div class="ugfx-admin-grid">
  <div class="ugfx-card p-4"><div class="ugfx-micro-label">ACCESS CONTROL</div><h3><?= $editing ? 'Edit admin user' : 'Create admin user' ?></h3><form method="post" class="ugfx-admin-form row g-3"><div class="col-md-6"><input class="form-control" name="username" placeholder="Username" required value="<?= htmlspecialchars((string)($editing['username'] ?? '')) ?>"></div><div class="col-md-6"><input class="form-control" name="password" placeholder="Password<?= $editing ? ' (leave blank to keep current)' : '' ?>"></div><div class="col-md-6"><select class="form-select" name="role" data-role-preset><option value="">Preset role…</option><?php foreach (['superadmin','admin','editor','dj'] as $role): ?><option value="<?= $role ?>" <?= (($editing['role'] ?? 'editor') === $role) ? 'selected' : '' ?>><?= ucfirst($role) ?></option><?php endforeach; ?></select></div><div class="col-md-6 d-flex align-items-center gap-3 flex-wrap"><div class="form-check"><input class="form-check-input" type="checkbox" name="temp_login" id="tempLogin" <?= !empty($editing['temp_login']) ? 'checked' : '' ?>><label class="form-check-label" for="tempLogin">Temp local login</label></div><div class="form-check"><input class="form-check-input" type="checkbox" name="super_admin_lock" id="superAdminLock" <?= !empty($editing['super_admin_lock']) ? 'checked' : '' ?>><label class="form-check-label" for="superAdminLock">Super Admin lock</label></div></div><div class="col-12"><label class="form-label">Per-page permissions</label><div class="ugfx-admin-empty mb-3">Ticked = access allowed. Unticked = blocked. Use the preset role dropdown to auto-fill these. Super Admin lock prevents delete and protects the account.</div><div class="row g-2"><?php $activePerms = (array)($editing['permissions'] ?? ugfx_admin_permission_defaults((string)($editing['role'] ?? 'editor'))); foreach (ugfx_admin_all_permissions() as $key => $label): ?><div class="col-md-4"><label class="ugfx-chip d-flex gap-2 align-items-center"><input type="checkbox" data-permission-box name="permissions[]" value="<?= htmlspecialchars($key) ?>" <?= in_array($key, $activePerms, true) ? 'checked' : '' ?>> <span><?= htmlspecialchars($label) ?></span></label></div><?php endforeach; ?></div></div><div class="col-12 d-flex gap-2 flex-wrap"><button class="btn ugfx-btn-primary">Save user</button><?php if ($editing): ?><a class="btn ugfx-btn-outline" href="users.php">New user</a><?php endif; ?></div></form><div class="ugfx-admin-empty mt-3">Passwords are now hashed automatically when you save a user. Temp local login still works while you are on your local server. Keep <strong>admin / letmein123</strong> until you move this live, then change it.</div></div>
  <div class="ugfx-card p-4"><div class="ugfx-admin-toolbar"><div><div class="ugfx-micro-label">CURRENT ADMINS</div><h3 class="mb-0">Manage roles</h3></div><div class="d-flex gap-2 flex-wrap"><span class="ugfx-chip"><?= count($items) ?> users</span><span class="ugfx-chip ugfx-chip-blue"><?= count($onlineUsers) ?> online now</span></div></div><div class="ugfx-admin-list"><?php foreach ($items as $item): ?><div class="ugfx-admin-item"><h4><?= htmlspecialchars((string)($item['username'] ?? '')) ?></h4><div class="ugfx-admin-meta"><span><?= htmlspecialchars(ucfirst((string)($item['role'] ?? 'admin'))) ?></span><span><?= !empty($item['temp_login']) ? 'Temp local' : 'Standard' ?></span><span><?= count((array)($item['permissions'] ?? [])) ?> permissions</span><?php if (!empty($item['super_admin_lock'])): ?><span>Super Admin lock</span><?php endif; ?><span><?= in_array($item, $onlineUsers, true) ? 'Online now' : 'Offline' ?></span></div><div class="mt-2 text-secondary">Permissions: <?= htmlspecialchars(implode(', ', (array)($item['permissions'] ?? []))) ?></div><div class="small text-secondary mt-2">Last login: <?= htmlspecialchars((string)($item['last_login'] ?? 'Never')) ?> · Last seen: <?= htmlspecialchars((string)($item['last_seen'] ?? 'Never')) ?></div><div class="ugfx-admin-actions"><a class="btn ugfx-btn-outline btn-sm" href="users.php?edit=<?= urlencode((string)($item['username'] ?? '')) ?>">Edit</a><?php if (empty($item['super_admin_lock']) && (string)($item['username'] ?? '') !== 'admin'): ?><form method="post" onsubmit="return confirm('Delete this admin user?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="username" value="<?= htmlspecialchars((string)($item['username'] ?? '')) ?>"><button class="btn btn-outline-danger btn-sm">Delete</button></form><?php else: ?><span class="ugfx-chip">Protected</span><?php endif; ?></div></div><?php endforeach; ?></div></div>
</div>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
<script>
(function(){
 const presets = {
  superadmin: ["dashboard", "chat", "news", "events", "pages", "friends", "djs", "schedule", "requests", "contact", "applications", "users", "media"],
  admin: ["dashboard", "chat", "news", "events", "pages", "friends", "djs", "schedule", "requests", "contact", "applications", "media"],
  editor: ["dashboard", "chat", "news", "events", "pages", "friends", "djs", "media"],
  dj: ["dashboard", "chat"]
 };
 const roleSelect=document.querySelector('[data-role-preset]');
 const boxes=[...document.querySelectorAll('[data-permission-box]')];
 if(!roleSelect) return;
 roleSelect.addEventListener('change',()=>{
   const vals=presets[roleSelect.value]||[];
   if(!vals.length) return;
   boxes.forEach(b=>{b.checked=vals.includes(b.value);});
 });
})();
</script>