<?php
// Include buffer controller (handles output buffering)
require_once 'includes/buffer_controller.php';
include 'includes/header.php'; // Includes config, functions, db connection

// Language variables ($lang_frontend, $lang_alerts) are expected to be loaded by header.php
$page_title = $lang_frontend['PAGE_TITLE_EMAIL_VALIDATION'] ?? 'Email Validation';

$alert_message = '';
$alert_type = 'danger'; // Default to danger

if (isset($_GET['token'])) {
    $token = sanitizeInput($_GET['token']);

    if (empty($token)) {
        $alert_message = $lang_alerts['ALERT_ERROR_INVALID_VALIDATION_TOKEN_PROVIDED'] ?? 'Invalid validation token provided.';
    } else {
        // Check token against the database
        // Ensure comparison with NOW() is in UTC as token expiry is stored in UTC
        $stmt = $pdo->prepare("SELECT id, name, is_email_verified FROM users WHERE email_validation_token = ? AND email_validation_token_expires_at > NOW()");
        $stmt->execute([$token]);
        $user = $stmt->fetch();

        if ($user) {
            if ($user['is_email_verified']) {
                $alert_message = $lang_alerts['ALERT_INFO_EMAIL_ALREADY_VALIDATED'] ?? 'Your email address has already been validated. You can now log in.';
                $alert_type = 'info';
            } else {
                // Token is valid, user not yet verified, and token not expired
                $update_stmt = $pdo->prepare("UPDATE users SET is_email_verified = TRUE, email_validation_token = NULL, email_validation_token_expires_at = NULL WHERE id = ?");
                if ($update_stmt->execute([$user['id']])) {
                    $alert_message = sprintf($lang_alerts['ALERT_SUCCESS_EMAIL_VALIDATED'] ?? 'Thank you, %s! Your email address has been successfully validated. You can now log in.', htmlspecialchars($user['name']));
                    $alert_type = 'success';

                    // Send Welcome Email if enabled
                    if (defined('WELCOME_EMAIL') && WELCOME_EMAIL) {
                        // We need the user's email address to send the welcome email
                        // The $user array from the initial token check contains `name` but not `email`.
                        // Let's fetch the email, or ensure $user contains it.
                        // For now, assume $user does not have email, so we fetch it based on $user['id']
                        $stmt_get_email = $pdo->prepare("SELECT email FROM users WHERE id = ?");
                        $stmt_get_email->execute([$user['id']]);
                        $user_email_data = $stmt_get_email->fetch();

                        if ($user_email_data && !empty($user_email_data['email'])) {
                            $user_email_for_welcome = $user_email_data['email'];
                            $welcome_subject = sprintf($lang_frontend['EMAIL_SUBJECT_USER_WELCOME'] ?? "Welcome to %s!", SITE_NAME);
                            $welcome_body = "<p>" . sprintf($lang_frontend['EMAIL_GREETING'] ?? 'Hello %s,', htmlspecialchars($user['name'])) . "</p>"
                                          . "<p>" . sprintf($lang_frontend['EMAIL_SUBJECT_USER_WELCOME'] ?? "Welcome to %s!", SITE_NAME) . " " . ($lang_frontend['EMAIL_TEXT_WELCOME_EXCITED'] ?? "We're excited to have you on board.") . "</p>"
                                          . "<p>" . ($lang_frontend['EMAIL_TEXT_WELCOME_VALIDATED_ACCOUNT_ACTIVE'] ?? 'Your email address has been successfully validated, and your account is now active. You can log in and explore our services.') . "</p>"
                                          . "<p>" . sprintf($lang_frontend['EMAIL_TEXT_WELCOME_LOGIN_HERE'] ?? 'Login here: %s', "<a href=\"" . getCleanUrl('login') . "\">" . getCleanUrl('login') . "</a>") . "</p>"
                                          . "<p>" . ($lang_frontend['EMAIL_TEXT_WELCOME_SUPPORT_INFO'] ?? 'If you have any questions, feel free to check out our FAQ or contact support.') . "</p>"
                                          . "<p>" . ($lang_frontend['EMAIL_CLOSING_BEST_REGARDS'] ?? 'Best regards,') . "</p>"
                                          . "<p>" . sprintf($lang_frontend['EMAIL_SIGN_OFF_TEAM'] ?? 'The %s Team', SITE_NAME) . "</p>";
                            send_custom_email($user_email_for_welcome, $welcome_subject, $welcome_body);
                        } else {
                            error_log("Could not retrieve email for user ID: {$user['id']} to send welcome email after validation.");
                        }
                    }

                    // Optional: Notify admins that a user has verified their email
                    // $subject_admin_notify = "User Email Verified: " . htmlspecialchars($user['name']);
                    // $body_admin_notify = "<p>User " . htmlspecialchars($user['name']) . " (ID: {$user['id']}) has successfully verified their email address.</p>";
                    // notify_relevant_users('notify_user_email_verified', $subject_admin_notify, $body_admin_notify, [], true);

                } else {
                    $alert_message = $lang_alerts['ALERT_ERROR_EMAIL_VALIDATION_FAILED'] ?? 'There was an error validating your email address. Please try again or contact support.';
                    // Log this error for admin review
                    error_log("Failed to update user email validation status for user ID: {$user['id']}, token: {$token}");
                }
            }
        } else {
            // Token not found or expired
            // Check if a user exists with this token but it's expired to give a more specific message
            $stmt_expired_check = $pdo->prepare("SELECT id FROM users WHERE email_validation_token = ?");
            $stmt_expired_check->execute([$token]);
            if ($stmt_expired_check->fetch()) {
                $alert_message = $lang_alerts['ALERT_ERROR_VALIDATION_LINK_EXPIRED'] ?? 'This validation link has expired. Please request a new validation email if needed.';
            } else {
                $alert_message = $lang_alerts['ALERT_ERROR_VALIDATION_LINK_INVALID_OR_EXPIRED'] ?? 'Invalid or expired validation link. Please ensure you copied the link correctly or request a new one.';
            }
        }
    }
} else {
    $alert_message = $lang_alerts['ALERT_ERROR_NO_VALIDATION_TOKEN_PROVIDED'] ?? 'No validation token provided. Please use the link sent to your email address.';
}

// Store the alert in session to display it on the page (even after potential redirects or if header.php includes a redirect)
// Or display directly if this page is simple. For this page, direct display is fine.
$_SESSION['alert'] = displayAlert($alert_message, $alert_type);

// Redirect to login page after setting the alert, so the user sees the message there.
// Or, display message directly on this page. Let's display here for clarity.
?>

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-8 col-lg-6">
            <div class="card shadow">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0"><?php echo $lang_frontend['EMAIL_VALIDATION_HEADING'] ?? 'Email Validation'; ?></h4>
                </div>
                <div class="card-body">
                    <?php
                    if (isset($_SESSION['alert'])) {
                        echo $_SESSION['alert'];
                        unset($_SESSION['alert']); // Clear the alert after displaying
                    }
                    ?>
                    <div class="mt-3 text-center">
                        <a href="<?php echo getCleanUrl('login'); ?>" class="btn btn-primary"><?php echo $lang_frontend['EMAIL_VALIDATION_BUTTON_GO_TO_LOGIN'] ?? 'Go to Login'; ?></a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// End output buffering and flush
if (ob_get_level() > 0) {
    ob_end_flush();
}
include 'includes/footer.php';
?> 