<?php
// ─── First-run: create the initial admin account, then DELETE this file. ───
require __DIR__ . '/../app/bootstrap.php';
$done = ''; $err = '';
$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') {
  $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.';
  } 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">
  <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><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>
