<?php
namespace hakoniwa\blocks\filter\faq;

use hakoniwa\blocks\init\Define;

/**
 * ブロックフィルター
 */
class Filter {

    /**
     * constructor.
     */
    public function __construct() {
        add_filter( 'render_block_' . Define::value( 'plugin_name' ) . '/faq', [ $this, 'render_block' ], 10, 3 );
    }

    public function render_block( $block_content, $block ) {

        $html = '';

        foreach( $block['innerBlocks'] as $innerblocks ){
            $html .= $innerblocks['innerHTML'];
        }

        // 特定のタグのみ有効にするため削除
        // https://developers.google.com/search/docs/advanced/structured-data/faqpage?hl=ja
        // 質問に対する回答の全文。
        // 回答には、リンクやリストなど、HTML コンテンツを含めることもできます。
        // Google 検索では次の HTML タグが表示され、他のすべてのタグは無視されます: <h1> から <h6>、<br>、<ol>、<ul>、<li>、<a>、<p>、<div>、<b>、<strong>、<i>、<em>。

        $allowed_html = [
            'h1' => [],
            'h2' => [],
            'h3' => [],
            'h4' => [],
            'h5' => [],
            'h6' => [],
            'br' => [],
            'ol' => [],
            'ul' => [],
            'li' => [],
            'a' => [
                'href' => [],
                'target' => [],
            ],
            'p' => [],
            'div' => [],
            'b' => [],
            'strong' => [],
            'i' => [],
            'em' => [],
        ];

        $html = wp_kses( $html, $allowed_html );

        if ( ! empty( $block['attrs']['question'] ) && ! empty( $html ) ) {
            $json_array = [
                '@context' => 'https://schema.org',
                '@type' => 'FAQPage',
                'mainEntity' => [
                    '@type' => 'Question',
                    'name' => $block['attrs']['question'],
                    'acceptedAnswer' => [
                        '@type' => 'Answer',
                        'text' => $html,
                    ]
                ],
            ];

            add_action(
                'wp_head',
                function() use ( $json_array ) {
                    $output = "<script type='application/ld+json'>" . wp_json_encode( $json_array ) . "</script>" . "\n";
                    echo $output;
                },
                100
            );
        }

        return $block_content;
    }

}

use hakoniwa\blocks\filter\faq;
new Filter();
