<?php
/**
 * Module: JetSmartFilters Date Range Filters.
 */
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 ET\Builder\Packages\Module\Options\Text\TextStyle;
use Jet_Engine_Divi_Views\Utils;

class Active_Filters implements DependencyInterface {

	private static function get_default_settings() {
		return [
			'content_provider'             => 'not-selected',
			'apply_type'                   => 'ajax',
			'filters_label'                => __( 'Active filters:', 'jet-smart-filters' ),
			'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'];
			}
		}

		if ( array_key_exists( 'additional_providers_enabled', $prepared ) ) {
			$prepared['additional_providers_enabled'] = self::normalize_toggle_value( $prepared['additional_providers_enabled'] );
		}

		return $prepared;
	}

	/**
	 * Module's style components.
	 *
	 * This function is equivalent of JS function ModuleStyles located in
	 * module/styles.tsx.
	 *
	 * @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'] ?? [];
		$order_class                 = $args['orderClass'] ?? '';

        $title_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['titleTypography'] ?? null );
        $title_typography_styles = Utils\build_typography_styles(
            "{$args['orderClass']} .jet-smart-filters-active .jet-active-filters__title",
            $title_typography
        );

        $filters_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['filtersTypography'] ?? null );
        $filters_typography_styles = Utils\build_typography_styles(
            "{$args['orderClass']} .jet-smart-filters-active .jet-active-filter",
            $filters_typography
        );

        $filter_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['filterSpacing'] ?? null );
        $filter_spacing_styles = Utils\build_spacing_styles(
            "{$args['orderClass']} .jet-smart-filters-active .jet-active-filter",
            $filter_spacing
        );

        $filter_border = Utils\extract_border_attrs( $attrs['module']['decoration']['filterBorder'] ?? null );
        $filter_border_styles = Utils\build_border_styles(
            "{$args['orderClass']} .jet-smart-filters-active .jet-active-filter",
            $filter_border
        );

        /*$apply_border = Utils\extract_border_attrs( $attrs['module']['decoration']['applyBorder'] ?? null );
        $apply_border_styles = Utils\build_border_styles(
            "{$args['orderClass']} .apply-filters__button",
            $apply_border
        );

        $apply_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['applySpacing'] ?? null );
        $apply_spacing_styles = Utils\build_spacing_styles(
            "{$order_class} .apply-filters__button",
            $apply_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(
                                    $title_typography_styles,
                                    $filters_typography_styles,
                                    $filter_border_styles,
                                    $filter_spacing_styles,
                                    //$apply_border_styles,
                                    //$apply_spacing_styles,
                                    [
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-active .jet-active-filters__title",
                                                'attr'     => $attrs['module']['decoration']['titleColor'] ?? [],
                                                'property' => 'color',
                                            ]
                                        ],
                                    ],
                                    [
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-active, {$args['orderClass']} .jet-smart-filters-active .jet-active-filters__list",
                                                'attr'     => $attrs['module']['decoration']['filtersPosition'] ?? [],
                                                'property' => 'flex-direction',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-active .jet-active-filters__list",
                                                'attr'     => $attrs['module']['decoration']['filtersGap'] ?? [],
                                                'property' => 'gap',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-active .jet-active-filter",
                                                'attr'     => $attrs['module']['decoration']['filterColor'] ?? [],
                                                'property' => 'color',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-active .jet-active-filter",
                                                'attr'     => $attrs['module']['decoration']['filterBgColor'] ?? [],
                                                'property' => 'background-color',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-active .jet-active-filter:hover",
                                                'attr'     => $attrs['module']['decoration']['filterHoverColor'] ?? [],
                                                'property' => 'color',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-active .jet-active-filter:hover",
                                                'attr'     => $attrs['module']['decoration']['filterHoverBgColor'] ?? [],
                                                'property' => 'background-color',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-active .jet-active-filter__remove",
                                                'attr'     => $attrs['module']['decoration']['removeSize'] ?? [],
                                                'property' => 'font-size',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-active .jet-active-filter__remove",
                                                'attr'     => $attrs['module']['decoration']['removeColor'] ?? [],
                                                'property' => 'color',
                                            ]
                                        ],





                                    ],
                                )
							],
						]
					),
				],
			]
		);
	}

	/**
	 * 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 for Dynamic module.
	 *
	 * This function is equivalent of JS function moduleClassnames located in
	 * src/components/dynamic-module/module-classnames.ts.
	 *
	 * @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( 'active' );

		$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'  => [ Active_Filters::class, 'module_classnames' ],
				'stylesComponent'     => [ Active_Filters::class, 'module_styles' ],
				'scriptDataComponent' => [ Active_Filters::class, 'module_script_data' ],
				'parentAttrs'         => $parent_attrs,
				'parentId'            => $parent->id ?? '',
				'parentName'          => $parent->blockName ?? '',
				'children'            => [ $content ],
			]
		);
	}

	/**
	 * Get JetEngine render class instance
	 */
	public static function get_jet_engine_render_instance( $attributes ) {
		return jet_engine()->listings->get_render_instance( self::get_jet_engine_render_name(), $attributes );
	}

	/**
	 * Return name of JetEngine renderer for current module
	 */
	public static function get_jet_engine_render_name() {
		return 'dynamic-field';
	}

	/**
	 * Loads `DynamicField` 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 . 'active-filters/';

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