<?php

namespace AIPT\Api\BulkGenerator\FAQ;

defined( 'ABSPATH' ) || exit;

/**
 * Generates and injects Schema.org FAQPage JSON-LD structured data.
 *
 * Reads FAQ items from the `_aipt_faq_data` post meta field and outputs
 * a valid Schema.org FAQPage JSON-LD <script> tag in wp_head on single
 * WooCommerce product pages, when schema injection is enabled in settings.
 *
 * @package AIPT\Api\BulkGenerator\FAQ
 * @since 2.5.0
 */
class FAQSchemaGenerator {

	/**
	 * FAQ display settings instance.
	 *
	 * @var FAQDisplaySettings
	 */
	private FAQDisplaySettings $settings;

	/**
	 * Constructor.
	 *
	 * @param FAQDisplaySettings $settings FAQ display settings instance.
	 */
	public function __construct( FAQDisplaySettings $settings ) {
		$this->settings = $settings;
	}

	/**
	 * Register WordPress action hooks.
	 *
	 * Hooks inject_schema() into wp_head at priority 10.
	 *
	 * @return void
	 */
	public function register_hooks(): void {
		add_action( 'wp_head', [ $this, 'inject_schema' ], 10 );
	}

	/**
	 * Inject the Schema.org FAQPage JSON-LD structured data block.
	 *
	 * Only runs on single WooCommerce product pages when schema injection is
	 * enabled. Reads FAQ items from the `_aipt_faq_data` post meta (a JSON
	 * array of {question, answer} objects), builds the Schema.org structure,
	 * and echoes a <script type="application/ld+json"> tag.
	 *
	 * @return void
	 */
	public function inject_schema(): void {

		if ( ! is_singular( 'product' ) ) {
			return;
		}

		if ( ! $this->settings->get( 'schema_enabled' ) ) {
			return;
		}

		$product_id = get_queried_object_id();
		if ( ! $product_id ) {
			return;
		}

		$faq_data = get_post_meta( $product_id, '_aipt_faq_data', true );
		if ( empty( $faq_data ) ) {
			return;
		}

		$faqs = json_decode( $faq_data, true );
		if ( ! is_array( $faqs ) || empty( $faqs ) ) {
			return;
		}

		$schema = [
			'@context'   => 'https://schema.org',
			'@type'      => 'FAQPage',
			'mainEntity' => array_map(
				function ( $faq ) {
					return [
						'@type'          => 'Question',
						'name'           => wp_strip_all_tags( $faq['question'] ?? '' ),
						'acceptedAnswer' => [
							'@type' => 'Answer',
							'text'  => wp_strip_all_tags( $faq['answer'] ?? '' ),
						],
					];
				},
				$faqs
			),
		];

		$schema['mainEntity'] = array_values(
			array_filter(
				$schema['mainEntity'],
				fn( $q ) => ! empty( $q['name'] )
			)
		);

		if ( empty( $schema['mainEntity'] ) ) {
			return;
		}

		echo '<script type="application/ld+json">'
			. wp_json_encode( $schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT )
			. '</script>' . "\n";
	}
}
