<?php

declare(strict_types=1);

/**
 * Community-branded "reset password" — "/reset-password?token=…". Completes the
 * forgot-password flow using the same `password_resets` token the platform
 * issues. On success it updates the password, kills the token + every remember
 * cookie for that account (a reset is how a compromised account is recovered),
 * clears the login lock, then sends the user to the community sign-in page.
 */

require __DIR__ . '/_shell.php';

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

$b = forum_base();
$token = (string) ($_POST['token'] ?? $_GET['token'] ?? '');
$error = '';
$reset = null;

if ($token !== '') {
    try {
        $reset = DB::FetchAll('SELECT * FROM password_resets WHERE token = ? AND expires_at > ?', [$token, date('Y-m-d H:i:s')])[0] ?? null;
    } catch (\Throwable $e) {
        $reset = null;
    }
}

if ($reset === null) {
    $error = 'This reset link is invalid or has expired. Please request a new one.';
} elseif (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    if (!Security::CSRF()->Check((string) ($_POST['_token'] ?? ''))) {
        $error = 'Your session expired — please submit again.';
    } else {
        $new     = (string) ($_POST['password'] ?? '');
        $confirm = (string) ($_POST['confirm_password'] ?? '');
        $who = DB::FetchAll('SELECT username, email, fullname FROM users WHERE id = ?', [(int) $reset['user_id']])[0] ?? [];
        if (($pwErr = AuthGuard::passwordError($new, $who)) !== '') {
            $error = $pwErr;
        } elseif ($new !== $confirm) {
            $error = 'The two passwords do not match.';
        } else {
            $rsUser = DB::FetchAll('SELECT * FROM users WHERE id = ?', [(int) $reset['user_id']])[0] ?? ['id' => (int) $reset['user_id']];
            Events::fire('global.auth.beforePasswordReset', ['user' => $rsUser]);
            DB::Update('users', ['password' => Security::HashPassword($new)], ['id' => (int) $reset['user_id']]);
            try { DB::Query('DELETE FROM password_resets WHERE user_id = ?', [(int) $reset['user_id']]); } catch (\Throwable $e) {}
            // A reset recovers a possibly-compromised account: every long-lived
            // "remember me" token must die with the old password.
            try { DB::Query('DELETE FROM remember_tokens WHERE user_id = ?', [(int) $reset['user_id']]); } catch (\Throwable $e) {}
            // The legitimate owner just proved control of the mailbox — clear any lock.
            try {
                $un = (string) ($who['username'] ?? '');
                if ($un !== '') { AuthGuard::clearLoginFailures($un); }
            } catch (\Throwable $e) {}
            Events::fire('global.auth.afterPasswordReset', ['user' => $rsUser]);
            $_SESSION['_flash'] = ['message' => 'Your password has been reset — please sign in.', 'type' => 'success'];
            header('Location: ' . $b . '/login');
            exit;
        }
    }
}

forum_auth_head('Set a new password — PPPHP Community', '<meta name="robots" content="noindex,follow">');
?>
<div class="fx-auth-card">
  <h1>Set a new password</h1>
  <p class="fx-auth-sub">Choose a strong password you don't use anywhere else.</p>
  <?php if ($error): ?><div class="fx-formerr"><i class="bi bi-exclamation-circle"></i> <?= forum_e($error) ?></div><?php endif; ?>
  <?php if ($reset !== null): ?>
  <form method="post" action="<?= $b ?>/reset-password">
    <input type="hidden" name="_token" value="<?= forum_e(forum_csrf()) ?>">
    <input type="hidden" name="token" value="<?= forum_e($token) ?>">
    <div class="fx-field"><label>New password</label><input class="fx-input" type="password" name="password" required autofocus autocomplete="new-password" placeholder="Create a new password"></div>
    <div class="fx-field"><label>Confirm password</label><input class="fx-input" type="password" name="confirm_password" required autocomplete="new-password" placeholder="Repeat your new password"></div>
    <button class="fx-submit full" type="submit">Reset password</button>
  </form>
  <?php else: ?>
    <a class="fx-submit full" href="<?= $b ?>/forgot-password" style="text-align:center;text-decoration:none">Request a new link</a>
  <?php endif; ?>
  <p class="fx-auth-alt">Remembered it? <a href="<?= $b ?>/login">Back to sign in</a></p>
</div>
<?php forum_auth_foot(); ?>
