<?php
/**
 * Email-change confirmation handler. Reached via a unique token sent to
 * the NEW email address. Validates the token, checks expiry + uniqueness,
 * then performs the swap.
 *
 * No login required (the token itself is the proof of access to the new
 * address). Tokens are 64 hex chars from random_bytes(32) and are unique
 * per change request.
 */
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/common.php';

$status  = 'error';
$heading = 'Email Change';
$message = '';

$token = (string)($_GET['token'] ?? '');

if (strlen($token) !== 64 || !ctype_xdigit($token)) {
    $message = 'This confirmation link is invalid.';
} else {
    try {
        $stmt = $pdo->prepare('SELECT id, email, pending_email, email_change_expiry
                               FROM sm_poets
                               WHERE email_change_token = :token
                               LIMIT 1');
        $stmt->bindValue(':token', $token, PDO::PARAM_STR);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            $message = 'This confirmation link is invalid or has already been used.';
        } elseif (!$row['email_change_expiry'] || strtotime($row['email_change_expiry']) < time()) {
            // Clear the stale token row so a new request can be made cleanly.
            $cl = $pdo->prepare('UPDATE sm_poets SET pending_email = NULL, email_change_token = NULL, email_change_expiry = NULL WHERE id = :id');
            $cl->bindValue(':id', (int)$row['id'], PDO::PARAM_INT);
            $cl->execute();
            $message = 'This confirmation link has expired. Please return to your profile and request the change again.';
        } else {
            $new_email = (string)$row['pending_email'];
            // Race-condition guard: another account may have claimed this email since.
            $u = $pdo->prepare('SELECT id FROM sm_poets WHERE email = :email AND id <> :id LIMIT 1');
            $u->bindValue(':email', $new_email, PDO::PARAM_STR);
            $u->bindValue(':id',    (int)$row['id'], PDO::PARAM_INT);
            $u->execute();
            if ($u->fetchColumn()) {
                $cl = $pdo->prepare('UPDATE sm_poets SET pending_email = NULL, email_change_token = NULL, email_change_expiry = NULL WHERE id = :id');
                $cl->bindValue(':id', (int)$row['id'], PDO::PARAM_INT);
                $cl->execute();
                $message = 'That email address is now in use by another account. The change was not applied.';
            } else {
                $apply = $pdo->prepare('UPDATE sm_poets
                                        SET email = :email,
                                            email_confirmed = 1,
                                            pending_email = NULL,
                                            email_change_token = NULL,
                                            email_change_expiry = NULL
                                        WHERE id = :id');
                $apply->bindValue(':email', $new_email, PDO::PARAM_STR);
                $apply->bindValue(':id',    (int)$row['id'], PDO::PARAM_INT);
                $apply->execute();
                $status  = 'success';
                $heading = 'Email Updated';
                $message = 'Your email address has been changed to ' . htmlspecialchars($new_email, ENT_QUOTES, 'UTF-8') . '. Sign in with this address from now on.';
            }
        }
    } catch (Throwable $e) {
        error_log('confirm-email-change: ' . $e->getMessage());
        $message = 'Something went wrong while confirming your email. Please try again.';
    }
}

include_once __DIR__ . '/header.php';
include_once __DIR__ . '/menu.php';
?>

<div class="container" style="max-width: 580px;">
  <h2><?= htmlspecialchars($heading, ENT_QUOTES, 'UTF-8') ?></h2>
  <?php if ($status === 'success'): ?>
    <span class="msg"><?= $message /* already escaped above */ ?></span>
    <p style="text-align: center; margin-top: 18px;"><a href="login.php" class="button-primary">Sign in</a></p>
  <?php else: ?>
    <span class="error"><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></span>
    <p style="text-align: center; margin-top: 18px;"><a href="login.php">Return to login</a></p>
  <?php endif; ?>
</div>

<?php include_once __DIR__ . '/footer.php'; ?>
