<?php
$pageTitle = 'View as User — Dev Admin';
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= htmlspecialchars($pageTitle) ?> · Hammerhead Workspace</title>
<link rel="stylesheet" href="/assets/css/app.css?v=<?= defined('ASSET_VERSION') ? ASSET_VERSION : time() ?>">
<style>
  body { background:var(--bg); }
  .dev-wrap { max-width:860px; margin:40px auto; padding:0 20px; }
  .dev-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:28px; }
  .dev-badge { background:#1e3a8a; color:#fff; border-radius:20px; font-size:11px; font-weight:700;
               letter-spacing:.08em; padding:4px 12px; text-transform:uppercase; }
  .dev-title { font-size:22px; font-weight:800; color:var(--navy-900); margin:0; }
  .search-box { width:100%; padding:11px 16px; border:1.5px solid var(--border);
                border-radius:12px; font-size:14px; margin-bottom:18px;
                outline:none; transition:border-color .2s; }
  .search-box:focus { border-color:#3b82f6; }
  .user-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(240px,1fr)); gap:12px; }
  .user-card { background:#fff; border:1.5px solid var(--border); border-radius:14px;
               padding:16px 18px; cursor:pointer; transition:border-color .15s, box-shadow .15s;
               display:flex; align-items:center; gap:13px; }
  .user-card:hover { border-color:#3b82f6; box-shadow:0 3px 14px rgba(59,130,246,0.13); }
  .user-avatar { width:40px; height:40px; border-radius:50%; display:flex; align-items:center;
                 justify-content:center; font-size:16px; font-weight:800; flex-shrink:0; color:#fff; }
  .avatar-superadmin { background:#7c3aed; }
  .avatar-manager    { background:#1d63e0; }
  .avatar-employee   { background:#059669; }
  .user-info { min-width:0; }
  .user-name { font-weight:700; font-size:14px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
  .user-meta { font-size:11.5px; color:var(--text-muted); margin-top:2px; }
  .user-role { display:inline-block; background:rgba(59,130,246,0.1); color:#1d4ed8;
               border-radius:20px; font-size:10.5px; font-weight:700; padding:1px 8px; margin-top:4px; }
  .section-label { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.07em;
                   color:var(--text-muted); margin:22px 0 10px; }
  .flash-err { background:#fef2f2; border:1px solid #fca5a5; color:#991b1b; padding:12px 16px;
               border-radius:10px; font-size:13px; margin-bottom:16px; }
  .back-link { display:inline-flex; align-items:center; gap:6px; color:var(--blue-600);
               font-size:13px; font-weight:600; text-decoration:none; margin-bottom:20px; }
  .back-link:hover { text-decoration:underline; }
  .no-results { color:var(--text-muted); font-size:13px; padding:20px 0; }
</style>
</head>
<body>
<div class="dev-wrap">

  <div class="dev-header">
    <div>
      <div style="margin-bottom:6px;"><span class="dev-badge">🔧 Dev Admin</span></div>
      <h1 class="dev-title">View as User</h1>
      <p style="color:var(--text-muted);font-size:13px;margin:4px 0 0;">
        Select any user to preview their dashboard. <strong>Read-only</strong> — no data will be changed.
      </p>
    </div>
    <a href="/logout" style="font-size:13px;color:var(--text-muted);text-decoration:none;">Sign out</a>
  </div>

  <?php if (!empty($_SESSION['dev_flash'])): ?>
    <div class="flash-err"><?= htmlspecialchars($_SESSION['dev_flash']) ?></div>
    <?php unset($_SESSION['dev_flash']); ?>
  <?php endif; ?>

  <input type="text" class="search-box" id="devSearch"
         placeholder="🔍  Search by name, username, or role..."
         oninput="filterUsers(this.value)" autofocus>

  <div id="userList">
    <?php
    $groups = [
      'Super Admins'  => array_filter($allUsers, fn($u) => $u['user_type'] === 'superadmin'),
      'Managers'      => array_filter($allUsers, fn($u) => $u['user_type'] === 'manager'),
      'Employees'     => array_filter($allUsers, fn($u) => $u['user_type'] === 'employee'),
    ];
    foreach ($groups as $label => $users):
      if (empty($users)) continue;
    ?>
    <div class="section-label" data-group><?= htmlspecialchars($label) ?></div>
    <div class="user-grid">
      <?php foreach ($users as $u):
        $initial = mb_strtoupper(mb_substr($u['name'], 0, 1));
        $avatarClass = 'avatar-' . $u['user_type'];
        $searchData  = strtolower($u['name'] . ' ' . ($u['username'] ?? '') . ' ' . ($u['role_name'] ?? '') . ' ' . $u['user_type']);
      ?>
      <div class="user-card" data-search="<?= htmlspecialchars($searchData) ?>"
           onclick="viewAs('<?= htmlspecialchars($u['user_type']) ?>', <?= (int)$u['id'] ?>, '<?= htmlspecialchars(addslashes($u['name'])) ?>')">
        <div class="user-avatar <?= $avatarClass ?>"><?= htmlspecialchars($initial) ?></div>
        <div class="user-info">
          <div class="user-name"><?= htmlspecialchars($u['name']) ?></div>
          <div class="user-meta">@<?= htmlspecialchars($u['username'] ?? '—') ?></div>
          <?php if ($u['role_name']): ?>
            <div class="user-role"><?= htmlspecialchars($u['role_name']) ?></div>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endforeach; ?>
    <div class="no-results" id="noResults" style="display:none;">No users match your search.</div>
  </div>

</div>

<!-- Hidden form to POST the selection (GET would expose user_id in server logs) -->
<form id="viewAsForm" method="POST" action="/dev/impersonate/start">
  <input type="hidden" name="user_type" id="fi_type">
  <input type="hidden" name="user_id"   id="fi_id">
</form>

<script>
function viewAs(type, id, name) {
  if (!confirm('Preview as ' + name + '?\n\nThis is read-only — their data will not be changed.')) return;
  document.getElementById('fi_type').value = type;
  document.getElementById('fi_id').value   = id;
  document.getElementById('viewAsForm').submit();
}

function filterUsers(q) {
  q = q.toLowerCase().trim();
  const cards = document.querySelectorAll('.user-card');
  let visible = 0;
  cards.forEach(c => {
    const match = !q || c.dataset.search.includes(q);
    c.style.display = match ? '' : 'none';
    if (match) visible++;
  });
  // Hide section labels if all cards under them are hidden
  document.querySelectorAll('[data-group]').forEach(lbl => {
    const grid = lbl.nextElementSibling;
    const any  = grid && Array.from(grid.children).some(c => c.style.display !== 'none');
    lbl.style.display = any ? '' : 'none';
    if (grid) grid.style.display = any ? '' : 'none';
  });
  document.getElementById('noResults').style.display = visible === 0 ? 'block' : 'none';
}
</script>
</body>
</html>
