<?php
/**
 * File Path: templates/partials/section-more-by-author.php
 *
 * My Book Showroom - More by This Author Section
 *
 * FREE tier. Renders other books by the same author(s), capped at 6.
 * No "View all" link (intentional - SS-12a).
 *
 * GP-UI-1: Returns with zero output when:
 *  - Admin toggle is off.
 *  - No author terms are assigned.
 *  - No other published books by this author.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! mbs_is_registered() ) {
	return;
}

// SS-12c: Respect the "Show More by Author" admin toggle.
if ( ! (bool) mbs_get_setting( 'general', 'show_more_by_author', '1' ) ) {
	return;
}

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

$author_terms = get_the_terms( $post_id, MBS_TAX_AUTHOR ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- template-scope variable; not a global
if ( empty( $author_terms ) || is_wp_error( $author_terms ) ) {
	return;
}

$author_ids = wp_list_pluck( $author_terms, 'term_id' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- template-scope variable; not a global

$author_books = new WP_Query( array( // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- template-scope variable; not a global
	'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
	'tax_query'      => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- standard WP query pattern; VIP rule does not apply to this plugin
		array(
			'taxonomy' => MBS_TAX_AUTHOR,
			'field'    => 'term_id',
			'terms'    => $author_ids,
		),
	),
	'no_found_rows'  => true,
) );

// GP-UI-1: suppress section when no other books exist.
if ( ! $author_books->have_posts() ) {
	wp_reset_postdata();
	return;
}
?>

<div class="mbs-wrapper mbs-section mbs-section-more-by-author">
	<h3><?php esc_html_e( 'More by This Author', 'my-book-showroom' ); ?></h3>
	<div class="mbs-author-grid">
		<?php while ( $author_books->have_posts() ) : $author_books->the_post(); ?>
			<div class="mbs-author-book">
				<?php echo MBS_Cover_Renderer::render( get_the_ID() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- MBS_Cover_Renderer::render() returns fully escaped HTML ?>
				<h4><a href="<?php echo esc_url( get_permalink() ); ?>"><?php echo esc_html( get_the_title() ); ?></a></h4>
			</div>
		<?php endwhile; ?>
	</div>
</div>
<?php wp_reset_postdata(); ?>
