<?php
/**
 * File Path: templates/partials/section-series-order.php
 *
 * My Book Showroom -- Series Reading Order Section
 *
 * FREE tier. Renders an "Also in this series" section on single-book pages
 * when the book belongs to a series with other published books.
 *
 * Sprint RO-Display (Group 8a): When the Series Reading Order toggle is
 * enabled and the current book is not suppressed from reading order display,
 * this section renders two rows (Series Order + Reading Order) when the two
 * sequences differ. When they are identical the duplicate row is suppressed.
 * When the toggle is off or the book is suppressed, only the Series Order row
 * is shown (existing behavior).
 *
 * Sort mode (Series Order row):
 *   -- Books ordered by mbs_series_position ascending.
 *   -- Badge shows canonical series position (#1, #2 ...).
 *
 * Sort mode (Reading Order row):
 *   -- Books ordered by the admin-configured reading sequence (DAO).
 *   -- Badge shows reading order slot (#1, #2 ...).
 *
 * Section absent when:
 *   - The book has no series term.
 *   - The book is the only entry in its series.
 *
 * Section position follows mbs_section_order (caller responsibility).
 * All output uses MBS_Cover_Renderer per R5.
 *
 * @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;
}

// P6-006: Respect the "Show More in Series" admin toggle.
if ( ! (bool) mbs_get_setting( 'general', 'show_more_in_series', '1' ) ) {
	return;
}

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

// Get the series term(s) for this book.
$series_terms = wp_get_post_terms( $post_id, 'mbs_series', array( 'fields' => 'all' ) );
if ( is_wp_error( $series_terms ) || empty( $series_terms ) ) {
	return;
}

// Use the primary (first) series.
$series_term = $series_terms[0];
$series_id   = (int) $series_term->term_id;

// Sprint RO-Display (Group 8a): reading order toggle + per-book suppress flag.
$show_series_ro   = '1' === get_option( 'mbs_setting_show_series_reading_order', '0' );
$series_ro_hidden = (bool) MBS_Book_Meta_DAO::get_series_reading_order_hidden( $post_id );
$use_two_rows     = $show_series_ro && ! $series_ro_hidden;

// ── Build Series Order IDs (Series Order row, always needed) ──────────────────
$ord_ids_raw = MBS_Series_Reading_Order_DAO::get_order_sorted_ids( $series_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_Series_Reading_Order_DAO::get_ordered_book_ids( $series_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, suppress the second row.
	if ( $ord_ids === $ro_ids ) {
		$use_two_rows = false;
	}
}

// GP-UI-1: nothing to render when this is the only book in the series.
if ( empty( $ord_ids ) ) {
	return;
}

// ── 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 position maps ────────────────────────────────────────────────────────
// Series Order: badge = canonical series position from post_meta.
// Reading Order: badge = 1-based slot in the full (unfiltered) reading order list.
// V5-D-001 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-section mbs-section-series-order">
	<h3 class="mbs-series-order-heading">
		<?php
		printf(
			/* translators: %s: series name */
			esc_html__( 'Also in %s', 'my-book-showroom' ),
			esc_html( $series_term->name )
		);
		?>
	</h3>

	<?php if ( $use_two_rows ) : ?>

		<?php /* Sprint RO-Display: two-row display -- Series 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( 'Series Order', 'my-book-showroom' ); ?></h3>
				<div class="mbs-series-order-grid">
					<?php foreach ( $ord_books as $series_book ) : ?>
						<?php
						$badge_num  = (int) get_post_meta( $series_book->ID, 'mbs_series_position', true );
						$badge_aria = $badge_num > 0
							/* translators: %d: position of this book in the series */
							? sprintf( esc_attr__( 'Book %d in series', 'my-book-showroom' ), $badge_num )
							: '';
						?>
						<div class="mbs-series-order-item">
							<a href="<?php echo esc_url( get_permalink( $series_book->ID ) ); ?>" class="mbs-series-order-link">
								<div class="mbs-series-order-cover">
									<?php echo MBS_Cover_Renderer::render( $series_book->ID ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- fully escaped ?>
									<?php if ( $badge_num > 0 ) : ?>
										<span class="mbs-series-order-number" aria-label="<?php echo $badge_aria; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $badge_aria is set via esc_attr__(), already escaped ?>">
											#<?php echo esc_html( $badge_num ); ?>
										</span>
									<?php endif; ?>
								</div>
								<span class="mbs-series-order-title"><?php echo esc_html( $series_book->post_title ); ?></span>
							</a>
						</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-series-order-grid">
					<?php foreach ( $ro_books as $series_book ) : ?>
						<?php
						$badge_num  = $ro_position_map[ (int) $series_book->ID ] ?? 0;
						$badge_aria = $badge_num > 0
							/* translators: %d: reading order position */
							? sprintf( esc_attr__( 'Suggested reading order: #%d', 'my-book-showroom' ), $badge_num )
							: '';
						?>
						<div class="mbs-series-order-item">
							<a href="<?php echo esc_url( get_permalink( $series_book->ID ) ); ?>" class="mbs-series-order-link">
								<div class="mbs-series-order-cover">
									<?php echo MBS_Cover_Renderer::render( $series_book->ID ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- fully escaped ?>
									<?php if ( $badge_num > 0 ) : ?>
										<span class="mbs-series-order-number mbs-series-position-badge" aria-label="<?php echo $badge_aria; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $badge_aria is set via esc_attr__(), already escaped ?>">
											#<?php echo esc_html( $badge_num ); ?>
										</span>
									<?php endif; ?>
								</div>
								<span class="mbs-series-order-title"><?php echo esc_html( $series_book->post_title ); ?></span>
							</a>
						</div>
					<?php endforeach; ?>
				</div>
			</div>
			<?php endif; ?>

		</div>

	<?php else : ?>

		<?php /* Single-row: Series Order only (toggle off or sequences identical) */ ?>
		<div class="mbs-series-order-grid">
			<?php foreach ( $ord_books as $series_book ) : ?>
				<?php
				$badge_num  = (int) get_post_meta( $series_book->ID, 'mbs_series_position', true );
				$badge_aria = $badge_num > 0
					/* translators: %d: position of this book in the series */
					? sprintf( esc_attr__( 'Book %d in series', 'my-book-showroom' ), $badge_num )
					: '';
				?>
				<div class="mbs-series-order-item">
					<a href="<?php echo esc_url( get_permalink( $series_book->ID ) ); ?>" class="mbs-series-order-link">
						<div class="mbs-series-order-cover">
							<?php echo MBS_Cover_Renderer::render( $series_book->ID ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- fully escaped ?>
							<?php if ( $badge_num > 0 ) : ?>
								<span class="mbs-series-order-number" aria-label="<?php echo $badge_aria; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $badge_aria is set via esc_attr__(), already escaped ?>">
									#<?php echo esc_html( $badge_num ); ?>
								</span>
							<?php endif; ?>
						</div>
						<span class="mbs-series-order-title"><?php echo esc_html( $series_book->post_title ); ?></span>
					</a>
				</div>
			<?php endforeach; ?>
		</div>

	<?php endif; ?>

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

<?php
// Restore global post state if get_posts() altered it.
wp_reset_postdata();
