<?php
/**
 * Admin AJAX handlers for modules hub UI preferences.
 *
 * @package WP_PowerSuite\Core\Http\Controllers
 * @since 1.0.0
 */

namespace WP_PowerSuite\Core\Http\Controllers;

use WP_PowerSuite\Core\AdminAppearance;
use WP_PowerSuite\Core\CommandPaletteData;
use WP_PowerSuite\Core\Http\AjaxRouter;
use WP_PowerSuite\Core\OptionStore;
use WP_PowerSuite\Core\WhiteLabel;
use WP_PowerSuite\AI\ConnectionSettings;
use WP_PowerSuite\AI\ConnectionTester;

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

final class ModuleUiController {

	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_toggle_favorite', [ $controller, 'toggleFavorite' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_save_view_mode', [ $controller, 'saveViewMode' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_save_description_mode', [ $controller, 'saveDescriptionMode' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_save_module_order', [ $controller, 'saveModuleOrder' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_save_quick_launcher_shortcut', [ $controller, 'saveQuickLauncherShortcut' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_save_performance_monitor', [ $controller, 'savePerformanceMonitorEnabled' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_save_interface_appearance', [ $controller, 'saveInterfaceAppearance' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_save_white_label', [ $controller, 'saveWhiteLabel' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_reset_white_label', [ $controller, 'resetWhiteLabel' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_save_ai_connections', [ $controller, 'saveAiConnections' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_test_ai_connection', [ $controller, 'testAiConnection' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_command_palette_data', [ $controller, 'getCommandPaletteData' ] );
	}

	public function savePerformanceMonitorEnabled(): void {
		$enabled = isset( $_POST['enabled'] ) && $_POST['enabled'] === '1';
		$success = OptionStore::getInstance()->set( 'enable_performance_monitor', $enabled );

		if ( ! $success ) {
			wp_send_json_error(
				[
					'message' => __( 'Failed to save Performance Monitor setting.', 'wp-powersuite' ),
					'code'    => 'save_failed',
				]
			);
		}

		wp_send_json_success(
			[
				'enabled' => $enabled,
				'url'     => $enabled ? \WP_PowerSuite\Core\AdminMenu::performanceMonitorUrl() : '',
				'message' => $enabled
					? __( 'Performance Monitor enabled. Tracking starts on the next request.', 'wp-powersuite' )
					: __( 'Performance Monitor disabled.', 'wp-powersuite' ),
			]
		);
	}

	public function saveInterfaceAppearance(): void {
		if ( ! isset( $_POST['interface_color_mode'] ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Interface color mode is required.', 'wp-powersuite' ),
					'code'    => 'missing_interface_color_mode',
				]
			);
		}

		$mode = sanitize_key( wp_unslash( (string) $_POST['interface_color_mode'] ) );
		$color_raw = isset( $_POST['custom_brand_color'] )
			? sanitize_text_field( wp_unslash( (string) $_POST['custom_brand_color'] ) )
			: AdminAppearance::DEFAULT_BRAND_COLOR;

		$success = OptionStore::getInstance()->setInterfaceAppearance( $mode, $color_raw );

		if ( ! $success ) {
			wp_send_json_error(
				[
					'message' => __( 'Failed to save interface appearance settings.', 'wp-powersuite' ),
					'code'    => 'save_failed',
				]
			);
		}

		$snapshot = AdminAppearance::getSettingsSnapshot();

		wp_send_json_success(
			[
				'interface_color_mode' => $snapshot['mode'],
				'custom_brand_color'   => $snapshot['color'],
				'palette'              => $snapshot['palette'],
				'appearance_css'       => AdminAppearance::inlineCss(),
				'message'              => __( 'Interface appearance saved.', 'wp-powersuite' ),
			]
		);
	}

	public function getCommandPaletteData(): void {
		wp_send_json_success( CommandPaletteData::getPayload() );
	}

	public function toggleFavorite(): void {
		$module_id = $this->getModuleId();
		if ( $module_id === '' ) {
			wp_send_json_error(
				[
					'message' => __( 'Invalid module ID provided.', 'wp-powersuite' ),
					'code'    => 'invalid_module_id',
				]
			);
		}

		$favorite    = isset( $_POST['favorite'] ) && $_POST['favorite'] === '1';
		$option_store = OptionStore::getInstance();
		$success     = $favorite
			? $option_store->addFavorite( $module_id )
			: $option_store->removeFavorite( $module_id );

		if ( ! $success ) {
			wp_send_json_error(
				[
					'message' => __( 'Failed to update favorite status. Please try again.', 'wp-powersuite' ),
					'code'    => 'update_failed',
				]
			);
		}

		wp_send_json_success(
			[
				'module_id' => $module_id,
				'favorite'  => $favorite,
				'favorites' => $option_store->getFavorites(),
				'message'   => $favorite
					? __( 'Added to favorites.', 'wp-powersuite' )
					: __( 'Removed from favorites.', 'wp-powersuite' ),
			]
		);
	}

	public function saveViewMode(): void {
		if ( ! isset( $_POST['view_mode'] ) || $_POST['view_mode'] === '' ) {
			wp_send_json_error(
				[
					'message' => __( 'View mode is required.', 'wp-powersuite' ),
					'code'    => 'missing_view_mode',
				]
			);
		}

		$view_mode = sanitize_text_field( wp_unslash( $_POST['view_mode'] ) );
		if ( ! in_array( $view_mode, [ 'grid', 'list' ], true ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Invalid view mode specified.', 'wp-powersuite' ),
					'code'    => 'invalid_view_mode',
				]
			);
		}

		$option_store = OptionStore::getInstance();
		if ( ! $option_store->setViewMode( $view_mode ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Failed to save view mode. Please try again.', 'wp-powersuite' ),
					'code'    => 'save_failed',
				]
			);
		}

		wp_send_json_success(
			[
				'view_mode' => $view_mode,
				'message'   => __( 'View mode saved successfully.', 'wp-powersuite' ),
			]
		);
	}

	public function saveDescriptionMode(): void {
		if ( ! isset( $_POST['description_mode'] ) || $_POST['description_mode'] === '' ) {
			wp_send_json_error(
				[
					'message' => __( 'Description mode is required.', 'wp-powersuite' ),
					'code'    => 'missing_description_mode',
				]
			);
		}

		$description_mode = sanitize_text_field( wp_unslash( $_POST['description_mode'] ) );
		if ( ! in_array( $description_mode, [ 'show', 'hide', 'truncate' ], true ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Invalid description mode specified.', 'wp-powersuite' ),
					'code'    => 'invalid_description_mode',
				]
			);
		}

		$option_store = OptionStore::getInstance();
		if ( ! $option_store->setDescriptionMode( $description_mode ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Failed to save description mode. Please try again.', 'wp-powersuite' ),
					'code'    => 'save_failed',
				]
			);
		}

		wp_send_json_success(
			[
				'description_mode' => $description_mode,
				'message'          => __( 'Description mode saved successfully.', 'wp-powersuite' ),
			]
		);
	}

	public function saveModuleOrder(): void {
		if ( ! isset( $_POST['module_order'] ) || ! is_array( $_POST['module_order'] ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Invalid module order data provided.', 'wp-powersuite' ),
					'code'    => 'invalid_order',
				]
			);
			return;
		}

		$order = array_values(
			array_unique(
				array_filter(
					array_map( 'sanitize_key', wp_unslash( $_POST['module_order'] ) )
				)
			)
		);

		if ( $order === [] ) {
			wp_send_json_error(
				[
					'message' => __( 'Invalid module order data provided.', 'wp-powersuite' ),
					'code'    => 'invalid_order',
				]
			);
			return;
		}

		$option_store = OptionStore::getInstance();
		if ( ! $option_store->setModuleOrder( $order ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Failed to save module order. Please try again.', 'wp-powersuite' ),
					'code'    => 'save_failed',
				]
			);
		}

		wp_send_json_success(
			[
				'module_order' => $order,
				'message'      => __( 'Module order saved successfully.', 'wp-powersuite' ),
			]
		);
	}

	public function saveQuickLauncherShortcut(): void {
		$shortcut = isset( $_POST['shortcut'] ) ? sanitize_key( wp_unslash( $_POST['shortcut'] ) ) : '';
		$valid    = [ 'ctrl-k', 'ctrl-shift-k', 'alt-p', 'ctrl-alt-k' ];
		if ( ! in_array( $shortcut, $valid, true ) ) {
			$shortcut = 'ctrl-shift-k';
		}

		OptionStore::getInstance()->set( 'quick_launcher_shortcut', $shortcut );
		wp_send_json_success( [ 'shortcut' => $shortcut ] );
	}

	public function saveWhiteLabel(): void {
		$raw = isset( $_POST['white_label'] ) && is_array( $_POST['white_label'] )
			? wp_unslash( $_POST['white_label'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized below
			: [];

		$settings = WhiteLabel::sanitizeSettings(
			array_merge(
				WhiteLabel::getSettings(),
				[
					'enabled'                   => ! empty( $raw['enabled'] ),
					'plugin_name'               => $raw['plugin_name'] ?? '',
					'plugin_short_name'         => $raw['plugin_short_name'] ?? '',
					'plugin_description'        => $raw['plugin_description'] ?? '',
					'plugin_author'             => $raw['plugin_author'] ?? '',
					'plugin_author_uri'         => $raw['plugin_author_uri'] ?? '',
					'company_name'              => $raw['company_name'] ?? '',
					'menu_title'                => $raw['menu_title'] ?? '',
					'dashboard_title'           => $raw['dashboard_title'] ?? '',
					'website_url'               => $raw['website_url'] ?? '',
					'support_url'               => $raw['support_url'] ?? '',
					'documentation_url'         => $raw['documentation_url'] ?? '',
					'logo_attachment_id'        => $raw['logo_attachment_id'] ?? 0,
					'menu_icon_attachment_id'   => $raw['menu_icon_attachment_id'] ?? 0,
					'email_sender_name'         => $raw['email_sender_name'] ?? '',
					'email_footer_text'         => $raw['email_footer_text'] ?? '',
					'hide_powered_by'           => ! empty( $raw['hide_powered_by'] ),
					'hide_license_menu'         => ! empty( $raw['hide_license_menu'] ),
					'hide_white_label_settings' => ! empty( $raw['hide_white_label_settings'] ),
					'hide_external_links'       => ! empty( $raw['hide_external_links'] ),
				]
			)
		);

		if ( $settings['enabled'] && ! WhiteLabel::hasAgencyLicense() ) {
			$settings['enabled'] = false;
		}

		$success = OptionStore::getInstance()->set( 'white_label', $settings );
		if ( ! $success ) {
			wp_send_json_error(
				[
					'message' => __( 'Failed to save white-label settings.', 'wp-powersuite' ),
					'code'    => 'save_failed',
				]
			);
		}

		WhiteLabel::clearCache();
		do_action( 'wp_powersuite_white_label_saved', $settings );

		wp_send_json_success(
			[
				'white_label'          => $settings,
				'logoUrl'              => WhiteLabel::logoUrl(),
				'menuIconUrl'          => WhiteLabel::menuIconUrl(),
				'whiteLabelDirectUrl'  => WhiteLabel::whiteLabelDirectUrl(),
				'licenseDirectUrl'     => WhiteLabel::licenseDirectUrl(),
				'hideWhiteLabelTab'    => WhiteLabel::shouldHideWhiteLabelSettings(),
				'message'              => __( 'Branding saved.', 'wp-powersuite' ),
			]
		);
	}

	public function resetWhiteLabel(): void {
		$settings = WhiteLabel::defaultSettings();
		$success  = OptionStore::getInstance()->set( 'white_label', $settings );

		if ( ! $success ) {
			wp_send_json_error(
				[
					'message' => __( 'Failed to reset white-label settings.', 'wp-powersuite' ),
					'code'    => 'reset_failed',
				]
			);
		}

		WhiteLabel::clearCache();
		do_action( 'wp_powersuite_white_label_saved', $settings );

		wp_send_json_success(
			[
				'white_label' => $settings,
				'message'     => __( 'White-label settings reset.', 'wp-powersuite' ),
			]
		);
	}

	public function saveAiConnections(): void {
		$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 ( [ 'api_key', 'gemini_api_key', 'claude_api_key', 'network_api_key', 'network_gemini_api_key', 'network_claude_api_key' ] as $field ) {
			if ( array_key_exists( $field, $raw ) ) {
				$payload[ $field ] = sanitize_text_field( (string) $raw[ $field ] );
			}
		}

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

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

	public function testAiConnection(): void {
		$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 ) ) {
			wp_send_json_error(
				[
					'message' => $result->get_error_message(),
					'code'    => $result->get_error_code(),
				]
			);
		}

		wp_send_json_success(
			[
				'message' => __( 'Connection successful.', 'wp-powersuite' ),
			]
		);
	}

	private function getModuleId(): string {
		if ( ! isset( $_POST['module_id'] ) || $_POST['module_id'] === '' ) {
			return '';
		}

		return sanitize_key( wp_unslash( $_POST['module_id'] ) );
	}
}
