<?php
/**
 * Frontend shortcodes for Divi Library layouts on Divi 5.
 *
 * Canonical tag: `[divi_shortcode id="…"]` ({@see DSM_SHORTCODE}).
 * Compatibility alias: `[divi_library_layout id="…"]` (appears in migrated / third-party content).
 *
 * Divi 4 registers `divi_shortcode` in {@see Dsm_Supreme_Modules_Pro_For_Divi::define_admin_hooks()};
 * that class is not loaded on the Divi 5 bootstrap path, so we register here when D5 builder is active.
 *
 * @package DiviSupreme
 */

declare(strict_types=1);

namespace DiviSupreme\Includes;

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

/**
 * Registers and handles library-layout shortcodes on Divi 5 via {@see DiviLibraryLayoutRenderer::render_layout()}.
 */
final class DsmDiviShortcode {

	/**
	 * Legacy / alternate shortcode tag found in some migrated layouts.
	 */
	public const LIBRARY_LAYOUT_ALIAS = 'divi_library_layout';

	/**
	 * Register the shortcode when Divi 5 builder is active.
	 *
	 * @return void
	 */
	public static function register(): void {
		if ( ! function_exists( 'et_builder_d5_enabled' ) || ! et_builder_d5_enabled() ) {
			return;
		}

		if ( ! defined( 'DSM_SHORTCODE' ) ) {
			define( 'DSM_SHORTCODE', 'divi_shortcode' );
		}

		add_shortcode( DSM_SHORTCODE, array( self::class, 'handle' ) );

		// Compatibility: migrated content may still store `[divi_library_layout id="…"]`.
		if ( ! shortcode_exists( self::LIBRARY_LAYOUT_ALIAS ) ) {
			add_shortcode( self::LIBRARY_LAYOUT_ALIAS, array( self::class, 'handle' ) );
		}
	}

	/**
	 * Shortcode callback: render a Divi Library layout by post ID.
	 *
	 * @param array<string, string>|string $atts    Shortcode attributes.
	 * @param string|null                  $content Inner content (unused).
	 * @param string                       $tag     Shortcode name.
	 * @return string Markup (Builder HTML; not HTML-escaped).
	 */
	public static function handle( $atts = array(), $content = null, $tag = '' ): string {
		unset( $content );

		$atts = is_array( $atts ) ? $atts : array();
		$tag  = is_string( $tag ) && '' !== $tag ? $tag : ( defined( 'DSM_SHORTCODE' ) ? DSM_SHORTCODE : 'divi_shortcode' );

		$atts = shortcode_atts(
			array(
				'id' => '',
			),
			$atts,
			$tag
		);

		$layout_id = DiviLibraryLayoutRenderer::normalize_post_id( $atts['id'] ?? '' );

		if ( $layout_id <= 0 ) {
			return '';
		}

		$post = get_post( $layout_id );

		if ( ! $post instanceof \WP_Post ) {
			return '';
		}

		$layout_type = defined( 'ET_BUILDER_LAYOUT_POST_TYPE' ) ? ET_BUILDER_LAYOUT_POST_TYPE : 'et_pb_layout';

		if ( $layout_type !== $post->post_type ) {
			return '';
		}

		$html = DiviLibraryLayoutRenderer::render_layout( $layout_id, 'dsm_divi_shortcode' );

		return is_string( $html ) ? $html : '';
	}
}
