<?php
/**
 * Module: JetSmartFilters Search.
 */
namespace Jet_Engine_Divi_Views\Components\Jet_Smart_Filters\Modules;

if ( ! defined( 'ABSPATH' ) ) {
	die( 'Direct access forbidden.' );
}

use ET\Builder\Framework\DependencyManagement\Interfaces\DependencyInterface;
use ET\Builder\Packages\ModuleLibrary\ModuleRegistration;
use ET\Builder\Packages\Module\Module;
use ET\Builder\FrontEnd\BlockParser\BlockParserStore;
use ET\Builder\FrontEnd\Module\Style;
use Jet_Engine_Divi_Views\Utils;

class Search implements DependencyInterface {

	private static function get_default_settings() {
		return [
			'filter_id'                   => 0,
			'content_provider'            => 'not-selected',
			'apply_type'                  => 'ajax',
			'apply_button_text'           => __( 'Apply', 'jet-smart-filters' ),
			'hide_apply_button'           => false,
			'typing_min_letters_count'    => 3,
			'show_label'                  => false,
			'query_id'                    => '',
			'additional_providers_enabled'=> false,
			'additional_providers_list'   => [
				[
					'additional_provider'       => '',
					'additional_providers_list' => '',
				],
			],
		];
	}

	private static function normalize_toggle_value( $value ) {
		if ( is_array( $value ) ) {
			return self::map_responsive_value(
				$value,
				static function ( $current ) {
					if ( is_bool( $current ) ) {
						return $current;
					}

					return in_array( $current, [ 'on', 'yes', 'true', '1', 1 ], true );
				}
			);
		}

		if ( is_bool( $value ) ) {
			return $value;
		}

		return in_array( $value, [ 'on', 'yes', 'true', '1', 1 ], true );
	}

	private static function get_prepared_attrs( $attrs ) {
		$defaults = self::get_default_settings();
		$prepared = $defaults;

		foreach ( $attrs as $key => $value ) {
			if ( isset( $value['innerContent']['desktop']['value'] ) ) {
				$prepared[ $key ] = $value['innerContent']['desktop']['value'];
			}
		}

		foreach ( [
			'hide_apply_button',
			'show_label',
			'additional_providers_enabled',
		] as $toggle_key ) {
			if ( array_key_exists( $toggle_key, $prepared ) ) {
				$prepared[ $toggle_key ] = self::normalize_toggle_value( $prepared[ $toggle_key ] );
			}
		}

		return $prepared;
	}

	/**
	 * Module's style components.
	 *
	 * @param array $args {
	 *     An array of arguments.
	 *
	 *      @type string $id                Module ID. In VB, the ID of module is UUIDV4. In FE, the ID is order index.
	 *      @type string $name              Module name.
	 *      @type string $attrs             Module attributes.
	 *      @type string $parentAttrs       Parent attrs.
	 *      @type string $orderClass        Selector class name.
	 *      @type string $parentOrderClass  Parent selector class name.
	 *      @type string $wrapperOrderClass Wrapper selector class name.
	 *      @type string $settings          Custom settings.
	 *      @type string $state             Attributes state.
	 *      @type string $mode              Style mode.
	 *      @type ModuleElements $elements  ModuleElements instance.
	 * }
	 */
	public static function module_styles( $args ) {

		$elements                    = $args['elements'];
		$settings                    = $args['settings'] ?? [];
		$default_printed_style_attrs = $args['defaultPrintedStyleAttrs'] ?? [];
		$attrs                       = $args['attrs'] ?? [];

		$selectors = [
			'filter_wrapper'    => "{$args['orderClass']} .jet-search-filter",
			'input'             => "{$args['orderClass']} .jet-search-filter__input",
			'input_wrapper'     => "{$args['orderClass']} .jet-search-filter__input-wrapper",
			'input_clear'       => "{$args['orderClass']} .jet-search-filter__input-clear",
			'input_loading'     => "{$args['orderClass']} .jet-search-filter__input-loading",
			'apply_button'      => "{$args['orderClass']} .jet-search-filter__submit",
			'apply_button_hover'=> "{$args['orderClass']} .jet-search-filter__submit:hover",
			'label'             => "{$args['orderClass']} .jet-filter-label",
		];

		$button_alignment = self::map_responsive_value(
			$attrs['module']['decoration']['buttonAlignment'] ?? null,
			static function ( $value ) {
				if ( 'left' === $value ) {
					return 'flex-start';
				}

				if ( 'right' === $value ) {
					return 'flex-end';
				}

				return $value;
			}
		);

		$input_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['inputTypography'] ?? null );
		$input_typography_styles = Utils\build_typography_styles(
			$selectors['input'],
			$input_typography
		);

		$input_border = Utils\extract_border_attrs( $attrs['module']['decoration']['inputBorder'] ?? null );
		$input_border_styles = Utils\build_border_styles(
			$selectors['input'],
			$input_border
		);

		$input_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['inputSpacing'] ?? null );
		$input_spacing_legacy_padding = Utils\extract_spasing_attrs( $attrs['module']['decoration']['inputPadding'] ?? null );
		$input_spacing_legacy_margin = Utils\extract_spasing_attrs( $attrs['module']['decoration']['inputMargin'] ?? null );
		$input_spacing['padding'] = $input_spacing['padding'] ?? $input_spacing_legacy_padding['padding'] ?? [];
		$input_spacing['margin']  = $input_spacing['margin'] ?? $input_spacing_legacy_margin['margin'] ?? [];
		$input_spacing_styles = Utils\build_spacing_styles(
			$selectors['input'],
			$input_spacing
		);

		$label_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['labelTypography'] ?? null );
		$label_typography_styles = Utils\build_typography_styles(
			$selectors['label'],
			$label_typography
		);

		
		$label_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['labelSpacing'] ?? null );
		$label_spacing_legacy_padding = Utils\extract_spasing_attrs( $attrs['module']['decoration']['labelPadding'] ?? null );
		$label_spacing_legacy_margin = Utils\extract_spasing_attrs( $attrs['module']['decoration']['labelMargin'] ?? null );
		$label_spacing['padding'] = $label_spacing['padding'] ?? $label_spacing_legacy_padding['padding'] ?? [];
		$label_spacing['margin']  = $label_spacing['margin'] ?? $label_spacing_legacy_margin['margin'] ?? [];
		$label_spacing_styles = Utils\build_spacing_styles(
			$selectors['label'],
			$label_spacing
		);

		$button_border = Utils\extract_border_attrs( $attrs['module']['decoration']['buttonBorder'] ?? null );
		$button_border_styles = Utils\build_border_styles(
			$selectors['apply_button'],
			$button_border
		);

		$button_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['buttonSpacing'] ?? null );
		$button_spacing_legacy_padding = Utils\extract_spasing_attrs( $attrs['module']['decoration']['buttonPadding'] ?? null );
		$button_spacing_legacy_margin = Utils\extract_spasing_attrs( $attrs['module']['decoration']['buttonMargin'] ?? null );
		$button_spacing['padding'] = $button_spacing['padding'] ?? $button_spacing_legacy_padding['padding'] ?? [];
		$button_spacing['margin']  = $button_spacing['margin'] ?? $button_spacing_legacy_margin['margin'] ?? [];
		$button_spacing_styles = Utils\build_spacing_styles(
			$selectors['apply_button'],
			$button_spacing
		);


		Style::add(
			[
				'id'            => $args['id'],
				'name'          => $args['name'],
				'orderIndex'    => $args['orderIndex'],
				'storeInstance' => $args['storeInstance'],
				'styles'        => [
					$elements->style(
						[
							'attrName'   => 'module',
							'styleProps' => [
								'defaultPrintedStyleAttrs' => $default_printed_style_attrs['module']['decoration'] ?? [],
								'disabledOn'               => [
									'disabledModuleVisibility' => $settings['disabledModuleVisibility'] ?? null,
								],
								'advancedStyles' => array_merge(
									$input_typography_styles,
									$input_border_styles,
									$input_spacing_styles,
									$label_typography_styles,
															$label_spacing_styles,
									$button_border_styles,
									$button_spacing_styles,
									[
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['input_wrapper'],
												'attr'     => $attrs['module']['decoration']['contentInputWidth'] ?? [],
												'property' => 'max-width',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['filter_wrapper'],
												'attr'     => $attrs['module']['decoration']['contentLineHorizontalAlignment'] ?? [],
												'property' => 'justify-content',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['filter_wrapper'],
												'attr'     => $attrs['module']['decoration']['contentLineVerticalAlignment'] ?? [],
												'property' => 'align-items',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['input'],
												'attr'     => $attrs['module']['decoration']['inputColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['input'] . '::placeholder',
												'attr'     => $attrs['module']['decoration']['inputColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['input'] . ':-ms-input-placeholder',
												'attr'     => $attrs['module']['decoration']['inputColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['input'] . '::-ms-input-placeholder',
												'attr'     => $attrs['module']['decoration']['inputColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['input_clear'],
												'attr'     => $attrs['module']['decoration']['inputColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['input_loading'],
												'attr'     => $attrs['module']['decoration']['inputColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['input'],
												'attr'     => $attrs['module']['decoration']['inputBackgroundColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['label'],
												'attr'     => $attrs['module']['decoration']['labelAlignment'] ?? [],
												'property' => 'text-align',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['label'],
												'attr'     => $attrs['module']['decoration']['labelColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['apply_button'],
												'attr'     => $attrs['module']['decoration']['buttonNormalColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['apply_button'],
												'attr'     => $attrs['module']['decoration']['buttonNormalBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['apply_button_hover'],
												'attr'     => $attrs['module']['decoration']['buttonHoverColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['apply_button_hover'],
												'attr'     => $attrs['module']['decoration']['buttonHoverBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['apply_button_hover'],
												'attr'     => $attrs['module']['decoration']['buttonHoverBorderColor'] ?? [],
												'property' => 'border-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['apply_button'],
												'attr'     => $button_alignment ?? [],
												'property' => 'align-self',
											]
										],
									]
								),
							],
						]
					),
				],
			]
		);
	}

	/**
	 * Set script data of used module options.
	 *
	 * @since ??
	 *
	 * @param array $args {
	 *   Array of arguments.
	 *
	 *   @type string $id       Module id.
	 *   @type string $selector Module selector.
	 *   @type array  $attrs    Module attributes.
	 * }
	 */
	public static function module_script_data( $args ) {
	}

	/**
	 * Map responsive attr values and keep breakpoint structure.
	 *
	 * @param mixed    $attr
	 * @param callable $map
	 *
	 * @return array|null
	 */
	private static function map_responsive_value( $attr, $map ) {
		if ( empty( $attr ) ) {
			return null;
		}

		$breakpoints = [ 'desktop', 'tablet', 'phone' ];
		$has_bp = false;

		foreach ( $breakpoints as $bp ) {
			if ( isset( $attr[ $bp ] ) ) {
				$has_bp = true;
				break;
			}
		}

		if ( $has_bp ) {
			$out = $attr;
			foreach ( $breakpoints as $bp ) {
				if ( ! isset( $attr[ $bp ] ) ) {
					continue;
				}

				$val = $attr[ $bp ]['value'] ?? $attr[ $bp ]['default'] ?? null;
				if ( null === $val ) {
					continue;
				}

				$mapped = $map( $val );
				$out[ $bp ]['value'] = $mapped;
				$out[ $bp ]['default'] = $mapped;
			}

			return $out;
		}

		$val = $attr['value'] ?? $attr['default'] ?? null;
		if ( null === $val ) {
			return $attr;
		}

		$mapped = $map( $val );
		$attr['value'] = $mapped;
		$attr['default'] = $mapped;

		return $attr;
	}

	/**
	 * Module classnames function for Dynamic module.
	 *
	 * @since ??
	 *
	 * @param array $args {
	 *     An array of arguments.
	 *
	 *     @type object $classnamesInstance Instance of ET\Builder\Packages\Module\Layout\Components\Classnames.
	 *     @type array  $attrs              Block attributes data that being rendered.
	 * }
	 */
	public static function module_classnames( $args ) {
	}

	/**
	 * Dynamic module render callback which outputs server side rendered HTML on the Front-End.
	 *
	 * @since ??
	 *
	 * @param array          $attrs    Block attributes that were saved by VB.
	 * @param string         $content  Block content.
	 * @param \WP_Block      $block    Parsed block object that being rendered.
	 * @param ModuleElements $elements ModuleElements instance.
	 *
	 * @return string HTML rendered of module.
	 */
	public static function render_callback( $attrs, $content, $block, $elements ) {
		$prepared_attrs = self::get_prepared_attrs( $attrs );

		$parent       = BlockParserStore::get_parent( $block->parsed_block['id'], $block->parsed_block['storeInstance'] );
		$parent_attrs = $parent->attrs ?? [];

		$filters_block_type = jet_smart_filters()->blocks->get_block_type( 'search' );
		$content = $filters_block_type->render_callback( $prepared_attrs );

		return Module::render(
			[
				// FE only.
				'orderIndex'          => $block->parsed_block['orderIndex'],
				'storeInstance'       => $block->parsed_block['storeInstance'],

				// VB equivalent.
				'id'                  => $block->parsed_block['id'],
				'name'                => $block->block_type->name,
				'moduleCategory'      => $block->block_type->category,
				'attrs'               => $attrs,
				'elements'            => $elements,
				'classnamesFunction'  => [ Search::class, 'module_classnames' ],
				'stylesComponent'     => [ Search::class, 'module_styles' ],
				'scriptDataComponent' => [ Search::class, 'module_script_data' ],
				'parentAttrs'         => $parent_attrs,
				'parentId'            => $parent->id ?? '',
				'parentName'          => $parent->blockName ?? '',
				'children'            => [ $content ],
			]
		);
	}

	/**
	 * Loads `Search` and registers Front-End render callback and REST API Endpoints.
	 *
	 * @since ??
	 *
	 * @return void
	 */
	public function load() {

		$module_json_folder_path = JET_ENGINE_DIVI_VIEWS_MODULES_JSON_PATH . 'search/';

		add_action(
			'init',
			function() use ( $module_json_folder_path ) {
				ModuleRegistration::register_module(
					$module_json_folder_path,
					[
						'render_callback' => [ Search::class, 'render_callback' ],
					]
				);
			}
		);
	}
}
