<?php
/**
 * Module: JetEngine Dynamic Field.
 */
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_Field 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 = [
			'wrapper'            => "{$order_class} .jet-listing-dynamic-field",
			'display_inline'     => "{$order_class} .jet-listing-dynamic-field.display-inline",
			'inline_wrap'        => "{$order_class} .jet-listing-dynamic-field__inline-wrap",
			'content'            => "{$order_class} .jet-listing-dynamic-field__content",
			'content_link'       => "{$order_class} .jet-listing-dynamic-field__content a",
			'icon'               => "{$order_class} .jet-listing-dynamic-field__icon",
			'icon_svg_path'      => "{$order_class} .jet-listing-dynamic-field__icon svg path",
			'icon_ltr'           => "body:not(.rtl) {$order_class} .jet-listing-dynamic-field__icon",
			'icon_rtl'           => "body.rtl {$order_class} .jet-listing-dynamic-field__icon",
			'field_box_combined' => "{$order_class} .jet-listing-dynamic-field.display-multiline, {$order_class} .jet-listing-dynamic-field.display-inline .jet-listing-dynamic-field__inline-wrap, {$order_class} .jet-listing-dynamic-field__content",
		];

		$field_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['fieldTypography'] ?? null );
		$field_typography_styles = Utils\build_typography_styles(
			$selectors['content'],
			$field_typography
		);

		$field_border = Utils\extract_border_attrs( $attrs['module']['decoration']['fieldBorder'] ?? null );
		$field_border_styles = Utils\build_border_styles(
			$selectors['field_box_combined'],
			$field_border
		);

		$field_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['fieldSpacing'] ?? null );
		$field_spacing_styles = Utils\build_spacing_styles(
			$selectors['field_box_combined'],
			$field_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(
									$field_typography_styles,
									$field_border_styles,
									$field_spacing_styles,
									[
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['content'],
												'attr'     => $attrs['module']['decoration']['fieldColor'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['content_link'],
												'attr'     => $attrs['module']['decoration']['fieldColor'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['content_link'],
												'attr'     => $field_typography['textTransform'] ?? [],
												'property' => 'text-transform',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['content_link'],
												'attr'     => $field_typography['fontStyle'] ?? [],
												'property' => 'font-style',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['content_link'],
												'attr'     => $field_typography['textDecoration'] ?? [],
												'property' => 'text-decoration',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['content'],
												'attr'     => $attrs['module']['decoration']['contentAlignment'] ?? [],
												'property' => 'text-align',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['field_box_combined'],
												'attr'     => $attrs['module']['decoration']['fieldBg'] ?? [],
												'property' => 'background-color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['inline_wrap'],
												'attr'     => $attrs['module']['decoration']['fieldWidth'] ?? [],
												'property' => 'width',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['content'],
												'attr'     => $attrs['module']['decoration']['fieldWidth'] ?? [],
												'property' => 'width',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['display_inline'],
												'attr'     => $attrs['module']['decoration']['fieldAlignment'] ?? [],
												'property' => 'justify-content',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['icon'],
												'attr'     => $attrs['module']['decoration']['iconColor'] ?? [],
												'property' => 'color',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['icon_svg_path'],
												'attr'     => $attrs['module']['decoration']['iconColor'] ?? [],
												'property' => 'fill',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['icon'],
												'attr'     => $attrs['module']['decoration']['iconSize'] ?? [],
												'property' => 'font-size',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['icon_ltr'],
												'attr'     => $attrs['module']['decoration']['iconGap'] ?? [],
												'property' => 'margin-right',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['icon_rtl'],
												'attr'     => $attrs['module']['decoration']['iconGap'] ?? [],
												'property' => 'margin-left',
											],
										],
										[
											'componentName' => 'divi/common',
											'props'         => [
												'selector' => $selectors['icon'],
												'attr'     => $attrs['module']['decoration']['iconVerticalGap'] ?? [],
												'property' => 'margin-top',
											],
										],
									]
								),
							],
						]
					),
				],
			]
		);
	}

	/**
	 * 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_wp_excerpt',
			'hide_if_empty',
			'dynamic_field_filter',
			'dynamic_field_custom',
			'related_list_is_linked',
			'related_list_is_single',
		);

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

		// Divi UploadContainer may return media object instead of plain URL/ID.
		if ( ! empty( $prepared_attrs['selected_field_icon_url'] ) && is_array( $prepared_attrs['selected_field_icon_url'] ) ) {
			if ( isset( $prepared_attrs['selected_field_icon_url']['url'] ) ) {
				$prepared_attrs['selected_field_icon_url'] = $prepared_attrs['selected_field_icon_url']['url'];
			}
		}

		if ( ! empty( $prepared_attrs['selected_field_icon'] ) && is_array( $prepared_attrs['selected_field_icon'] ) ) {
			if ( isset( $prepared_attrs['selected_field_icon']['id'] ) ) {
				$prepared_attrs['selected_field_icon'] = absint( $prepared_attrs['selected_field_icon']['id'] );
			} elseif ( isset( $prepared_attrs['selected_field_icon']['url'] ) ) {
				$prepared_attrs['selected_field_icon_url'] = $prepared_attrs['selected_field_icon']['url'];
				$prepared_attrs['selected_field_icon']     = 0;
			}
		}

		// Backward compatibility: if icon field has URL string, move it to URL attr.
		if ( ! empty( $prepared_attrs['selected_field_icon'] ) && is_string( $prepared_attrs['selected_field_icon'] ) ) {
			$icon_string = trim( $prepared_attrs['selected_field_icon'] );
			if ( filter_var( $icon_string, FILTER_VALIDATE_URL ) ) {
				$prepared_attrs['selected_field_icon_url'] = $icon_string;
				$prepared_attrs['selected_field_icon']     = 0;
			} elseif ( is_numeric( $icon_string ) ) {
				$prepared_attrs['selected_field_icon'] = absint( $icon_string );
			}
		}

		// Ensure both icon attributes are set for JetEngine renderer compatibility.
		if ( ! empty( $prepared_attrs['selected_field_icon'] ) && empty( $prepared_attrs['selected_field_icon_url'] ) ) {
			$icon_url = wp_get_attachment_url( absint( $prepared_attrs['selected_field_icon'] ) );
			if ( $icon_url ) {
				$prepared_attrs['selected_field_icon_url'] = $icon_url;
			}
		}

		if ( empty( $prepared_attrs['selected_field_icon'] ) && ! empty( $prepared_attrs['selected_field_icon_url'] ) && is_string( $prepared_attrs['selected_field_icon_url'] ) ) {
			$attachment_id = attachment_url_to_postid( $prepared_attrs['selected_field_icon_url'] );
			if ( $attachment_id ) {
				$prepared_attrs['selected_field_icon'] = absint( $attachment_id );
			}
		}

		$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 sprintf(
			'<div class="jet-listing-dynamic-field-block" data-is-block="jet-engine/dynamic-field">%s</div>',
			$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 . 'dynamic-field/';

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