<?php
/**
 * Frontend shortcode `[divi_shortcode id="…"]` for Divi 5 (library layouts).
 *
 * Divi 4 registers the same tag 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 `divi_shortcode` on Divi 5 using {@see DiviLibraryLayoutRenderer::render_layout()}.
 */
final class DsmDiviShortcode {

	/**
	 * 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' ) );
	}

	/**
	 * 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, $tag );

		$atts = is_array( $atts ) ? $atts : array();

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

		$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 : '';
	}
}
