<?php
/**
 * File Path: templates/partials/section-amazon-reviews.php
 *
 * My Book Showroom — Amazon Reviews Section (PRO)
 *
 * Renders imported Amazon reviews from PA-API.
 *
 * Sprint Step 7: format-aware. One panel per format row that has an ASIN.
 * Reviews are keyed by ASIN: get_post_meta( $post_id, 'mbs_amazon_reviews_{asin}', true )
 * with a fallback to the legacy single-key 'mbs_amazon_reviews' postmeta.
 *
 * JS in mbs-format-tabs.js listens for the 'mbs:format:changed' event and
 * calls MBS.AmazonReviews.switchFormat( format_row_id ) to show/hide panels.
 * The entire section wrapper is hidden (display:none) when the active format
 * has no ASIN or no imported reviews — per GP-UI-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() || ! mbs_is_pro() ) {
	MBS_Pro_Gate::comment( 'Amazon reviews section' );
	return;
}

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

$format_rows = MBS_Format_Row_DAO::get_by_post( $post_id );

// Build an array of panels: each format row with a non-empty ASIN gets its own panel.
// Reviews are loaded from per-ASIN postmeta or the legacy single-key blob.
$panels = array();

if ( ! empty( $format_rows ) ) {
	foreach ( $format_rows as $row ) {
		$asin = sanitize_text_field( $row->asin ?? '' );
		if ( ! $asin ) {
			continue;
		}

		// Per-ASIN postmeta (set by PA-API importer when multi-format support is active).
		$meta_key     = 'mbs_amazon_reviews_' . sanitize_key( $asin );
		$review_data  = get_post_meta( $post_id, $meta_key, true );

		// Legacy fallback: single-key blob, only used when the ASIN matches.
		if ( empty( $review_data ) ) {
			$legacy = get_post_meta( $post_id, 'mbs_amazon_reviews', true );
			if ( ! empty( $legacy ) && ( $legacy['asin'] ?? '' ) === $asin ) {
				$review_data = $legacy;
			}
		}

		if ( empty( $review_data ) || empty( $review_data['reviews'] ) ) {
			continue;
		}

		$panels[] = array(
			'format_row_id' => (int) $row->id,
			'asin'          => $asin,
			'data'          => $review_data,
		);
	}
}

// Fallback: if no format rows have ASINs but the legacy meta exists, render it
// without a format_row_id (book-level, always visible).
if ( empty( $panels ) && empty( $format_rows ) ) {
	$legacy = get_post_meta( $post_id, 'mbs_amazon_reviews', true );
	if ( ! empty( $legacy ) && ! empty( $legacy['reviews'] ) ) {
		$panels[] = array(
			'format_row_id' => 0, // book-level; JS never hides this
			'asin'          => sanitize_text_field( $legacy['asin'] ?? '' ),
			'data'          => $legacy,
		);
	}
}

if ( empty( $panels ) ) {
	return; // GP-UI-1: no element when there's nothing to show.
}

// Determine the first format_row_id to show on initial load.
$first_format_row_id = $panels[0]['format_row_id'];

?>
<div class="mbs-wrapper mbs-section mbs-section-amazon-reviews" id="mbs-amazon-reviews-section">
	<h2><?php esc_html_e( 'Amazon Reviews', 'my-book-showroom' ); ?></h2>

	<?php foreach ( $panels as $panel ) :
		$review_data   = $panel['data'];
		$reviews       = $review_data['reviews'] ?? array();
		$total         = $review_data['total_on_amazon'] ?? count( $reviews );
		$asin          = $panel['asin'];
		$format_row_id = $panel['format_row_id'];

		// First panel is visible; remaining are hidden until JS switches format.
		$panel_display = ( $format_row_id === $first_format_row_id ) ? '' : ' style="display:none;"';
	?>
	<div class="mbs-amazon-reviews-panel"
	     data-format-row-id="<?php echo esc_attr( $format_row_id ); ?>"
	     data-asin="<?php echo esc_attr( $asin ); ?>"<?php echo $panel_display;  // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $panel_display is a static string or esc_attr output ?>>

		<?php if ( ! empty( $reviews ) ) : ?>
		<div class="mbs-amazon-review-list">
			<?php foreach ( $reviews as $review ) : ?>
			<div class="mbs-amazon-review">
				<?php
				if ( class_exists( 'MBS_Star_Rating' ) ) {
					echo MBS_Star_Rating::render_read_only( (float) $review['rating'], null ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- MBS_Star_Rating::render_read_only returns escaped HTML
				} else {
					echo esc_html( number_format( (float) $review['rating'], 1 ) ) . ' &#9733;';
				}
				?>
				<?php if ( ! empty( $review['title'] ) ) : ?>
				<h4 class="mbs-review-title"><?php echo esc_html( $review['title'] ); ?></h4>
				<?php endif; ?>
				<div class="mbs-review-text">
					<?php echo wp_kses_post( $review['body'] ); ?>
				</div>
				<div class="mbs-review-meta">
					<span class="mbs-review-author"><?php echo esc_html( $review['reviewer_name'] ?? __( 'Amazon Customer', 'my-book-showroom' ) ); ?></span>
					<span class="mbs-review-date"><?php echo esc_html( $review['date'] ?? '' ); ?></span>
					<?php if ( ! empty( $review['verified'] ) ) : ?>
					<span class="mbs-verified">&#10003; <?php esc_html_e( 'Verified Purchase', 'my-book-showroom' ); ?></span>
					<?php endif; ?>
				</div>
			</div>
			<?php endforeach; ?>
		</div>

		<p class="mbs-amazon-footer">
			<?php
			printf(
				/* translators: 1: number of reviews shown, 2: total reviews on Amazon */
				esc_html__( 'Showing %1$d of %2$d reviews', 'my-book-showroom' ),
				count( $reviews ),
				absint( $total )
			);
			?>
			—
			<a href="<?php echo esc_url( 'https://amazon.com/dp/' . rawurlencode( $asin ) . '#customerReviews' ); ?>"
			   target="_blank" rel="noopener noreferrer">
				<?php esc_html_e( 'Read all on Amazon →', 'my-book-showroom' ); ?>
			</a>
		</p>
		<?php endif; ?>

	</div>
	<?php endforeach; ?>

</div>
