<?php
declare(strict_types=1);

Auth::requireRole('admin');

$users = Database::all(
    'SELECT id, username, full_name, email, role, is_active, last_login_at,
            (password_hash IS NULL) AS needs_password
       FROM users ORDER BY full_name'
);

$editId = get_int('edit');
$editing = $editId !== null
    ? Database::one('SELECT * FROM users WHERE id = :id', ['id' => $editId])
    : null;

$PAGE_TITLE = t('users_title');

require BASE_DIR . '/includes/layout/header.php';
?>

<div class="grid grid-main">

  <section class="panel">
    <div class="panel-head"><h2 class="panel-title"><?= e(t('users_title')) ?> · <?= count($users) ?></h2></div>
    <div class="panel-body is-flush">
      <div class="table-wrap">
        <table class="data">
          <thead>
            <tr>
              <th><?= e(t('full_name')) ?></th>
              <th><?= e(t('role')) ?></th>
              <th><?= e(t('last_login')) ?></th>
              <th><?= e(t('active')) ?></th>
              <th></th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($users as $u): ?>
            <tr>
              <td class="cell-name">
                <?= e($u['full_name']) ?>
                <span class="cell-meta"><?= e($u['username']) ?><?= $u['email'] ? ' · ' . e($u['email']) : '' ?></span>
              </td>
              <td class="small"><?= e(t('role_' . $u['role'])) ?></td>
              <td class="small muted">
                <?php if ($u['needs_password']): ?>
                  <span style="color:var(--t-72)"><?= e(t('no_password_set')) ?></span>
                <?php else: ?>
                  <?= e(fmt_datetime($u['last_login_at'])) ?>
                <?php endif; ?>
              </td>
              <td class="small"><?= $u['is_active'] ? '✓' : '—' ?></td>
              <td class="num">
                <a class="btn btn-sm btn-ghost" href="<?= e(url('users', 'index', ['edit' => $u['id']])) ?>">
                  <?= e(t('edit')) ?>
                </a>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </section>

  <div>
    <section class="panel">
      <div class="panel-head">
        <h2 class="panel-title"><?= e($editing ? t('edit') : t('add')) ?></h2>
      </div>
      <div class="panel-body">
        <form method="post" action="<?= e(url('users', 'save')) ?>" class="stack">
          <?= Csrf::field() ?>
          <?php if ($editing): ?><input type="hidden" name="id" value="<?= (int) $editing['id'] ?>"><?php endif; ?>

          <div class="field">
            <label class="label" for="full_name"><?= e(t('full_name')) ?></label>
            <input type="text" id="full_name" name="full_name" required maxlength="128"
                   value="<?= e($editing['full_name'] ?? '') ?>">
          </div>

          <div class="field">
            <label class="label" for="u-username"><?= e(t('username')) ?></label>
            <input type="text" id="u-username" name="username" required maxlength="64"
                   value="<?= e($editing['username'] ?? '') ?>">
          </div>

          <div class="field">
            <label class="label" for="u-email"><?= e(t('email')) ?></label>
            <input type="email" id="u-email" name="email" maxlength="190"
                   value="<?= e($editing['email'] ?? '') ?>">
          </div>

          <div class="field">
            <label class="label" for="u-role"><?= e(t('role')) ?></label>
            <select id="u-role" name="role">
              <?php foreach (['viewer', 'analyst', 'admin'] as $r): ?>
                <option value="<?= e($r) ?>" <?= ($editing['role'] ?? 'analyst') === $r ? 'selected' : '' ?>>
                  <?= e(t('role_' . $r)) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <label class="check">
            <input type="checkbox" name="is_active" value="1"
              <?= (!$editing || $editing['is_active']) ? 'checked' : '' ?>>
            <?= e(t('active')) ?>
          </label>

          <div class="form-actions">
            <button type="submit" class="btn btn-primary"><?= e(t('save')) ?></button>
            <?php if ($editing): ?>
              <a class="btn" href="<?= e(url('users', 'index')) ?>"><?= e(t('cancel')) ?></a>
            <?php endif; ?>
          </div>
        </form>
      </div>
    </section>

    <?php if ($editing): ?>
    <section class="panel">
      <div class="panel-head"><h2 class="panel-title"><?= e(t('set_password')) ?></h2></div>
      <div class="panel-body">
        <form method="post" action="<?= e(url('users', 'password')) ?>" class="stack">
          <?= Csrf::field() ?>
          <input type="hidden" name="id" value="<?= (int) $editing['id'] ?>">
          <div class="field">
            <label class="label" for="set-pw"><?= e(t('new_password')) ?></label>
            <input type="password" id="set-pw" name="new_password" autocomplete="new-password"
                   minlength="<?= (int) MIN_PASSWORD_LENGTH ?>" required>
          </div>
          <p class="hint"><?= e(t('password_too_short', ['n' => MIN_PASSWORD_LENGTH])) ?>
             Setting a password signs this person out of any open session.</p>
          <div><button class="btn" type="submit"><?= e(t('set_password')) ?></button></div>
        </form>
      </div>
    </section>
    <?php endif; ?>
  </div>

</div>

<?php require BASE_DIR . '/includes/layout/footer.php'; ?>
