<?php
/**
 * Shortcode Resolver.
 *
 * Replaces data-shortcode markers with their rendered WordPress output.
 *
 * @package Antimanual_Builder
 * @since 1.0.0
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class AMBLD_Render_Shortcode_Resolver.
 *
 * @since 1.0.0
 */
class AMBLD_Render_Shortcode_Resolver {

	/**
	 * Resolve all shortcode markers in the given HTML.
	 *
	 * Replaces each <div data-shortcode="..."> marker with the rendered
	 * output of the contained shortcode, preserving wrapper attributes
	 * (id, class, data-amb-section, etc.).
	 *
	 * @since 1.0.0
	 * @param string $html HTML that may contain shortcode markers.
	 * @return string HTML with shortcode markers replaced by rendered output.
	 */
	public static function resolve( $html ) {
		if ( '' === $html || false === strpos( $html, 'data-shortcode=' ) ) {
			return $html;
		}

		return preg_replace_callback(
			'/<div\b([^>]*?)\bdata-shortcode="([^"]*)"([^>]*)>[\s\S]*?<\/div>/i',
			function ( $m ) {
				$shortcode = wp_specialchars_decode( $m[2], ENT_QUOTES );
				$rendered  = do_shortcode( $shortcode );
				$attrs_open = $m[1] . ' data-shortcode="' . $m[2] . '"' . $m[3];
				return '<div' . $attrs_open . '>' . $rendered . '</div>';
			},
			$html
		);
	}

	/**
	 * Check if HTML contains any shortcode markers.
	 *
	 * @since 1.0.0
	 * @param string $html HTML to check.
	 * @return bool True if shortcode markers are present.
	 */
	public static function has_shortcode_markers( $html ) {
		return '' !== $html && false !== strpos( $html, 'data-shortcode=' );
	}
}