<?php

declare(strict_types=1);

/**
 * Community-branded "forgot password" — "/forgot-password". Reuses the platform's
 * secure reset backend: one identical response for every outcome (never an
 * account-existence oracle), bot honeypot + rate limiting, and a token stored in
 * `password_resets`. Emails an on-brand reset link that lands on our own
 * community `/reset-password` page. Degrades safely if no mailer is configured.
 */

require __DIR__ . '/_shell.php';

use PpPhp\Core\Security;
use PpPhp\Core\DB;
use PpPhp\Core\Auth\AuthGuard;
use PpPhp\Core\Events;

$b = forum_base();
if (forum_logged_in()) {
    header('Location: ' . $b . '/');
    exit;
}

$message = '';
$isError = false;
// One wording for every outcome. Saying "sent" for a real address and something
// else for an unknown one turns this page into an oracle for which accounts exist.
$same = 'If that email is registered, we\'ve sent a reset link. Check your inbox.';

if (!AuthGuard::get('enable_password_reset')) {
    $message = 'Password reset isn\'t available right now. Please contact an administrator.';
    $isError = true;
} elseif (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    if (!Security::CSRF()->Check((string) ($_POST['_token'] ?? ''))) {
        $message = 'Your session expired — please submit again.';
        $isError = true;
    } elseif (AuthGuard::looksAutomated($_POST)
        || AuthGuard::tooMany('forgot', (int) AuthGuard::get('forgot_max'), (int) AuthGuard::get('forgot_window'))) {
        $message = $same;   // bot or flood: answer identically, do nothing
    } else {
        AuthGuard::hit('forgot');
        $email = trim((string) ($_POST['email'] ?? ''));
        $user = $email !== '' ? (DB::FetchAll('SELECT id, username FROM users WHERE email = ?', [$email])[0] ?? null) : null;
        if ($user) {
            $pwMsg = '';
            if (Events::fire('global.auth.beforePasswordReminder', ['user' => $user, 'message' => &$pwMsg]) === false) {
                $message = $pwMsg !== '' ? $pwMsg : $same;
            } else {
                $token = Security::GenerateToken();
                DB::Query('CREATE TABLE IF NOT EXISTS password_resets (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, user_id INT UNSIGNED NOT NULL, token VARCHAR(64) NOT NULL, expires_at DATETIME NOT NULL, created_at DATETIME NOT NULL, INDEX idx_pr_token (token), INDEX idx_pr_user (user_id))');
                $hours = max(1, (int) AuthGuard::get('reset_token_hours') ?: 24);
                DB::Insert('password_resets', [
                    'user_id'    => (int) $user['id'],
                    'token'      => $token,
                    'expires_at' => date('Y-m-d H:i:s', time() + 3600 * $hours),
                    'created_at' => date('Y-m-d H:i:s'),
                ]);
                if (function_exists('pp_send_email')) {
                    $sch  = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
                    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
                    $link = $sch . '://' . $host . $b . '/reset-password?token=' . rawurlencode($token);
                    $html = '<p>Hello ' . forum_e((string) $user['username']) . ',</p>'
                          . '<p>We received a request to reset your PPPHP Community password. '
                          . 'Click the button below to choose a new one — this link expires in ' . $hours . ' hour' . ($hours === 1 ? '' : 's') . '.</p>'
                          . '<p><a href="' . $link . '" style="display:inline-block;background:#6366f1;color:#fff;font-weight:700;padding:11px 22px;border-radius:8px;text-decoration:none">Reset your password</a></p>'
                          . '<p style="color:#64748b;font-size:13px">If you didn\'t ask for this, you can safely ignore this email — your password won\'t change.</p>';
                    pp_send_email($email, 'Reset your PPPHP Community password', $html, ['action' => 'password_reset', 'htmlbody' => $html]);
                }
                Events::fire('global.auth.afterPasswordReminder', ['user' => $user]);
                $message = $same;
            }
        } else {
            $message = $same;
        }
    }
}

forum_auth_head('Reset your password — PPPHP Community', '<meta name="robots" content="noindex,follow">');
?>
<div class="fx-auth-card">
  <h1>Forgot your password?</h1>
  <p class="fx-auth-sub">No worries — enter your email and we'll send you a reset link.</p>
  <?php if ($message !== ''): ?>
    <div class="<?= $isError ? 'fx-formerr' : 'fx-formok' ?>"><i class="bi bi-<?= $isError ? 'exclamation-circle' : 'check-circle' ?>"></i> <?= forum_e($message) ?></div>
  <?php endif; ?>
  <?php if (!$isError): ?>
  <form method="post" action="<?= $b ?>/forgot-password">
    <input type="hidden" name="_token" value="<?= forum_e(forum_csrf()) ?>">
    <input class="fx-hp" type="text" name="website" tabindex="-1" autocomplete="off" aria-hidden="true">
    <div class="fx-field"><label>Account email</label><input class="fx-input" type="email" name="email" required autofocus autocomplete="email" placeholder="you@example.com"></div>
    <button class="fx-submit full" type="submit">Send reset link</button>
  </form>
  <?php endif; ?>
  <p class="fx-auth-alt">Remembered it? <a href="<?= $b ?>/login">Back to sign in</a></p>
</div>
<p class="fx-auth-note"><i class="bi bi-shield-check"></i> For your safety we never reveal whether an email is registered</p>
<?php forum_auth_foot(); ?>
