<?php

/**
 * Text Badge Module.
 *
 * @package DiviSupreme.
 */

declare(strict_types=1);

namespace DiviSupreme\Modules;

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


use ET\Builder\Framework\DependencyManagement\Interfaces\DependencyInterface;
use ET\Builder\Framework\Utility\HTMLUtility;
use ET\Builder\FrontEnd\Module\Style;
use ET\Builder\Packages\Module\Module;
use ET\Builder\Packages\Module\Options\Element\ElementClassnames;
use ET\Builder\Packages\ModuleLibrary\ModuleRegistration;
use ET\Builder\Packages\Module\Layout\Components\StyleCommon\CommonStyle;
use ET\Builder\Packages\Module\Options\Text\TextStyle;
use ET\Builder\Packages\Module\Options\Css\CssStyle;
use ET\Builder\Packages\Module\Options\Link\LinkUtils;


/**
 * Class that handles "Text Badge Module" module.
 */
class TextBadge implements DependencyInterface
{


	/**
	 * Register module.
	 * `DependencyInterface` interface ensures class method name `load()` is executed for initialization.
	 */
	public function load()
	{
		add_action('init', array(self::class, 'register_module'));
	}

	/**
	 * Initilises the module.
	 *
	 * @return void
	 */
	public static function dsm_initialise()
	{
		add_action(
			'divi_module_library_modules_dependency_tree',
			function ($dependency_tree) {
				$dependency_tree->add_dependency(new self());
			}
		);
	}


	/**
	 * Register module.
	 */
	public static function register_module()
	{

		$module_json_path = DSM_DIR_PATH . 'divi-5/public/packages/module-library/text-badges';

		ModuleRegistration::register_module(
			$module_json_path,
			array(
				'render_callback' => array(self::class, 'render_callback'),
			)
		);
	}

	/**
	 * Render module style.
	 *
	 * @param array $args - Arguments.
	 */
	public static function module_styles($args)
	{
		$attrs = $args['attrs'] ?? array();
		$elements = $args['elements'];

		Style::add(
			array(
				'id' => $args['id'],
				'name' => $args['name'],
				'orderIndex' => $args['orderIndex'],
				'storeInstance' => $args['storeInstance'],
				'styles' => array(
					// Module.
					$elements->style(
						array(
							'attrName' => 'module',
							'styleProps' => array(
								'disabledOn' => array(
									'disabledModuleVisibility' => $args['settings']['disabledModuleVisibility'] ?? null,
								),
							),
						)
					),

					CssStyle::style(
						array(
							'selector' => $args['orderClass'],
							'attr' => $attrs['css'] ?? array(),
						)
					),

					TextStyle::style(
						array(
							'selector' => $args['orderClass'],
							'attr' => $attrs['module']['advanced']['text'] ?? array(),
						)
					),

					$elements->style(
						array(
							'attrName' => 'main_text',
						)
					),

					$elements->style(
						array(
							'attrName' => 'badges_text',
						)
					),

					$elements->style(
						array(
							'attrName' => 'badges_background_color',
						)
					),

					$elements->style(
						array(
							'attrName' => 'badges_gap',
						)
					),

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']} .dsm-badges",
							'attr' => $attrs['badges_background_color']['innerContent'] ?? array(),
							'property' => 'background-color',
						)
					),

					CommonStyle::style(
						array(
							'selector' => "{$args['orderClass']} .dsm-text-badges .dsm-badges",
							'attr' => $attrs['badges_gap']['innerContent'] ?? array(),
							'property' => 'margin-left',
						)
					),
				),
			)
		);
	}

	/**
	 * Render module script data.
	 *
	 * @param array $args - Arguments.
	 */
	public static function module_script_data($args)
	{
		$elements = $args['elements'];

		// Element Script Data Options.
		$elements->script_data(
			array(
				'attrName' => 'module',
			)
		);
	}

	/**
	 * Render module classnames.
	 *
	 * @param array $args - Arguments.
	 */
	public static function module_classnames($args)
	{
		$classnames_instance = $args['classnamesInstance'];
		$attrs = $args['attrs'];
		$module_link_attr = $attrs['module']['advanced']['link'] ?? array();

		$classnames_instance->add(
			ElementClassnames::classnames(
				array(
					'attrs' => array_merge(
						$attrs['module']['decoration'] ?? array(),
						array(
							'link' => $module_link_attr,
						)
					),
				)
			)
		);

		if (LinkUtils::is_enabled($module_link_attr)) {
			$classnames_instance->add('dsm-link');
		}
	}

	/**
	 * Ensure `main_text` stores headingLink shape for server render.
	 *
	 * @param array<string, mixed> $attrs Module attrs by reference.
	 * @return void
	 */
	private static function ensure_main_text_heading_link_shape(array &$attrs): void
	{
		if (!isset($attrs['main_text']['innerContent']) || !is_array($attrs['main_text']['innerContent'])) {
			return;
		}

		$inner = &$attrs['main_text']['innerContent'];

		foreach (array_keys($inner) as $breakpoint) {
			if (!isset($inner[$breakpoint]) || !is_array($inner[$breakpoint])) {
				continue;
			}

			if (!array_key_exists('value', $inner[$breakpoint])) {
				continue;
			}

			$value = &$inner[$breakpoint]['value'];

			if (is_string($value)) {
				$value = array(
					'text' => $value,
					'url' => '',
					'target' => 'off',
				);
				continue;
			}

			if (!is_array($value)) {
				continue;
			}

			if (!array_key_exists('url', $value)) {
				$value['url'] = '';
			}

			if (!array_key_exists('target', $value)) {
				$value['target'] = 'off';
			}
		}
	}

	/**
	 * Render module HTML output.
	 *
	 * @param array     $attrs - Modules Attributes.
	 * @param string    $content - Content.
	 * @param \WP_Block $block - Block.
	 * @param mixed     $elements - Elements.
	 */
	public static function render_callback($attrs, $content, $block, $elements)
	{
		if (isset($elements->module_attrs) && is_array($elements->module_attrs)) {
			self::ensure_main_text_heading_link_shape($elements->module_attrs);
		}

		if (is_array($attrs)) {
			self::ensure_main_text_heading_link_shape($attrs);
		}

		$badge_text_placement = $attrs['badges_placement']['innerContent']['desktop']['value'] ?? 'after';

		$main_html = $elements->render(
			array(
				'attrName' => 'main_text',
			)
		);

		$badges_html = $elements->render(
			array(
				'attrName' => 'badges_text',
			)
		);

		$badge_span = '';
		if ('' !== trim(wp_strip_all_tags((string) $badges_html))) {
			$badge_span = '<span class="dsm-badges">' . $badges_html . '</span>';
		}

		$before_badge = 'before' === $badge_text_placement ? $badge_span : '';
		$after_badge = 'after' === $badge_text_placement ? $badge_span : '';

		$text_badge_markup = sprintf(
			'<div class="dsm-text-badges">%1$s%2$s%3$s</div>',
			$before_badge,
			$main_html,
			$after_badge
		);

		// Module Inner.
		// Essentially, this is the module content.
		// Were wrapping the title and content in a div with class `et_pb_module_inner`.
		$module_inner = HTMLUtility::render(
			array(
				'tag' => 'div',
				'attributes' => array(
					'class' => 'et_pb_module_inner',
				),
				'childrenSanitizer' => 'et_core_esc_previously',
				'children' => $text_badge_markup,
			)
		);

		// This are the module elements that will be rendered in the frontend.
		$module_elements = $elements->style_components(
			array(
				'attrName' => 'module',
			)
		);

		// This are the children of the module container, which are the module elements and the module inner.
		$module_container_children = $module_elements . $module_inner;

		return Module::render(
			array(
				// FE only.
				'orderIndex' => $block->parsed_block['orderIndex'],
				'storeInstance' => $block->parsed_block['storeInstance'],

				// VB equivalent.
				'attrs' => $attrs,
				'elements' => $elements,
				'id' => $block->parsed_block['id'],
				'moduleClassName' => 'dsm_text_badges',
				'name' => $block->block_type->name,
				'classnamesFunction' => array(self::class, 'module_classnames'),
				'moduleCategory' => $block->block_type->category,
				'stylesComponent' => array(self::class, 'module_styles'),
				'scriptDataComponent' => array(self::class, 'module_script_data'),
				'children' => $module_container_children,
			)
		);
	}
}
