<?php
include(__DIR__ . '/../includes/auth.php');
requireRole(['master','admin']);
require_once __DIR__ . '/../includes/auth_paths.php';
require_once __DIR__ . '/includes/admin_lib.php';

$users = ah_load_users();
if (!is_array($users)) $users = [];

$permKeys = [
  'pages' => 'Page Builder',
  'users' => 'User Manager',
  'events' => 'Events',
  'fans' => 'Fans',
  'contact' => 'Contact Inbox',
  'applications' => 'Applications',
  'chat' => 'Live Chat',
  'requests' => 'Song Requests',
  'about' => 'About Content',
  'schedule' => 'Schedule',
  'media' => 'Media',
  'news' => 'Newsreel',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? 'create';
  $username = trim((string)($_POST['username'] ?? ''));

  if ($action === 'create') {
    $password = (string)($_POST['password'] ?? '');
    $role = $_POST['role'] ?? 'dj';
    $permissions = [];

    if ($role === 'dj') {
      foreach ($_POST['permissions'] ?? [] as $perm => $level) {
        $permissions[$perm] = $level;
      }
    }

    foreach ($users as $u) {
      if (($u['username'] ?? '') === $username) {
        die('Username already exists.');
      }
    }

    $users[] = [
      'username' => $username,
      'password' => password_hash($password, PASSWORD_DEFAULT),
      'role' => $role,
      'permissions' => $permissions
    ];
  }

  if ($action === 'update') {
    foreach ($users as &$u) {
      if (($u['username'] ?? '') === $username) {
        if (!empty($_POST['password'])) {
          $u['password'] = password_hash((string)$_POST['password'], PASSWORD_DEFAULT);
        }
        if (($u['username'] ?? '') !== 'master') {
          $u['role'] = $_POST['role'] ?? ($u['role'] ?? 'dj');
        }
        if (($u['role'] ?? 'dj') === 'dj') {
          $u['permissions'] = $_POST['permissions'] ?? [];
        } else {
          $u['permissions'] = [];
        }
      }
    }
    unset($u);
  }

  if ($action === 'delete') {
    if ($username === 'master') {
      die('Master admin cannot be removed.');
    }
    $users = array_values(array_filter($users, fn($u) => ($u['username'] ?? '') !== $username));
  }

  ah_save_users($users);
  header('Location: manage_users.php');
  exit;
}

$pageTitle = 'User Manager';
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">👥 User Manager</h1>
  <p class="content-muted">Manage external-auth users from inside Almost Heaven. Password changes save as secure hashes.</p>
</section>

<section class="admin-users-layout">
  <div class="content-card">
    <h2 class="text-warning">➕ Create User</h2>
    <form method="post" class="admin-form">
      <input type="hidden" name="action" value="create">
      <div class="admin-form-grid">
        <div>
          <label>Username</label>
          <input type="text" name="username" class="admin-input mb-2" placeholder="Username" required>
        </div>
        <div>
          <label>Password</label>
          <input type="password" name="password" class="admin-input mb-2" placeholder="Temporary password" required>
        </div>
      </div>

      <label>Role</label>
      <select name="role" id="create-role" class="admin-select mb-3" onchange="togglePermissions(this.value, 'create-permissions')">
        <option value="admin">Admin (Full Access)</option>
        <option value="dj">DJ (Custom Access)</option>
      </select>

      <div id="create-permissions" style="display:none;" class="mb-3">
        <label class="text-muted">DJ Permissions</label>
        <div class="perm-grid">
          <?php foreach ($permKeys as $key => $label): ?>
            <div class="perm-item">
              <div>
                <span><?= htmlspecialchars($label) ?></span>
                <small class="content-muted">Choose the level for this area.</small>
              </div>
              <div>
                <label><input type="radio" name="permissions[<?= $key ?>]" value="view"> View</label><br>
                <label><input type="radio" name="permissions[<?= $key ?>]" value="full"> Full</label>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

      <button type="submit" class="admin-btn">Create User</button>
    </form>
  </div>

  <div class="content-card">
    <h2 class="text-warning">📜 Existing Users</h2>
    <div class="users-list">
      <?php foreach ($users as $u): $u = ah_normalize_user_record(is_array($u) ? $u : []); ?>
        <div class="user-row-card">
          <div>
            <h3><?= htmlspecialchars($u['username'] ?? '') ?> <span class="content-muted">(<?= htmlspecialchars($u['role']) ?>)</span></h3>
            <div class="user-row-meta">
              <?php if (!empty($u['permissions'])): ?>
                <?php foreach ($u['permissions'] as $perm => $level): ?>
                  <span class="preview-badge"><?= htmlspecialchars($perm) ?>: <?= htmlspecialchars($level) ?></span>
                <?php endforeach; ?>
              <?php else: ?>
                Full admin access or no custom permissions set.
              <?php endif; ?>
            </div>

            <form method="post" class="admin-form" style="margin-top:14px;">
              <input type="hidden" name="action" value="update">
              <input type="hidden" name="username" value="<?= htmlspecialchars($u['username'] ?? '') ?>">
              <div class="admin-form-grid">
                <div>
                  <label>Change password</label>
                  <input type="password" name="password" class="admin-input mb-2" placeholder="Leave blank to keep current">
                </div>
                <div>
                  <?php if (($u['username'] ?? '') !== 'master'): ?>
                    <label>Role</label>
                    <select name="role" class="admin-select mb-2" onchange="togglePermissions(this.value, 'perm-<?= htmlspecialchars($u['username'] ?? '') ?>')">
                      <option value="admin" <?= $u['role'] === 'admin' ? 'selected' : '' ?>>Admin</option>
                      <option value="dj" <?= $u['role'] === 'dj' ? 'selected' : '' ?>>DJ</option>
                    </select>
                  <?php else: ?>
                    <label>Role</label>
                    <input type="text" class="admin-input mb-2" value="master" disabled>
                  <?php endif; ?>
                </div>
              </div>

              <div id="perm-<?= htmlspecialchars($u['username'] ?? '') ?>" style="display:<?= $u['role'] === 'dj' ? 'block' : 'none' ?>;" class="mb-3">
                <div class="perm-grid">
                  <?php foreach ($permKeys as $key => $label): ?>
                    <div class="perm-item">
                      <div>
                        <span><?= htmlspecialchars($label) ?></span>
                        <small class="content-muted">Current access: <?= htmlspecialchars($u['permissions'][$key] ?? 'none') ?></small>
                      </div>
                      <div>
                        <label><input type="radio" name="permissions[<?= $key ?>]" value="view" <?= (($u['permissions'][$key] ?? '') === 'view') ? 'checked' : '' ?>> View</label><br>
                        <label><input type="radio" name="permissions[<?= $key ?>]" value="full" <?= (($u['permissions'][$key] ?? '') === 'full') ? 'checked' : '' ?>> Full</label>
                      </div>
                    </div>
                  <?php endforeach; ?>
                </div>
              </div>

              <div class="user-row-actions">
                <button type="submit" class="admin-btn">Save Changes</button>
                <?php if (($u['username'] ?? '') !== 'master'): ?>
                  <button type="submit" formaction="manage_users.php" formmethod="post" class="admin-btn ghost" name="action" value="delete" onclick="return confirm('Delete this user?')">Delete User</button>
                <?php endif; ?>
              </div>
            </form>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>

<script>
function togglePermissions(role, targetId) {
  var el = document.getElementById(targetId);
  if (!el) return;
  el.style.display = role === 'dj' ? 'block' : 'none';
}
</script>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
