<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

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

if (!$token) {
    die("Invalid verification link.");
}

try {
    // Find user with this token
    $stmt = $pdo->prepare("SELECT id FROM users WHERE verification_token = ?");
    $stmt->execute([$token]);
    $user = $stmt->fetch();

    if (!$user) {
        die("Invalid or expired verification link.");
    }

    // Mark as verified
    $stmt = $pdo->prepare("UPDATE users SET email_verified = 1, verification_token = NULL WHERE id = ?");
    $stmt->execute([$user['id']]);

    // Redirect to login with success
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
    // Assuming frontend is on port 5173 for dev, or same host for prod.
    // For simplicity, we'll redirect to /login (frontend handles routing)
    // Adjust based on where this PHP is served relative to the frontend.
    // If strict separation: http://localhost:5173/login?verified=true
    
    // We'll output a simple HTML with redirect to handle different environments gracefully
    echo "
    <html>
    <head>
        <title>Email Verified</title>
        <meta http-equiv='refresh' content='3;url=/login?verified=true' />
        <style>
            body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: #f0fdf4; color: #166534; }
            .card { background: white; padding: 2rem; border-radius: 1rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); text-align: center; }
            h1 { margin-bottom: 0.5rem; }
            a { color: #16a34a; text-decoration: none; font-weight: bold; }
        </style>
    </head>
    <body>
        <div class='card'>
            <h1>✅ Email Verified!</h1>
            <p>Your email has been successfully verified.</p>
            <p>Redirecting you to login...</p>
            <p><small>(If not redirected, <a href='/login?verified=true'>click here</a>)</small></p>
        </div>
    </body>
    </html>
    ";

} catch (Exception $e) {
    die("Error verifying email: " . $e->getMessage());
}
?>
