<?php
// Include header (which includes all dependencies)
include 'includes/header.php';

// Language variables ($lang_frontend, $lang_alerts) are expected to be loaded by header.php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_CSRF'] ?? 'Invalid CSRF token. Please try again.', 'danger');
        redirectTo('login');
        exit;
    }

    // Use centralized email validation function
    $email_validation = validateEmail($_POST['email'] ?? '');
    if (!$email_validation['valid']) {
        $_SESSION['alert'] = displayAlert($email_validation['errors'][0] ?? $lang_alerts['ALERT_ERROR_INVALID_EMAIL_PROVIDED'] ?? 'Invalid email address provided.', 'danger');
        redirectTo('login');
        exit;
    }
    $email = $email_validation['sanitized'];

    $stmt = $pdo->prepare("SELECT id, name, is_email_verified, email_validation_token_expires_at FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user) {
        if ($user['is_email_verified']) {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_INFO_EMAIL_ALREADY_VERIFIED'] ?? 'This email address has already been verified. You can log in.', 'info');
        } else {
            // Check if user already has a valid (non-expired) token
            $has_valid_token = false;
            if (!empty($user['email_validation_token_expires_at'])) {
                $stmt_check_token = $pdo->prepare("SELECT id FROM users WHERE email = ? AND email_validation_token IS NOT NULL AND email_validation_token_expires_at > NOW()");
                $stmt_check_token->execute([$email]);
                $has_valid_token = $stmt_check_token->fetch() !== false;
            }

            if ($has_valid_token) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_INFO_VALIDATION_TOKEN_STILL_VALID'] ?? 'A validation email was recently sent. Please check your inbox (and spam folder). If you did not receive it, please wait a few minutes before requesting again.', 'info');
            } else {
                // User found and not verified, generate new token and send email
                $email_validation_token = bin2hex(random_bytes(32));
                $dt = new DateTime('now', new DateTimeZone(TIMEZONE)); // Current time in application timezone
                $dt->modify('+24 hours'); // Add 24 hours
                $dt->setTimezone(new DateTimeZone('UTC')); // Convert to UTC
                $email_validation_token_expires_at_utc = $dt->format('Y-m-d H:i:s');

                $update_stmt = $pdo->prepare("UPDATE users SET email_validation_token = ?, email_validation_token_expires_at = ? WHERE id = ?");
                if ($update_stmt->execute([$email_validation_token, $email_validation_token_expires_at_utc, $user['id']])) {
                    $validation_link = getBaseUrl() . '/validate_email.php?token=' . $email_validation_token;
                    $subject_user_validation = sprintf($lang_frontend['EMAIL_SUBJECT_USER_VALIDATE_EMAIL'] ?? 'Validate Your Email Address - %s', SITE_NAME);
                    $body_user_validation = "<p>" . sprintf($lang_frontend['EMAIL_GREETING'] ?? 'Hello %s,', htmlspecialchars($user['name'])) . "</p>" .
                        "<p>" . sprintf($lang_frontend['EMAIL_TEXT_RESEND_VALIDATION_REQUEST_RECEIVED'] ?? 'We received a request to resend the email validation link for your account at %s.', SITE_NAME) . "</p>" .
                        "<p>" . ($lang_frontend['EMAIL_TEXT_VALIDATE_INSTRUCTION'] ?? 'Please click the link below to validate your email address and activate your account:') . "</p>" .
                        "<p><a href=\"" . $validation_link . "\">" . htmlspecialchars($validation_link) . "</a></p>" .
                        "<p>" . ($lang_frontend['EMAIL_TEXT_LINK_EXPIRY_24H'] ?? 'This link will expire in 24 hours.') . "</p>" .
                        "<p>" . ($lang_frontend['EMAIL_TEXT_IGNORE_IF_NOT_REQUESTED_RESEND'] ?? 'If you did not request this, please ignore this email.') . "</p>";

                    send_custom_email($email, $subject_user_validation, $body_user_validation);

                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_NEW_VALIDATION_EMAIL_SENT'] ?? 'A new validation email has been sent to your email address. Please check your inbox (and spam folder) to activate your account.', 'success');
                } else {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_RESEND_VALIDATION_DB_ERROR'] ?? 'Could not resend validation email due to a database error. Please try again later.', 'danger');
                    error_log("Failed to update validation token for user ID: {$user['id']} during resend attempt.");
                }
            }
        }
    } else {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_WARNING_NO_ACCOUNT_FOUND_EMAIL'] ?? 'No account found with that email address.', 'warning');
    }
} else {
    // Not a POST request, just redirect to login
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_REQUEST_METHOD'] ?? 'Invalid request method.', 'danger');
}

redirectTo('login');
if (ob_get_level() > 0) {
    ob_end_flush();
}
exit;
?>