<?php
require_once('common.php');

$heading = 'Email Confirmation';
$body    = '';

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

// Tokens are 64 hex chars (bin2hex of 32 random bytes).
if ($token === '' || !ctype_xdigit($token) || strlen($token) !== 64) {
    $body = 'This confirmation link is invalid. Please check the link in your email, or sign up again.';
} else {
    try {
        $stmt = $pdo->prepare("SELECT id, email_confirmed FROM sm_poets WHERE confirm_token = :t");
        $stmt->bindValue(':t', $token, PDO::PARAM_STR);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            $body = 'This confirmation link is invalid or has already been used. If you have already confirmed, please <a href="login.php">log in</a>.';
        } else {
            // Confirm the account and consume the token.
            $upd = $pdo->prepare("UPDATE sm_poets SET email_confirmed = 1, confirm_token = NULL WHERE id = :id");
            $upd->bindValue(':id', $row['id'], PDO::PARAM_INT);
            $upd->execute();

            $heading = 'You are confirmed!';
            $body = 'Your email address has been confirmed. You can now <a href="login.php">log in</a> and submit your work.';
        }
    } catch (PDOException $e) {
        error_log('confirm-email.php DB error: ' . $e->getMessage());
        $body = 'A temporary error occurred. Please try again shortly.';
    }
}

include_once('header.php');
include_once('menu.php');
?>

<div class="container" style="max-width:600px; margin:40px auto; text-align:center;">
    <h2><?php echo htmlspecialchars($heading, ENT_QUOTES, 'UTF-8'); ?></h2>
    <p><?php echo $body; /* trusted static strings only */ ?></p>
</div>

<?php
include_once('footer.php');
