<?php
/**
 * Twig template rendering for atomic widgets, with optional Theme Builder sync guard.
 *
 * @package Sifency_Addons
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

trait Sifency_Has_Atomic_Template {

	/**
	 * When true, render is blocked unless Theme Builder sync state is valid (same rules as Sifency_Addons_Widget_Base).
	 */
	protected function requires_sync_environment(): bool {
		return false;
	}

	/**
	 * Additional variables injected into the Twig context.
	 * Use-case: resolve dynamic content (e.g., `post_title`) or compute wrapper classes.
	 *
	 * @return array
	 */
	protected function get_template_additional_context(): array {
		return array();
	}

	/**
	 * @return bool True if rendering may proceed.
	 */
	protected function resolve_atomic_dependencies(): bool {
		if ( ! $this->requires_sync_environment() ) {
			return true;
		}

		if ( ! class_exists( '\Sifency_Addons_Theme_Builder_Master' ) ) {
			return false;
		}

		$state_valid = \Sifency_Addons_Theme_Builder_Master::sync_environment_state();

		if ( ! is_array( $state_valid ) || empty( $state_valid['hash_check'] ) ) {
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor internal fallback markup.
			echo \Sifency_Addons_Theme_Builder_Master::render_fallback_dom();
			return false;
		}

		return true;
	}

	public function get_initial_config() {
		$config = parent::get_initial_config();

		$config['twig_main_template'] = $this->get_main_template();
		$config['twig_templates']     = $this->get_templates_contents();

		return $config;
	}

	protected function render() {
		if ( ! $this->resolve_atomic_dependencies() ) {
			return;
		}

		try {
			$renderer = \Elementor\Modules\AtomicWidgets\Elements\TemplateRenderer\Template_Renderer::instance();

			foreach ( $this->get_templates() as $name => $path ) {
				if ( $renderer->is_registered( $name ) ) {
					continue;
				}
				$renderer->register( $name, $path );
			}

			$context = array(
				'id'             => $this->get_id(),
				'interaction_id' => $this->get_interaction_id(),
				'type'           => $this->get_name(),
				'settings'       => $this->get_atomic_settings(),
				'base_styles'    => $this->get_base_styles_dictionary(),
			);

			$context = array_merge( $context, $this->get_template_additional_context() );

			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo $renderer->render( $this->get_main_template(), $context );
		} catch ( \Exception $e ) {
			if ( \Elementor\Utils::is_elementor_debug() ) {
				throw $e;
			}
		}
	}

	protected function get_templates_contents() {
		return array_map(
			static function ( $path ) {
				return \Elementor\Utils::file_get_contents( $path );
			},
			$this->get_templates()
		);
	}

	protected function get_main_template() {
		$templates = $this->get_templates();

		if ( count( $templates ) > 1 ) {
			\Elementor\Utils::safe_throw( 'When having more than one template, override get_main_template().' );
			return null;
		}

		foreach ( $templates as $key => $path ) {
			return $key;
		}

		return null;
	}

	/**
	 * Map of template handle => absolute path to .twig file.
	 *
	 * @return array<string, string>
	 */
	abstract protected function get_templates(): array;
}
