<?php
/**
 * Admin AJAX handlers for plugin settings export, import, and data lifecycle.
 *
 * @package WP_PowerSuite\Core\Http\Controllers
 * @since 1.0.0
 */

namespace WP_PowerSuite\Core\Http\Controllers;

use WP_PowerSuite\Core\ConfigService;
use WP_PowerSuite\Core\DataRegistry;
use WP_PowerSuite\Core\Http\AjaxRouter;
use WP_PowerSuite\Core\ModuleRegistry;
use WP_PowerSuite\Core\NetworkScope;
use WP_PowerSuite\Core\OptionStore;

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

final class ConfigController {

	private static ?self $instance = null;

	private ConfigService $config_service;

	private function __construct() {
		$this->config_service = new ConfigService();
	}

	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_config_export', [ $controller, 'exportConfig' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_config_import', [ $controller, 'importConfig' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_config_save_preset', [ $controller, 'savePreset' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_config_load_preset', [ $controller, 'loadPreset' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_config_delete_preset', [ $controller, 'deletePreset' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_config_list_presets', [ $controller, 'listPresets' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_clear_cache', [ $controller, 'clearCache' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_clear_inactive_data', [ $controller, 'clearInactiveData' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_clear_all_data', [ $controller, 'clearAllData' ] );
		AjaxRouter::registerAdminAction( 'wp_powersuite_reset_to_defaults', [ $controller, 'resetToDefaults' ] );
	}

	public function exportConfig(): void {
		$config = $this->config_service->exportConfig();
		wp_send_json_success( [ 'config' => $config ] );
	}

	public function importConfig(): void {
		$data = isset( $_POST['config'] ) ? json_decode( wp_unslash( $_POST['config'] ), true ) : null; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON decoded and validated before import
		if ( ! is_array( $data ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid configuration data.', 'wp-powersuite' ) ] );
			return;
		}

		$merge  = ! empty( $_POST['merge'] );
		$result = $this->config_service->importConfig( $data, $merge );
		if ( ! $result['success'] ) {
			wp_send_json_error( [ 'message' => $result['message'] ] );
			return;
		}

		wp_send_json_success(
			[
				'message' => $result['message'],
				'errors'  => $result['errors'] ?? [],
			]
		);
	}

	public function savePreset(): void {
		$name   = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
		$result = $this->config_service->savePreset( $name );
		if ( ! $result['success'] ) {
			wp_send_json_error( [ 'message' => $result['message'] ] );
			return;
		}

		wp_send_json_success(
			[
				'message' => $result['message'],
				'id'      => $result['id'] ?? '',
			]
		);
	}

	public function loadPreset(): void {
		$id     = isset( $_POST['id'] ) ? sanitize_key( wp_unslash( $_POST['id'] ) ) : '';
		$merge  = ! empty( $_POST['merge'] );
		$result = $this->config_service->loadPreset( $id, $merge );
		if ( ! $result['success'] ) {
			wp_send_json_error( [ 'message' => $result['message'] ] );
			return;
		}

		wp_send_json_success( [ 'message' => $result['message'] ] );
	}

	public function deletePreset(): void {
		$id     = isset( $_POST['id'] ) ? sanitize_key( wp_unslash( $_POST['id'] ) ) : '';
		$result = $this->config_service->deletePreset( $id );
		wp_send_json_success( [ 'message' => $result['message'] ] );
	}

	public function listPresets(): void {
		$presets = $this->config_service->getPresets();
		wp_send_json_success( [ 'presets' => $presets ] );
	}

	public function clearCache(): void {
		OptionStore::getInstance()->clearCache();
		ModuleRegistry::getInstance()->refreshCache();
		wp_send_json_success( [ 'message' => __( 'Cache cleared.', 'wp-powersuite' ) ] );
	}

	public function clearInactiveData(): void {
		$option_store = OptionStore::getInstance();
		$registry     = ModuleRegistry::getInstance();
		$registry->init();
		$all_modules = $registry->getAllModules();
		$enabled     = $option_store->getEnabledModules();
		$settings    = NetworkScope::usesNetworkStorage()
			? get_site_option( 'wp_powersuite_settings', [] )
			: get_option( 'wp_powersuite_settings', [] );
		if ( ! is_array( $settings ) ) {
			$settings = [];
		}

		$reserved = [
			'enabled_modules',
			'favorites',
			'favorites_customized',
			'legacy_favorites_customized_migration',
			'module_order',
			'ui_preferences',
			'quick_launcher_shortcut',
			'enable_performance_monitor',
			'interface_color_mode',
			'custom_brand_color',
			'white_label',
		];
		$removed = 0;
		foreach ( array_keys( $settings ) as $key ) {
			if ( in_array( $key, $reserved, true ) ) {
				continue;
			}
			if ( isset( $all_modules[ $key ] ) && ! in_array( $key, $enabled, true ) ) {
				unset( $settings[ $key ] );
				$removed++;
			}
		}

		if ( NetworkScope::usesNetworkStorage() ) {
			update_site_option( 'wp_powersuite_settings', $settings );
		} else {
			update_option( 'wp_powersuite_settings', $settings, false );
		}
		$option_store->clearCache();
		wp_send_json_success(
			[
				'message' => sprintf(
					/* translators: %d: number of modules */
					_n( 'Removed data for %d disabled module.', 'Removed data for %d disabled modules.', $removed, 'wp-powersuite' ),
					$removed
				),
			]
		);
	}

	public function clearAllData(): void {
		DataRegistry::deleteAllPluginData();
		OptionStore::getInstance()->clearCache();
		ModuleRegistry::getInstance()->refreshCache();
		wp_send_json_success( [ 'message' => __( 'All plugin data has been deleted.', 'wp-powersuite' ) ] );
	}

	public function resetToDefaults(): void {
		$option_store = OptionStore::getInstance();
		$option_store->clearCache();
		$success = $option_store->resetToDefaults();

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

		foreach ( DataRegistry::getStandaloneModuleOptions() as $opt ) {
			delete_option( $opt );
			if ( is_multisite() ) {
				delete_site_option( $opt );
			}
		}

		foreach ( DataRegistry::getModuleDataLocations() as $locations ) {
			$opts = $locations['options'] ?? [];
			if ( ! is_array( $opts ) ) {
				continue;
			}
			foreach ( $opts as $opt ) {
				if ( is_string( $opt ) && $opt !== '' ) {
					delete_option( $opt );
					if ( is_multisite() ) {
						delete_site_option( $opt );
					}
				}
			}
		}

		ModuleRegistry::getInstance()->refreshCache();

		wp_send_json_success(
			[
				'message' => __( 'Settings have been reset to defaults. All modules are disabled.', 'wp-powersuite' ),
			]
		);
	}
}
