<?php
/**
 * Module: JetSmartFilters Date Period Filter.
 */
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 Date_Period_Filter 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 filter', 'jet-smart-filters' ),
			'show_label'         => false,
			'query_id'           => '',
		];
	}

	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, $block ) {

		$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',
		] as $toggle_key ) {
			if ( array_key_exists( $toggle_key, $prepared_attrs ) ) {
				$prepared_attrs[ $toggle_key ] = self::normalize_toggle_value( $prepared_attrs[ $toggle_key ] );
			}
		}

		if ( empty( $prepared_attrs['blockID'] ) ) {
			$prepared_attrs['blockID'] = $block->parsed_block['id'] ?? '';
		}

		return $prepared_attrs;
	}

	/**
	 * 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'] ?? '';
		$block_id                    = $attrs['blockID']['innerContent']['desktop']['value'] ?? $attrs['blockID'] ?? '';
		$block_id                    = is_string( $block_id ) ? sanitize_html_class( $block_id ) : '';
		$popup_selector              = $block_id ? "#datepickers-container .jet-date-period-{$block_id}.datepicker" : '#datepickers-container .datepicker';

		$datepicker_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['datepickerTypography'] ?? null );
		$datepicker_typography_styles = Utils\build_typography_styles(
			"{$order_class} .jet-date-period__datepicker-button",
			$datepicker_typography
		);

		$datepicker_border = Utils\extract_border_attrs( $attrs['module']['decoration']['datepickerBorder'] ?? null );
		$datepicker_border_styles = Utils\build_border_styles(
			"{$order_class} .jet-date-period__datepicker-button",
			$datepicker_border
		);

		$datepicker_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['datepickerSpacing'] ?? null );
		$datepicker_spacing_styles = Utils\build_spacing_styles(
			"{$order_class} .jet-date-period__datepicker-button",
			$datepicker_spacing
		);

		$next_prev_border = Utils\extract_border_attrs( $attrs['module']['decoration']['nextPrevBorder'] ?? null );
		$next_prev_border_styles = Utils\build_border_styles(
			"{$args['orderClass']} .jet-date-period__prev, {$args['orderClass']} .jet-date-period__next",
			$next_prev_border
		);

		$calendar_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['calendarTypography'] ?? null );
		$calendar_typography_styles = Utils\build_typography_styles(
			$popup_selector,
			$calendar_typography
		);

        $calendar_border = Utils\extract_border_attrs( $attrs['module']['decoration']['calendarBorder'] ?? null );
        $calendar_border_styles = Utils\build_border_styles(
            $popup_selector,
            $calendar_border
        );

        $label_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['labelTypography'] ?? null );
        $label_typography_styles = Utils\build_typography_styles(
            "{$args['orderClass']} .jet-filter-label",
            $label_typography
        );

        $apply_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['applyTypography'] ?? null );
        $apply_typography_styles = Utils\build_typography_styles(
            "{$args['orderClass']} .apply-filters__button",
            $apply_typography
        );

        $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(
									$datepicker_typography_styles,
									$datepicker_border_styles,
									$datepicker_spacing_styles,
									$next_prev_border_styles,
									$calendar_typography_styles,
                                    $calendar_border_styles,
                                    $label_typography_styles,
                                    $apply_typography_styles,
                                    $apply_border_styles,
                                    $apply_spacing_styles,
									[
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__datepicker-button",
												'attr'     => $attrs['module']['decoration']['datepickerNormalColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__datepicker-button",
												'attr'     => $attrs['module']['decoration']['datepickerNormalBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__datepicker-button:hover",
												'attr'     => $attrs['module']['decoration']['datepickerHoverColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__datepicker-button:hover",
												'attr'     => $attrs['module']['decoration']['datepickerHoverBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__wrapper",
												'attr'     => $attrs['module']['decoration']['datepickerAlignment'] ?? [],
												'property' => 'justify-content',
											]
										],

										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__prev",
												'attr'     => $attrs['module']['decoration']['nextPrevHorOffset'] ?? [],
												'property' => 'margin-right',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__next",
												'attr'     => $attrs['module']['decoration']['nextPrevHorOffset'] ?? [],
												'property' => 'margin-left',
											]
										],

										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__prev, {$args['orderClass']} .jet-date-period__next",
												'attr'     => $attrs['module']['decoration']['nextPrevHorWidth'] ?? [],
												'property' => 'width',
											]
										],

										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__prev, {$args['orderClass']} .jet-date-period__next",
												'attr'     => $attrs['module']['decoration']['nextPrevNormalColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__prev, {$args['orderClass']} .jet-date-period__next",
												'attr'     => $attrs['module']['decoration']['nextPrevNormalBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__prev:hover, {$args['orderClass']} .jet-date-period__next:hover",
												'attr'     => $attrs['module']['decoration']['nextPrevHoverColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__prev:hover, {$args['orderClass']} .jet-date-period__next:hover",
												'attr'     => $attrs['module']['decoration']['nextPrevHoverBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .jet-date-period__prev:hover, {$args['orderClass']} .jet-date-period__next:hover",
												'attr'     => $attrs['module']['decoration']['nextPrevHoverBorderColor'] ?? [],
												'property' => 'border-color',
											]
										],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => $popup_selector,
                                                'attr'     => $attrs['module']['decoration']['calendarVerOffset'] ?? [],
                                                'property' => 'margin-top',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => $popup_selector,
                                                'attr'     => $attrs['module']['decoration']['calendarHorOffset'] ?? [],
                                                'property' => 'margin-left',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => $popup_selector,
                                                'attr'     => $attrs['module']['decoration']['calendarWidth'] ?? [],
                                                'property' => 'width',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => $popup_selector,
                                                'attr'     => $attrs['module']['decoration']['calendarBgColor'] ?? [],
                                                'property' => 'background-color',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$popup_selector} .datepicker--cell",
                                                'attr'     => $attrs['module']['decoration']['cellNormalColor'] ?? [],
                                                'property' => 'color',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$popup_selector} .datepicker--cell",
                                                'attr'     => $attrs['module']['decoration']['cellNormalBgColor'] ?? [],
                                                'property' => 'background-color',
                                            ]
                                        ],

                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$popup_selector} .datepicker--cell.-focus-,
                                                               {$popup_selector} .datepicker--cell.-in-range-.-focus-,
                                                               {$popup_selector} .datepicker--cell.-week-hover-,
                                                               {$popup_selector} .datepicker--cell.-range-from-,
                                                               {$popup_selector} .datepicker--cell.-range-to-",
                                                'attr'     => $attrs['module']['decoration']['cellHoverColor'] ?? [],
                                                'property' => 'color',

                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$popup_selector} .datepicker--cell.-focus-,
                                                               {$popup_selector} .datepicker--cell.-in-range-.-focus-,
                                                               {$popup_selector} .datepicker--cell.-week-hover-,
                                                               {$popup_selector} .datepicker--cell.-range-from-,
                                                               {$popup_selector} .datepicker--cell.-range-to-",
                                                'attr'     => $attrs['module']['decoration']['cellHoverBgColor'] ?? [],
                                                'property' => 'background-color',
                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$popup_selector} .datepicker--cell.-selected-,
                                                               {$popup_selector} .datepicker--cell.-week-selected-",
                                                'attr'     => $attrs['module']['decoration']['cellActiveColor'] ?? [],
                                                'property' => 'color',

                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$popup_selector} .datepicker--cell.-selected-,
                                                               {$popup_selector} .datepicker--cell.-week-selected-",
                                                'attr'     => $attrs['module']['decoration']['cellActiveBgColor'] ?? [],
                                                'property' => 'background-color',

                                            ]
                                        ],

                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$popup_selector} .datepicker--cell.-current-",
                                                'attr'     => $attrs['module']['decoration']['cellCurrentColor'] ?? [],
                                                'property' => 'color',

                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$popup_selector} .datepicker--cell.-current-",
                                                'attr'     => $attrs['module']['decoration']['cellCurrentBgColor'] ?? [],
                                                'property' => 'background-color',

                                            ]
                                        ],

                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-filter-label",
                                                'attr'     => $attrs['module']['decoration']['labelColor'] ?? [],
                                                'property' => 'color',

                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-filter-label",
                                                'attr'     => $attrs['module']['decoration']['labelGapY'] ?? [],
                                                'property' => 'margin-bottom',

                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-filter-label",
                                                'attr'     => $attrs['module']['decoration']['labelAlignment'] ?? [],
                                                'property' => 'text-align',

                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .apply-filters__button",
                                                'attr'     => $attrs['module']['decoration']['applyNormalColor'] ?? [],
                                                'property' => 'color',

                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .apply-filters__button",
                                                'attr'     => $attrs['module']['decoration']['applyNormalBgColor'] ?? [],
                                                'property' => 'background-color',

                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .apply-filters__button:hover",
                                                'attr'     => $attrs['module']['decoration']['applyHoverColor'] ?? [],
                                                'property' => 'color',

                                            ]
                                        ],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => "{$args['orderClass']} .apply-filters__button:hover",
												'attr'     => $attrs['module']['decoration']['applyHoverBgColor'] ?? [],
												'property' => 'background-color',

											]
										],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .apply-filters__button:hover",
                                                'attr'     => $attrs['module']['decoration']['applyHoverBorderColor'] ?? [],
                                                'property' => 'border-color',

                                            ]
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .apply-filters__button",
                                                'attr'     => $attrs['module']['decoration']['applyAlignment'] ?? [],
                                                '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 ) {
	}

	/**
	 * 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, $block );

		$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( 'date-period' );
		$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'  => [ Date_Period_Filter::class, 'module_classnames' ],
				'stylesComponent'     => [ Date_Period_Filter::class, 'module_styles' ],
				'scriptDataComponent' => [ Date_Period_Filter::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 . 'date-period-filter/';

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