<?php
/**
 * File Path: templates/taxonomy-mbs-author.php
 *
 * Taxonomy Archive — mbs_author
 *
 * FREE tier:
 *   Basic book grid filtered by the current author term. Matches the
 *   pre-Round-4 layout exactly.
 *
 * PRO tier (enhanced, per Doc 1c §taxonomy-mbs-author.php):
 *   Above the book grid, renders an author hero containing:
 *     · Author banner photo (mbs_author_photo_id)
 *     · Author bio          (mbs_author_bio)
 *     · Social links row    (website + 7 platforms — bio and website_url
 *                            newly consumed here per PLG-048, Round 4)
 *
 * The hero partial decides its own content gates per GP-UI-1 Golden Rule:
 * individual fields render only when their term_meta value is populated,
 * and the entire partial returns empty if every field is blank.
 *
 * 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.
 *
 * @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() ) {
	get_header();
	echo '<p>' . esc_html__( 'This feature requires a registered license.', 'my-book-showroom' ) . '</p>';
	get_footer();
	exit;
}

get_header();

// Queried term is the mbs_author we're archiving. Needed for the hero partial.
$author_term    = get_queried_object();
$author_term_id = ( $author_term instanceof WP_Term ) ? (int) $author_term->term_id : 0;

// SHC-6: Resolve layout for this author term (per-term PRO override or global default).
$layout_slug = MBS_Layout_Registry::resolve_slug_for_term( $author_term_id, 'grid' );
$layout_obj  = MBS_Layout_Registry::get_layout( $layout_slug );
?>

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

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

	<?php
	// Enhanced hero — PRO only. The partial itself does the per-field
	// GP-UI-1 Golden Rule gating and will render empty if the author has
	// no photo, no bio, no website, and no social URLs.
	if ( mbs_is_pro() && $author_term_id ) {
		mbs_get_template_part(
			'partials/section-author-hero',
			array( 'author_term_id' => $author_term_id )
		);
	}
	?>

	<?php if ( ! mbs_is_pro() ) : ?>

		<?php mbs_get_template_part( 'partials/breadcrumbs' ); ?>
		<?php
		// S14-5: Author bio from mbs_author_bio term meta.
		// GP-UI-1: only render when non-empty.
		// wp_kses_post(wpautop()) preserves paragraph markup saved via wp_kses_post().
		$author_bio = '';
		if ( $author_term instanceof WP_Term ) {
			$author_bio = (string) get_term_meta( $author_term->term_id, 'mbs_author_bio', true );
			if ( '' === $author_bio && '' !== trim( $author_term->description ) ) {
				$author_bio = $author_term->description;
			}
		}
		?>
		<?php if ( '' !== $author_bio ) : ?>
			<div class="mbs-author-bio mbs-author-bio--free">
				<?php echo wp_kses_post( wpautop( $author_bio ) ); ?>
			</div>
		<?php endif; ?>

		<?php
		// S14-5: Social links — 7 platform keys + website_url, read individually from
		// term meta. Pattern matches partials/section-author-hero.php exactly.
		// GP-UI-1: skip entire block when no platform has a URL.
		$social_platforms = array(
			'mbs_author_website_url'   => __( 'Website', 'my-book-showroom' ),
			'mbs_author_twitter_url'   => __( 'Twitter / X', 'my-book-showroom' ),
			'mbs_author_instagram_url' => __( 'Instagram', 'my-book-showroom' ),
			'mbs_author_facebook_url'  => __( 'Facebook', 'my-book-showroom' ),
			'mbs_author_tiktok_url'    => __( 'TikTok', 'my-book-showroom' ),
			'mbs_author_goodreads_url' => __( 'Goodreads', 'my-book-showroom' ),
			'mbs_author_bookbub_url'   => __( 'BookBub', 'my-book-showroom' ),
			'mbs_author_linkedin_url'  => __( 'LinkedIn', 'my-book-showroom' ),
		);
		$rendered_social = array();
		foreach ( $social_platforms as $meta_key => $label ) {
			$link_url = '';
			if ( $author_term instanceof WP_Term ) {
				$link_url = esc_url( (string) get_term_meta( $author_term->term_id, $meta_key, true ) );
			}
			if ( '' === $link_url ) {
				continue;
			}
			$platform_slug     = str_replace( array( 'mbs_author_', '_url' ), '', $meta_key );
			$rendered_social[] = '<a href="' . $link_url
				. '" class="mbs-social-link mbs-social-link--' . esc_attr( $platform_slug )
				. '" target="_blank" rel="noopener noreferrer">'
				. esc_html( $label ) . '</a>';
		}
		?>
		<?php if ( ! empty( $rendered_social ) ) : ?>
			<div class="mbs-author-social mbs-author-social--free">
				<?php echo implode( ' ', $rendered_social ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- pre-escaped above ?>
			</div>
		<?php endif; ?>

	<?php endif; // ! mbs_is_pro() ?>

	<?php
	// S14-5: Book grid — ALL tiers. PRO users already see the hero partial above;
	// both tiers get the book grid. Run a fresh WP_Query for date DESC ordering.
	// SHC-6: Layout Registry renders the grid via the resolved layout object.
	if ( $author_term instanceof WP_Term ) :
		// Include private posts for users who have the capability (e.g. logged-in admins),
		// so private books like the dummy install book are visible to the site owner.
		$s14_post_statuses = current_user_can( 'read_private_posts' )
			? array( 'publish', 'private' )
			: array( 'publish' );
		$s14_author_query = new WP_Query( array(
			'post_type'      => MBS_POST_TYPE,
			'posts_per_page' => (int) mbs_get_setting( 'formatting', 'items_per_page', 6 ),
			'paged'          => max( 1, get_query_var( 'paged' ) ),
			'post_status'    => $s14_post_statuses,
			'no_found_rows'  => false,
			'orderby'        => 'date',
			'order'          => 'DESC',
			'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_term->term_id,
				),
			),
		) );
		echo $layout_obj->render( $s14_author_query ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted renderer returns pre-escaped HTML
		if ( $s14_author_query->max_num_pages > 1 ) :
			echo paginate_links( array( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted renderer returns pre-escaped HTML
				'total'   => $s14_author_query->max_num_pages,
				'current' => max( 1, get_query_var( 'paged' ) ),
			) );
		endif;
	else :
		// Fallback: no queried term — use the global WP loop.
		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();
		endif;
	endif;
	?>

</div>

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