<?php
/**
 * File Path: templates/taxonomy-mbs-collection.php
 *
 * Taxonomy Archive — mbs_collection
 *
 * Displays all books belonging to a specific collection, with the collection
 * type shown in the header when available.
 *
 * CE-2: PRO reading order. When mbs_is_pro() and a reading order has been
 * persisted via Settings → Collections, books are displayed in the
 * admin-configured sequence. Falls back silently to WordPress default (date)
 * order on FREE — no visible difference to visitors.
 *
 * SHC-6: Layout Registry. The active layout is resolved via
 * MBS_Layout_Registry::resolve_slug_for_term() and ::get_layout() — honouring
 * the per-term override (PRO) or the global default setting.
 * Note: Collection archives never render position badges regardless of layout.
 *
 * @package    My_Book_Showroom
 * @subpackage Templates
 * @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() ) {
	get_header();
	echo '<p>' . esc_html__( 'This feature requires a registered license.', 'my-book-showroom' ) . '</p>';
	get_footer();
	exit;
}

get_header();

$term    = get_queried_object();
$term_id = ( $term instanceof WP_Term ) ? (int) $term->term_id : 0;

// Resolve the collection type label for display in the header.
$type_label = '';
if ( $term instanceof WP_Term ) {
	$type_slug  = (string) get_term_meta( $term->term_id, 'mbs_collection_type', true );
	$type_label = MBS_Taxonomy_Collection::get_type_label( $type_slug );
}

// CE-2: Determine reading order mode (PRO).
// Applied when mbs_is_pro() AND a reading order has been explicitly persisted
// via Settings → Collections for this term. Falls back silently to standard
// WP loop on FREE — no HTML comment shown to visitors.
$use_reading_order = mbs_is_pro()
                     && $term_id
                     && MBS_Collection_Reading_Order_DAO::has_persisted_order( $term_id );

// SHC-6: Resolve layout for this term (per-term PRO override or global default).
// Collections do not render position badges regardless of layout slug.
$layout_slug = MBS_Layout_Registry::resolve_slug_for_term( $term_id, 'grid' );
$layout_obj  = MBS_Layout_Registry::get_layout( $layout_slug );
?>

<div class="mbs-wrapper mbs-taxonomy-archive mbs-taxonomy-archive-collection">

	<?php mbs_get_template_part( 'partials/breadcrumbs' ); ?>

	<header class="mbs-archive-header">
		<h1 class="mbs-archive-title">
			<?php
			printf(
				/* translators: %s: collection name */
				esc_html__( 'Collection: %s', 'my-book-showroom' ),
				esc_html( single_term_title( '', false ) )
			);
			?>
		</h1>

		<?php if ( $type_label ) : ?>
			<p class="mbs-collection-type">
				<span class="mbs-collection-type-label"><?php echo esc_html( $type_label ); ?></span>
			</p>
		<?php endif; ?>

		<?php if ( $term instanceof WP_Term && ! empty( $term->description ) ) : ?>
			<div class="mbs-term-description">
				<?php echo wp_kses_post( wpautop( $term->description ) ); ?>
			</div>
		<?php endif; ?>
	</header>
<?php
// F-BNR-C: Collection banner image — PRO only.
if ( mbs_is_pro() && $term_id ) :
	$banner_id = (int) get_term_meta( $term_id, 'mbs_collection_banner_id', true );
	if ( $banner_id ) :
		?>
		<div class="mbs-collection-banner">
			<?php echo wp_get_attachment_image( // R5-exempt: collection banner image (mbs_collection_banner_id), book cover grid uses MBS_Cover_Renderer
				$banner_id,
				'full',
				false,
				array(
					'class' => 'mbs-collection-banner-img',
					'alt'   => $term->name,
				)
			); ?>
		</div>
		<?php
	endif;
endif;
?>

	<?php if ( $use_reading_order ) : ?>

		<?php
		// CE-2: Reading order — PRO. Query books in the admin-configured sequence.
		// SHC-6: Layout Registry renders the ordered query. No position badges for
		// collections (per SHC-6 compatibility table).
		$ordered_ids = MBS_Collection_Reading_Order_DAO::get_ordered_book_ids( $term_id );

		// V2-C-029: Guard against empty reading order — post__in=[] is
		// undefined in WP_Query and may return all posts.
		if ( empty( $ordered_ids ) ) {
			echo '<p>' . esc_html__( 'No books found in this collection.', 'my-book-showroom' ) . '</p>';
		} else {
			$ro_query    = new WP_Query( array(
				'post_type'      => MBS_POST_TYPE,
				'post_status'    => 'publish',
				'posts_per_page' => count( $ordered_ids ),
				'post__in'       => $ordered_ids,
				'orderby'        => 'post__in', // preserves DAO order exactly
				'no_found_rows'  => true,
			) );
			echo $layout_obj->render( $ro_query ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted renderer returns pre-escaped HTML
		}
		?>

	<?php else : ?>

		<?php
		// Standard path — date order (FREE or no persisted reading order).
		// SHC-6: Layout Registry renders the full grid. Pagination follows when needed.
		global $wp_query;
		echo $layout_obj->render( $wp_query ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted renderer returns pre-escaped HTML
		if ( $wp_query->max_num_pages > 1 ) :
			the_posts_pagination( array(
				'mid_size'  => 2,
				'prev_text' => __( '← Previous', 'my-book-showroom' ),
				'next_text' => __( 'Next →', 'my-book-showroom' ),
			) );
		endif;
		?>

	<?php endif; ?>
</div>

<?php
mbs_get_template_part( 'partials/power-badge' );
get_footer();
