<?php
/**
 * Classic Editor Integration Class
 *
 * Manages integration with WordPress Classic Editor (TinyMCE)
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.4
 */

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

/**
 * Classic Editor Integration class
 */
class SmartyPress_AI_Classic_Editor_Integration {

	/**
	 * AI Providers
	 *
	 * @var array
	 */
	private $providers;

	/**
	 * Constructor
	 *
	 * @param array $providers AI providers instances.
	 */
	public function __construct( $providers ) {
		$this->providers = $providers;
	}

	/**
	 * Initialize Classic Editor integration
	 */
	public function init() {
		// Only load on post edit screens with Classic Editor
		add_action( 'admin_enqueue_scripts', array( $this, 'maybe_enqueue_assets' ) );
		add_filter( 'mce_buttons', array( $this, 'add_tinymce_buttons' ), 10, 2 );
		add_filter( 'mce_external_plugins', array( $this, 'register_tinymce_plugin' ), 10, 1 );
		// Add AI Writer button next to Add Media
		add_action( 'media_buttons', array( $this, 'render_ai_writer_button' ), 15 );
	}

	/**
	 * Get enabled post types for the plugin
	 *
	 * @return array List of enabled post types.
	 */
	private function get_enabled_post_types() {
		$settings = get_option( 'smartypress_ai_settings', array() );
		return $settings['enabled_post_types'] ?? array( 'post', 'page', 'product' );
	}

	/**
	 * Check if current post type is enabled
	 *
	 * @return bool
	 */
	private function is_post_type_enabled() {
		$current_screen = get_current_screen();
		if ( ! $current_screen ) {
			return false;
		}
		$enabled_types = $this->get_enabled_post_types();
		return in_array( $current_screen->post_type, $enabled_types, true );
	}

	/**
	 * Check if Classic Editor is active for current post
	 *
	 * @return bool
	 */
	private function is_classic_editor_active() {
		$screen = get_current_screen();
		
		// Check if we're on a post edit screen
		if ( ! $screen || ! in_array( $screen->base, array( 'post', 'post-new' ), true ) ) {
			return false;
		}

		$post_type = $screen->post_type;

		// WooCommerce products always use classic editor for description
		if ( $post_type === 'product' && class_exists( 'WooCommerce' ) ) {
			return true;
		}

		// Check if block editor is disabled for this post type
		if ( function_exists( 'use_block_editor_for_post_type' ) ) {
			if ( ! use_block_editor_for_post_type( $post_type ) ) {
				return true;
			}
		}

		// Check if block editor is disabled for current post.
		$post_id = filter_input( INPUT_GET, 'post', FILTER_VALIDATE_INT );
		if ( function_exists( 'use_block_editor_for_post' ) && $post_id ) {
			$post = get_post( absint( $post_id ) );
			if ( $post && ! use_block_editor_for_post( $post ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Render AI Writer button next to Add Media
	 *
	 * @param string $editor_id Current editor ID.
	 */
	public function render_ai_writer_button( $editor_id ) {
		// Only for main content editor
		if ( $editor_id !== 'content' ) {
			return;
		}

		// Check if post type is enabled
		if ( ! $this->is_post_type_enabled() ) {
			return;
		}

		// Check if classic editor is active
		if ( ! $this->is_classic_editor_active() ) {
			return;
		}

		?>
		<div class="smartypress-ai-classic-above-wrapper" id="smartypress-ai-writer-wrapper">
			<button type="button" class="smartypress-ai-classic-above-btn" id="smartypress-ai-writer-btn">
				<svg class="smartypress-ai-writer-icon" width="16" height="16" viewBox="0 0 1000 1000" fill="none" xmlns="http://www.w3.org/2000/svg">
					<path d="M825 788a38 38 0 0 0 38-38 63 63 0 0 1 62-62 38 38 0 0 0 0-75 63 63 0 0 1-62-63 38 38 0 0 0-75 0 63 63 0 0 1-63 63 38 38 0 0 0 0 75 63 63 0 0 1 63 62 38 38 0 0 0 37 38z m0-132a137 137 0 0 0-6-6 135 135 0 0 0 6-6 137 137 0 0 0 6 6 134 134 0 0 0-6 6z m-450 32a38 38 0 0 0 38-38 263 263 0 0 1 262-262 38 38 0 0 0 0-75 263 263 0 0 1-262-263 38 38 0 0 0-75 0 263 263 0 0 1-263 263 38 38 0 0 0 0 75 263 263 0 0 1 263 262 38 38 0 0 0 37 38z m0-193a337 337 0 0 0-145-145 338 338 0 0 0 145-145 337 337 0 0 0 145 145 337 337 0 0 0-145 145z m450-307a38 38 0 0 0 38-38 63 63 0 0 1 62-62 38 38 0 0 0 0-75 63 63 0 0 1-62-63 38 38 0 0 0-75 0 63 63 0 0 1-63 63 38 38 0 0 0 0 75 63 63 0 0 1 63 62 38 38 0 0 0 37 38z m0-132a136 136 0 0 0-6-6 136 136 0 0 0 6-6 136 136 0 0 0 6 6 136 136 0 0 0-6 6z" fill="#F59E0B"/>
				</svg>
				<?php esc_html_e( 'SmartyPress AI Writer', 'smartypress-ai-engine' ); ?>
			</button>
			<div class="smartypress-ai-classic-dropdown" id="smartypress-ai-writer-dropdown" style="display:none;">
				<a href="#" data-action="title"><?php esc_html_e( 'Generate Title', 'smartypress-ai-engine' ); ?></a>
				<a href="#" data-action="content"><?php esc_html_e( 'Generate Content', 'smartypress-ai-engine' ); ?></a>
				<a href="#" data-action="excerpt"><?php esc_html_e( 'Generate Excerpt', 'smartypress-ai-engine' ); ?></a>
				<?php /* Temporarily hidden - Suggest Categories
				<a href="#" data-action="categories"><?php esc_html_e( 'Suggest Categories', 'smartypress-ai-engine' ); ?></a>
				*/ ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Enqueue assets if Classic Editor is active
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function maybe_enqueue_assets( $hook ) {
		// Only on post edit screens
		if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ), true ) ) {
			return;
		}

		// Only if Classic Editor is active
		if ( ! $this->is_classic_editor_active() ) {
			return;
		}

		// Check if current post type is enabled
		if ( ! $this->is_post_type_enabled() ) {
			return;
		}

		$settings = get_option( 'smartypress_ai_settings', array() );

		// Enqueue modal JavaScript
		wp_enqueue_script(
			'smartypress-ai-classic-modal',
			SPAI_CG_PLUGIN_URL . '/assets/classic-editor/classic-editor-modal.js',
			array( 'wp-api-fetch', 'wp-i18n' ),
			SPAI_CG_PLUGIN_VERSION,
			true
		);

		// Set script translations for classic editor modal
		wp_set_script_translations(
			'smartypress-ai-classic-modal',
			'smartypress-ai-engine',
			SMARTYPRESS_AI_PLUGIN_DIR . 'languages'
		);

		// Enqueue modal CSS
		wp_enqueue_style(
			'smartypress-ai-classic-modal',
			SPAI_CG_PLUGIN_URL . '/assets/classic-editor/classic-editor-modal.css',
			array(),
			SPAI_CG_PLUGIN_VERSION
		);

		// Get available providers (show all supported providers)
		$available_providers = SmartyPress_AI_Providers::get_all();
		$all_supported_providers = array( 'openai', 'deepseek' );
		
		$providers_to_show = ! empty( $available_providers ) 
			? array_keys( $available_providers ) 
			: $all_supported_providers;

		// Localize script with configuration
		wp_localize_script(
			'smartypress-ai-classic-modal',
			'smartypressAI',
			array(
				'restUrl'        => rest_url( 'smartypress/v1/' ),
				'nonce'          => wp_create_nonce( 'wp_rest' ),
				'pluginUrl'      => SMARTYPRESS_AI_PLUGIN_URL,
				'adminUrl'       => admin_url(),
				'settings'       => $settings,
				'providers'      => $providers_to_show,
				'providerModels' => $this->get_provider_models(),
				'localeDefaultLanguage' => smartypress_ai_get_language_by_locale(),
			)
		);

		// Localize wand features
		wp_localize_script(
			'smartypress-ai-classic-modal',
			'smartypressWand',
			array(
				'features'  => SmartyPress_AI_Wand_Features::get_features(),
				'restUrl'   => rest_url( 'smartypress/v1/' ),
				'nonce'     => wp_create_nonce( 'wp_rest' ),
				'pluginUrl' => SMARTYPRESS_AI_PLUGIN_URL,
				'adminUrl'  => admin_url(),
				'providers' => $providers_to_show,
				'settings'  => $settings,
			)
		);
	}

	/**
	 * Add buttons to TinyMCE toolbar
	 *
	 * @param array  $buttons Toolbar buttons.
	 * @param string $editor_id Editor ID.
	 * @return array Modified buttons.
	 */
	public function add_tinymce_buttons( $buttons, $editor_id ) {
		// Only add to main content editor and excerpt editor (WooCommerce short description)
		if ( ! in_array( $editor_id, array( 'content', 'excerpt' ), true ) ) {
			return $buttons;
		}

		// Only if Classic Editor is active
		if ( ! $this->is_classic_editor_active() ) {
			return $buttons;
		}

		// Check if current post type is enabled
		if ( ! $this->is_post_type_enabled() ) {
			return $buttons;
		}

		// Add Magic Wand button
		$buttons[] = 'smartypress_wand';

		return $buttons;
	}

	/**
	 * Register TinyMCE plugin
	 *
	 * @param array $plugins External plugins.
	 * @return array Modified plugins.
	 */
	public function register_tinymce_plugin( $plugins ) {
		// Only if Classic Editor is active
		if ( ! $this->is_classic_editor_active() ) {
			return $plugins;
		}

		// Check if current post type is enabled
		if ( ! $this->is_post_type_enabled() ) {
			return $plugins;
		}

		$plugins['smartypress_ai'] = SPAI_CG_PLUGIN_URL . '/assets/classic-editor/tinymce-plugin.js?ver=' . SPAI_CG_PLUGIN_VERSION;

		return $plugins;
	}

	/**
	 * Get available models for each provider
	 *
	 * @return array Provider models.
	 */
	private function get_provider_models() {
		$provider_models = array();
		
		// Use static Providers class to get available providers
		// This ensures we get the latest initialized providers
		$available = SmartyPress_AI_Providers::get_available_providers();
		
		foreach ( $available as $provider_name => $provider ) {
			if ( method_exists( $provider, 'get_available_models' ) ) {
				$provider_models[ $provider_name ] = $provider->get_available_models();
			}
		}
		
		// Fallback to instance providers if static class has none
		if ( empty( $provider_models ) ) {
			foreach ( $this->providers as $provider_name => $provider ) {
				if ( method_exists( $provider, 'get_available_models' ) ) {
					$provider_models[ $provider_name ] = $provider->get_available_models();
				}
			}
		}
		
		return $provider_models;
	}
}
