<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$token = $_GET['token'] ?? '';

if (empty($token)) {
    $_SESSION['flash_error'] = "Invalid or missing verification token.";
    header("Location: login");
    exit();
}

try {
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email_verification_token = ? AND is_email_verified = FALSE");
    $stmt->execute([$token]);
    $user_id = $stmt->fetchColumn();

    if ($user_id) {
        // Verify user and clear token
        $upd = $pdo->prepare("UPDATE users SET is_email_verified = TRUE, email_verification_token = NULL WHERE id = ?");
        $upd->execute([$user_id]);

        $_SESSION['flash_success'] = "Your email has been verified successfully! You may now log in.";
    } else {
        $_SESSION['flash_error'] = "Invalid token or email already verified.";
    }
} catch (PDOException $e) {
    $_SESSION['flash_error'] = "Database error during verification.";
}

header("Location: login");
exit();
