<?php
if (!defined('ABSPATH')) {
	exit;
}

class ProbonoSEO_FAQ_Schema {
	private static $instance = null;

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

	private function __construct() {
		$this->init_hooks();
	}

	private function init_hooks() {
		if (get_option('probonoseo_aio_faq_schema', '1') === '1') {
			add_action('wp_head', array($this, 'output_faq_schema'), 7);
		}
	}

	public function output_faq_schema() {
		if (!is_singular()) {
			return;
		}

		global $post;

		if (empty($post->post_content)) {
			return;
		}

		$faqs = $this->extract_faq_blocks($post->post_content);

		if (empty($faqs)) {
			return;
		}

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

		foreach ($faqs as $faq) {
			$schema['mainEntity'][] = array(
				'@type'          => 'Question',
				'name'           => $faq['question'],
				'acceptedAnswer' => array(
					'@type' => 'Answer',
					'text'  => $faq['answer'],
				),
			);
		}

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

	private function extract_faq_blocks($content) {
		$faqs = array();

		if (!has_blocks($content)) {
			return $faqs;
		}

		$blocks = parse_blocks($content);

		foreach ($blocks as $block) {
			if ($block['blockName'] === 'core/details') {
				$summary = '';
				$answer  = '';

				foreach ($block['innerBlocks'] as $inner) {
					if ($inner['blockName'] === 'core/paragraph' && empty($summary)) {
						$summary = wp_strip_all_tags(render_block($inner));
					} elseif (!empty($summary)) {
						$answer .= wp_strip_all_tags(render_block($inner));
					}
				}

				if (!empty($summary) && !empty($answer)) {
					$faqs[] = array(
						'question' => trim($summary),
						'answer'   => trim($answer),
					);
				}
			}
		}

		return $faqs;
	}
}

function probonoseo_init_faq_schema() {
	ProbonoSEO_FAQ_Schema::get_instance();
}
add_action('init', 'probonoseo_init_faq_schema');