<?php
/**
 * SEO Optimization module.
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.0
 */

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

/**
 * Bootstraps SEO optimization integrations and REST routes.
 */
class SmartyPress_AI_SEO_Optimization_Module extends SmartyPress_AI_Module_Base {

	/**
	 * SEO provider registry.
	 *
	 * @var SmartyPress_AI_SEO_Provider_Registry
	 */
	private $registry;

	/**
	 * REST controller.
	 *
	 * @var SmartyPress_AI_SEO_Optimization_Controller
	 */
	private $controller;

	/**
	 * Constructor.
	 *
	 * @param array $providers AI providers.
	 * @param array $settings  Plugin settings.
	 */
	public function __construct( $providers = array(), $settings = array() ) {
		$this->module_id      = 'seo_optimization';
		$this->module_name    = 'SEO Optimization';
		$this->module_version = '1.0.0';

		$this->registry = new SmartyPress_AI_SEO_Provider_Registry();
		$this->registry->register( new SmartyPress_AI_Rank_Math_Integration() );
		$this->registry->register( new SmartyPress_AI_Generic_SEO_Integration() );

		$this->controller = new SmartyPress_AI_SEO_Optimization_Controller(
			$providers,
			$settings,
			$this->registry,
			new SmartyPress_AI_SEO_Fix_Prompt_Builder()
		);

		parent::__construct( $providers, $settings );
	}

	/**
	 * Register module settings hook.
	 *
	 * @return void
	 */
	public function register_settings() {
		do_action( 'smartypress_ai_module_seo_optimization_settings', $this );
	}

	/**
	 * Get module settings.
	 *
	 * @return array
	 */
	public function get_module_settings() {
		$module_settings = $this->settings['modules']['seo_optimization'] ?? array();
		if ( ! is_array( $module_settings ) ) {
			$module_settings = array( 'enabled' => (bool) $module_settings );
		}

		return wp_parse_args(
			$module_settings,
			array(
				'enabled'                 => $this->is_enabled(),
				'enable_rank_math_fixes'  => true,
				'auto_apply'              => false,
				'allow_image_alt_updates' => false,
			)
		);
	}

	/**
	 * Register WordPress hooks.
	 *
	 * @return void
	 */
	protected function register_hooks() {
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_gutenberg_feature_data' ), 40 );
	}

	/**
	 * Register REST routes.
	 *
	 * @return void
	 */
	protected function register_rest_routes() {
		add_action( 'rest_api_init', array( $this, 'register_module_rest_routes' ), 20 );
	}

	/**
	 * Register module REST routes.
	 *
	 * @return void
	 */
	public function register_module_rest_routes() {
		$this->controller->register_routes();
	}

	/**
	 * Enqueue SEO optimization editor extension and localize feature data.
	 *
	 * @return void
	 */
	public function enqueue_gutenberg_feature_data() {
		if ( ! $this->is_enabled() || ! wp_script_is( 'smartypress-ai-gutenberg', 'enqueued' ) ) {
			return;
		}

		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		$post_type = $screen && ! empty( $screen->post_type ) ? $screen->post_type : '';
		$active_provider = $this->registry->get_active_provider( $post_type );
		$settings = $this->get_module_settings();
		$asset_file = SPAI_SO_PLUGIN_DIR . '/assets/dist/seo-optimization-editor.asset.php';
		$js_file = SPAI_SO_PLUGIN_DIR . '/assets/dist/seo-optimization-editor.js';
		$css_file = SPAI_SO_PLUGIN_DIR . '/assets/dist/seo-optimization-editor.css';

		if ( ! file_exists( $js_file ) ) {
			return;
		}

		if ( file_exists( $asset_file ) ) {
			$asset = require $asset_file;
		} else {
			$asset = array(
				'dependencies' => array(
					'wp-plugins',
					'wp-element',
					'wp-components',
					'wp-data',
					'wp-i18n',
					'wp-blocks',
					'wp-block-editor',
					'wp-api-fetch',
					'smartypress-ai-gutenberg',
				),
				'version'      => SPAI_SO_PLUGIN_VERSION,
			);
		}

		wp_enqueue_script(
			'smartypress-ai-seo-optimization-editor',
			SPAI_SO_PLUGIN_URL . '/assets/dist/seo-optimization-editor.js',
			$asset['dependencies'],
			$asset['version'],
			true
		);

		wp_set_script_translations(
			'smartypress-ai-seo-optimization-editor',
			'smartypress-ai-engine',
			SMARTYPRESS_AI_PLUGIN_DIR . 'languages'
		);

		if ( file_exists( $css_file ) ) {
			wp_enqueue_style(
				'smartypress-ai-seo-optimization-editor',
				SPAI_SO_PLUGIN_URL . '/assets/dist/seo-optimization-editor.css',
				array( 'wp-components', 'smartypress-ai-gutenberg' ),
				$asset['version']
			);
		}

		wp_localize_script(
			'smartypress-ai-seo-optimization-editor',
			'smartypressAISeoOptimization',
			array(
				'enabled'              => true,
				'restUrl'              => 'smartypress/v1/',
				'nonce'                => wp_create_nonce( 'wp_rest' ),
				'postType'             => $post_type,
				'providers'            => $this->registry->get_script_data( $post_type ),
				'activeProvider'       => $active_provider ? $active_provider->get_id() : '',
				'useUniversalAnalyzer' => true,
				'debugAnalyzer'        => ! empty( $settings['enable_debug'] ),
				'autoApply'            => (bool) $settings['auto_apply'],
				'allowImageAltUpdates' => (bool) $settings['allow_image_alt_updates'],
			)
		);
	}
}
