<?php
/**
 * Module: JetSmartFilters Pagination.
 */
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 Pagination implements DependencyInterface {

	private static function get_default_settings() {
		return [
			'content_provider'          => 'not-selected',
			'apply_type'                => 'ajax',
			'query_id'                  => '',
			'enable_items'              => true,
			'pages_center_offset'       => 0,
			'pages_end_offset'          => 0,
			'enable_prev_next'          => true,
			'prev_text'                 => __( 'Prev Text', 'jet-smart-filters' ),
			'next_text'                 => __( 'Next Text', 'jet-smart-filters' ),
			'hide_inactive_prev_next'   => true,
			'enable_load_more'          => false,
			'load_more_text'            => __( 'Load More', 'jet-smart-filters' ),
			'autoscroll'                => true,
			'provider_top_offset'       => 0,
		];
	}

	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 ( [
			'enable_items',
			'enable_prev_next',
			'hide_inactive_prev_next',
			'enable_load_more',
			'autoscroll',
		] 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 = [
			'pagination'         => "{$args['orderClass']} .jet-filters-pagination",
			'item'               => "{$args['orderClass']} .jet-filters-pagination__item",
			'link'               => "{$args['orderClass']} .jet-filters-pagination__link",
			'current_link'       => "{$args['orderClass']} .jet-filters-pagination__current .jet-filters-pagination__link",
			'dots'               => "{$args['orderClass']} .jet-filters-pagination__dots",
			'load_more'          => "{$args['orderClass']} .jet-filters-pagination__load-more .jet-filters-pagination__link",
			'load_more_wrapper'  => "{$args['orderClass']} .jet-filters-pagination__load-more",
			'link_hover'         => "{$args['orderClass']} .jet-filters-pagination__link:hover",
			'load_more_hover'    => "{$args['orderClass']} .jet-filters-pagination__load-more .jet-filters-pagination__link:hover",
		];

		$pagination_border = Utils\extract_border_attrs( $attrs['module']['decoration']['paginationBorder'] ?? null );
		$pagination_border_styles = Utils\build_border_styles(
			$selectors['pagination'],
			$pagination_border
		);

		$pagination_padding = Utils\extract_spasing_attrs( $attrs['module']['decoration']['paginationPadding'] ?? null );
		$pagination_padding_styles = Utils\build_spacing_styles(
			$selectors['pagination'],
			$pagination_padding
		);

		$items_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['itemsTypography'] ?? null );
		$items_typography_styles = Utils\build_typography_styles(
			$selectors['link'] . ', ' . $selectors['dots'],
			$items_typography
		);

		$items_padding = Utils\extract_spasing_attrs( $attrs['module']['decoration']['itemsPadding'] ?? null );
		$items_padding_styles = array_merge(
			Utils\build_spacing_styles( $selectors['link'], $items_padding ),
			Utils\build_spacing_styles( $selectors['dots'], $items_padding )
		);

		$items_border = Utils\extract_border_attrs( $attrs['module']['decoration']['itemsBorder'] ?? null );
		$items_border_styles = array_merge(
			Utils\build_border_styles( $selectors['link'], $items_border ),
			Utils\build_border_styles( $selectors['dots'], $items_border )
		);

		$load_more_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['loadMoreTypography'] ?? null );
		$load_more_typography_styles = Utils\build_typography_styles(
			$selectors['load_more'],
			$load_more_typography
		);

		$load_more_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['loadMoreSpacing'] ?? null );
		$load_more_spacing_legacy_margin = Utils\extract_spasing_attrs( $attrs['module']['decoration']['loadMoreMargin'] ?? null );
		$load_more_spacing_legacy_padding = Utils\extract_spasing_attrs( $attrs['module']['decoration']['loadMorePadding'] ?? null );
		$load_more_spacing['margin']  = $load_more_spacing['margin'] ?? $load_more_spacing_legacy_margin['margin'] ?? [];
		$load_more_spacing['padding'] = $load_more_spacing['padding'] ?? $load_more_spacing_legacy_padding['padding'] ?? [];
		$load_more_margin_styles = [
			[
				'componentName' => 'divi/common',
				'props'         => [
					'selector' => $selectors['load_more_wrapper'],
					'attr'     => $load_more_spacing['margin'],
					'property' => 'margin',
				]
			],
		];
		$load_more_padding_styles = [
			[
				'componentName' => 'divi/common',
				'props'         => [
					'selector' => $selectors['load_more'],
					'attr'     => $load_more_spacing['padding'],
					'property' => 'padding',
				]
			],
		];

		$load_more_border = Utils\extract_border_attrs( $attrs['module']['decoration']['loadMoreBorder'] ?? null );
		$load_more_border_styles = Utils\build_border_styles(
			$selectors['load_more'],
			$load_more_border
		);

		$horizontal_gap = $attrs['module']['decoration']['itemsHorizontalGap'] ?? null;
		$vertical_gap   = $attrs['module']['decoration']['itemsVerticalGap'] ?? null;

		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(
									$pagination_border_styles,
									$pagination_padding_styles,
									$items_typography_styles,
									$items_padding_styles,
									$items_border_styles,
									$load_more_typography_styles,
									$load_more_margin_styles,
									$load_more_padding_styles,
									$load_more_border_styles,
									[
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['pagination'],
												'attr'     => $attrs['module']['decoration']['paginationBackgroundColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['link'],
												'attr'     => $attrs['module']['decoration']['itemsNormalColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['dots'],
												'attr'     => $attrs['module']['decoration']['itemsNormalColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['link'],
												'attr'     => $attrs['module']['decoration']['itemsNormalBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['dots'],
												'attr'     => $attrs['module']['decoration']['itemsNormalBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['link_hover'],
												'attr'     => $attrs['module']['decoration']['itemsHoverColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['link_hover'],
												'attr'     => $attrs['module']['decoration']['itemsHoverBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['link_hover'],
												'attr'     => $attrs['module']['decoration']['itemsHoverBorderColor'] ?? [],
												'property' => 'border-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['current_link'],
												'attr'     => $attrs['module']['decoration']['itemsActiveColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['current_link'],
												'attr'     => $attrs['module']['decoration']['itemsActiveBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['current_link'],
												'attr'     => $attrs['module']['decoration']['itemsActiveBorderColor'] ?? [],
												'property' => 'border-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['dots'],
												'attr'     => $attrs['module']['decoration']['itemsDotsColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['dots'],
												'attr'     => $attrs['module']['decoration']['itemsDotsBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['item'] . ' ' . $selectors['dots'],
												'attr'     => $attrs['module']['decoration']['itemsDotsBorderColor'] ?? [],
												'property' => 'border-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['pagination'],
												'attr'     => $horizontal_gap,
												'property' => 'column-gap',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['pagination'],
												'attr'     => $vertical_gap,
												'property' => 'row-gap',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['pagination'],
												'attr'     => $attrs['module']['decoration']['itemsAlignment'] ?? [],
												'property' => 'justify-content',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['load_more'],
												'attr'     => $attrs['module']['decoration']['loadMoreNormalColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['load_more'],
												'attr'     => $attrs['module']['decoration']['loadMoreNormalBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['load_more_hover'],
												'attr'     => $attrs['module']['decoration']['loadMoreHoverColor'] ?? [],
												'property' => 'color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['load_more_hover'],
												'attr'     => $attrs['module']['decoration']['loadMoreHoverBgColor'] ?? [],
												'property' => 'background-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['load_more_hover'],
												'attr'     => $attrs['module']['decoration']['loadMoreHoverBorderColor'] ?? [],
												'property' => 'border-color',
											]
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['load_more_wrapper'],
												'attr'     => $attrs['module']['decoration']['loadMorePosition'] ?? [],
												'property' => 'order',
											]
										],
									]
								),
							],
						]
					),
				],
			]
		);
	}

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

	/**
	 * Loads `Pagination` 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 . 'pagination/';

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