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

use hakoniwa\blocks\init\Define;

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

    /**
     * constructor.
     */
    public function __construct() {
        add_filter( 'render_block_' . Define::value( 'plugin_name' ) . '/filter-search', array( $this, 'render_block' ), 10, 3 );
    }

    public function render_block( $block_content, $block, $instance ) {
        $relation = 'or';

        // 検索結果ページのみ選択状態を反映させる
        if( is_search() ){
            global $wp_query;
        }

        // 絞り込み検索のデフォルト値
        $filter_search_terms_default_value = \WP_Block_Type_Registry::get_instance()->get_registered( Define::value( 'plugin_name' ) . '/filter-search-terms' );
//        var_dump( $filter_search_default_value->attributes );

        // wp_query から relation のデータを取得して form に反映させる
        global $wp_query;

        if( ! empty( $wp_query->query['relation'] ) ){
            $relation = $wp_query->query['relation'];
        }

        $html = $block_content;

        $regex = '@<input type="radio" name="relation" value="(\S+)" id="(?:\S+)".*?>@is';

/*        
        if( preg_match_all( $regex, $html, $matches ) ){
            var_dump($matches);
        }
*/

        $block_content = preg_replace_callback( 
            $regex,
            function ( $matches ) use ( $relation ) {
                // checked を一旦すべてリセット
                $delete_checked = str_replace( "checked", "", $matches[0] );

                if( $matches[1] == $relation ){
                    $add_checked = str_replace( 'value="' . $relation . '"', 'value="' . $relation . '" checked', $delete_checked );
                    return $add_checked;
                } else {
                    return $delete_checked;
                }
            },
            $block_content
        );

        return $block_content;
    }
}

use hakoniwa\blocks\filter\filterSearch;
new REGISTER_BLOCK_FILTER();
