<?php
// ─── Self-service admin password reset — locked behind a secret recovery key. ───
//
// Unlike admin/setup.php, this file may STAY on the server: it is inert until
// ADMIN_RESET_KEY is configured, and every reset requires that exact key.
//
//   Enable  : add  ADMIN_RESET_KEY=<long random string>  to `.env` in the site
//             root (documented in .env.example). Generate a key with:
//             php -r "echo bin2hex(random_bytes(32));"
//   Use     : browse to /admin/reset.php → recovery key + account email +
//             new password (twice). Full steps: DEPLOY-CPANEL.md.
//   Fallback: key never configured and every login lost? phpMyAdmin → SQL →
//             TRUNCATE TABLE users;  then open admin/setup.php once to create
//             a fresh admin account (re-upload setup.php if it was deleted).
//
// Security: constant-time key check (hash_equals); every key/email failure gets
// ONE generic message after sleep(2) — it never reveals whether the email exists
// or the key was wrong. The key and passwords are never echoed or logged.
require __DIR__ . '/../app/bootstrap.php';
security_headers(true);

config(); // loads .env so env() below can see ADMIN_RESET_KEY
$resetKey   = trim((string) (env('ADMIN_RESET_KEY') ?? config('admin_reset_key') ?? ''));
$configured = ($resetKey !== '');
$done = ''; $err = '';

if ($configured && $_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $key   = (string) ($_POST['key'] ?? '');
  $email = trim((string) ($_POST['email'] ?? ''));
  $pass  = (string) ($_POST['password'] ?? '');
  $pass2 = (string) ($_POST['password2'] ?? '');

  if (strlen($pass) < 8) {
    sleep(2); $err = 'The new password must be at least 8 characters.';
  } elseif ($pass !== $pass2) {
    sleep(2); $err = 'The two passwords do not match — type the same new password twice.';
  } else {
    $userId = 0;
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $st = db()->prepare('SELECT id FROM users WHERE email = ?');
      $st->execute([$email]);
      $userId = (int) $st->fetchColumn();
    }
    if (hash_equals($resetKey, $key) && $userId > 0) {
      db()->prepare('UPDATE users SET password_hash = ? WHERE id = ?')
        ->execute([password_hash($pass, PASSWORD_DEFAULT), $userId]);
      $done = 'Password updated. Sign in with your new password.';
    } else {
      sleep(2); // slow down guessing — and say nothing about which part failed
      $err = 'Reset failed — the recovery key and account email did not match. Check both and try again.';
    }
  }
}
?><!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Reset password · 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 $clR = function_exists('client_logo_url') ? client_logo_url() : ''; if ($clR !== ''): ?><div class="login-client" style="margin:-6px 0 16px"><img src="<?= e($clR) ?>" 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">Reset your admin password</h2>
  <?php if (!$configured): ?>
  <p style="color:var(--muted);font-size:13px;margin-bottom:16px">Self-service reset is switched off — no recovery key is configured.</p>
  <div class="badge b-warn" style="padding:10px 14px;display:block;margin-bottom:14px;white-space:normal;line-height:1.6">
    <b>Easiest fix:</b> sign in as an administrator once — the CMS now creates and stores a recovery key automatically (shown to you once). You can also manage it under <b>Team &amp; Access → Password recovery key</b>.
  </div>
  <p style="color:var(--muted);font-size:12.5px;margin-bottom:10px;line-height:1.6">Locked out of every account? Add the line below to <code>.env</code> in the site root (cPanel → File Manager), then reload this page — the freshly generated key becomes your recovery key:</p>
  <?php $suggested = bin2hex(random_bytes(32)); /* inert until placed in .env — generating one here reveals nothing */ ?>
  <div style="display:flex;gap:8px;align-items:center;margin-bottom:14px">
    <code id="rkVal" style="flex:1;word-break:break-all;font-size:11px;background:var(--line-2);padding:8px 10px;border-radius:8px">ADMIN_RESET_KEY=<?= e($suggested) ?></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>
  <p style="color:var(--muted);font-size:12px;margin-bottom:16px;line-height:1.6">Full steps: DEPLOY-CPANEL.md → “Forgotten admin password”.</p>
  <a class="btn btn-ghost btn-block" href="<?= admin_url('?p=login') ?>">Back to sign in</a>
  <?php elseif ($done): ?>
  <div class="badge b-ok" style="padding:10px 14px;display:block;margin:14px 0"><?= e($done) ?></div>
  <a class="btn btn-primary btn-block" href="<?= admin_url('?p=login') ?>">Go to sign in</a>
  <?php else: ?>
  <p style="color:var(--muted);font-size:13px;margin-bottom:20px">Enter the recovery key (from the site’s <code>.env</code>), the account’s email, and a new password.</p>
  <?php if ($err): ?><div class="badge b-warn" style="padding:10px 14px;display:block;margin-bottom:14px;white-space:normal;line-height:1.6"><?= e($err) ?></div><?php endif; ?>
  <form method="post" autocomplete="off"><?= csrf_field() ?>
    <div class="field"><label>Recovery key</label><input class="inp" type="password" name="key" required autofocus autocomplete="off"></div>
    <div class="field"><label>Account email</label><input class="inp" type="email" name="email" required></div>
    <div class="field"><label>New password (min 8 characters)</label><input class="inp" type="password" name="password" minlength="8" required autocomplete="new-password"></div>
    <div class="field"><label>Repeat new password</label><input class="inp" type="password" name="password2" minlength="8" required autocomplete="new-password"></div>
    <button class="btn btn-primary btn-block" style="margin-top:6px">Reset password</button>
  </form>
  <div style="text-align:center;margin-top:14px"><a href="<?= admin_url('?p=login') ?>" style="font-size:12.5px;color:var(--muted)">Back to sign in</a></div>
  <?php endif; ?>
</div></body></html>
