<?php
/**
 * Admin AJAX handlers for captcha provider connection tests.
 *
 * @package WP_PowerSuite\Core\Http\Controllers
 * @since 1.0.0
 */

namespace WP_PowerSuite\Core\Http\Controllers;

use WP_PowerSuite\Core\NetworkScope;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class CaptchaController {

	private static ?self $instance = null;

	public static function getInstance(): self {
		if ( self::$instance === null ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public static function register(): void {
		add_action( 'wp_ajax_wp_powersuite_captcha_test_connection', [ self::getInstance(), 'testConnection' ] );
	}

	public function testConnection(): void {
		if ( ! current_user_can( NetworkScope::adminCapability() ) ) {
			wp_send_json_error(
				[
					'message' => __( 'You do not have permission to perform this action.', 'wp-powersuite' ),
					'code'    => 'insufficient_permissions',
				]
			);
		}

		$module_id = isset( $_POST['module_id'] ) ? sanitize_key( wp_unslash( $_POST['module_id'] ) ) : '';
		if ( ! in_array( $module_id, [ 'google-recaptcha', 'cloudflare-turnstile' ], true ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Unsupported module for connection test.', 'wp-powersuite' ),
					'code'    => 'invalid_module',
				]
			);
		}

		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'wpps_captcha_test_' . $module_id ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Security check failed. Please refresh the page and try again.', 'wp-powersuite' ),
					'code'    => 'nonce_failed',
				]
			);
		}

		if ( ! OptionStoreModuleSettingsRepository::isModuleEnabled( $module_id ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Module is not enabled.', 'wp-powersuite' ),
					'code'    => 'module_disabled',
				]
			);
		}

		$token = isset( $_POST['token'] ) ? sanitize_text_field( wp_unslash( $_POST['token'] ) ) : '';

		$map = [
			'google-recaptcha'     => [ 'GoogleRecaptcha\\Module', 'google-recaptcha' ],
			'cloudflare-turnstile' => [ 'CloudflareTurnstile\\Module', 'cloudflare-turnstile' ],
		];
		[ $module_class, $module_dir ] = $map[ $module_id ];

		if ( ! class_exists( $module_class ) && defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
			$mod_file = WP_POWERSUITE_MODULES_DIR . $module_dir . DIRECTORY_SEPARATOR . 'module.php';
			if ( file_exists( $mod_file ) ) {
				require_once $mod_file;
			}
		}

		if ( ! class_exists( $module_class ) || ! method_exists( $module_class, 'runTestConnection' ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Module is not available to test.', 'wp-powersuite' ),
					'code'    => 'module_unavailable',
				]
			);
		}

		$result = call_user_func( [ $module_class, 'runTestConnection' ], $token );
		if ( is_array( $result ) && ! empty( $result['success'] ) ) {
			wp_send_json_success( $result );
		}

		wp_send_json_error(
			is_array( $result )
				? $result
				: [ 'message' => __( 'The connection test did not return a valid response.', 'wp-powersuite' ) ]
		);
	}
}
