<?php
/**
 * File Path: templates/partials/section-trailer.php
 *
 * My Book Showroom - Book Trailer Section (PRO)
 *
 * PRO tier. Renders book trailer video or embed. Returns an HTML comment
 * for FREE tier (mbs_pro_comment). Returns with zero output when no trailer
 * content is saved (GP-UI-1).
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- template-scope variables injected by mbs_get_template_part(); not global vars

if ( ! mbs_is_registered() ) {
	return;
}

if ( ! mbs_is_pro() ) {
	MBS_Pro_Gate::comment( 'Book Trailer section' );
	return;
}

$post_id = isset( $post_id ) ? (int) $post_id : get_the_ID();

$trailer_video_id = get_post_meta( $post_id, 'mbs_trailer_video_id', true );
$trailer_embed    = get_post_meta( $post_id, 'mbs_trailer_embed_url', true );

// GP-UI-1: suppress section when no trailer content is saved.
if ( ! $trailer_video_id && ! $trailer_embed ) {
	return;
}
?>

<div class="mbs-wrapper mbs-section mbs-section-trailer">
	<?php if ( $trailer_video_id ) : ?>
		<div class="mbs-trailer-video">
			<?php
			$trailer_src = wp_get_attachment_url( $trailer_video_id );
			if ( $trailer_src ) {
				echo wp_video_shortcode( array( 'src' => esc_url( $trailer_src ) ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted renderer returns pre-escaped HTML
			}
			?>
		</div>
	<?php elseif ( $trailer_embed ) : ?>
		<div class="mbs-trailer-embed">
			<?php
			// FE-013: Convert embed URL to oEmbed iframe (YouTube/Vimeo etc).
			// wp_kses_post() was stripping the iframe, rendering the raw URL as text.
			$_mbs_oembed = wp_oembed_get( $trailer_embed );
			if ( $_mbs_oembed ) {
				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- wp_oembed_get returns trusted HTML from registered oEmbed providers.
				echo $_mbs_oembed;
			} else {
				// Fallback: plain link when URL is not a recognized oEmbed provider.
				printf(
					'<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
					esc_url( $trailer_embed ),
					esc_html__( 'Watch trailer', 'my-book-showroom' )
				);
			}
			?>
		</div>
	<?php endif; ?>
</div>
