<?php
/**
 * Module: JetSmartFilters Color & Image.
 */
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 Color_Image implements DependencyInterface {

	private static function get_default_settings() {

		return [
			'filter_id'                   => 0,
			'content_provider'            => 'not-selected',
			'apply_type'                  => 'ajax',
			'apply_on'                    => 'value',
			'apply_button'                => true,
			'apply_button_text'           => __( 'Apply', 'jet-smart-filters' ),
			'show_label'                  => false,
			'query_id'                    => '',
			'additional_providers_enabled'=> false,
			'apply_indexer'               => false,
			'show_counter'                => false,
			'counter_prefix'              => '(',
			'counter_suffix'              => ')',
			'show_items_rule'             => 'show',
			'change_items_rule'           => 'always',
			'show_items_label'            => true,
			'filter_image_size'           => 'full',
			'search_enabled'              => false,
			'moreless_enabled'            => false,
			'dropdown_enabled'            => false,
			'dropdown_n_selected_enabled' => false,
			'dropdown_apply_button'       => false,
			'scroll_enabled'              => false,
		];
	}

	private static function normalize_toggle_value( $value ) {

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

		if ( is_numeric( $value ) ) {
			return (bool) absint( $value );
		}

		if ( ! is_string( $value ) ) {
			return $value;
		}

		$normalized = strtolower( trim( $value ) );

		if ( in_array( $normalized, [ 'on', 'true', 'yes' ], true ) ) {
			return true;
		}

		if ( in_array( $normalized, [ 'off', 'false', 'no', '' ], true ) ) {
			return false;
		}

		return $value;
	}

	private static function get_prepared_attrs( $attrs ) {

		$prepared_attrs = [];

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

		$prepared_attrs = wp_parse_args( $prepared_attrs, self::get_default_settings() );

		foreach ( [
			'apply_button',
			'show_label',
			'additional_providers_enabled',
			'apply_indexer',
			'show_counter',
			'show_items_label',
			'search_enabled',
			'moreless_enabled',
			'dropdown_enabled',
			'dropdown_n_selected_enabled',
			'dropdown_apply_button',
			'scroll_enabled',
		] as $toggle_key ) {
			if ( array_key_exists( $toggle_key, $prepared_attrs ) ) {
				$prepared_attrs[ $toggle_key ] = self::normalize_toggle_value( $prepared_attrs[ $toggle_key ] );
			}
		}

		return $prepared_attrs;
	}

	/**
	 * 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 = [
			'list_wrapper'          => "{$args['orderClass']} .jet-color-image-list-wrapper",
			'list_item'             => "{$args['orderClass']} .jet-color-image-list__row",
			'button'                => "{$args['orderClass']} .jet-color-image-list__button",
			'checked_button'        => "{$args['orderClass']} .jet-color-image-list__input:checked ~ .jet-color-image-list__button",
			'label'                 => "{$args['orderClass']} .jet-color-image-list__label",
			'decorator'             => "{$args['orderClass']} .jet-color-image-list__decorator",
			'decorator_span'        => "{$args['orderClass']} .jet-filter-row .jet-color-image-list__decorator > span",
			'checked_decorator_span'=> "{$args['orderClass']} .jet-filter-row .jet-color-image-list__input:checked ~ .jet-color-image-list__button .jet-color-image-list__decorator > span",
			'filter_label'          => "{$args['orderClass']} .jet-filter-label",
			'apply_button'          => "{$args['orderClass']} .apply-filters__button",
			'apply_button_hover'    => "{$args['orderClass']} .apply-filters__button:hover",
			'counter'               => "{$args['orderClass']} .jet-filters-counter",
		];

		$item_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['itemTypography'] ?? null );
		$item_typography_styles = Utils\build_typography_styles(
			$selectors['label'],
			$item_typography
		);

		$item_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['itemSpacing'] ?? null );
		$item_spacing_styles = Utils\build_spacing_styles(
			"{$args['orderClass']} .jet-filter-row .jet-color-image-list__button",
			$item_spacing
		);

		$item_border = Utils\extract_border_attrs( $attrs['module']['decoration']['itemBorder'] ?? null );
		$item_border_styles = Utils\build_border_styles(
			"{$args['orderClass']} .jet-filter-row .jet-color-image-list__button",
			$item_border
		);

		$decorator_border = Utils\extract_border_attrs( $attrs['module']['decoration']['colorImageBorder'] ?? null );
		$decorator_border_styles = Utils\build_border_styles(
			$selectors['decorator_span'],
			$decorator_border
		);

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

		$label_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['labelSpacing'] ?? null );
		$label_spacing_styles = Utils\build_spacing_styles(
			$selectors['filter_label'],
			$label_spacing
		);

		
		$apply_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['applySpacing'] ?? null );
		$apply_spacing_styles = Utils\build_spacing_styles(
			$selectors['apply_button'],
			$apply_spacing
		);

		$apply_border = Utils\extract_border_attrs( $attrs['module']['decoration']['applyBorder'] ?? null );
		$apply_border_styles = Utils\build_border_styles(
			$selectors['apply_button'],
			$apply_border
		);

		$counter_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['counterTypography'] ?? null );
		$counter_typography_styles = Utils\build_typography_styles(
			$selectors['counter'],
			$counter_typography
		);

		$counter_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['counterSpacing'] ?? null );
		$counter_spacing_styles = Utils\build_spacing_styles(
			$selectors['counter'],
			$counter_spacing
		);

		$counter_border = Utils\extract_border_attrs( $attrs['module']['decoration']['counterBorder'] ?? null );
		$counter_border_styles = Utils\build_border_styles(
			$selectors['counter'],
			$counter_border
		);

		$space_between_horizontal = $attrs['module']['decoration']['filtersSpaceBetweenHorizontal'] ?? null;
		$space_between_half = self::map_responsive_value( $space_between_horizontal, static function( $value ) {
			return "calc({$value} / 2)";
		} );
		$space_between_negative = self::map_responsive_value( $space_between_horizontal, static function( $value ) {
			return "calc(-{$value} / 2)";
		} );

		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(
									$item_typography_styles,
									$item_spacing_styles,
									$item_border_styles,
									$decorator_border_styles,
									$label_typography_styles,
									$label_spacing_styles,
															$apply_spacing_styles,
									$apply_border_styles,
									$counter_typography_styles,
									$counter_spacing_styles,
									$counter_border_styles,
									[
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['list_item'],
												'attr'     => $attrs['module']['decoration']['filtersPosition'] ?? [],
												'property' => 'display',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['list_item'],
												'attr'     => $space_between_half,
												'property' => 'margin-left',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['list_item'],
												'attr'     => $space_between_half,
												'property' => 'margin-right',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['list_wrapper'],
												'attr'     => $space_between_negative,
												'property' => 'margin-left',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['list_wrapper'],
												'attr'     => $space_between_negative,
												'property' => 'margin-right',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['list_item'],
												'attr'     => $attrs['module']['decoration']['filtersSpaceBetweenVertical'] ?? [],
												'property' => 'margin-bottom',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['list_wrapper'],
												'attr'     => $attrs['module']['decoration']['filtersListAlignment'] ?? [],
												'property' => 'text-align',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['button'],
												'attr'     => $attrs['module']['decoration']['itemNormalColor'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['button'],
												'attr'     => $attrs['module']['decoration']['itemNormalBgColor'] ?? [],
												'property' => 'background-color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['checked_button'],
												'attr'     => $attrs['module']['decoration']['itemCheckedColor'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['checked_button'],
												'attr'     => $attrs['module']['decoration']['itemCheckedBgColor'] ?? [],
												'property' => 'background-color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['checked_button'],
												'attr'     => $attrs['module']['decoration']['itemCheckedBorderColor'] ?? [],
												'property' => 'border-color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$selectors['decorator']} .jet-color-image-list__color",
												'attr'     => $attrs['module']['decoration']['colorImageSize'] ?? [],
												'property' => 'width',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$selectors['decorator']} .jet-color-image-list__color",
												'attr'     => $attrs['module']['decoration']['colorImageSize'] ?? [],
												'property' => 'height',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$selectors['decorator']} .jet-color-image-list__image",
												'attr'     => $attrs['module']['decoration']['colorImageSize'] ?? [],
												'property' => 'width',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['label'],
												'attr'     => $attrs['module']['decoration']['colorImageLabelOffset'] ?? [],
												'property' => 'margin-left',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['checked_decorator_span'],
												'attr'     => $attrs['module']['decoration']['colorImageCheckedBorderColor'] ?? [],
												'property' => 'border-color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['filter_label'],
												'attr'     => $attrs['module']['decoration']['labelAlignment'] ?? [],
												'property' => 'text-align',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['filter_label'],
												'attr'     => $attrs['module']['decoration']['labelColor'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['apply_button'],
												'attr'     => $attrs['module']['decoration']['applyNormalColor'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['apply_button'],
												'attr'     => $attrs['module']['decoration']['applyNormalBgColor'] ?? [],
												'property' => 'background-color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['apply_button_hover'],
												'attr'     => $attrs['module']['decoration']['applyHoverColor'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['apply_button_hover'],
												'attr'     => $attrs['module']['decoration']['applyHoverBgColor'] ?? [],
												'property' => 'background-color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['apply_button_hover'],
												'attr'     => $attrs['module']['decoration']['applyHoverBorderColor'] ?? [],
												'property' => 'border-color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['apply_button'],
												'attr'     => $attrs['module']['decoration']['applyAlignment'] ?? [],
												'property' => 'align-self',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['counter'],
												'attr'     => $attrs['module']['decoration']['counterColor'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['counter'],
												'attr'     => $attrs['module']['decoration']['counterBgColor'] ?? [],
												'property' => 'background-color',
											],
										],
									]
								),
							],
						]
					),
				],
			]
		);
	}

	/**
	 * 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;
	}

	/**
	 * 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 ) {
	}

	/**
	 * Module classnames function.
	 *
	 * @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( 'color-image' );
		$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'  => [ Color_Image::class, 'module_classnames' ],
				'stylesComponent'     => [ Color_Image::class, 'module_styles' ],
				'scriptDataComponent' => [ Color_Image::class, 'module_script_data' ],
				'parentAttrs'         => $parent_attrs,
				'parentId'            => $parent->id ?? '',
				'parentName'          => $parent->blockName ?? '',
				'children'            => [ $content ],
			]
		);
	}

	/**
	 * Loads `Color Image` 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 . 'color-image/';

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