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

if (($_SESSION['role'] ?? '') !== 'admin') {
  smurf_admin_denied('Admins only.');
}

$usersJson = 'C:\inetpub\Authentication\hometime\users.json';
$localUsersFile = __DIR__ . '/users.txt';
$masterCfgFile = __DIR__ . '/config/master_admin.php';

function ht_load_master_cfg(string $path): array {
  $cfg = ['enabled' => true, 'username' => 'admin', 'password' => 'masterdev1'];
  if (is_file($path)) {
    $loaded = include $path;
    if (is_array($loaded)) $cfg = array_merge($cfg, $loaded);
  }
  return $cfg;
}
function ht_load_json_users(string $path): array {
  if (!is_file($path)) return [];
  $raw = json_decode((string)file_get_contents($path), true);
  return is_array($raw) ? $raw : [];
}
function ht_save_json_users(string $path, array $users): bool {
  $dir = dirname($path);
  if (!is_dir($dir)) @mkdir($dir, 0777, true);
  return file_put_contents($path, json_encode($users, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "
") !== false;
}
function ht_save_local_users(string $path, array $users): bool {
  $lines = [];
  foreach ($users as $name => $row) {
    $pages = (array)($row['pages'] ?? []);
    $perm = in_array('*', $pages, true) ? 'all' : implode(',', array_map(fn($p)=>basename((string)$p, '.php'), $pages));
    $lines[] = $name . '|' . (string)($row['password'] ?? '') . '|' . (string)($row['role'] ?? 'viewer') . '|' . $perm;
  }
  return file_put_contents($path, implode("
", $lines) . (count($lines) ? "
" : '')) !== false;
}
function ht_perm_pages_to_storage(array $permPages, string $role): array {
  if ($role === 'admin') return ['*'];
  return array_values(array_map(fn($p) => $p . '.php', $permPages));
}

$users = ht_load_json_users($usersJson);
if (!is_array($users)) $users = [];
$masterCfg = ht_load_master_cfg($masterCfgFile);
$externalWriteOk = is_file($usersJson) ? is_writable($usersJson) : is_writable(dirname($usersJson));

$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);

$action = $_GET['action'] ?? '';
$u = (string)($_GET['u'] ?? '');
$editKey = ($action === 'edit' && isset($users[$u])) ? $u : '';
$editUser = $editKey !== '' ? $users[$editKey] : ['password'=>'','role'=>'viewer','pages'=>[]];
$editPerms = in_array('*', $editUser['pages'] ?? [], true) ? $grantPages : array_values(array_map(fn($p)=>basename((string)$p, '.php'), (array)($editUser['pages'] ?? [])));

if ($action === 'delete' && $u !== '' && isset($users[$u]) && !in_array($u, [(string)($masterCfg['username'] ?? 'admin'),'Musicman'], true)) {
  unset($users[$u]);
  $savedExternal = ht_save_json_users($usersJson, $users);
  ht_save_local_users($localUsersFile, $users);
  if (!$savedExternal) smurf_redirect_self(['deleted'=>1,'warn'=>'external-save'], ['action','u']);
  smurf_redirect_self(['deleted'=>1], ['action','u']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $mode = $_POST['mode'] ?? 'create';
  $existing = trim((string)($_POST['existing_user'] ?? ''));
  $username = trim((string)($_POST['username'] ?? ''));
  $password = (string)($_POST['password'] ?? '');
  $role = ($_POST['role'] ?? 'viewer') === 'admin' ? 'admin' : (($_POST['role'] ?? '') === 'dj' ? 'dj' : 'viewer');
  $permArr = $_POST['permissions'] ?? [];
  if (!is_array($permArr)) $permArr = [];
  $permArr = array_values(array_intersect($grantPages, array_map('trim', $permArr)));

  if ($mode === 'update' && $existing !== '' && isset($users[$existing])) {
    if ($password === '') $password = (string)($users[$existing]['password'] ?? '');
    $newName = $username !== '' ? $username : $existing;
    unset($users[$existing]);
    $users[$newName] = ['password'=>$password, 'role'=>$role, 'pages'=>ht_perm_pages_to_storage($permArr, $role)];
  } elseif ($username !== '' && $password !== '') {
    $users[$username] = ['password'=>$password, 'role'=>$role, 'pages'=>ht_perm_pages_to_storage($permArr, $role)];
  } else {
    smurf_redirect_self(['err'=>'missing'], ['action','u']);
  }

  $savedExternal = ht_save_json_users($usersJson, $users);
  ht_save_local_users($localUsersFile, $users);
  if (!$savedExternal) smurf_redirect_self(['saved'=>1,'warn'=>'external-save'], ['action','u']);
  smurf_redirect_self(['saved'=>1], ['action','u']);
}

$pageTitle = 'User Management — Home Time Radio';
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">👤 User Management</h1>
  <p style="opacity:.8;">Managed users are stored in <code><?= smurf_h($usersJson) ?></code> on the live server and mirrored to <code><?= smurf_h($localUsersFile) ?></code> locally. Temporary test login is controlled by <code><?= smurf_h($masterCfgFile) ?></code>.</p>
  <?php if ($action === 'edit'): ?><div class="msg success">Editing user: <strong><?= smurf_h($editKey) ?></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'] ?? '') === 'missing'): ?><div class="msg error">Username and password are required for new users.</div><?php endif; ?>
  <?php if (($_GET['warn'] ?? '') === 'external-save'): ?><div class="msg error">Saved locally, but the live users JSON could not be written.</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="existing_user" value="<?= smurf_h($editKey) ?>">

        <label>Username</label>
        <input class="input-field" name="username" required value="<?= smurf_h($editKey) ?>">

        <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="dj" <?= (($editUser['role'] ?? '') === 'dj') ? 'selected' : '' ?>>DJ</option>
          <option value="admin" <?= (($editUser['role'] ?? '') === 'admin') ? 'selected' : '' ?>>Admin</option>
        </select>

        <label>Page permissions</label>
        <div class="content-card" style="text-align:left;">
          <div style="opacity:.85;margin-bottom:10px;">Tick which admin tools this user may access.</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(ucwords(str_replace(['-','_'], ' ', $p))) ?></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">Live users JSON is not writable right now: <code><?= smurf_h($usersJson) ?></code></div><?php endif; ?>
      <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 $name => $row): $pages = (array)($row['pages'] ?? []); ?>
            <tr>
              <td><?= smurf_h($name) ?></td>
              <td><?= smurf_h((string)($row['role'] ?? 'viewer')) ?></td>
              <td><?= smurf_h(in_array('*', $pages, true) ? 'all' : implode(', ', array_map(fn($p)=>basename((string)$p, '.php'), $pages))) ?></td>
              <td>
                <a class="admin-btn" href="?action=edit&u=<?= urlencode($name) ?>">Edit</a>
                <?php if (!in_array($name, [(string)($masterCfg['username'] ?? 'admin'),'Musicman'], true)): ?>
                  <a class="admin-btn danger" href="?action=delete&u=<?= urlencode($name) ?>" onclick="return confirm('Delete this user?')">Delete</a>
                <?php else: ?>
                  <span class="admin-btn" style="opacity:.5;pointer-events:none;">Protected</span>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </section>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
