<?php
/**
 * File Path: templates/partials/section-related-books.php
 *
 * My Book Showroom — Related Books Section Partial (Story 13-5)
 *
 * FREE tier. Self-sufficient: queries related books directly so the section
 * works correctly when called from the single-book template section loop
 * (which cannot pre-populate $related_books due to closure scope isolation
 * in mbs_get_template_part).
 *
 * Relation axes (OR): series → collection → genre → author. All four axes
 * are queried together; any shared term qualifies a book as related.
 *
 * GP-UI-1: returns with zero output when no related books are found.
 * All cover output goes through MBS_Cover_Renderer per R5.
 * All output is scoped to .mbs-wrapper per TC-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();
}

if ( ! $post_id ) {
	return;
}

// ── Collect term IDs across all relationship axes ─────────────────────────────
$_mbs_rb_series  = wp_get_object_terms( $post_id, MBS_TAX_SERIES,     array( 'fields' => 'ids' ) );
$_mbs_rb_coll    = wp_get_object_terms( $post_id, MBS_TAX_COLLECTION, array( 'fields' => 'ids' ) );
$_mbs_rb_genre   = wp_get_object_terms( $post_id, MBS_TAX_GENRE,      array( 'fields' => 'ids' ) );
$_mbs_rb_author  = wp_get_object_terms( $post_id, MBS_TAX_AUTHOR,     array( 'fields' => 'ids' ) );

$_mbs_rb_series  = is_array( $_mbs_rb_series ) ? array_map( 'absint', $_mbs_rb_series ) : array();
$_mbs_rb_coll    = is_array( $_mbs_rb_coll )   ? array_map( 'absint', $_mbs_rb_coll )   : array();
$_mbs_rb_genre   = is_array( $_mbs_rb_genre )  ? array_map( 'absint', $_mbs_rb_genre )  : array();
$_mbs_rb_author  = is_array( $_mbs_rb_author ) ? array_map( 'absint', $_mbs_rb_author ) : array();

// ── Build tax_query OR clauses ─────────────────────────────────────────────────
$_mbs_rb_clauses = array();

if ( ! empty( $_mbs_rb_series ) ) {
	$_mbs_rb_clauses[] = array(
		'taxonomy' => MBS_TAX_SERIES,
		'field'    => 'term_id',
		'terms'    => $_mbs_rb_series,
		'operator' => 'IN',
	);
}
if ( ! empty( $_mbs_rb_coll ) ) {
	$_mbs_rb_clauses[] = array(
		'taxonomy' => MBS_TAX_COLLECTION,
		'field'    => 'term_id',
		'terms'    => $_mbs_rb_coll,
		'operator' => 'IN',
	);
}
if ( ! empty( $_mbs_rb_genre ) ) {
	$_mbs_rb_clauses[] = array(
		'taxonomy' => MBS_TAX_GENRE,
		'field'    => 'term_id',
		'terms'    => $_mbs_rb_genre,
		'operator' => 'IN',
	);
}
if ( ! empty( $_mbs_rb_author ) ) {
	$_mbs_rb_clauses[] = array(
		'taxonomy' => MBS_TAX_AUTHOR,
		'field'    => 'term_id',
		'terms'    => $_mbs_rb_author,
		'operator' => 'IN',
	);
}

// GP-UI-1: no taxonomy terms on any axis — nothing to relate to.
if ( empty( $_mbs_rb_clauses ) ) {
	return;
}

$_mbs_rb_tax_query = array_merge( array( 'relation' => 'OR' ), $_mbs_rb_clauses );

$_mbs_rb_query = new WP_Query( array(
	'post_type'           => MBS_POST_TYPE,
	'post_status'         => 'publish',
	'posts_per_page'      => 6,
	'post__not_in'        => array( $post_id ), // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_post__not_in -- standard WP query pattern; VIP rule does not apply to this plugin
	'orderby'             => 'rand',
	'ignore_sticky_posts' => true,
	'no_found_rows'       => true,
	'tax_query'           => $_mbs_rb_tax_query, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- standard WP query pattern; VIP rule does not apply to this plugin
) );

// GP-UI-1: no results.
if ( ! $_mbs_rb_query->have_posts() ) {
	wp_reset_postdata();
	return;
}

$_mbs_rb_heading = isset( $heading_text ) && '' !== $heading_text
	? $heading_text
	: __( 'You may also like', 'my-book-showroom' );
?>

<div class="mbs-wrapper mbs-section mbs-related-books">
	<h3 class="mbs-related-books-heading"><?php echo esc_html( $_mbs_rb_heading ); ?></h3>

	<div class="mbs-related-books-grid">
		<?php while ( $_mbs_rb_query->have_posts() ) : $_mbs_rb_query->the_post(); ?>
			<div class="mbs-related-book-item">
				<a href="<?php echo esc_url( get_permalink() ); ?>" class="mbs-related-book-link">
					<?php
					// R5: cover rendering via MBS_Cover_Renderer exclusively.
					echo MBS_Cover_Renderer::render( get_the_ID() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- MBS_Cover_Renderer::render() returns fully escaped HTML
					?>
					<span class="mbs-related-book-title"><?php echo esc_html( get_the_title() ); ?></span>
				</a>
			</div>
		<?php endwhile; ?>
	</div>
</div>
<?php wp_reset_postdata(); ?>
