<?php
/**
 * Settings AJAX for site-wide AI provider connections.
 *
 * @package WP_PowerSuite\AI
 */

namespace WP_PowerSuite\AI;

use WP_PowerSuite\Core\Http\AjaxRouter;
use WP_PowerSuite\Core\NetworkScope;

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

final class AdminController {

	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 {
		$controller = self::getInstance();
		AjaxRouter::registerAdminAction( 'wp_powersuite_save_ai_connections', [ $controller, 'saveAiConnections' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_test_ai_connection', [ $controller, 'testAiConnection' ] );
	}

	public function saveAiConnections(): void {
		check_ajax_referer( AjaxRouter::NONCE_ACTION, 'nonce' );
		if ( ! current_user_can( NetworkScope::adminCapability() ) ) {
			wp_send_json_error(
				[
					'message' => __( 'You do not have permission to perform this action.', 'wppowersuite-lite' ),
					'code'    => 'insufficient_permissions',
				]
			);
		}

		$raw = isset( $_POST['ai_connections'] ) && is_array( $_POST['ai_connections'] )
			? wp_unslash( $_POST['ai_connections'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized in ConnectionSettings
			: [];

		$payload = [
			'provider'             => sanitize_key( (string) ( $raw['provider'] ?? ConnectionSettings::get()['provider'] ?? 'openai' ) ),
			'use_network_api_keys' => ! empty( $raw['use_network_api_keys'] ),
		];

		foreach ( ProviderRegistry::keyFields() as $field ) {
			if ( array_key_exists( $field, $raw ) ) {
				$payload[ $field ] = sanitize_text_field( (string) $raw[ $field ] );
			}

			$network_field = 'network_' . $field;
			if ( array_key_exists( $network_field, $raw ) ) {
				$payload[ $network_field ] = sanitize_text_field( (string) $raw[ $network_field ] );
			}
		}

		if ( isset( $raw['clear_keys'] ) && is_array( $raw['clear_keys'] ) ) {
			$payload['clear_keys'] = array_values(
				array_filter(
					array_map(
						static fn( $field ): string => sanitize_key( (string) $field ),
						$raw['clear_keys']
					)
				)
			);
		}

		if ( isset( $raw['clear_network_keys'] ) && is_array( $raw['clear_network_keys'] ) ) {
			$payload['clear_network_keys'] = array_values(
				array_filter(
					array_map(
						static fn( $field ): string => sanitize_key( (string) $field ),
						$raw['clear_network_keys']
					)
				)
			);
		}

		$saved = ConnectionSettings::persist( $payload );
		if ( ! $saved ) {
			wp_send_json_error(
				[
					'message' => __( 'Failed to save AI connections.', 'wppowersuite-lite' ),
					'code'    => 'save_failed',
				]
			);
		}

		wp_send_json_success(
			[
				'ai_connections' => ConnectionSettings::getPublic(),
				'message'        => __( 'AI connections saved.', 'wppowersuite-lite' ),
			]
		);
	}

	public function testAiConnection(): void {
		check_ajax_referer( AjaxRouter::NONCE_ACTION, 'nonce' );
		if ( ! current_user_can( NetworkScope::adminCapability() ) ) {
			wp_send_json_error(
				[
					'message' => __( 'You do not have permission to perform this action.', 'wppowersuite-lite' ),
					'code'    => 'insufficient_permissions',
				]
			);
		}

		$provider = sanitize_key( (string) wp_unslash( $_POST['provider'] ?? ConnectionSettings::get()['provider'] ?? 'openai' ) );
		$api_key  = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['api_key'] ) ) : '';

		$result = ConnectionTester::test( $provider, $api_key );
		if ( is_wp_error( $result ) ) {
			if ( $result->get_error_code() !== 'missing_api_key' ) {
				ConnectionSettings::setProviderVerification( $provider, 'failed' );
			}

			wp_send_json_error(
				[
					'message'         => $result->get_error_message(),
					'code'            => $result->get_error_code(),
					'provider_status' => ConnectionSettings::getProviderDisplayStatus( $provider ),
				]
			);
		}

		ConnectionSettings::setProviderVerification( $provider, 'verified' );

		wp_send_json_success(
			[
				'message'         => __( 'Connection successful.', 'wppowersuite-lite' ),
				'provider_status' => ConnectionSettings::getProviderDisplayStatus( $provider ),
			]
		);
	}
}
