<?php
require_once __DIR__ . '/../config/cors.php';
require_once __DIR__ . '/../config/db.php';

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

if (empty($token)) {
    die("Invalid confirmation link.");
}

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

    if ($user) {
        // Mark as confirmed and clear token
        $updateStmt = $pdo->prepare("UPDATE users SET is_email_confirmed = 1, email_confirmation_token = NULL WHERE id = ?");
        $updateStmt->execute([$user['id']]);

        // Show a nice success message
        ?>
        <!DOCTYPE html>
        <html lang="en">

        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Email Confirmed - NROI Portal</title>
            <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
            <style>
                body {
                    font-family: 'Inter', sans-serif;
                    background-color: #f8fafc;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    height: 100vh;
                    margin: 0;
                }

                .card {
                    background: white;
                    padding: 2rem;
                    border-radius: 12px;
                    box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
                    text-align: center;
                    max-width: 400px;
                }

                h1 {
                    color: #1e293b;
                    margin-bottom: 1rem;
                }

                p {
                    color: #64748b;
                    margin-bottom: 2rem;
                }

                .btn {
                    background-color: #020617;
                    color: white;
                    padding: 0.75rem 1.5rem;
                    border-radius: 6px;
                    text-decoration: none;
                    font-weight: 600;
                }
            </style>
        </head>

        <body>
            <div class="card">
                <div style="font-size: 3rem; margin-bottom: 1rem;">✅</div>
                <h1>Email Confirmed!</h1>
                <p>Thank you for confirming your email. Your account is now linked and verified.</p>
            </div>
        </body>

        </html>
        <?php
    } else {
        die("Invalid or expired confirmation token.");
    }
} catch (Exception $e) {
    die("An error occurred: " . $e->getMessage());
}
?>