<?php
namespace WPUltimateSecurity\UltimateSecurity\Modules\Authentication\TwoFactor\Http;

use WPUltimateSecurity\UltimateSecurity\Modules\Authentication\TwoFactor\Providers\EmailProvider;
use WPUltimateSecurity\UltimateSecurity\Modules\Authentication\TwoFactor\Providers\TOTPProvider;
use WPUltimateSecurity\UltimateSecurity\Modules\Authentication\TwoFactor\Providers\HOTPProvider;
use WPUltimateSecurity\UltimateSecurity\Modules\Authentication\TwoFactor\Services\EncryptionService;
use WPUltimateSecurity\UltimateSecurity\Modules\Authentication\TwoFactor\Services\SimpleBackupCodeService;
use WPUltimateSecurity\UltimateSecurity\Modules\Authentication\TwoFactor\Services\TokenService;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;

/**
 * AJAX Handlers for 2FA
 *
 * Handles all AJAX endpoints for 2FA functionality
 */
class AjaxHandlers
{
	/**
	 * User meta keys for 2FA
	 */
	const META_2FA_CODE = 'ultimate_security_2fa_code';
	const META_2FA_PROVIDER = 'ultimate-security-2fa-provider';
	const META_2FA_UPDATED_AT = 'ultimate-security-2fa-updated-at';
	const META_2FA_PENDING = 'ultimate_security_2fa_pending';
	const META_EMAIL_AUTH_ENABLED = 'ultimate_security_enable_email_authentication';

	/**
	 * Transient keys
	 */
	const TRANSIENT_CODE_GENERATION = '2fa_code_generation_';
	const TRANSIENT_2FA_RESEND_COOLDOWN = '2fa_resend_cooldown_';

	/**
	 * Nonce action
	 */
	const NONCE_ACTION = 'ultimate_security_nonce';

	/**
	 * Register AJAX handlers
	 */
	public static function register()
	{
		// TOTP handlers
		add_action('wp_ajax_ultimate_security_update_totp_otp_code', [self::class, 'ajax_update_totp_code']);
		add_action('wp_ajax_ultimate_security_update_totp_secret_code', [self::class, 'ajax_reset_totp_secret']);

		// HOTP handlers
		add_action('wp_ajax_ultimate_security_update_hotp_otp_code', [self::class, 'ajax_update_hotp_code']);
		add_action('wp_ajax_ultimate_security_update_hotp_secret_code', [self::class, 'ajax_reset_hotp_secret']);

		// Email handlers
		add_action('wp_ajax_ultimate_security_sent_otp_email', [self::class, 'ajax_send_otp_email']);
		add_action('wp_ajax_ultimate_security_enable_otp_email', [self::class, 'ajax_enable_otp_email']);
		add_action('wp_ajax_nopriv_ultimate_security_resend_2fa_code', [self::class, 'ajax_resend_2fa_code']);

		// Encryption
		add_action('wp_ajax_ultimate_security_enable_encryption_database_keys', [self::class, 'ajax_enable_encryption']);

		// Reset
		add_action('wp_ajax_ultimate_security_user_2fa_reset', [self::class, 'ajax_reset_2fa']);
		add_action('wp_ajax_ultimate_security_user_2fa_set', [self::class, 'ajax_set_2fa']);
		add_action('wp_ajax_ultimate_security_user_2fa_get', [self::class, 'ajax_get_2fa']);

		// Backup Codes
		add_action('wp_ajax_ultimate_security_generate_backup_codes', [self::class, 'ajax_generate_backup_codes']);
		add_action('wp_ajax_ultimate_security_get_backup_codes_status', [self::class, 'ajax_get_backup_codes_status']);
		add_action('wp_ajax_ultimate_security_revoke_backup_codes', [self::class, 'ajax_revoke_backup_codes']);
	}

	/**
	 * AJAX: Update TOTP code
	 */
	public static function ajax_update_totp_code()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error(
				[
					'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
				]
			);
			wp_die();
		}

		// Check ownership/capability - users can only access their own data
		$current_user_id = get_current_user_id();
		$user_id = isset($_POST['user_id']) ? absint(sanitize_text_field(wp_unslash($_POST['user_id']))) : $current_user_id;
		if (!current_user_can('manage_options') && $current_user_id !== $user_id) {
			wp_send_json_error(['error_message' => __('Permission denied.', 'ultimate-security')]);
			exit;
		}
		$otp_data = TOTPProvider::get_otp_data($user_id);

		if (isset($otp_data['totp_code'])) {
			wp_send_json_success(['current_code' => $otp_data['totp_code']]);
			exit;
		} else {
			wp_send_json_error(['error_message' => __('User not found', 'ultimate-security')]);
			exit;
		}
	}

	/**
	 * AJAX: Reset TOTP secret
	 */
	public static function ajax_reset_totp_secret()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error(
				[
					'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
				]
			);
			wp_die();
		}

		// Check ownership/capability - users can only reset their own secret
		$current_user_id = get_current_user_id();
		$user_id = isset($_POST['user_id']) ? intval(wp_unslash($_POST['user_id'])) : $current_user_id;
		if (!current_user_can('manage_options') && $current_user_id !== $user_id) {
			wp_send_json_error(['error_message' => __('Permission denied.', 'ultimate-security')]);
			exit;
		}
		$otp_data = TOTPProvider::reset_secret($user_id);

		if ($otp_data) {
			wp_send_json_success($otp_data);
			exit;
		} else {
			wp_send_json_error(['error_message' => __('User not found', 'ultimate-security')]);
			exit;
		}
	}

	/**
	 * AJAX: Update HOTP code (generates next code and increments counter)
	 */
	public static function ajax_update_hotp_code()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error(
				[
					'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
				]
			);
			wp_die();
		}

		// Check ownership/capability - users can only access their own data
		$current_user_id = get_current_user_id();
		$user_id = isset($_POST['user_id']) ? intval(wp_unslash($_POST['user_id'])) : $current_user_id;
		if (!current_user_can('manage_options') && $current_user_id !== $user_id) {
			wp_send_json_error(['error_message' => __('Permission denied.', 'ultimate-security')]);
			exit;
		}

		// Generate next code and increment counter (event-based HOTP behavior)
		$otp_data = HOTPProvider::generate_next_code($user_id);

		if ($otp_data && isset($otp_data['hotp_code'])) {
			wp_send_json_success([
				'current_code' => $otp_data['hotp_code'],
				'counter' => $otp_data['hotp_counter']
			]);
			exit;
		} else {
			wp_send_json_error(['error_message' => __('Failed to generate code', 'ultimate-security')]);
			exit;
		}
	}

	/**
	 * AJAX: Reset HOTP secret
	 */
	public static function ajax_reset_hotp_secret()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error(
				[
					'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
				]
			);
			wp_die();
		}

		// Check ownership/capability - users can only reset their own secret
		$current_user_id = get_current_user_id();
		$user_id = isset($_POST['user_id']) ? intval(wp_unslash($_POST['user_id'])) : $current_user_id;
		if (!current_user_can('manage_options') && $current_user_id !== $user_id) {
			wp_send_json_error(['error_message' => __('Permission denied.', 'ultimate-security')]);
			exit;
		}
		$otp_data = HOTPProvider::reset_secret($user_id);

		if ($otp_data) {
			wp_send_json_success($otp_data);
			exit;
		} else {
			wp_send_json_error(['error_message' => __('User not found', 'ultimate-security')]);
			exit;
		}
	}

	/**
	 * AJAX: Send OTP email
	 */
	public static function ajax_send_otp_email()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error(
				[
					'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
				]
			);
			wp_die();
		}

		// Check ownership/capability - users can only send code to themselves
		$current_user_id = get_current_user_id();
		$user_id = isset($_POST['id']) ? (int) wp_unslash($_POST['id']) : $current_user_id;
		if (!current_user_can('manage_options') && $current_user_id !== $user_id) {
			wp_send_json_error(['error_message' => __('Permission denied.', 'ultimate-security')]);
			exit;
		}

		$options = Utils::ultimate_security_get_option();

		if (
			!isset($options['security']['2fa_authentication']['email_authentication']['2fa_email_verification_enable']) ||
			!$options['security']['2fa_authentication']['email_authentication']['2fa_email_verification_enable']
		) {
			wp_send_json_error(['error_message' => __('Email verification is not activated', 'ultimate-security')]);
			exit;
		}

		if (!$user_id) {
			wp_send_json_error(['error_message' => __('User not found', 'ultimate-security')]);
			exit;
		}

		$user = get_user_by('id', $user_id);
		if (!$user) {
			wp_send_json_error(['error_message' => __('User not found', 'ultimate-security')]);
			exit;
		}

		if (get_user_meta($user->ID, self::META_EMAIL_AUTH_ENABLED, true)) {
			wp_send_json_error(['error_message' => __('Email authentication already activated', 'ultimate-security')]);
			exit;
		}

		$allowed_roles = $options['security']['2fa_authentication']['email_authentication']['2fa_email_verification_enable_for'] ?? [];

		$allowed_role_codes = [];

		foreach ($allowed_roles as $role) {
			if (is_array($role) && !empty($role['code'])) {
				$allowed_role_codes[] = sanitize_key($role['code']);
			} elseif (is_string($role)) {
				$allowed_role_codes[] = sanitize_key($role);
			}
		}

		$is_allowed = empty($allowed_role_codes) || !empty(array_intersect($allowed_role_codes, $user->roles));

		if (!$is_allowed) {
			wp_send_json_error([
				'error_message' => __('You are not allowed for this action', 'ultimate-security')
			]);
		}


		$verification_code = EmailProvider::send_verification_code($user_id);

		if ($verification_code) {
			wp_send_json_success([
				'success_message' => __('Email Sent', 'ultimate-security'),
				// 'verification_code' => esc_html($verification_code),
			]);
			exit;
		} else {
			wp_send_json_error(['error_message' => __('Failed to send email', 'ultimate-security')]);
			exit;
		}
	}

	/**
	 * AJAX: Enable OTP email
	 */
	public static function ajax_enable_otp_email()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error(
				[
					'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
				]
			);
			wp_die();
		}

		// Check ownership/capability - users can only enable for themselves
		$current_user_id = get_current_user_id();
		$user_id = isset($_POST['id']) ? (int) wp_unslash($_POST['id']) : $current_user_id;
		if (!current_user_can('manage_options') && $current_user_id !== $user_id) {
			wp_send_json_error(['error_message' => __('Permission denied.', 'ultimate-security')]);
			exit;
		}

		$options = Utils::ultimate_security_get_option();
		$code = isset($_POST['value']) ? sanitize_text_field(wp_unslash($_POST['value'])) : '';

		if (
			!isset($options['security']['2fa_authentication']['email_authentication']['2fa_email_verification_enable']) ||
			!$options['security']['2fa_authentication']['email_authentication']['2fa_email_verification_enable']
		) {
			wp_send_json_error(['error_message' => __('Email verification is not activated', 'ultimate-security')]);
			exit;
		}

		if (!$user_id) {
			wp_send_json_error(['error_message' => __('User not found', 'ultimate-security')]);
			exit;
		}

		$user = get_user_by('id', $user_id);
		$stored_code = get_user_meta($user->ID, self::META_2FA_CODE, true);
		$is_enabled = get_user_meta($user->ID, self::META_EMAIL_AUTH_ENABLED, true);

		if (
			!$is_enabled &&
			is_string($stored_code) &&
			is_string($code) &&
			wp_check_password($code, $stored_code)
		) {
			EmailProvider::enable_for_user($user->ID);

			// Log 2FA enabled event
			if (class_exists('\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Storage\LogRepository')) {
				\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Storage\LogRepository::log_2fa_enabled($user->ID, 'email');
			}

			/**
			 * Fires after a 2FA method is enabled for a user.
			 *
			 * @since 1.1.0
			 * @param int $user_id The user ID.
			 * @param string $method The 2FA method that was enabled ('email', 'totp', 'hotp', 'sms').
			 * @param \WP_User $user The user object.
			 */
			do_action('ultimate_security_2fa_method_enabled', $user->ID, 'email', $user);

			wp_send_json_success([
				'success_message' => __('Email authentication is enabled', 'ultimate-security'),
			]);
			exit;
		} else {
			wp_send_json_error([
				'error_message' => __('Wrong verification code', 'ultimate-security'),
			]);
			exit;
		}
	}

	/**
	 * AJAX: Resend 2FA verification code (for login flow)
	 *
	 * Token-based: Uses user_id and token from POST data instead of cookies
	 */
	public static function ajax_resend_2fa_code()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_resend_2fa_code', 'nonce', false)) {
			wp_send_json_error(['error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security')]);
			exit;
		}

		// Get user ID and token from POST data (token-based approach)
		$user_id = isset($_POST['user_id']) ? absint($_POST['user_id']) : 0;
		$token = isset($_POST['token']) ? sanitize_text_field(wp_unslash($_POST['token'])) : '';

		if (!$user_id) {
			wp_send_json_error(['error_message' => __('Invalid session. Please log in again.', 'ultimate-security')]);
			exit;
		}

		// Validate the authentication token
		if (!TokenService::validate_auth_token($user_id, $token)) {
			wp_send_json_error(['error_message' => __('Session expired. Please log in again.', 'ultimate-security')]);
			exit;
		}

		// Verify user has pending 2FA
		$pending = get_user_meta($user_id, 'ultimate_security_2fa_pending', true);
		if (!$pending) {
			wp_send_json_error(['error_message' => __('No pending verification found.', 'ultimate-security')]);
			exit;
		}

		// Check for resend cooldown (60 seconds)
		$cooldown_data = get_transient(self::TRANSIENT_2FA_RESEND_COOLDOWN . $user_id);
		if ($cooldown_data && isset($cooldown_data['last_sent'])) {
			$time_since_last = time() - $cooldown_data['last_sent'];
			$remaining_time = 60 - $time_since_last;

			if ($remaining_time > 0) {
				wp_send_json_error([
					'error_message' => sprintf(
						__('Please wait %d seconds before requesting another code.', 'ultimate-security'),
						$remaining_time
					),
					'cooldown_remaining' => $remaining_time
				]);
				exit;
			}
		}

		// Send new verification code
		$verification_code = EmailProvider::send_verification_code($user_id);

		if ($verification_code) {
			// Set resend cooldown for 60 seconds
			set_transient(self::TRANSIENT_2FA_RESEND_COOLDOWN . $user_id, [
				'last_sent' => time(),
				'user_id' => $user_id
			], 60);

			wp_send_json_success([
				'success_message' => __('A new verification code has been sent to your email.', 'ultimate-security'),
				'cooldown_seconds' => 60
			]);
			exit;
		} else {
			wp_send_json_error(['error_message' => __('Failed to send verification code. Please try again.', 'ultimate-security')]);
			exit;
		}
	}

	/**
	 * AJAX: Enable encryption
	 */
	public static function ajax_enable_encryption()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error(
				[
					'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
				]
			);
			wp_die();
		}

		EncryptionService::enable_encryption_for_existing_keys();
		wp_send_json_success();
		exit;
	}

	/**
	 * AJAX: Reset 2FA
	 */
	public static function ajax_reset_2fa()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error(
				[
					'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
				]
			);
			wp_die();
		}

		// Check ownership/capability - users can only reset their own 2FA
		$current_user_id = get_current_user_id();
		$user_id = isset($_POST['user_id']) ? intval(wp_unslash($_POST['user_id'])) : $current_user_id;
		if (!current_user_can('manage_options') && $current_user_id !== $user_id) {
			wp_send_json_error(['error_message' => __('Permission denied.', 'ultimate-security')]);
			exit;
		}

		if (!$user_id) {
			wp_send_json_error(['error_message' => __('User ID can\'t be zero.', 'ultimate-security')]);
			exit;
		}

		$user = get_user_by('id', $user_id);
		if (!$user) {
			wp_send_json_error(['error_message' => __('Invalid user.', 'ultimate-security')]);
			exit;
		}

		// Get current provider before reset for logging
		$previous_provider = get_user_meta($user->ID, self::META_2FA_PROVIDER, true);

		// Reset all 2FA methods
		EmailProvider::disable_for_user($user_id);
		delete_user_meta($user->ID, self::META_2FA_PROVIDER);
		delete_user_meta($user->ID, self::META_2FA_UPDATED_AT);
		delete_user_meta($user->ID, self::META_2FA_PENDING);

		// Log 2FA disabled event
		if ($previous_provider && class_exists('\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Storage\LogRepository')) {
			$method = strtolower($previous_provider);
			if ($previous_provider === 'Authenticator Application') {
				$method = 'totp';
			}
			\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Storage\LogRepository::log_2fa_disabled($user->ID, $method);
		}

		/**
		 * Fires after a 2FA method is disabled/reset for a user.
		 *
		 * @since 1.1.0
		 * @param int $user_id The user ID.
		 * @param string $previous_method The 2FA method that was disabled.
		 * @param \WP_User $user The user object.
		 */
		$method_disabled = $previous_provider ? strtolower($previous_provider) : 'unknown';
		if ($previous_provider === 'Authenticator Application') {
			$method_disabled = 'totp';
		}
		do_action('ultimate_security_2fa_method_disabled', $user->ID, $method_disabled, $user);

		wp_send_json_success(['success_message' => __('Reset 2FA Method successfully', 'ultimate-security')]);
		exit;
	}
	public static function ajax_get_2fa()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error(
				[
					'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
				]
			);
			wp_die();
		}

		// Check ownership/capability - users can only view their own 2FA status
		$current_user_id = get_current_user_id();
		$user_id = isset($_POST['user_id']) ? intval(wp_unslash($_POST['user_id'])) : $current_user_id;
		if (!current_user_can('manage_options') && $current_user_id !== $user_id) {
			wp_send_json_error(['error_message' => __('Permission denied.', 'ultimate-security')]);
			exit;
		}

		if (!$user_id) {
			wp_send_json_error(['error_message' => __('User ID can\'t be zero.', 'ultimate-security')]);
			exit;
		}

		$user = get_user_by('id', $user_id);
		if (!$user) {
			wp_send_json_error(['error_message' => __('Invalid user.', 'ultimate-security')]);
			exit;
		}
		$provider = get_user_meta($user->ID, self::META_2FA_PROVIDER, true);

		wp_send_json_success([
			'success_message' => __('Reset 2FA Method successfully', 'ultimate-security'),
			'provider' => $provider,
		]);
		exit;
	}
	public static function ajax_set_2fa()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error(
				[
					'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
				]
			);
			wp_die();
		}

		// Check ownership/capability - users can only set their own 2FA method
		$current_user_id = get_current_user_id();
		$user_id = isset($_POST['user_id']) ? intval(wp_unslash($_POST['user_id'])) : $current_user_id;
		if (!current_user_can('manage_options') && $current_user_id !== $user_id) {
			wp_send_json_error(['error_message' => __('Permission denied.', 'ultimate-security')]);
			exit;
		}

		$provider = isset($_POST['provider']) ? sanitize_text_field(wp_unslash($_POST['provider'])) : 0;
		if (!$user_id) {
			wp_send_json_error(['error_message' => __('User ID can\'t be zero.', 'ultimate-security')]);
			exit;
		}
		if (!$provider) {
			wp_send_json_error(['error_message' => __('Method can\'t be empty.', 'ultimate-security')]);
			exit;
		}

		$user = get_user_by('id', $user_id);
		if (!$user) {
			wp_send_json_error(['error_message' => __('Invalid user.', 'ultimate-security')]);
			exit;
		}

		// Get old provider for logging method change
		$old_provider = get_user_meta($user->ID, self::META_2FA_PROVIDER, true);

		update_user_meta($user->ID, self::META_2FA_PROVIDER, $provider);
		update_user_meta($user->ID, self::META_2FA_UPDATED_AT, date('Y-m-d H:i:s'));
		update_user_meta($user->ID, self::META_2FA_PENDING, true);

		// Log 2FA method change
		if (class_exists('\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Storage\LogRepository')) {
			$new_method = strtolower($provider);
			if ($provider === 'Authenticator Application') {
				$new_method = 'totp';
			}
			if ($old_provider && $old_provider !== $provider) {
				$old_method = strtolower($old_provider);
				if ($old_provider === 'Authenticator Application') {
					$old_method = 'totp';
				}
				\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Storage\LogRepository::log_2fa_method_changed($user->ID, $old_method, $new_method);
			} else {
				\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Storage\LogRepository::log_2fa_enabled($user->ID, $new_method);
			}
		}

		wp_send_json_success(['success_message' => __('Saved 2FA Method successfully', 'ultimate-security')]);
		exit;
	}

	/**
	 * AJAX: Generate backup codes
	 */
	public static function ajax_generate_backup_codes()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error([
				'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
			]);
			wp_die();
		}

		// Check capability
		if (!current_user_can('manage_options')) {
			$user_id = get_current_user_id();
			// Allow users to generate for themselves
			$requested_user_id = isset($_POST['user_id']) ? intval(wp_unslash($_POST['user_id'])) : 0;
			if ($user_id !== $requested_user_id) {
				wp_send_json_error(['error_message' => __('You do not have permission to generate backup codes for other users.', 'ultimate-security')]);
				exit;
			}
		}

		$user_id = isset($_POST['user_id']) ? intval(wp_unslash($_POST['user_id'])) : get_current_user_id();

		if (!$user_id) {
			wp_send_json_error(['error_message' => __('User ID is required.', 'ultimate-security')]);
			exit;
		}

		$user = get_user_by('id', $user_id);
		if (!$user) {
			wp_send_json_error(['error_message' => __('Invalid user.', 'ultimate-security')]);
			exit;
		}

		// Check if Pro backup code service exists (use it if available)
		if (class_exists('\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Services\BackupCodeService')) {
			$codes = \WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Services\BackupCodeService::generate_codes($user_id);
		} else {
			$codes = SimpleBackupCodeService::generate_codes($user_id);
		}

		// Format codes for display
		$formatted_codes = SimpleBackupCodeService::format_codes_for_display($codes);

		wp_send_json_success([
			'success_message' => __('Backup codes generated successfully. Save these codes in a secure place.', 'ultimate-security'),
			'backup_codes' => $formatted_codes,
			'count' => count($codes),
		]);
		exit;
	}

	/**
	 * AJAX: Get backup codes status
	 */
	public static function ajax_get_backup_codes_status()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error([
				'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
			]);
			wp_die();
		}

		$user_id = isset($_POST['user_id']) ? intval(wp_unslash($_POST['user_id'])) : get_current_user_id();

		if (!$user_id) {
			wp_send_json_error(['error_message' => __('User ID is required.', 'ultimate-security')]);
			exit;
		}

		// Check if Pro backup code service exists
		if (class_exists('\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Services\BackupCodeService')) {
			$remaining = \WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Services\BackupCodeService::get_remaining_count($user_id);
			$status = [
				'has_codes' => $remaining > 0,
				'remaining' => $remaining,
				'is_low' => $remaining > 0 && $remaining <= 3,
			];
		} else {
			$status = SimpleBackupCodeService::get_status($user_id);
		}

		wp_send_json_success([
			'status' => $status,
		]);
		exit;
	}

	/**
	 * AJAX: Revoke backup codes
	 */
	public static function ajax_revoke_backup_codes()
	{
		// Verify nonce for security
		if (!check_ajax_referer('ultimate_security_nonce', 'security', false)) {
			wp_send_json_error([
				'error_message' => __('Security verification failed. Please refresh the page and try again.', 'ultimate-security'),
			]);
			wp_die();
		}

		// Check capability - only admins can revoke other users' codes
		if (!current_user_can('manage_options')) {
			$user_id = get_current_user_id();
			$requested_user_id = isset($_POST['user_id']) ? intval(wp_unslash($_POST['user_id'])) : 0;
			if ($user_id !== $requested_user_id) {
				wp_send_json_error(['error_message' => __('You do not have permission to revoke backup codes for other users.', 'ultimate-security')]);
				exit;
			}
		}

		$user_id = isset($_POST['user_id']) ? intval(wp_unslash($_POST['user_id'])) : 0;

		if (!$user_id) {
			wp_send_json_error(['error_message' => __('User ID is required.', 'ultimate-security')]);
			exit;
		}

		$user = get_user_by('id', $user_id);
		if (!$user) {
			wp_send_json_error(['error_message' => __('Invalid user.', 'ultimate-security')]);
			exit;
		}

		// Check if Pro backup code service exists
		if (class_exists('\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Services\BackupCodeService')) {
			\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Services\BackupCodeService::revoke_codes($user_id);
		} else {
			SimpleBackupCodeService::revoke_codes($user_id);
		}

		wp_send_json_success([
			'success_message' => __('Backup codes revoked successfully.', 'ultimate-security'),
		]);
		exit;
	}
}
