<?php
if ( ! class_exists( 'NISHIKI_BLOCKS_PRO_FILTER_SEARCH_KEYWORDS' ) ) {
	class NISHIKI_BLOCKS_PRO_FILTER_SEARCH_KEYWORDS {

		const BLOCK_PREFIX = 'nishiki-blocks-pro';
		const BLOCK_FUNC_PREFIX = 'nishiki_blocks_pro';

		/**
		 * Construct.
		 */
		public function __construct() {
			add_filter( 'register_block_type_args', array( $this, 'custom_modify_block_args' ), 10, 2 );
		}

		/**
		 * ダイナミックブロックうに関する設定を追加
		 */
		public function custom_modify_block_args( $args, $block_type ) {
			$attributes = 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',
							),
						);

			if ( 'nishiki-blocks-pro/filter-search-keywords' === $block_type ) {
				$args['attributes'] = $attributes;
				$args['render_callback'] = array( $this, 'block_callback' );
			}

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

			global $wp_query;

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

			$classes[] = 'wp-block-nishiki-blocks-pro-filter-search__item';

			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 ' . $wrapper_attributes . '>';
			if ( ! empty( $attributes['label'] ) ) {
				$output .= '<p class="label">' . esc_html( $attributes['label'] ) . '</p>';
			}

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

			$output .= '<input type="text" name="s" id="keywords" value="' . wp_kses_post( $value ) . '" placeholder="' . wp_kses_post( $placeholder ) . '"/>';
			$output .= '</div>';

			return $output;
		}
	
	}
	
	$output = new NISHIKI_BLOCKS_PRO_FILTER_SEARCH_KEYWORDS();
}
