<?php
namespace hakoniwa\blocks\ssr\filterSearchKeywords;

use hakoniwa\blocks\init\Define;
use hakoniwa\blocks\util\Misc;

class Register {

	/**
	 * Construct.
	 */
	public function __construct() {

		add_action( 'init', [ $this, 'register_dynamic_block' ] );
		
	}

	/**
	 * ダイナミックブロック登録
	 *
	 * @return void
	 */
	public function register_dynamic_block() {

		$args = array(
			'label'	=> array(
				'type'    => 'string',
				'default' => 'キーワード検索',
			),
			'placeholder'	=> array(
				'type'    => 'string',
				'default' => 'キーワードを入れてください',
			),
			'widthDesktop' => array(
				'type'    => 'string',
				'default' => '50',
			),
			'widthTablet'	=> array(
				'type'    => 'string',
				'default' => '50',
			),
			'widthSmartPhone'	=> array(
				'type'    => 'string',
				'default' => '100',
			),
		);

		register_block_type(
			Define::value( 'plugin_path' ) . 'build/filter-search-keywords',
			array(
				'attributes'      => $args,
				'render_callback' => array( $this, 'block_callback' ),
			)
		);
	}

	/**
	 * レンダリング
	 *
	 * @param array $attributes 属性
	 * @return $card
	 */
	public function block_callback( $attributes, $content, $block ) {

		$output = '';
		$classes	= [];
		$placeholder = '';
		$searched_keyword = '';

		if ( ! empty( $attributes['widthDesktop'] ) ) {
			$classes[] = $attributes['widthDesktop'] == '100' ? 'width-100' : 'width-50';
		}

		if ( ! empty( $attributes['widthTablet'] ) ) {
			$classes[] = $attributes['widthTablet'] == '100' ? 'md:width-100' : 'md:width-50';
		}

		if ( ! empty( $attributes['widthSmartPhone'] ) ) {
			$classes[] = $attributes['widthSmartPhone'] == '100' ? 'sp:width-100' : 'sp:width-50';
		}

		$wrapper_attributes = get_block_wrapper_attributes( 
			array( 
				'class' => trim( implode( ' ', $classes ) ),
			)
		);

		if ( ! empty( $attributes['placeholder'] ) ) {
			$placeholder = $attributes['placeholder'];
		}

		$output .= '<div ' . wp_kses_post( $wrapper_attributes ) . '>';
		if ( ! empty( $attributes['label'] ) ) {
			$output .= '<p class="label">' . esc_html( $attributes['label'] ) . '</p>';
		}
		if( ! empty( get_query_var('s') ) ){
			$searched_keyword = get_query_var('s');
		}
		$output .= '<input type="text" name="s" value="' . wp_kses_post( $searched_keyword ) . '" placeholder="' . wp_kses_post( $placeholder ) . '"/>';
		$output .= '</div>';

		return $output;
	}

}

use hakoniwa\blocks\ssr\filterSearchKeywords;
new Register();