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

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

$usersJson = __DIR__ . '/../data/users.json';
$externalAuth = 'C:\inetpub\Authentication\hometimeradio\auth_config.php';

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 {
  return file_put_contents($path, json_encode($users, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n") !== false;
}
function ht_load_external_auth(string $externalAuth): array {
  $cfg = ['temp_admin_user' => '', 'temp_admin_pass' => '', 'users' => []];
  if (is_file($externalAuth)) {
    $loaded = include $externalAuth;
    if (is_array($loaded)) $cfg = array_merge($cfg, $loaded);
  }
  if (!isset($cfg['users']) || !is_array($cfg['users'])) $cfg['users'] = [];
  return $cfg;
}
function ht_save_external_auth(string $path, array $cfg): bool {
  $dir = dirname($path);
  if (!is_dir($dir)) @mkdir($dir, 0777, true);
  return @file_put_contents($path, "<?php\nreturn " . var_export($cfg, true) . ";\n") !== 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);
$authCfg = ht_load_external_auth($externalAuth);
$externalWriteOk = is_file($externalAuth) ? is_writable($externalAuth) : is_writable(dirname($externalAuth));

$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, ['admin','Musicman'], true)) {
  unset($users[$u]);
  ht_save_json_users($usersJson, $users);
  $authCfg['users'] = array_values(array_filter((array)$authCfg['users'], function($row) use ($u) {
    return (string)($row['u'] ?? $row['username'] ?? '') !== $u;
  }));
  $savedExternal = ht_save_external_auth($externalAuth, $authCfg);
  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']);
  }

  ht_save_json_users($usersJson, $users);

  $authCfg['users'] = [];
  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));
    $authCfg['users'][] = ['u'=>$name, 'p'=>(string)($row['password'] ?? ''), 'role'=>(string)($row['role'] ?? 'viewer'), 'perm'=>$perm];
  }
  $savedExternal = ht_save_external_auth($externalAuth, $authCfg);
  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;">This upgraded manager keeps Home Time user data in <code><?= smurf_h($usersJson) ?></code> and mirrors it to <code><?= smurf_h($externalAuth) ?></code> when that file is available.</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 external auth file 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">External auth file is not writable right now: <code><?= smurf_h($externalAuth) ?></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, ['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'; ?>
