<?php
// ─── First-run: create the initial admin account, then DELETE this file. ───
require __DIR__ . '/../app/bootstrap.php';
security_headers(true);
$done = ''; $err = '';
$rkKey = ''; $rkWritten = false;
$hasUsers = count_rows('users') > 0;

if ($hasUsers) {
  $err = 'An admin account already exists. For security, delete this file (admin/setup.php).';
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $name = trim($_POST['name'] ?? '');
  $email = trim($_POST['email'] ?? '');
  $pass = $_POST['password'] ?? '';
  if ($name && filter_var($email, FILTER_VALIDATE_EMAIL) && strlen($pass) >= 8) {
    db()->prepare('INSERT INTO users(name,email,password_hash,role) VALUES(?,?,?,?)')
      ->execute([$name, $email, password_hash($pass, PASSWORD_DEFAULT), 'admin']);
    $done = 'Admin account created. Now DELETE admin/setup.php, then sign in.';
    // Provision the password-recovery key in the same step (no manual .env
    // editing). Shown ONCE below; written to .env when the file is writable.
    if (!recovery_key_configured()) {
      [$rkKey, $rkWritten] = provision_recovery_key();
      unset($_SESSION['reveal_reset_key']);   // shown here, not on the next admin page
    }
  } else {
    $err = 'Enter a name, a valid email, and a password of at least 8 characters.';
  }
}
?><!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Setup · ExpertAims CMS</title><link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"><link rel="stylesheet" href="<?= base_url('assets/admin.css') ?>"></head>
<body style="display:grid;place-items:center;min-height:100vh;background:var(--canvas)">
<div class="card" style="width:100%;max-width:420px;padding:30px">
  <img src="<?= base_url('assets/ea-wordmark.png') ?>" alt="ExpertAims" style="height:34px;margin-bottom:18px">
  <?php $clS = function_exists('client_logo_url') ? client_logo_url() : ''; if ($clS !== ''): ?><div class="login-client" style="margin:-6px 0 16px"><img src="<?= e($clS) ?>" alt="" onerror="this.parentNode.style.display='none'"><span><?= e(setting('site_name','')) ?></span></div><?php endif; ?>
  <h2 style="font-size:19px;font-weight:700;margin-bottom:4px">Create your admin account</h2>
  <p style="color:var(--muted);font-size:13px;margin-bottom:20px">This one-time step creates the first login.</p>
  <?php if ($done): ?><div class="badge b-ok" style="padding:10px 14px;display:block;margin-bottom:14px"><?= e($done) ?></div>
  <?php if ($rkKey !== ''): ?>
  <div style="border:1px solid var(--warn);border-radius:12px;padding:14px;margin-bottom:14px">
    <b style="font-size:13px;display:block;margin-bottom:6px">Password recovery key — save it now (shown only this once)</b>
    <p style="color:var(--muted);font-size:12px;line-height:1.6;margin-bottom:10px"><?= $rkWritten
      ? 'This key unlocks the “forgot password” page (<code>admin/reset.php</code>). It was stored in the site’s <code>.env</code> automatically — keep a copy in a password manager too.'
      : 'The site’s <code>.env</code> isn’t writable, so this could <b>not</b> be stored automatically. Add the whole line below to <code>.env</code> in the site root to activate the reset page.' ?></p>
    <div style="display:flex;gap:8px;align-items:center">
      <code id="rkVal" style="flex:1;word-break:break-all;font-size:11px;background:var(--line-2);padding:8px 10px;border-radius:8px"><?= $rkWritten ? e($rkKey) : 'ADMIN_RESET_KEY=' . e($rkKey) ?></code>
      <button type="button" class="btn btn-ghost btn-sm" onclick="var t=document.getElementById('rkVal').textContent;(navigator.clipboard?navigator.clipboard.writeText(t):Promise.reject()).then(()=>{this.textContent='Copied ✓';},()=>{var r=document.createRange();r.selectNodeContents(document.getElementById('rkVal'));var s=getSelection();s.removeAllRanges();s.addRange(r);document.execCommand('copy');this.textContent='Copied ✓';});">Copy</button>
    </div>
  </div>
  <?php endif; ?>
  <a class="btn btn-primary btn-block" href="<?= admin_url('?p=login') ?>">Go to sign in</a>
  <?php elseif ($err): ?><div class="badge b-warn" style="padding:10px 14px;display:block;margin-bottom:14px"><?= e($err) ?></div><?php if (!$hasUsers): ?><a class="btn btn-ghost btn-block" href="">Try again</a><?php endif; ?>
  <?php else: ?>
  <form method="post"><?= csrf_field() ?>
    <div class="field"><label>Your name</label><input class="inp" name="name" required autofocus></div>
    <div class="field"><label>Email</label><input class="inp" type="email" name="email" required></div>
    <div class="field"><label>Password (min 8 characters)</label><input class="inp" type="password" name="password" minlength="8" required></div>
    <button class="btn btn-primary btn-block" style="margin-top:6px">Create account</button>
  </form>
  <?php endif; ?>
</div></body></html>
