<?php
require_once 'config/db.php';
$token = $_GET['token'] ?? '';
$isValid = false;
$message = '';

if (!empty($token)) {
    $stmt = $pdo->prepare("SELECT * FROM email_change_requests WHERE token = ? AND expires_at > NOW()");
    $stmt->execute([$token]);
    $request = $stmt->fetch();
    if ($request) {
        $isValid = true;
    } else {
        $message = "Invalid or expired token. Please request a new email change from your profile.";
    }
} else {
    $message = "No token provided.";
}
?>
<!DOCTYPE html>
<html lang="en">

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

        .card {
            background: white;
            padding: 40px;
            border-radius: 20px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
            width: 100%;
            max-width: 450px;
            text-align: center;
        }

        .logo {
            height: 80px;
            margin-bottom: 20px;
        }

        h1 {
            font-size: 24px;
            color: #0f172a;
            margin-bottom: 10px;
        }

        p {
            color: #64748b;
            margin-bottom: 30px;
            font-size: 15px;
            line-height: 1.5;
        }

        .input-group {
            text-align: left;
            margin-bottom: 20px;
        }

        label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: #475569;
            margin-bottom: 8px;
        }

        input {
            width: 100%;
            padding: 12px 16px;
            border-radius: 10px;
            border: 1px solid #e2e8f0;
            font-size: 15px;
            box-sizing: border-box;
            transition: all 0.2s;
        }

        input:focus {
            border-color: #2563eb;
            outline: none;
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

        button {
            width: 100%;
            padding: 14px;
            background: #0f172a;
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }

        button:hover {
            background: #1e293b;
            transform: translateY(-1px);
        }

        button:active {
            transform: translateY(0);
        }

        .error {
            color: #ef4444;
            background: #fef2f2;
            padding: 15px;
            border-radius: 10px;
            border: 1px solid #fee2e2;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .success {
            color: #10b981;
            background: #ecfdf5;
            padding: 15px;
            border-radius: 10px;
            border: 1px solid #d1fae5;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .spinner {
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top: 3px solid white;
            width: 20px;
            height: 20px;
            animation: spin 0.8s linear infinite;
            display: none;
            margin: 0 auto;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }
    </style>
</head>

<body>
    <div class="card">
        <img src="assets/images/nroi_logo.png" alt="NROI Logo" class="logo">
        <?php if ($isValid): ?>
            <h1>Update Your Email</h1>
            <p>Verification successful! You can now securely update your email address below.</p>
            <form id="emailChangeForm">
                <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
                <div class="input-group">
                    <label for="new_email">New Email Address</label>
                    <input type="email" id="new_email" name="new_email" placeholder="example@gmail.com" required>
                </div>
                <div id="formMessage"></div>
                <button type="submit" id="submitBtn">
                    <span id="btnText">Update Email Address</span>
                    <div class="spinner" id="btnSpinner"></div>
                </button>
            </form>
        <?php else: ?>
            <h1 style="color: #ef4444;">Verification Failed</h1>
            <p>
                <?php echo htmlspecialchars($message); ?>
            </p>
            <a href="index.php" style="color: #2563eb; text-decoration: none; font-weight: 600;">Go back to Login</a>
        <?php endif; ?>
    </div>

    <script>
        const form = document.getElementById('emailChangeForm');
        if (form) {
            form.addEventListener('submit', async (e) => {
                e.preventDefault();
                const btn = document.getElementById('submitBtn');
                const text = document.getElementById('btnText');
                const spinner = document.getElementById('btnSpinner');
                const message = document.getElementById('formMessage');
                const newEmail = document.getElementById('new_email').value;

                text.style.display = 'none';
                spinner.style.display = 'block';
                btn.disabled = true;
                message.innerHTML = '';

                try {
                    const response = await fetch('api/confirm_new_email.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            token: form.token.value,
                            new_email: newEmail
                        })
                    });
                    const res = await response.json();

                    if (res.success) {
                        message.innerHTML = `<div class="success">${res.message}</div>`;
                        form.style.display = 'none';
                        setTimeout(() => {
                            window.location.href = 'index.php';
                        }, 3000);
                    } else {
                        message.innerHTML = `<div class="error">${res.message}</div>`;
                        text.style.display = 'block';
                        spinner.style.display = 'none';
                        btn.disabled = false;
                    }
                } catch (e) {
                    message.innerHTML = `<div class="error">An error occurred. Please try again.</div>`;
                    text.style.display = 'block';
                    spinner.style.display = 'none';
                    btn.disabled = false;
                }
            });
        }
    </script>
</body>

</html>