<?php
/**
 * Review List Widget - Render Functions
 *
 * @package GGM_Commerce
 */

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

/**
 * Render the premium widget content.
 *
 * @param GGM_Commerce_Widget_Review_List $widget Widget instance.
 */
function ggmc_review_list_render_premium_content( $widget ) {
	$settings = $widget->get_settings_for_display();

	// Get product data.
	$product_data = $widget->get_product_data();
	$product_id   = $product_data ? $product_data->id : 0;

	// Get reviews.
	$reviews             = array();
	$total_reviews       = 0;
	$average_rating      = 0;
	$rating_distribution = array( 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0 );

	if ( $product_id && class_exists( 'GGM_Commerce_Reviews' ) ) {
		$reviews             = GGM_Commerce_Reviews::get_product_reviews(
			$product_id,
			array(
				'limit'   => (int) $settings['reviews_per_page'],
				'orderby' => $settings['orderby'],
				'order'   => $settings['order'],
			)
		);
		$total_reviews       = GGM_Commerce_Reviews::get_product_review_count( $product_id );
		$rating_distribution = GGM_Commerce_Reviews::get_rating_distribution( $product_id );
		$average_rating      = $product_data->average_rating ?? 0;
	}

	// In editor mode, show placeholder data.
	if ( ggmc_is_editor_mode() && empty( $reviews ) ) {
		$reviews             = ggmc_review_list_get_placeholder_reviews();
		$total_reviews       = 3;
		$average_rating      = 4.3;
		$rating_distribution = array( 1 => 0, 2 => 1, 3 => 2, 4 => 5, 5 => 12 );
	}

	// Start output.
	echo '<div class="ggmc-reviews-section" id="product-reviews">';

	// Section title.
	if ( 'yes' === $settings['show_title'] ) {
		$title_tag = $settings['title_html_tag'] ?? 'h3';
		echo '<' . esc_attr( $title_tag ) . ' class="ggmc-reviews-title">' . esc_html( $settings['section_title'] ) . '</' . esc_attr( $title_tag ) . '>';
	}

	// Rating summary.
	if ( 'yes' === $settings['show_summary'] && $total_reviews > 0 ) {
		ggmc_review_list_render_rating_summary( $average_rating, $total_reviews, $rating_distribution );
	}

	// Reviews list.
	if ( ! empty( $reviews ) ) {
		echo '<div class="ggmc-reviews-list">';
		foreach ( $reviews as $review ) {
			ggmc_review_list_render_review_card( $review, $settings );
		}
		echo '</div>';

		// Pagination.
		if ( 'yes' === $settings['show_pagination'] && $total_reviews > count( $reviews ) ) {
			echo '<div class="ggmc-reviews-pagination">';
			echo '<button class="ggmc-load-more-reviews" data-product-id="' . esc_attr( $product_id ) . '" data-offset="' . esc_attr( count( $reviews ) ) . '">';
			echo esc_html__( 'Load More Reviews', 'ggm-commerce' );
			echo '</button>';
			echo '</div>';
		}
	} else {
		echo '<div class="ggmc-no-reviews">';
		echo '<p>' . esc_html( $settings['no_reviews_text'] ) . '</p>';
		echo '</div>';
	}

	echo '</div>';

	// Add JavaScript for Helpful button and Load More.
	ggmc_review_list_render_reviews_script( $product_id, $settings );
}

/**
 * Render JavaScript for review interactions.
 *
 * @param int   $product_id Widget product ID.
 * @param array $settings   Widget settings.
 */
function ggmc_review_list_render_reviews_script( $product_id, $settings ) {
	?>
	<script>
	(function($) {
		$(document).ready(function() {
			var $wrapper = $('#product-reviews');

			// Helpful button click handler
			$wrapper.on('click', '.ggmc-helpful-btn', function(e) {
				e.preventDefault();
				var $btn = $(this);
				var reviewId = $btn.data('review-id');

				if ($btn.hasClass('voted') || $btn.prop('disabled')) {
					return;
				}

				$btn.prop('disabled', true);

				$.ajax({
					url: '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>',
					type: 'POST',
					data: {
						action: 'ggmc_vote_review_helpful',
						review_id: reviewId,
						nonce: '<?php echo esc_js( wp_create_nonce( 'ggmc_vote_helpful' ) ); ?>'
					},
					success: function(response) {
						if (response.success) {
							$btn.addClass('voted');
							var $count = $btn.find('.ggmc-helpful-count');
							if ($count.length) {
								$count.text('(' + response.data.helpful_votes + ')');
							} else {
								$btn.append(' <span class="ggmc-helpful-count">(' + response.data.helpful_votes + ')</span>');
							}
							$btn.find('.ggmc-helpful-text').text('Thanks!');
						} else {
							var msg = response.data && response.data.message ? response.data.message : 'Could not record vote.';
							alert(msg);
						}
					},
					error: function() {
						alert('An error occurred. Please try again.');
					},
					complete: function() {
						$btn.prop('disabled', false);
					}
				});
			});

			// Load More button click handler
			$wrapper.on('click', '.ggmc-load-more-reviews', function(e) {
				e.preventDefault();
				var $btn = $(this);
				var productId = $btn.data('product-id');
				var offset = $btn.data('offset');

				if ($btn.prop('disabled')) {
					return;
				}

				var originalText = $btn.text();
				$btn.prop('disabled', true).text('Loading...');

				$.ajax({
					url: '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>',
					type: 'POST',
					data: {
						action: 'ggmc_load_more_reviews',
						product_id: productId,
						offset: offset,
						limit: <?php echo absint( $settings['reviews_per_page'] ?? 5 ); ?>,
						nonce: '<?php echo esc_js( wp_create_nonce( 'ggmc_load_reviews' ) ); ?>'
					},
					success: function(response) {
						if (response.success && response.data.html) {
							$wrapper.find('.ggmc-reviews-list').append(response.data.html);
							$btn.data('offset', offset + response.data.count);

							if (!response.data.has_more) {
								$btn.parent().remove();
							} else {
								$btn.text(originalText);
							}
						} else {
							$btn.text(originalText);
						}
					},
					error: function() {
						$btn.text(originalText);
					},
					complete: function() {
						$btn.prop('disabled', false);
					}
				});
			});
		});
	})(jQuery);
	</script>
	<?php
}

/**
 * Render rating summary with distribution bars.
 *
 * @param float $average      Average rating.
 * @param int   $total        Total number of reviews.
 * @param array $distribution Rating distribution counts keyed by star value (1–5).
 */
function ggmc_review_list_render_rating_summary( $average, $total, $distribution ) {
	echo '<div class="ggmc-rating-summary">';

	// Left side - average rating.
	echo '<div class="ggmc-summary-average">';
	echo '<div class="ggmc-average-number">' . esc_html( number_format( $average, 1 ) ) . '</div>';
	// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_stars() returns pre-escaped HTML
	echo '<div class="ggmc-average-stars">' . GGM_Commerce_Reviews::render_stars( $average ) . '</div>';
	/* translators: %d: number of reviews */
	echo '<div class="ggmc-total-reviews">' . esc_html( sprintf( _n( '%d review', '%d reviews', $total, 'ggm-commerce' ), $total ) ) . '</div>';
	echo '</div>';

	// Right side - distribution bars with percentages.
	echo '<div class="ggmc-summary-distribution">';
	for ( $i = 5; $i >= 1; $i-- ) {
		$count      = isset( $distribution[ $i ] ) ? $distribution[ $i ] : 0;
		$percentage = $total > 0 ? round( ( $count / $total ) * 100 ) : 0;
		echo '<div class="ggmc-distribution-row">';
		echo '<span class="ggmc-distribution-label">' . esc_html( $i ) . ' star</span>';
		echo '<div class="ggmc-distribution-bar"><div class="ggmc-distribution-fill" style="width: ' . esc_attr( $percentage ) . '%"></div></div>';
		echo '<span class="ggmc-distribution-count">' . esc_html( $percentage ) . '%</span>';
		echo '</div>';
	}
	echo '</div>';

	echo '</div>';
}

/**
 * Render an individual review card.
 *
 * @param object|array $review   Review data object or array.
 * @param array        $settings Widget settings.
 */
function ggmc_review_list_render_review_card( $review, $settings ) {
	$is_object = is_object( $review );

	echo '<div class="ggmc-review-card">';

	// Header row.
	echo '<div class="ggmc-review-header">';

	// Stars.
	$rating = $is_object ? $review->rating : $review['rating'];
	// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_stars() returns pre-escaped HTML
	echo '<div class="ggmc-review-stars">' . GGM_Commerce_Reviews::render_stars( $rating, false ) . '</div>';

	// Verified badge.
	if ( 'yes' === $settings['show_verified_badge'] ) {
		$verified = $is_object ? $review->verified_purchase : ( $review['verified_purchase'] ?? false );
		if ( $verified ) {
			echo '<span class="ggmc-verified-badge">Verified Purchase</span>';
		}
	}

	echo '</div>';

	// Review title (if exists and enabled).
	$show_review_title = $settings['show_review_title'] ?? 'yes';
	$title             = $is_object ? ( $review->title ?? '' ) : ( $review['title'] ?? '' );
	if ( 'yes' === $show_review_title && ! empty( $title ) ) {
		$review_title_tag = $settings['review_title_html_tag'] ?? 'h4';
		echo '<' . esc_attr( $review_title_tag ) . ' class="ggmc-review-title">' . esc_html( $title ) . '</' . esc_attr( $review_title_tag ) . '>';
	}

	// Review content.
	$content = $is_object ? $review->content : $review['content'];
	echo '<div class="ggmc-review-content">' . esc_html( $content ) . '</div>';

	// Footer row.
	echo '<div class="ggmc-review-footer">';

	// Reviewer info.
	echo '<div class="ggmc-reviewer-info">';
	if ( 'yes' === $settings['show_reviewer_name'] ) {
		$name = $is_object ? $review->author_name : $review['author_name'];
		echo '<span class="ggmc-reviewer-name">' . esc_html( $name ) . '</span>';
	}
	if ( 'yes' === $settings['show_date'] ) {
		$date = $is_object ? $review->created_at : $review['created_at'];
		echo '<span class="ggmc-review-date">' . esc_html( date_i18n( get_option( 'date_format' ), strtotime( $date ) ) ) . '</span>';
	}
	echo '</div>';

	// Helpful button.
	if ( 'yes' === $settings['show_helpful'] ) {
		$review_id    = $is_object ? $review->id : $review['id'];
		$helpful_count = $is_object ? ( $review->helpful_votes ?? 0 ) : ( $review['helpful_votes'] ?? 0 );
		echo '<div class="ggmc-helpful-section">';
		echo '<button class="ggmc-helpful-btn" data-review-id="' . esc_attr( $review_id ) . '">';
		echo '<span class="ggmc-helpful-icon">&#128077;</span> ';
		echo '<span class="ggmc-helpful-text">Helpful</span>';
		if ( $helpful_count > 0 ) {
			echo ' <span class="ggmc-helpful-count">(' . esc_html( $helpful_count ) . ')</span>';
		}
		echo '</button>';
		echo '</div>';
	}

	echo '</div>'; // footer
	echo '</div>'; // card
}

/**
 * Get placeholder reviews for editor preview.
 *
 * @return array Array of placeholder review data.
 */
function ggmc_review_list_get_placeholder_reviews() {
	return array(
		array(
			'id'                => 1,
			'rating'            => 5,
			'title'             => 'Excellent product!',
			'content'           => 'This product exceeded my expectations. The quality is outstanding and it arrived quickly. Highly recommend!',
			'author_name'       => 'John D.',
			'created_at'        => gmdate( 'Y-m-d H:i:s', strtotime( '-2 days' ) ),
			'verified_purchase' => true,
			'helpful_votes'     => 12,
		),
		array(
			'id'                => 2,
			'rating'            => 4,
			'title'             => 'Great value for money',
			'content'           => 'Very satisfied with this purchase. Good quality and reasonable price. Would buy again.',
			'author_name'       => 'Sarah M.',
			'created_at'        => gmdate( 'Y-m-d H:i:s', strtotime( '-1 week' ) ),
			'verified_purchase' => true,
			'helpful_votes'     => 8,
		),
		array(
			'id'                => 3,
			'rating'            => 4,
			'title'             => 'Good product',
			'content'           => 'Nice product overall. Delivery was a bit slow but the product itself is great.',
			'author_name'       => 'Mike R.',
			'created_at'        => gmdate( 'Y-m-d H:i:s', strtotime( '-2 weeks' ) ),
			'verified_purchase' => false,
			'helpful_votes'     => 3,
		),
	);
}
