<?php
/**
 * Module: JetEngine Dynamic Repeater.
 */
namespace Jet_Engine_Divi_Views\Components\Jet_Engine\Modules;

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

use ET\Builder\Framework\DependencyManagement\Interfaces\DependencyInterface;
use ET\Builder\Packages\ModuleLibrary\ModuleRegistration;
use Jet_Engine_Divi_Views\Module_Render;
use ET\Builder\FrontEnd\Module\Style;
use Jet_Engine_Divi_Views\Utils;
use Jet_Engine_Divi_Views\Components\Jet_Engine\Current_Object_Trait;

class Dynamic_Repeater implements DependencyInterface {

	use Current_Object_Trait;

	/**
	 * 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'] ?? '';

		$selectors = [
			'items'              => "{$order_class} .jet-listing-dynamic-repeater__items",
			'item_content'       => "{$order_class} .jet-listing-dynamic-repeater__item > *",
			'item_content_hover' => "{$order_class} .jet-listing-dynamic-repeater__item > *:hover",
			'delimiter'          => "{$order_class} .jet-listing-dynamic-repeater__delimiter",
			'counter'            => "{$order_class} .jet-listing-dynamic-repeater__item .jet-listing-dynamic-repeater__counter",
		];

		$general_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['generalTypography'] ?? null );
		$general_typography_styles = Utils\build_typography_styles(
			$selectors['item_content'],
			$general_typography
		);

		$item_border = Utils\extract_border_attrs( $attrs['module']['decoration']['itemBorder'] ?? null );
		$item_border_styles = Utils\build_border_styles(
			$selectors['item_content'],
			$item_border
		);

		$item_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['itemSpacing'] ?? null );
		$item_spacing_styles = Utils\build_spacing_styles(
			$selectors['item_content'],
			$item_spacing
		);

		$delimiter_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['delimiterTypography'] ?? null );
		$delimiter_typography_styles = Utils\build_typography_styles(
			$selectors['delimiter'],
			$delimiter_typography
		);

		$delimiter_margin = Utils\extract_spasing_attrs( $attrs['module']['decoration']['delimiterMargin'] ?? null );
		$delimiter_margin_styles = Utils\build_spacing_styles(
			$selectors['delimiter'],
			$delimiter_margin
		);

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

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

		$counter_margin = Utils\extract_spasing_attrs( $attrs['module']['decoration']['counterItemMargin'] ?? null );
		$counter_margin_styles = Utils\build_spacing_styles(
			$selectors['counter'],
			$counter_margin
		);

		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(
									$general_typography_styles,
									$item_border_styles,
									$item_spacing_styles,
									$delimiter_typography_styles,
									$delimiter_margin_styles,
									$counter_typography_styles,
									$counter_border_styles,
									$counter_margin_styles,
									[
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['items'],
												'attr'     => $attrs['module']['decoration']['itemsDirection'] ?? [],
												'property' => 'flex-direction',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['items'],
												'attr'     => $attrs['module']['decoration']['itemsAlignment'] ?? [],
												'property' => 'justify-content',
											],
										],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => $selectors['items'],
                                                'attr'     => $attrs['module']['decoration']['itemsAlignment'] ?? [],
                                                'property' => 'align-items',
                                            ],
                                        ],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['item_content'],
												'attr'     => $attrs['module']['decoration']['itemsAlignment'] ?? [],
												'property' => 'justify-content',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['item_content'],
												'attr'     => $attrs['module']['decoration']['itemColor'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['item_content'],
												'attr'     => $attrs['module']['decoration']['itemBackgroundColor'] ?? [],
												'property' => 'background-color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['item_content_hover'],
												'attr'     => $attrs['module']['decoration']['itemColorHover'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['item_content_hover'],
												'attr'     => $attrs['module']['decoration']['itemBackgroundColorHover'] ?? [],
												'property' => 'background-color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['item_content_hover'],
												'attr'     => $attrs['module']['decoration']['itemBorderColorHover'] ?? [],
												'property' => 'border-color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['delimiter'],
												'attr'     => $attrs['module']['decoration']['delimiterColor'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['counter'],
												'attr'     => $attrs['module']['decoration']['counterItemColor'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['counter'],
												'attr'     => $attrs['module']['decoration']['counterItemBackgroundColor'] ?? [],
												'property' => 'background-color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['counter'],
												'attr'     => $attrs['module']['decoration']['counterItemDepth'] ?? [],
												'property' => 'z-index',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['counter'],
												'attr'     => $attrs['module']['decoration']['counterSelfAlign'] ?? [],
												'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 = [];

		$object_was_set = self::set_current_object( $attrs );

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

		$toggle_keys = array(
			'dynamic_field_counter',
			'dynamic_field_leading_zero',
			'hide_if_empty',
		);

		foreach ( $toggle_keys as $toggle_key ) {
			if ( ! isset( $prepared_attrs[ $toggle_key ] ) ) {
				continue;
			}

			$value = $prepared_attrs[ $toggle_key ];

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

			if ( in_array( $value, array( 'on', 'true', '1', 1, true, 'yes' ), true ) ) {
				$prepared_attrs[ $toggle_key ] = true;
			} elseif ( in_array( $value, array( 'off', 'false', '0', 0, false, 'no', '' ), true ) ) {
				$prepared_attrs[ $toggle_key ] = false;
			}
		}

		$render = self::get_jet_engine_render_instance( $prepared_attrs );
		$divi_module_render = new Module_Render();

		$content = $divi_module_render->render_content(
			$render,
			$attrs,
			$block,
			$elements,
			self::class
		);

		if ( $object_was_set ) {
			self::reset_current_object();
		}

		return $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-repeater';
	}

	/**
	 * Loads `DynamicImage` 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 . 'dynamic-repeater/';

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