<?php
include 'includes/header.php';

// $page_title is now set after language files are loaded by header.php
// Ensure $lang_frontend and $lang_navigation are available from header.php's centralized loader
$page_title = $lang_frontend['PAGE_TITLE_REGISTER'] ?? ($lang_navigation['NAV_REGISTER'] ?? 'Register');
?>

<?php
if (isLoggedIn()) {
    redirectTo('index');
}

if (!ALLOW_REGISTER) {
    redirectTo('index');
}

// Display any alerts at the top of the registration form
if (isset($_SESSION['alert'])) {
    echo $_SESSION['alert'];
    unset($_SESSION['alert']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token first
    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('register');
    }

    // Validate honeypot
    if (!validateHoneypot()) {
        // Bot detected, redirect with generic message
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_REGISTRATION_HONEYPOT'] ?? 'Registration completed successfully!', 'success');
        redirectTo('login');
        exit;
    }

    // Validate hCaptcha
    if (!validateHCaptcha($_POST['h-captcha-response'] ?? '')) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_CAPTCHA_VERIFICATION'] ?? 'Please complete the captcha verification to continue.', 'danger');
        $_SESSION['form_data'] = preserveFormData(['name', 'email', 'company', 'country_code', 'city']);
        redirectTo('register');
        exit;
    }

    $name = sanitizeInput($_POST['name']);
    $email = sanitizeInput($_POST['email']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $company = sanitizeInput($_POST['company']);
    // Disallow registration for blocked companies
    foreach (BLOCKED_COMPANIES as $blocked) {
        if (strcasecmp($company, $blocked) === 0) {
            $_SESSION['alert'] = displayAlert('Registration from scammers is not allowed.', 'danger');
            redirectTo('register');
            exit;
        }
    }
    $country_code = isset($_POST['country_code']) ? sanitizeInput($_POST['country_code']) : null;
    $city = isset($_POST['city']) ? sanitizeInput($_POST['city']) : null;

    // Enhanced validation with preserved form data
    $form_data = preserveFormData(['name', 'email', 'company', 'country_code', 'city']);
    $validation_errors = [];

    // Basic field validation
    if (empty($name)) {
        $validation_errors[] = $lang_frontend['VALIDATION_FULL_NAME_REQUIRED'] ?? 'Full name is required';
    }

    // Enhanced email validation
    $email_validation = validateEmail($email);
    if (!$email_validation['valid']) {
        $validation_errors = array_merge($validation_errors, $email_validation['errors']);
    } else {
        $email = $email_validation['sanitized'];
    }

    // Enhanced password validation
    if (empty($password)) {
        $validation_errors[] = $lang_frontend['VALIDATION_PASSWORD_REQUIRED'] ?? 'Password is required';
    } else {
        $password_validation = validatePassword($password);
        if (!$password_validation['valid']) {
            $validation_errors = array_merge($validation_errors, $password_validation['errors']);
        }
    }

    if (empty($confirm_password)) {
        $validation_errors[] = $lang_frontend['VALIDATION_CONFIRM_PASSWORD_REQUIRED'] ?? 'Please confirm your password';
    } elseif ($password !== $confirm_password) {
        $validation_errors[] = $lang_frontend['VALIDATION_PASSWORDS_NO_MATCH'] ?? 'Passwords do not match';
    }

    // Location field validation
    if (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS && empty($country_code)) {
        $validation_errors[] = $lang_frontend['VALIDATION_COUNTRY_REQUIRED'] ?? 'Country is required when location fields are enabled';
    }

    // If we have validation errors, set alert and preserve form data
    if (!empty($validation_errors)) {
        $error_message = sprintf($lang_frontend['VALIDATION_ERROR_WRAPPER'] ?? 'Please correct the following errors:<ul><li>%s</li></ul>', implode('</li><li>', $validation_errors));
        $_SESSION['alert'] = displayAlert($error_message, 'danger', true, false);
        $_SESSION['form_data'] = $form_data;
        redirectTo('register'); // Redirect if basic validation errors exist
    }

    // Check rate limiting after basic validation but before processing
    $rate_limit_check = checkRateLimit('register', $email);
    if (!$rate_limit_check['allowed']) {
        $_SESSION['alert'] = displayAlert($rate_limit_check['message'], 'warning');
        $_SESSION['form_data'] = $form_data; // Preserve form data
        redirectTo('register');
        exit;
    }

    // Record this attempt for rate limiting
    recordSubmissionAttempt('register', $email);

    // Check if email already exists
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);

    if ($stmt->rowCount() > 0) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_EMAIL_EXISTS'] ?? 'Email already exists. Please use a different email or login.', 'danger');
    } else {
        // Upload avatar if provided
        $avatar = '';
        if (!empty($_FILES['avatar']['name'])) {
            // Check if the file is an actual image
            if (function_exists('getimagesize') && is_uploaded_file($_FILES['avatar']['tmp_name'])) {
                $image_info = @getimagesize($_FILES['avatar']['tmp_name']);
                if (!$image_info) {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_AVATAR_INVALID_IMAGE'] ?? 'Uploaded avatar is not a valid image. Please upload a valid image file (e.g., JPG, PNG, GIF).', 'danger');
                    $_SESSION['form_data'] = $form_data; // Preserve form data
                    redirectTo('register');
                    exit; // Halt registration
                }
            } else if (!is_uploaded_file($_FILES['avatar']['tmp_name']) && $_FILES['avatar']['error'] !== UPLOAD_ERR_NO_FILE) {
                // Check for other upload errors only if a file was partially uploaded or an error occurred other than no file.
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_AVATAR_UPLOAD'] ?? 'Avatar upload error. Please try again.', 'danger');
                $_SESSION['form_data'] = $form_data; // Preserve form data
                redirectTo('register');
                exit; // Halt registration
            }

            // Attempt to upload the file if it seems valid so far
            $avatar_filename = uploadFile($_FILES['avatar'], 'uploads/avatars/');
            if ($avatar_filename === false) {
                // uploadFile sets its own specific alert, or a generic one if not already set by prior checks.
                // We ensure an alert is set if uploadFile returns false.
                if (!isset($_SESSION['alert'])) { // Set a generic one if uploadFile didn't.
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_AVATAR_UPLOAD_FAILED_GENERIC'] ?? 'Avatar upload failed. Please check file size, type, or permissions.', 'danger');
                }
                $_SESSION['form_data'] = $form_data; // Preserve form data
                redirectTo('register');
                exit; // Halt registration
            }
            $avatar = $avatar_filename; // Assign the successfully uploaded filename
        }

        // Hash password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        // Prepare for email validation if enabled
        $is_email_verified = true; // Default to true
        $email_validation_token = null;
        $email_validation_token_expires_at_utc = null;

        if (FORCE_EMAIL_VALIDATION) {
            $is_email_verified = false;
            $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');
        }

        // Prepare location fields
        $db_country_code = (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS && !empty($country_code)) ? $country_code : null;
        $db_city = (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS && !empty($city)) ? $city : null;

        // Insert new user
        $stmt = $pdo->prepare("INSERT INTO users (name, email, password, avatar, company, role, is_email_verified, email_validation_token, email_validation_token_expires_at, country_code, city) VALUES (?, ?, ?, ?, ?, 'member', ?, ?, ?, ?, ?)");
        $stmt->execute([$name, $email, $hashed_password, $avatar, $company, $is_email_verified, $email_validation_token, $email_validation_token_expires_at_utc, $db_country_code, $db_city]);
        $new_user_id = $pdo->lastInsertId();

        // Link any guest subscriptions to this new user account
        if (function_exists('linkGuestSubscriptions')) {
            linkGuestSubscriptions($new_user_id, $email, $pdo);
        }

        // Send notification to admins about new registration
        $subject_admin_notify = sprintf($lang_frontend['EMAIL_SUBJECT_ADMIN_NEW_USER_REGISTRATION'] ?? "New User Registration: %s", htmlspecialchars($name));
        $body = "<p>A new user has registered on the platform.</p>" . // This part could be a lang string too
            "<p><strong>Name:</strong> " . htmlspecialchars($name) . "</p>" .
            "<p><strong>Email:</strong> " . htmlspecialchars($email) . "</p>" .
            "<p><strong>Company:</strong> " . htmlspecialchars($company) . "</p>" .
            "<p>You can view their profile (if an admin view exists) or manage users in the admin panel.</p>" .
            "<p>User ID: {$new_user_id}</p>"; // Include user ID for reference

        // It's an admin-only event, so specific_user_ids is empty, and is_admin_event is true.
        notify_relevant_users('notify_new_user_registration', $subject_admin_notify, $body, [], true);

        if (FORCE_EMAIL_VALIDATION && !$is_email_verified) {
            // Send validation email to user
            $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($name)) . "</p>" .
                "<p>" . sprintf($lang_frontend['EMAIL_TEXT_THANK_YOU_FOR_REGISTERING'] ?? 'Thank you for registering 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_YOU'] ?? 'If you did not register, please ignore this email.') . "</p>";

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

            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_INFO_REGISTRATION_VALIDATION_SENT'] ?? 'Registration successful! A validation email has been sent to your email address. Please check your inbox (and spam folder) to activate your account.', 'info');
        } else {
            // This means registration is successful and either validation is not forced, or user is already marked verified (e.g. admin created by admin)
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_REGISTRATION_LOGIN_NOW'] ?? 'Registration successful! You can now login.');

            // Send Welcome Email if enabled and user is effectively verified at this point
            if (defined('WELCOME_EMAIL') && WELCOME_EMAIL && $is_email_verified) {
                $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($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_ACCOUNT_CREATED'] ?? 'Your account has been successfully created. You can now 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($email, $welcome_subject, $welcome_body);
            }
        }
        redirectTo('login');
    }
}
?>
<?php if (defined('USE_LOGO_LOGIN') && USE_LOGO_LOGIN && defined('LOGO_LOGIN_URL') && !empty(LOGO_LOGIN_URL)): ?>
    <center><img src="<?php echo LOGO_LOGIN_URL; ?>" alt="" <?php echo (defined('LOGO_LOGIN_WIDTH') && LOGO_LOGIN_WIDTH) ? 'width="' . LOGO_LOGIN_WIDTH . '"' : ''; ?>><br><br></center>

<?php endif; ?>
<div class="row justify-content-center">
    <?php
    if (isset($_SESSION['alert'])) {
        echo $_SESSION['alert'];
        unset($_SESSION['alert']);
    }
    ?>
    <div class="col-md-8">
        <div class="card shadow">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0">
                    <?php echo $lang_frontend['HOME_CREATE_ACCOUNT_TITLE'] ?? ($lang_frontend['REGISTER_HEADING'] ?? 'Create an Account'); ?>
                </h4>
            </div>
            <div class="card-body">
                <?php if (SITE_REGISTER_MESSAGE !== ''): ?>
                    <p><?php echo htmlspecialchars(SITE_REGISTER_MESSAGE, ENT_QUOTES, 'UTF-8'); ?></p>
                <?php endif; ?>
                <form id="registerForm" action="<?php echo getCleanUrl('register'); ?>" method="post"
                    enctype="multipart/form-data">
                    <?php echo get_csrf_input_field(); ?>
                    <div class="mb-3">
                        <label for="company"
                            class="form-label"><?php echo $lang_frontend['FORM_LABEL_COMPANY'] ?? 'Company'; ?></label>
                        <input type="text" class="form-control" id="company" name="company">
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="name"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_FULL_NAME'] ?? 'Full Name'; ?>
                                <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="name" name="name" required
                                value="<?php echo isset($_SESSION['form_data']['name']) ? $_SESSION['form_data']['name'] : ''; ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="email"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_EMAIL'] ?? 'Email address'; ?>
                                <span class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="email" name="email" required
                                value="<?php echo isset($_SESSION['form_data']['email']) ? $_SESSION['form_data']['email'] : ''; ?>">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="password"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_PASSWORD'] ?? 'Password'; ?>
                                <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="password" name="password" required>
                            <div class="form-text">
                                <?php echo $lang_frontend['FORM_TEXT_PASSWORD_REQUIREMENTS'] ?? 'Password must contain uppercase, lowercase, number, and be at least 8 characters'; ?>
                            </div>
                            <div id="passwordStrength" class="mt-1"></div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="confirm_password"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_CONFIRM_PASSWORD'] ?? 'Confirm Password'; ?>
                                <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="confirm_password" name="confirm_password"
                                required>
                        </div>
                    </div>

                    <?php if (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS): ?>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="country_code"
                                    class="form-label"><?php echo $lang_frontend['FORM_LABEL_COUNTRY'] ?? 'Country'; ?>
                                    <span class="text-danger">*</span></label>
                                <select class="form-select" id="country_code" name="country_code" required>
                                    <option value="">
                                        <?php echo $lang_frontend['FORM_OPTION_SELECT_COUNTRY'] ?? '-- Select Country --'; ?>
                                    </option>
                                    <?php
                                    $countries = get_country_list();
                                    $default_country = defined('DEFAULT_COUNTRY') ? DEFAULT_COUNTRY : 'US';
                                    foreach ($countries as $code => $country_name): ?>
                                        <option value="<?php echo htmlspecialchars($code); ?>" <?php echo ($code === $default_country) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($country_name); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="city"
                                    class="form-label"><?php echo $lang_frontend['FORM_LABEL_CITY'] ?? 'City'; ?></label>
                                <input type="text" class="form-control" id="city" name="city">
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="mb-3">
                        <label for="avatar"
                            class="form-label"><?php echo $lang_frontend['FORM_LABEL_PROFILE_PICTURE_OPTIONAL'] ?? 'Profile Picture (Optional)'; ?></label>
                        <input type="file" class="form-control" id="avatar" name="avatar" accept="image/*"
                            data-max-size="<?php echo MAX_UPLOAD_SIZE; ?>" data-allowed-types="jpg,jpeg,png,gif,svg">
                    </div>
                    <div class="form-text">
                        <?php echo sprintf($lang_frontend['FORM_TEXT_MAX_FILE_SIZE'] ?? 'Max file size: %sMB.', MAX_UPLOAD_SIZE / 1024 / 1024); ?>
                        <br><br>
                    </div>

                    <?php echo generateHCaptchaField(); ?>

                    <?php echo generateHoneypotField(); ?>

                    <div class="d-grid">
                        <button type="submit"
                            class="btn btn-primary btn-lg"><?php echo $lang_frontend['REGISTER_BUTTON_REGISTER'] ?? ($lang_navigation['NAV_REGISTER'] ?? 'Register'); ?></button>
                    </div>
                </form>
            </div>
            <div class="card-footer">
                <div class="text-center">
                    <?php echo $lang_frontend['REGISTER_TEXT_ALREADY_ACCOUNT'] ?? 'Already have an account?'; ?> <a
                        href="<?php echo getCleanUrl('login'); ?>"><?php echo $lang_frontend['REGISTER_LINK_LOGIN_HERE'] ?? 'Login here'; ?></a>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Clear session form data after displaying
if (isset($_SESSION['form_data'])) {
    unset($_SESSION['form_data']);
}

// Generate validation script
$validation_rules = [
    'name' => [
        'required' => true,
        'requiredMessage' => $lang_frontend['VALIDATION_FULL_NAME_REQUIRED'] ?? 'Full name is required'
    ],
    'email' => [
        'required' => true,
        'type' => 'email',
        'requiredMessage' => $lang_frontend['VALIDATION_EMAIL_REQUIRED'] ?? 'Email address is required' // Assuming VALIDATION_EMAIL_REQUIRED exists or will be added
    ],
    'password' => [
        'required' => true,
        'type' => 'password',
        'minLength' => 8,
        'requiredMessage' => $lang_frontend['VALIDATION_PASSWORD_REQUIRED'] ?? 'Password is required'
    ],
    'confirm_password' => [
        'required' => true,
        'requiredMessage' => $lang_frontend['VALIDATION_CONFIRM_PASSWORD_REQUIRED'] ?? 'Please confirm your password'
    ]
];

echo generateFormValidationScript('registerForm', $validation_rules);
?>

<script>
    // Password strength indicator
    document.addEventListener('DOMContentLoaded', function () {
        const passwordField = document.getElementById('password');
        const strengthDiv = document.getElementById('passwordStrength');

        if (passwordField && strengthDiv) {
            passwordField.addEventListener('input', function () {
                updatePasswordStrength(this.value, strengthDiv);
            });
        }

        function updatePasswordStrength(password, strengthDiv) {
            let strength = 0;
            let feedback = [];

            if (password.length >= 8) strength += 1;
            else if (password.length > 0) feedback.push('<?php echo addslashes($lang_frontend['JS_PASSWORD_STRENGTH_MIN_LENGTH'] ?? 'At least 8 characters'); ?>');

            if (/[a-z]/.test(password)) strength += 1;
            else if (password.length > 0) feedback.push('<?php echo addslashes($lang_frontend['JS_PASSWORD_STRENGTH_LOWERCASE'] ?? 'Lowercase letter'); ?>');

            if (/[A-Z]/.test(password)) strength += 1;
            else if (password.length > 0) feedback.push('<?php echo addslashes($lang_frontend['JS_PASSWORD_STRENGTH_UPPERCASE'] ?? 'Uppercase letter'); ?>');

            if (/[0-9]/.test(password)) strength += 1;
            else if (password.length > 0) feedback.push('<?php echo addslashes($lang_frontend['JS_PASSWORD_STRENGTH_NUMBER'] ?? 'Number'); ?>');

            let strengthClass = '';
            let strengthText = '';

            if (password.length === 0) {
                strengthDiv.innerHTML = '';
                return;
            }

            if (strength >= 4) {
                strengthClass = 'text-success';
                strengthText = '<?php echo addslashes($lang_frontend['JS_PASSWORD_STRENGTH_STRONG'] ?? 'Strong password'); ?>';
            } else if (strength >= 2) {
                strengthClass = 'text-warning';
                strengthText = '<?php echo addslashes($lang_frontend['JS_PASSWORD_STRENGTH_MEDIUM'] ?? 'Medium password'); ?>';
            } else {
                strengthClass = 'text-danger';
                strengthText = '<?php echo addslashes($lang_frontend['JS_PASSWORD_STRENGTH_WEAK'] ?? 'Weak password'); ?>';
            }

            if (feedback.length > 0) {
                strengthText += ' - <?php echo addslashes(sprintf($lang_frontend['JS_PASSWORD_STRENGTH_MISSING'] ?? 'Missing: %s', "")); ?>' + feedback.join(', ');
            }

            strengthDiv.innerHTML = `<small class="${strengthClass}">${strengthText}</small>`;
        }

        // Bot detection for suspicious name patterns
        const nameField = document.getElementById('name');
        const submitButton = document.querySelector('#registerForm button[type="submit"]');
        const originalButtonText = submitButton.textContent;
        let isNameSuspicious = false;

        if (nameField && submitButton) {
            nameField.addEventListener('input', function () {
                checkNamePattern(this.value.trim());
            });

            // Also check on form load if name has preserved value
            if (nameField.value.trim()) {
                checkNamePattern(nameField.value.trim());
            }
        }

        function checkNamePattern(name) {
            if (!name || name.length < 2) {
                isNameSuspicious = false;
                enableSubmitButton();
                return;
            }

            // Check for suspicious patterns typical of bots
            const suspiciousPatterns = [
                // All uppercase (but allow single letters/initials)
                /^[A-Z\s]{3,}$/,
                // Mixed case but with unusual patterns (alternating case, too many capitals)
                /^[A-Z][a-z][A-Z][a-z]/,  // Alternating case like "JoHn"
                /^[A-Z]{2,}[a-z]+[A-Z]{2,}/, // Multiple caps like "JOHNsmith" or "johnSMITH"
                // Too many capital letters in the middle
                /[a-z][A-Z]{2,}[a-z]/, // Like "joHNsmith"
                // Suspicious character combinations
                /[A-Z]{3,}/, // 3 or more consecutive capitals in any position
            ];

            // Check if name matches any suspicious pattern
            isNameSuspicious = suspiciousPatterns.some(pattern => pattern.test(name));

            if (isNameSuspicious) {
                disableSubmitButton();
            } else {
                enableSubmitButton();
            }
        }

        function disableSubmitButton() {
            if (submitButton && !submitButton.disabled) {
                submitButton.disabled = true;
                submitButton.style.cursor = 'not-allowed';
            }
        }

        function enableSubmitButton() {
            if (submitButton && isNameSuspicious === false) {
                submitButton.disabled = false;
                submitButton.style.cursor = 'pointer';
            }
        }

        // Prevent form submission if name is suspicious
        document.getElementById('registerForm').addEventListener('submit', function (e) {
            if (isNameSuspicious) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
        });
    });
</script>

<?php include 'includes/footer.php'; ?>