<?php

declare(strict_types=1);

/**
 * Email confirmation — "/verify?token=…". Activates the pending account the
 * token belongs to, then invites the user to sign in.
 */

require __DIR__ . '/_shell.php';

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

$b = forum_base();
$token = (string) ($_GET['token'] ?? '');
$ok = false;
$msg = 'No confirmation token was provided.';

if ($token !== '') {
    try {
        DB::Query('CREATE TABLE IF NOT EXISTS account_activations (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_aa_token (token), INDEX idx_aa_user (user_id))');
        $row = DB::FetchAll('SELECT user_id FROM account_activations WHERE token = ? AND expires_at > ?', [$token, date('Y-m-d H:i:s')])[0] ?? null;
        if ($row) {
            $sf = (string) AuthGuard::get('status_field') ?: 'status';
            DB::Query('UPDATE `users` SET `' . $sf . '` = ? WHERE id = ?', ['active', (int) $row['user_id']]);
            DB::Query('DELETE FROM account_activations WHERE user_id = ?', [(int) $row['user_id']]);
            $ok = true;
            $msg = 'Your email is confirmed. You can now sign in and join the conversation.';
        } else {
            $msg = 'This confirmation link is invalid or has expired. Try registering again or request a new link.';
        }
    } catch (\Throwable $e) {
        $msg = 'We could not confirm your email right now. Please try again shortly.';
    }
}

forum_auth_head('Email confirmation — PPPHP Community', '<meta name="robots" content="noindex,follow">');
?>
<div class="fx-auth-card" style="text-align:center">
  <div style="font-size:44px;line-height:1;margin-bottom:10px;color:<?= $ok ? 'var(--fx-green)' : 'var(--fx-muted)' ?>">
    <i class="bi bi-<?= $ok ? 'patch-check-fill' : 'exclamation-circle' ?>"></i>
  </div>
  <h1><?= $ok ? 'Email confirmed' : 'Link problem' ?></h1>
  <p class="fx-auth-sub" style="margin-bottom:22px"><?= forum_e($msg) ?></p>
  <a class="fx-submit full" href="<?= $b ?>/<?= $ok ? 'login' : 'register' ?>"><?= $ok ? 'Sign in' : 'Back to sign up' ?></a>
</div>
<?php forum_auth_foot(); ?>
