<?php
/**
 * File Path: templates/partials/section-audio-sample.php
 *
 * My Book Showroom — Audio Sample Section (PRO)
 *
 * Renders the HTML5 audio player for audiobook samples.
 *
 * @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() || ! mbs_is_pro() ) {
	MBS_Pro_Gate::comment( 'Audio sample section' );
	return;
}

if ( ! isset( $post_id ) ) {
	$post_id = get_the_ID();
}

// Improved logic: Prefer the passed $format_row (from format selector AJAX).
// If none passed or it has no audio, fall back to the first format row that actually has an audio_sample_id.
// This fixes the bug where the audio player always used the first row regardless of selected format.

if ( empty( $format_row ) || empty( $format_row->audio_sample_id ) ) {
	$format_rows = MBS_Format_Row_DAO::get_by_post( $post_id );
	$format_row  = null;

	foreach ( $format_rows as $row ) {
		if ( ! empty( $row->audio_sample_id ) ) {
			$format_row = $row;
			break;
		}
	}
}

if ( empty( $format_row ) || empty( $format_row->audio_sample_id ) ) {
	return;
}

$audio_url = wp_get_attachment_url( $format_row->audio_sample_id );
if ( empty( $audio_url ) ) {
	return;
}
?>

<div class="mbs-wrapper mbs-section mbs-section-audio">
	<h2><?php echo esc_html__( 'Listen to a Sample', 'my-book-showroom' ); ?></h2>
	<audio controls class="mbs-audio-player">
		<source src="<?php echo esc_url( $audio_url ); ?>" type="audio/mpeg">
		<?php echo esc_html__( 'Your browser does not support the audio element.', 'my-book-showroom' ); ?>
	</audio>
</div>
