<?php
/**
 * Structured data output for Content Widgets.
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Content_Widgets_Schema
 */
final class Rsmspark_Content_Widgets_Schema {

	/**
	 * Build FAQPage schema graph from accordion items.
	 *
	 * @param array<int, array{title?: string, content?: string}> $items Sanitized items.
	 * @return array<string, mixed>|null
	 */
	public static function faq_page( array $items ) {
		$entities = array();

		foreach ( $items as $item ) {
			if ( ! is_array( $item ) ) {
				continue;
			}

			if ( 'category' === ( $item['item_type'] ?? 'item' ) ) {
				continue;
			}

			$question = trim( (string) ( $item['title'] ?? '' ) );
			$answer   = trim( wp_strip_all_tags( (string) ( $item['content'] ?? '' ) ) );

			if ( '' === $question || '' === $answer ) {
				continue;
			}

			$entities[] = array(
				'@type'          => 'Question',
				'name'           => $question,
				'acceptedAnswer' => array(
					'@type' => 'Answer',
					'text'  => $answer,
				),
			);
		}

		if ( empty( $entities ) ) {
			return null;
		}

		return array(
			'@context'   => 'https://schema.org',
			'@type'      => 'FAQPage',
			'mainEntity' => $entities,
		);
	}

	/**
	 * Print FAQPage JSON-LD script tag.
	 *
	 * @param array<int, array{title?: string, content?: string}> $items Sanitized items.
	 * @return void
	 */
	public static function print_faq_page_json_ld( array $items ) {
		$data = self::faq_page( $items );
		if ( null === $data ) {
			return;
		}

		wp_print_inline_script_tag(
			wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ),
			array( 'type' => 'application/ld+json' )
		);
	}
}
