<?php
/**
 * File Path: templates/partials/format-selector.php
 *
 * My Book Showroom — Format Selector Partial
 *
 * Renders the format selector tabs/buttons on single book pages.
 * Updated to use canonical schema column names, removed inline styles (GP-CSS-1),
 * and added full translation support (GP-LANG-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 ( ! isset( $post_id ) ) {
	$post_id = get_the_ID();
}

$format_rows = MBS_Format_Row_DAO::get_by_post( $post_id );

if ( empty( $format_rows ) ) {
	return;
}

// Build the JSON payload for client-side switching — per-format links + array_values fix
$formats_data = array();
$show_isbn    = (bool) mbs_get_setting( 'general', 'show_isbn' );   // P6-002: master ISBN visibility toggle
$show_isbn10  = (bool) mbs_get_setting( 'general', 'show_isbn10' ); // ISBN-10 sub-toggle (only applies when show_isbn is on)

foreach ( $format_rows as $row ) {
	$buy_links = MBS_Buy_Link_DAO::get_for_format( (int) $row->id );
	// Global buy-link fallback: when no per-format links exist, use book-level
	// Global Buy Links (format_row_id IS NULL) so the JS format-switch display
	// is never empty while the author has global links configured.
	if ( empty( $buy_links ) ) {
		$buy_links = MBS_Buy_Link_DAO::get_for_book( $post_id );
	}

	// Resolve cover URL using same hierarchy as MBS_Cover_Renderer:
	// PRO/Publisher: format cover → book cover → placeholder. FREE: book cover → placeholder.
	$cover_url = '';
	if ( mbs_is_pro() && ! empty( $row->cover_image_id ) ) {
		$cover_url = wp_get_attachment_url( (int) $row->cover_image_id ) ?: '';
	}
	if ( ! $cover_url ) {
		$book_thumb_id = get_post_thumbnail_id( $post_id ); // R5-exempt: cover URL for JS data-mbs-formats payload
		if ( $book_thumb_id ) {
			$cover_url = wp_get_attachment_url( $book_thumb_id ) ?: '';
		}
	}

	$formats_data[] = array(
		'format_row_id' => (int) $row->id,
		'format'        => sanitize_text_field( $row->format ),
		'price'         => MBS_Formatting::format_price( (float) ( $row->price ?? 0 ) ),
		'isbn13'        => $show_isbn ? MBS_ISBN_Helper::format_isbn( $row->isbn13 ?? '' ) : '',
		'isbn10'        => ( $show_isbn && $show_isbn10 && ! empty( $row->isbn13 ) ) ? ( MBS_ISBN_Helper::isbn13_to_isbn10( $row->isbn13 ) ?: '' ) : '',
		'asin'          => sanitize_text_field( $row->asin ?? '' ),
		'page_length'   => (int) ( $row->page_length ?? 0 ),
		'duration_hh'   => isset( $row->duration_hh ) && '' !== $row->duration_hh ? (int) $row->duration_hh : null,
		'duration_mm'   => isset( $row->duration_mm ) && '' !== $row->duration_mm ? (int) $row->duration_mm : null,
		'subtitle'      => sanitize_text_field( $row->subtitle ?? '' ),
		'cover_url'     => esc_url_raw( $cover_url ),
		'cover_image_id'=> (int) ( $row->cover_image_id ?? 0 ),
		'buy_links'     => array_values( array_map(
			function( $link ) {
				$key = sanitize_key( $link->retailer_key ?? '' );
				$url = mbs_is_pro()
					? MBS_Affiliate_Rewriter::rewrite( $link->url, $key ?: null )
					: $link->url;
				return array(
					'url'          => esc_url_raw( $url ),
					'retailer_key' => $key,
				);
			},
			array_filter( $buy_links, function( $link ) {
				// Exclude reader-platform links (rendered in external-links zone).
				return ! empty( $link->url ) && ( $link->link_type ?? 'buy' ) === 'buy';
			} )
		) ),
	);
}

?>
<div class="mbs-wrapper mbs-format-selector" data-mbs-formats="<?php echo esc_attr( wp_json_encode( $formats_data ) ); ?>">
	<div class="mbs-format-tabs">
		<?php foreach ( $format_rows as $index => $row ) :
			$label = $row->format_label
				? $row->format_label
				: MBS_Format_Options::get_format_label( $row->format );
		?>
			<button type="button"
			        class="mbs-format-tab <?php echo esc_attr( $index === 0 ? 'active' : '' ); ?>"
			        data-format-row-id="<?php echo esc_attr( $row->id ); ?>">
				<?php echo esc_html( $label ); ?>
			</button>
		<?php endforeach; ?>
	</div>
</div>
