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


$usersFile = __DIR__ . '/users.txt';
$externalAuth = 'C:/inetpub/Authentication/radiogalaxyfx/auth_config.php';
if (!file_exists($usersFile)) file_put_contents($usersFile, '');

function load_users_rows(string $usersFile): array {
  $lines = file($usersFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
  $rows = [];
  foreach ($lines as $line) {
    $p = explode('|', $line);
    if (count($p) < 4) continue;
    $rows[] = ['u'=>$p[0],'p'=>$p[1],'role'=>$p[2],'perm'=>$p[3]];
  }
  return $rows;
}
function save_users_rows(string $usersFile, array $rows): void {
  $out = array_map(fn($r)=>$r['u'].'|'.$r['p'].'|'.$r['role'].'|'.$r['perm'], $rows);
  file_put_contents($usersFile, implode("\n", $out) . (count($out)?"\n":""));
}

function load_external_auth_cfg(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 normalize_external_users(array $rows): array {
  $out = [];
  foreach ($rows as $row) {
    if (!is_array($row)) continue;
    $u = trim((string)($row['u'] ?? $row['username'] ?? ''));
    $p = (string)($row['p'] ?? $row['password'] ?? '');
    $role = ((string)($row['role'] ?? 'viewer') === 'admin') ? 'admin' : 'viewer';
    $perm = (string)($row['perm'] ?? $row['permissions'] ?? '');
    if ($u !== '' && $p !== '') {
      $out[] = ['u'=>$u,'p'=>$p,'role'=>$role,'perm'=>$perm];
    }
  }
  return $out;
}

function save_external_auth_users(string $externalAuth, array $cfg, array $rows): bool {
  $cfg['users'] = array_values(array_map(fn($r)=>[
    'u' => (string)$r['u'],
    'p' => (string)$r['p'],
    'role' => (string)$r['role'],
    'perm' => (string)$r['perm'],
  ], $rows));

  $dir = dirname($externalAuth);
  if (!is_dir($dir)) {
    @mkdir($dir, 0777, true);
  }

  $export = "<?php\nreturn " . var_export($cfg, true) . ";\n";
  return @file_put_contents($externalAuth, $export) !== false;
}

$authCfg = load_external_auth_cfg($externalAuth);
$externalWriteOk = is_file($externalAuth) ? is_writable($externalAuth) : is_writable(dirname($externalAuth));

$users = normalize_external_users($authCfg['users'] ?? []);
if (!$users) {
  $users = load_users_rows($usersFile);
}

$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);
$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' && (!$CAN_EDIT)) { smurf_admin_denied('You do not have permission to manage users.'); }

if ($action === 'delete' && $i >= 0 && isset($users[$i])) {
  array_splice($users, $i, 1);
  $savedExternal = save_external_auth_users($externalAuth, $authCfg, $users);
  save_users_rows($usersFile, $users);
  if (!$savedExternal) {
    smurf_redirect_self(['deleted'=>1, 'warn'=>'external-save'], ['action','i']);
  }
  smurf_redirect_self(['deleted'=>1], ['action','i']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to manage users.');
  $mode = $_POST['mode'] ?? 'create';
  $editIndex = (int)($_POST['edit_index'] ?? -1);
  $u = trim($_POST['username'] ?? '');
  $p = trim($_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];
    } else {
      if ($p === '') {
        smurf_redirect_self(['err'=>'password'], ['action','i']);
      }
      $users[] = ['u'=>$u,'p'=>$p,'role'=>$role,'perm'=>$perm];
    }
    $savedExternal = save_external_auth_users($externalAuth, $authCfg, $users);
    save_users_rows($usersFile, $users);
    if (!$savedExternal) {
      smurf_redirect_self(['saved'=>1, 'warn'=>'external-save'], ['action','i']);
    }
    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;">Permissions auto-update from real admin pages, including Events, Media Library, Backup/Restore and any new admin tools you add later. Managed users are stored in <code><?= smurf_h($externalAuth) ?></code> and mirrored to <code><?= smurf_h($usersFile) ?></code> as fallback.</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; ?>
  <?php if (($_GET['warn'] ?? '') === 'external-save'): ?><div class="msg error">Saved locally, but could not write to external auth file. Check write permissions for <code><?= smurf_h($externalAuth) ?></code>.</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>
      <?php if (!$CAN_EDIT): ?><p style="opacity:.78;">User accounts are visible here for reference only.</p><?php else: ?>
      <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(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>
      <?php endif; ?>
    </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 $idx => $row): ?>
            <tr>
              <td><?= smurf_h($row['u']) ?></td>
              <td><?= smurf_h($row['role']) ?></td>
              <td><?= smurf_h($row['perm']) ?></td>
              <td>
                <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>
    </section>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
