<?php
/**
 * Editor integration: the "AEO Controls" panel, as a block editor sidebar
 * panel (Gutenberg) or, when the block editor isn't in use for a post (e.g.
 * the Classic Editor plugin is active), a fallback meta box offering the
 * same Generate Summary/FAQ buttons against the same REST endpoints.
 *
 * @package Priizmo_Engine
 */

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

/**
 * Class Priizmo_Engine_Editor
 */
class Priizmo_Engine_Editor {

	/**
	 * Constructor. Hooks block editor asset enqueueing and the Classic
	 * Editor meta box fallback.
	 */
	public function __construct() {
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_editor_assets' ) );
		add_action( 'add_meta_boxes', array( $this, 'maybe_register_classic_meta_box' ), 10, 2 );
		add_action( 'admin_enqueue_scripts', array( $this, 'maybe_enqueue_classic_assets' ) );
	}

	/**
	 * Enqueues the "AEO Controls" document sidebar panel script and styles.
	 */
	public function enqueue_editor_assets() {
		wp_enqueue_script(
			'priizmo-engine-editor',
			PRIIZMO_ENGINE_PLUGIN_URL . 'assets/js/editor.js',
			array(
				'wp-plugins',
				'wp-edit-post',
				'wp-element',
				'wp-components',
				'wp-data',
				'wp-i18n',
				'wp-api-fetch',
				'wp-notices',
			),
			PRIIZMO_ENGINE_VERSION,
			true
		);

		wp_enqueue_style(
			'priizmo-engine-editor',
			PRIIZMO_ENGINE_PLUGIN_URL . 'assets/css/editor.css',
			array( 'wp-edit-post' ),
			PRIIZMO_ENGINE_VERSION
		);
	}

	/**
	 * Registers the "AEO Controls" meta box, but only for posts that won't
	 * actually load the block editor (e.g. the Classic Editor plugin is
	 * forcing the old editor, or Gutenberg isn't available at all) --
	 * otherwise this would just duplicate the sidebar panel above.
	 *
	 * Scoped to the 'post' post type, matching every other post-type
	 * assumption already baked into this plugin (bulk processing, the
	 * automatic front-end summary/FAQ display filters, etc.).
	 *
	 * @param string  $post_type Current post type.
	 * @param WP_Post $post      Current post object.
	 */
	public function maybe_register_classic_meta_box( $post_type, $post ) {
		if ( 'post' !== $post_type ) {
			return;
		}

		if ( $post && function_exists( 'use_block_editor_for_post' ) && use_block_editor_for_post( $post ) ) {
			return;
		}

		add_meta_box(
			'priizmo-engine-controls',
			__( 'AEO Controls', 'priizmo-ai-summary-faq-schema' ),
			array( $this, 'render_classic_meta_box' ),
			$post_type,
			'side',
			'high'
		);
	}

	/**
	 * Enqueues the Classic Editor fallback script/styles, only on the
	 * post edit screen and only when that specific post won't use the
	 * block editor (see maybe_register_classic_meta_box()).
	 *
	 * @param string $hook_suffix Current admin page hook suffix.
	 */
	public function maybe_enqueue_classic_assets( $hook_suffix ) {
		if ( ! in_array( $hook_suffix, array( 'post.php', 'post-new.php' ), true ) ) {
			return;
		}

		$post = get_post();

		if ( ! $post || 'post' !== $post->post_type ) {
			return;
		}

		if ( function_exists( 'use_block_editor_for_post' ) && use_block_editor_for_post( $post ) ) {
			return;
		}

		wp_enqueue_script(
			'priizmo-engine-classic-editor',
			PRIIZMO_ENGINE_PLUGIN_URL . 'assets/js/classic-editor-controls.js',
			array( 'wp-api-fetch' ),
			PRIIZMO_ENGINE_VERSION,
			true
		);

		wp_enqueue_style(
			'priizmo-engine-classic-editor',
			PRIIZMO_ENGINE_PLUGIN_URL . 'assets/css/editor.css',
			array(),
			PRIIZMO_ENGINE_VERSION
		);

		wp_localize_script(
			'priizmo-engine-classic-editor',
			'priizmoEngineClassicEditor',
			array(
				'i18n' => array(
					'generateSummary' => __( 'Generate AI Summary', 'priizmo-ai-summary-faq-schema' ),
					'generateFaq'     => __( 'Generate AI FAQs', 'priizmo-ai-summary-faq-schema' ),
					'generating'      => __( 'Generating…', 'priizmo-ai-summary-faq-schema' ),
					'cachedSummary'   => __( 'Cached summary:', 'priizmo-ai-summary-faq-schema' ),
					'noFaq'           => __( 'No FAQs have been generated yet.', 'priizmo-ai-summary-faq-schema' ),
					'summaryError'    => __( 'Failed to generate the AI summary.', 'priizmo-ai-summary-faq-schema' ),
					'faqError'        => __( 'Failed to generate AI FAQs.', 'priizmo-ai-summary-faq-schema' ),
				),
			)
		);
	}

	/**
	 * Renders the Classic Editor fallback meta box: the same controls and
	 * cached-value previews as the block editor's "AEO Controls" panel
	 * (editor.js), server-rendered from the post's currently saved meta
	 * since there's no block-editor data store to read live unsaved state
	 * from here. Generate Summary/FAQ operate on the post's last-saved
	 * content (see Priizmo_Engine_Rest::get_plain_text_content()'s fallback);
	 * classic-editor-controls.js doesn't submit a `content` param.
	 *
	 * @param WP_Post $post Current post.
	 */
	public function render_classic_meta_box( $post ) {
		$summary   = get_post_meta( $post->ID, Priizmo_Engine_Post_Meta::META_KEY, true );
		$faq_items = Priizmo_Engine_Post_Meta::get_faq_items( $post->ID );
		?>
		<div id="priizmo-engine-classic-controls" data-post-id="<?php echo esc_attr( $post->ID ); ?>">
			<p><?php esc_html_e( 'Generate an AI-powered TL;DR summary optimized for AI search engines like ChatGPT and Perplexity.', 'priizmo-ai-summary-faq-schema' ); ?></p>
			<p>
				<button type="button" id="priizmo-engine-classic-generate-summary" class="button button-primary">
					<?php esc_html_e( 'Generate AI Summary', 'priizmo-ai-summary-faq-schema' ); ?>
				</button>
			</p>
			<div id="priizmo-engine-classic-summary-preview">
				<?php if ( ! empty( $summary ) ) : ?>
					<div class="priizmo-engine-controls-preview">
						<strong><?php esc_html_e( 'Cached summary:', 'priizmo-ai-summary-faq-schema' ); ?></strong>
						<p><?php echo esc_html( $summary ); ?></p>
					</div>
				<?php else : ?>
					<p class="priizmo-engine-controls-empty"><?php esc_html_e( 'No summary has been generated yet.', 'priizmo-ai-summary-faq-schema' ); ?></p>
				<?php endif; ?>
			</div>
			<p class="priizmo-engine-controls-hint">
				<?php esc_html_e( 'Display it with the ', 'priizmo-ai-summary-faq-schema' ); ?>
				<code>[priizmo_summary]</code>
				<?php esc_html_e( ' shortcode, or choose an automatic placement under Settings > Priizmo AI Summary & FAQ Schema.', 'priizmo-ai-summary-faq-schema' ); ?>
			</p>

			<hr class="priizmo-engine-controls-divider" />

			<p><?php esc_html_e( 'Generate AI-powered FAQs with structured FAQPage schema, so AI search engines can surface direct answers from this post.', 'priizmo-ai-summary-faq-schema' ); ?></p>
			<p>
				<button type="button" id="priizmo-engine-classic-generate-faq" class="button button-secondary">
					<?php esc_html_e( 'Generate AI FAQs', 'priizmo-ai-summary-faq-schema' ); ?>
				</button>
			</p>
			<div id="priizmo-engine-classic-faq-preview">
				<?php if ( ! empty( $faq_items ) ) : ?>
					<ul class="priizmo-engine-controls-faq-preview">
						<?php foreach ( $faq_items as $item ) : ?>
							<li>
								<strong><?php echo esc_html( $item['question'] ); ?></strong>
								<p><?php echo esc_html( $item['answer'] ); ?></p>
							</li>
						<?php endforeach; ?>
					</ul>
				<?php else : ?>
					<p class="priizmo-engine-controls-empty"><?php esc_html_e( 'No FAQs have been generated yet.', 'priizmo-ai-summary-faq-schema' ); ?></p>
				<?php endif; ?>
			</div>
			<p class="priizmo-engine-controls-hint">
				<?php esc_html_e( 'Appears automatically at the end of the post, or place it manually with the ', 'priizmo-ai-summary-faq-schema' ); ?>
				<code>[priizmo_faq]</code>
				<?php esc_html_e( ' shortcode.', 'priizmo-ai-summary-faq-schema' ); ?>
			</p>
		</div>
		<?php
	}
}
