<?php
/**
 * FAQ — storage, retrieval, and schema.org/FAQPage JSON-LD injection
 * on single-product pages.
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio;

defined( 'ABSPATH' ) || exit;

final class FAQ {

	const META_KEY = '_cpais_faq';

	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'wp_head', array( $this, 'render_schema' ), 20 );
		add_shortcode( 'cpais_faq', array( $this, 'render_shortcode' ) );
	}

	/**
	 * Sanitize FAQ list before saving.
	 * Each item: { question: string, answer: string }.
	 * Questions: plain text. Answers: limited HTML via wp_kses_post.
	 *
	 * @return array<int, array{question: string, answer: string}>
	 */
	public static function sanitize( $items ) {
		if ( ! is_array( $items ) ) {
			return array();
		}
		$clean = array();
		foreach ( $items as $item ) {
			if ( ! is_array( $item ) ) {
				continue;
			}
			$q = isset( $item['question'] ) ? sanitize_text_field( (string) $item['question'] ) : '';
			$a = isset( $item['answer'] )   ? wp_kses_post( (string) $item['answer'] )         : '';
			if ( '' === $q || '' === $a ) {
				continue;
			}
			$clean[] = array( 'question' => $q, 'answer' => $a );
		}
		// Hard cap — 25 items is already excessive for a rich snippet.
		return array_slice( $clean, 0, 25 );
	}

	/**
	 * Save FAQ list to product meta.
	 *
	 * @param int   $product_id WC product ID.
	 * @param array $items      List of { question, answer } items.
	 * @return int|false Number of items saved, or false on failure.
	 */
	public static function save( $product_id, array $items ) {
		$product_id = absint( $product_id );
		if ( ! $product_id || 'product' !== get_post_type( $product_id ) ) {
			return false;
		}
		$clean = self::sanitize( $items );
		if ( empty( $clean ) ) {
			delete_post_meta( $product_id, self::META_KEY );
			return 0;
		}
		update_post_meta( $product_id, self::META_KEY, $clean );
		return count( $clean );
	}

	public static function get( $product_id ) {
		$items = get_post_meta( absint( $product_id ), self::META_KEY, true );
		return is_array( $items ) ? $items : array();
	}

	/**
	 * Emit schema.org/FAQPage JSON-LD on single product pages.
	 * Controlled by setting `faq_schema_enabled`.
	 */
	public function render_schema() {
		if ( ! function_exists( 'is_product' ) || ! is_product() ) {
			return;
		}
		$settings = Settings::get_all();
		if ( empty( $settings['faq_schema_enabled'] ) ) {
			return;
		}
		$product_id = (int) get_queried_object_id();
		$items      = self::get( $product_id );
		if ( empty( $items ) ) {
			return;
		}

		$schema = array(
			'@context'   => 'https://schema.org',
			'@type'      => 'FAQPage',
			'mainEntity' => array(),
		);
		foreach ( $items as $item ) {
			$schema['mainEntity'][] = array(
				'@type'          => 'Question',
				'name'           => wp_strip_all_tags( $item['question'] ),
				'acceptedAnswer' => array(
					'@type' => 'Answer',
					'text'  => wp_strip_all_tags( $item['answer'] ),
				),
			);
		}

		$json = wp_json_encode(
			$schema,
			JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
		);
		echo wp_kses(
			'<script type="application/ld+json">' . $json . '</script>' . "\n",
			array(
				'script' => array(
					'type' => true,
				),
			)
		);
	}

	/**
	 * [cpais_faq id="123"] — renders a plain HTML FAQ list.
	 * Falls back to the current product on single-product pages.
	 */
	public function render_shortcode( $atts ) {
		$atts = shortcode_atts( array( 'id' => 0 ), $atts, 'cpais_faq' );
		$product_id = absint( $atts['id'] );
		if ( ! $product_id && function_exists( 'is_product' ) && is_product() ) {
			$product_id = (int) get_queried_object_id();
		}
		if ( ! $product_id ) {
			return '';
		}
		$items = self::get( $product_id );
		if ( empty( $items ) ) {
			return '';
		}

		$out = '<div class="cpais-faq">';
		foreach ( $items as $item ) {
			$out .= '<details class="cpais-faq__item">';
			$out .= '<summary class="cpais-faq__question">' . esc_html( $item['question'] ) . '</summary>';
			$out .= '<div class="cpais-faq__answer">' . wp_kses_post( $item['answer'] ) . '</div>';
			$out .= '</details>';
		}
		$out .= '</div>';
		return $out;
	}
}
