<?php
$active = 'users';
$pageTitle = 'Bulk Credentials Generated';
require __DIR__ . '/../layout/admin_header.php';
?>
<div class="topbar">
  <div>
    <h1>Login Credentials Generated</h1>
    <div class="crumbs">Workspace → Admin → User Management → Bulk Generate</div>
  </div>
  <div class="user-chip"><span class="dot"></span> <?= htmlspecialchars($admin['name']) ?></div>
</div>

<?php if (empty($generated)): ?>
  <div class="alert alert-success">Everyone already has login access — nothing new to generate.</div>
  <a href="/admin/users" class="btn-secondary" style="text-decoration:none;display:inline-block;">← Back to User Management</a>
<?php else: ?>
  <div class="alert alert-error" style="font-weight:700;">
    ⚠️ This is the ONLY time these temporary passwords will be shown. Copy or download this list now
    and share each password with its person before you leave this page — it cannot be retrieved again afterward.
  </div>

  <div class="card">
    <div class="toolbar">
      <div style="font-weight:700;"><?= count($generated) ?> new login<?= count($generated) === 1 ? '' : 's' ?> created</div>
      <button class="btn-primary" onclick="downloadCsv()">⬇ Download as CSV</button>
    </div>
    <table id="credTable">
      <thead><tr><th>Name</th><th>Type</th><th>Username</th><th>Temporary Password</th></tr></thead>
      <tbody>
        <?php foreach ($generated as $g): ?>
          <tr>
            <td style="font-weight:700;"><?= htmlspecialchars($g['name']) ?></td>
            <td><?= htmlspecialchars(ucfirst($g['type'])) ?></td>
            <td><code><?= htmlspecialchars($g['username']) ?></code></td>
            <td><code style="background:#fef3e2;padding:3px 8px;border-radius:6px;font-weight:700;"><?= htmlspecialchars($g['password']) ?></code></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <a href="/admin/users" class="btn-secondary" style="text-decoration:none;display:inline-block;">Done — Back to User Management</a>

  <script>
    const rows = <?= json_encode($generated) ?>;
    function downloadCsv(){
      let csv = 'Name,Type,Username,Temporary Password\n';
      rows.forEach(r => {
        csv += `"${r.name}","${r.type}","${r.username}","${r.password}"\n`;
      });
      const blob = new Blob([csv], { type: 'text/csv' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'hammerhead_new_logins.csv';
      a.click();
      URL.revokeObjectURL(url);
    }
  </script>
<?php endif; ?>

<?php require __DIR__ . '/../layout/admin_footer.php'; ?>
