<?php
/**
 * File Path: templates/partials/section-more-in-universe.php
 *
 * My Book Showroom - More in This Universe Section (PRO)
 *
 * PRO tier. Renders other published books in the same universe,
 * capped at 6. Check order (SS-12 checklist):
 *   (a) Option check FIRST - silent return if Universe feature is OFF.
 *   (b) THEN PRO check - HTML comment for FREE users.
 *   (c) THEN content check + query.
 *
 * Sprint RO-Display (Group 8b): When the Universe Reading Order toggle is
 * enabled, a persisted reading order exists, and the current book is not
 * suppressed, renders two rows (Universe Order + Reading Order) when the
 * sequences differ. Identical sequences collapse to a single row.
 *
 * Uses the primary (first) universe term (D-003 fix).
 * Excludes the current book (D-004 fix).
 * Includes a "View all" link to the universe archive.
 *
 * @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;
}

// (a) Option check FIRST: silent return if Universe feature is disabled.
if ( ! (int) get_option( 'mbs_setting_advanced_universe_enabled', 0 ) ) {
	return;
}

// (b) PRO check: HTML comment for FREE users.
if ( ! mbs_is_pro() ) {
	MBS_Pro_Gate::comment( 'More in This Universe section' );
	return;
}

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

// (c) Content check: fetch universe term(s).
$terms = wp_get_post_terms( $post_id, MBS_TAX_UNIVERSE );
if ( is_wp_error( $terms ) || empty( $terms ) ) {
	return; // GP-UI-1: no universe assigned.
}

// Use the primary (first) term.
$primary_term    = $terms[0];
$universe_term_id = (int) $primary_term->term_id;

// Sprint RO-Display (Group 8b): universe reading order toggle + per-book suppress flag.
$show_universe_ro   = '1' === get_option( 'mbs_setting_show_universe_reading_order', '0' );
$universe_ro_hidden = (bool) MBS_Book_Meta_DAO::get_universe_reading_order_hidden( $post_id );
$has_order          = MBS_Universe_Reading_Order_DAO::has_persisted_order( $universe_term_id );
$use_two_rows       = $show_universe_ro && ! $universe_ro_hidden && $has_order;

// ── Build Universe Order IDs ──────────────────────────────────────────────────
$ord_ids_raw = MBS_Universe_Reading_Order_DAO::get_order_sorted_ids( $universe_term_id );
// Exclude current book, cap at 6.
$ord_ids = array_slice(
	array_values( array_filter( $ord_ids_raw, fn( $id ) => (int) $id !== $post_id ) ),
	0, 6
);

// ── Build Reading Order IDs (only when two-row mode is active) ────────────────
$ro_ids = array();
if ( $use_two_rows ) {
	$ro_ids_raw = MBS_Universe_Reading_Order_DAO::get_ordered_book_ids( $universe_term_id );
	// Exclude current book, cap at 6.
	$ro_ids = array_slice(
		array_values( array_filter( $ro_ids_raw, fn( $id ) => (int) $id !== $post_id ) ),
		0, 6
	);
	// Dedup: if sequences are identical after filtering, collapse to single row.
	if ( $ord_ids === $ro_ids ) {
		$use_two_rows = false;
	}
}

if ( empty( $ord_ids ) ) {
	return; // GP-UI-1: no other books in this universe.
}

// ── Helper: fetch post objects for a given ID list ─────────────────────────────
$_mbs_fetch_books = static function( array $ids ): array {
	if ( empty( $ids ) ) {
		return array();
	}
	return get_posts( array(
		'post_type'      => MBS_POST_TYPE,
		'post_status'    => 'publish',
		'posts_per_page' => count( $ids ),
		'post__in'       => $ids,
		'orderby'        => 'post__in',
		'no_found_rows'  => true,
	) );
};

$ord_books = $_mbs_fetch_books( $ord_ids );
if ( empty( $ord_books ) ) {
	return;
}

$ro_books = $use_two_rows ? $_mbs_fetch_books( $ro_ids ) : array();

// ── Build reading order position map (for badges in the RO row) ───────────────
// V5-D-002 fix: reuse $ro_ids_raw (already fetched above) — no second DAO call.
$ro_position_map = array();
if ( $use_two_rows ) {
	foreach ( $ro_ids_raw as $ro_idx => $ro_id ) {
		$ro_position_map[ (int) $ro_id ] = $ro_idx + 1;
	}
}
?>

<div class="mbs-wrapper mbs-section mbs-section-more-in-universe">
	<h3>
		<?php
		printf(
			/* translators: %s: universe name */
			esc_html__( 'More in %s', 'my-book-showroom' ),
			esc_html( $primary_term->name )
		);
		?>
	</h3>

	<?php if ( $use_two_rows ) : ?>

		<?php /* Sprint RO-Display: two-row display -- Universe Order + Reading Order */ ?>
		<div class="mbs-archive-ordered-rows">

			<div class="mbs-archive-row mbs-archive-row--order">
				<h3 class="mbs-archive-row__label"><?php esc_html_e( 'Universe Order', 'my-book-showroom' ); ?></h3>
				<div class="mbs-universe-grid">
					<?php foreach ( $ord_books as $_mbs_book ) : ?>
						<div class="mbs-universe-book">
							<?php echo MBS_Cover_Renderer::render( $_mbs_book->ID ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- fully escaped ?>
							<h4><a href="<?php echo esc_url( get_permalink( $_mbs_book->ID ) ); ?>"><?php echo esc_html( $_mbs_book->post_title ); ?></a></h4>
						</div>
					<?php endforeach; ?>
				</div>
			</div>

			<?php if ( ! empty( $ro_books ) ) : ?>
			<div class="mbs-archive-row mbs-archive-row--reading-order">
				<h3 class="mbs-archive-row__label"><?php esc_html_e( 'Reading Order', 'my-book-showroom' ); ?></h3>
				<div class="mbs-universe-grid">
					<?php foreach ( $ro_books as $_mbs_book ) : ?>
						<?php
						$_mbs_ro_pos  = $ro_position_map[ (int) $_mbs_book->ID ] ?? 0;
						?>
						<div class="mbs-universe-book">
							<?php echo MBS_Cover_Renderer::render( $_mbs_book->ID ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- fully escaped ?>
							<h4><a href="<?php echo esc_url( get_permalink( $_mbs_book->ID ) ); ?>"><?php echo esc_html( $_mbs_book->post_title ); ?></a></h4>
							<?php if ( $_mbs_ro_pos > 0 ) : ?>
								<span class="mbs-series-position-badge" aria-label="<?php
									/* translators: %d: reading order position */
									echo esc_attr( sprintf( __( 'Position %d in universe reading order', 'my-book-showroom' ), $_mbs_ro_pos ) );
								?>">#<?php echo esc_html( $_mbs_ro_pos ); ?></span>
							<?php endif; ?>
						</div>
					<?php endforeach; ?>
				</div>
			</div>
			<?php endif; ?>

		</div>

	<?php else : ?>

		<?php /* Single-row: Universe Order only */ ?>
		<div class="mbs-universe-grid">
			<?php foreach ( $ord_books as $_mbs_book ) : ?>
				<div class="mbs-universe-book">
					<?php echo MBS_Cover_Renderer::render( $_mbs_book->ID ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- fully escaped ?>
					<h4><a href="<?php echo esc_url( get_permalink( $_mbs_book->ID ) ); ?>"><?php echo esc_html( $_mbs_book->post_title ); ?></a></h4>
				</div>
			<?php endforeach; ?>
		</div>

	<?php endif; ?>

	<p class="mbs-view-all">
		<a href="<?php echo esc_url( get_term_link( $primary_term, MBS_TAX_UNIVERSE ) ); ?>">
			<?php
			printf(
				/* translators: %s: universe name */
				esc_html__( 'View all in %s', 'my-book-showroom' ),
				esc_html( $primary_term->name )
			);
			?>
		</a>
	</p>
</div>
<?php wp_reset_postdata(); ?>
