<?php
/**
 * Product Comparison Widget — Render Functions
 *
 * Standalone functions prefixed ggmc_product_comparison_ used by the widget class.
 *
 * @package GGM_Commerce
 */

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

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

	// Get comparison instance
	$comparison = GGM_Commerce_Product_Comparison::instance();
	$items      = $comparison->get_items();
	$count      = $comparison->get_count();

	// Get available fields based on activated premium components
	$available_fields = $comparison->get_available_fields();

	// Get currency settings
	$currency_options  = get_option( 'ggm_commerce_currency_options', array() );
	$currency_symbol   = isset( $currency_options['symbol'] ) ? $currency_options['symbol'] : '£';
	$currency_position = isset( $currency_options['position'] ) ? $currency_options['position'] : 'before';

	$sticky_class = 'yes' === $settings['sticky_first_column'] ? ' sticky-labels' : '';

	?>
	<div class="ggmc-comparison-wrapper<?php echo esc_attr( $sticky_class ); ?>">
		<?php if ( 'yes' === $settings['show_title'] && ! empty( $settings['title'] ) ) : ?>
			<h2 class="ggmc-comparison-title"><?php echo esc_html( $settings['title'] ); ?>
				<span class="ggmc-comparison-count">(<?php echo esc_html( $count ); ?>)</span>
			</h2>
		<?php endif; ?>

		<?php if ( empty( $items ) ) : ?>
			<div class="ggmc-comparison-empty">
				<div class="ggmc-comparison-empty-icon">
					<?php
					if ( ! empty( $settings['empty_state_icon']['value'] ) ) {
						ggmc_render_icon( $settings['empty_state_icon'], array( 'aria-hidden' => 'true' ) );
					} else {
						echo '<i class="eicon-exchange"></i>';
					}
					?>
				</div>
				<p class="ggmc-comparison-empty-message"><?php echo esc_html( $settings['empty_message'] ); ?></p>
				<?php if ( 'yes' === $settings['show_add_products_cta'] ) : ?>
					<?php
					$shop_url = ! empty( $settings['add_products_url']['url'] )
						? $settings['add_products_url']['url']
						: home_url( '/shop/' );
					?>
					<a href="<?php echo esc_url( $shop_url ); ?>" class="ggmc-comparison-cta-btn">
						<?php echo esc_html( $settings['add_products_text'] ); ?>
					</a>
				<?php endif; ?>
			</div>
		<?php else : ?>
			<?php if ( 'yes' === $settings['show_clear_all'] ) : ?>
				<div class="ggmc-comparison-actions">
					<button type="button" class="ggmc-compare-clear-btn">
						<i class="eicon-trash-o"></i> <?php esc_html_e( 'Clear All', 'ggm-commerce' ); ?>
					</button>
				</div>
			<?php endif; ?>

			<?php ggmc_product_comparison_render_comparison_table( $items, $settings, $available_fields ); ?>

			<?php if ( 'yes' === $settings['show_add_products_cta'] && $count < GGM_Commerce_Product_Comparison::get_max_products() ) : ?>
				<div class="ggmc-comparison-add-more">
					<?php
					$shop_url = ! empty( $settings['add_products_url']['url'] )
						? $settings['add_products_url']['url']
						: home_url( '/shop/' );
					?>
					<a href="<?php echo esc_url( $shop_url ); ?>" class="ggmc-comparison-add-more-btn">
						<?php
						if ( ! empty( $settings['add_more_icon']['value'] ) ) {
							ggmc_render_icon( $settings['add_more_icon'], array( 'aria-hidden' => 'true' ) );
						} else {
							echo '<i class="eicon-plus-circle"></i>';
						}
						?>
						<?php esc_html_e( 'Add More Products', 'ggm-commerce' ); ?>
					</a>
				</div>
			<?php endif; ?>
		<?php endif; ?>
	</div>
	<?php
}

/**
 * Render comparison table.
 *
 * @param array $items            Comparison items (product objects).
 * @param array $settings         Widget settings.
 * @param array $available_fields Available comparison fields.
 */
function ggmc_product_comparison_render_comparison_table( $items, $settings, $available_fields ) {
	$tax = ggm_commerce_tax();
	?>
	<div class="ggmc-comparison-table-wrapper">
		<table class="ggmc-comparison-table">
			<thead>
				<tr>
					<th class="field-label"></th>
					<?php foreach ( $items as $product ) : ?>
						<th class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
							<?php if ( 'yes' === $settings['show_remove_button'] ) : ?>
								<button type="button" class="ggmc-comparison-remove-btn ggmc-remove-from-compare"
									data-product-id="<?php echo esc_attr( $product->id ); ?>"
									title="<?php esc_attr_e( 'Remove from comparison', 'ggm-commerce' ); ?>">
									<i class="eicon-close"></i>
								</button>
							<?php endif; ?>
						</th>
					<?php endforeach; ?>
				</tr>
			</thead>
			<tbody>
				<?php
				// Image row
				if ( 'yes' === $settings['show_image'] ) :
					?>
					<tr class="comparison-row-image">
						<td class="field-label"><?php esc_html_e( 'Image', 'ggm-commerce' ); ?></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<div class="ggmc-comparison-image">
									<?php if ( ! empty( $product->image_url ) ) : ?>
										<img src="<?php echo esc_url( $product->image_url ); ?>"
											alt="<?php echo esc_attr( $product->name ); ?>">
									<?php else : ?>
										<div class="ggmc-no-image"><i class="eicon-image-bold"></i></div>
									<?php endif; ?>
								</div>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>

				<?php
				// Name row
				if ( 'yes' === $settings['show_name'] ) :
					?>
					<tr class="comparison-row-name">
						<td class="field-label"><?php esc_html_e( 'Product', 'ggm-commerce' ); ?></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<div class="ggmc-comparison-product-name">
									<a href="<?php echo esc_url( GGM_Commerce_Helpers::get_product_details_url( $product->id ) ); ?>">
										<?php echo esc_html( $product->name ); ?>
									</a>
								</div>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>

				<?php
				// Price row
				if ( 'yes' === $settings['show_price'] ) :
					?>
					<tr class="comparison-row-price">
						<td class="field-label"><?php esc_html_e( 'Price', 'ggm-commerce' ); ?></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<div class="ggmc-comparison-price">
									<?php if ( ! empty( $product->sale_price ) && $product->sale_price < $product->price ) : ?>
										<span class="sale-price"><?php echo esc_html( $tax->format_price( $product->sale_price ) ); ?></span>
										<span class="original-price"><?php echo esc_html( $tax->format_price( $product->price ) ); ?></span>
									<?php else : ?>
										<span class="current-price"><?php echo esc_html( $tax->format_price( $product->price ) ); ?></span>
									<?php endif; ?>
								</div>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>

				<?php
				// Stock row
				if ( 'yes' === $settings['show_stock'] ) :
					?>
					<tr class="comparison-row-stock">
						<td class="field-label"><?php esc_html_e( 'Availability', 'ggm-commerce' ); ?></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<?php ggmc_product_comparison_render_stock_status( $product ); ?>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>

				<?php
				// SKU row
				if ( 'yes' === $settings['show_sku'] ) :
					?>
					<tr class="comparison-row-sku">
						<td class="field-label"><?php esc_html_e( 'SKU', 'ggm-commerce' ); ?></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<?php echo esc_html( $product->sku ?? '-' ); ?>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>

				<?php
				// Description row
				if ( 'yes' === $settings['show_description'] ) :
					?>
					<tr class="comparison-row-description">
						<td class="field-label"><?php esc_html_e( 'Description', 'ggm-commerce' ); ?></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<div class="ggmc-comparison-description">
									<?php echo esc_html( wp_trim_words( $product->short_description ?? '', 20 ) ); ?>
								</div>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>

				<?php
				// Categories row
				if ( 'yes' === $settings['show_categories'] ) :
					?>
					<tr class="comparison-row-categories">
						<td class="field-label"><?php esc_html_e( 'Categories', 'ggm-commerce' ); ?></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<?php
								$cats = isset( $product->categories ) ? $product->categories : array();
								if ( ! empty( $cats ) ) {
									// Categories are already an array of strings (names)
									echo esc_html( implode( ', ', $cats ) );
								} else {
									echo '-';
								}
								?>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>

				<?php
				// Tags row
				if ( 'yes' === $settings['show_tags'] ) :
					?>
					<tr class="comparison-row-tags">
						<td class="field-label"><?php esc_html_e( 'Tags', 'ggm-commerce' ); ?></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<?php
								$tags = isset( $product->tags ) ? $product->tags : array();
								if ( ! empty( $tags ) ) {
									// Tags are already an array of strings (names)
									echo esc_html( implode( ', ', $tags ) );
								} else {
									echo '-';
								}
								?>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>

				<?php
				// Rating row
				if ( 'yes' === $settings['show_rating'] ) :
					?>
					<tr class="comparison-row-rating">
						<td class="field-label"><?php esc_html_e( 'Rating', 'ggm-commerce' ); ?></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<?php ggmc_product_comparison_render_rating( $product ); ?>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>

				<?php
				// Weight row
				if ( 'yes' === $settings['show_weight'] ) :
					?>
					<tr class="comparison-row-weight">
						<td class="field-label"><?php esc_html_e( 'Weight', 'ggm-commerce' ); ?></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<?php
								if ( ! empty( $product->weight ) ) {
									echo esc_html( $product->weight . ' ' . get_option( 'ggm_commerce_weight_unit', 'kg' ) );
								} else {
									echo '-';
								}
								?>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>

				<?php
				// Dimensions row
				if ( 'yes' === $settings['show_dimensions'] ) :
					?>
					<tr class="comparison-row-dimensions">
						<td class="field-label"><?php esc_html_e( 'Dimensions', 'ggm-commerce' ); ?></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<?php
								$dims = array();
								if ( ! empty( $product->length ) ) {
									$dims[] = $product->length;
								}
								if ( ! empty( $product->width ) ) {
									$dims[] = $product->width;
								}
								if ( ! empty( $product->height ) ) {
									$dims[] = $product->height;
								}
								if ( ! empty( $dims ) ) {
									$unit = get_option( 'ggm_commerce_dimension_unit', 'cm' );
									echo esc_html( implode( ' x ', $dims ) . ' ' . $unit );
								} else {
									echo '-';
								}
								?>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>

				<?php
				// Custom Attributes rows (premium field) - each attribute as its own row
				if ( 'yes' === $settings['show_custom_attributes'] && isset( $available_fields['custom_attributes'] ) ) :
					$show_icon = 'yes' === $settings['show_attribute_icon'];
					$show_unit = 'yes' === $settings['show_attribute_unit'];

					// Collect all unique attributes (with icon and unit) across all products
					$all_attributes = array();
					foreach ( $items as $product ) {
						$custom_attrs = isset( $product->custom_attributes ) ? $product->custom_attributes : array();
						foreach ( $custom_attrs as $attr ) {
							if ( ! isset( $all_attributes[ $attr->name ] ) ) {
								$all_attributes[ $attr->name ] = array(
									'name' => $attr->name,
									'icon' => $attr->icon ?? '',
									'unit' => $attr->unit ?? '',
								);
							}
						}
					}

					// Create a row for each unique attribute
					foreach ( $all_attributes as $attr_data ) :
						$attr_name = $attr_data['name'];
						$attr_icon = $attr_data['icon'];
						$attr_unit = $attr_data['unit'];

						// Parse icon (may be JSON or legacy class string)
						$icon_data = null;
						$has_icon  = $show_icon && ! empty( $attr_icon );
						if ( $has_icon ) {
							$icon_data = json_decode( $attr_icon, true );
							// If not JSON, treat as legacy class string
							if ( ! is_array( $icon_data ) && ! empty( $attr_icon ) ) {
								$icon_data = array(
									'value'   => $attr_icon,
									'library' => 'fa-solid',
								);
							}
							// Validate we have a value
							if ( empty( $icon_data['value'] ) ) {
								$has_icon  = false;
								$icon_data = null;
							}
						}
						?>
						<tr class="ggmc-comparison-row-custom-attribute">
							<td class="field-label">
								<span class="ggmc-attr-name">
									<?php if ( $has_icon && $icon_data ) : ?>
										<span class="ggmc-attr-icon"><?php ggmc_render_icon( $icon_data, array( 'aria-hidden' => 'true' ) ); ?></span>
									<?php endif; ?>
									<?php echo esc_html( $attr_name ); ?>
								</span>
								<?php if ( $show_unit && ! empty( $attr_unit ) ) : ?>
									<span class="ggmc-attr-unit">(<?php echo esc_html( $attr_unit ); ?>)</span>
								<?php endif; ?>
							</td>
							<?php foreach ( $items as $product ) : ?>
								<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
									<?php
									$custom_attrs = isset( $product->custom_attributes ) ? $product->custom_attributes : array();
									$attr_value   = '-';
									$value_unit   = '';
									foreach ( $custom_attrs as $attr ) {
										if ( $attr->name === $attr_name ) {
											$attr_value = $attr->attribute_value ?? $attr->value ?? '-';
											$value_unit = $attr->unit ?? '';
											break;
										}
									}
									echo esc_html( $attr_value );
									// Show unit after value if enabled and unit exists
									if ( $show_unit && ! empty( $value_unit ) && '-' !== $attr_value ) {
										echo ' <span class="ggmc-attr-unit">' . esc_html( $value_unit ) . '</span>';
									}
									?>
								</td>
							<?php endforeach; ?>
						</tr>
					<?php endforeach; ?>
				<?php endif; ?>

				<?php
				// Barcode row (premium field)
				if ( 'yes' === $settings['show_barcode'] && isset( $available_fields['barcode'] ) ) :
					?>
					<tr class="comparison-row-barcode">
						<td class="field-label"><?php esc_html_e( 'Barcode', 'ggm-commerce' ); ?></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<?php echo esc_html( $product->barcode ?? '-' ); ?>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>

				<?php
				// Kit Contents row (premium field)
				if ( 'yes' === $settings['show_kit_contents'] && isset( $available_fields['kit_contents'] ) ) :
					// Check if any product has kit components
					$has_kit_products = false;
					foreach ( $items as $product ) {
						if ( ! empty( $product->kit_components ) ) {
							$has_kit_products = true;
							break;
						}
					}

					if ( $has_kit_products ) :
						?>
						<tr class="comparison-row-kit-contents">
							<td class="field-label"><?php esc_html_e( 'Kit Contents', 'ggm-commerce' ); ?></td>
							<?php foreach ( $items as $product ) : ?>
								<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
									<?php
									$kit_components = isset( $product->kit_components ) ? $product->kit_components : array();
									if ( ! empty( $kit_components ) ) {
										echo '<ul class="ggmc-kit-contents-list">';
										foreach ( $kit_components as $component ) {
											$qty  = isset( $component->quantity ) ? intval( $component->quantity ) : 1;
											$name = isset( $component->product_name ) ? $component->product_name : __( 'Unknown', 'ggm-commerce' );
											echo '<li>';
											if ( $qty > 1 ) {
												echo esc_html( $qty . '× ' . $name );
											} else {
												echo esc_html( $name );
											}
											echo '</li>';
										}
										echo '</ul>';
									} else {
										echo '-';
									}
									?>
								</td>
							<?php endforeach; ?>
						</tr>
					<?php endif; ?>
				<?php endif; ?>

				<?php
				// Add to Cart row
				if ( 'yes' === $settings['show_add_to_cart'] ) :
					?>
					<tr class="comparison-row-add-to-cart">
						<td class="field-label"></td>
						<?php foreach ( $items as $product ) : ?>
							<td class="ggmc-compare-product" data-product-id="<?php echo esc_attr( $product->id ); ?>">
								<button type="button" class="ggmc-comparison-add-to-cart ggmc-add-to-cart-btn"
									data-product-id="<?php echo esc_attr( $product->id ); ?>"
									<?php echo ( isset( $product->stock ) && $product->stock <= 0 ) ? 'disabled' : ''; ?>>
									<?php
									if ( ! empty( $settings['add_to_cart_icon']['value'] ) ) {
										ggmc_render_icon( $settings['add_to_cart_icon'], array( 'aria-hidden' => 'true' ) );
									} else {
										echo '<i class="fas fa-shopping-cart"></i>';
									}
									?>
									<?php esc_html_e( 'Add to Cart', 'ggm-commerce' ); ?>
								</button>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endif; ?>
			</tbody>
		</table>
	</div>
	<?php
}

/**
 * Render stock status for a product.
 *
 * @param object $product Product object.
 */
function ggmc_product_comparison_render_stock_status( $product ) {
	$stock = isset( $product->stock ) ? intval( $product->stock ) : 0;

	if ( $stock > 10 ) {
		$status_class = 'in-stock';
		$status_text  = __( 'In Stock', 'ggm-commerce' );
	} elseif ( $stock > 0 ) {
		$status_class = 'low-stock';
		/* translators: %d: stock quantity */
		$status_text = sprintf( __( 'Low Stock (%d)', 'ggm-commerce' ), $stock );
	} else {
		$status_class = 'out-of-stock';
		$status_text  = __( 'Out of Stock', 'ggm-commerce' );
	}

	echo '<span class="ggmc-stock-status ' . esc_attr( $status_class ) . '">' . esc_html( $status_text ) . '</span>';
}

/**
 * Render product rating stars and value.
 *
 * @param object $product Product object.
 */
function ggmc_product_comparison_render_rating( $product ) {
	$rating       = isset( $product->average_rating ) ? floatval( $product->average_rating ) : 0;
	$rating_count = isset( $product->rating_count ) ? intval( $product->rating_count ) : 0;

	echo '<div class="ggmc-comparison-rating">';
	echo '<div class="rating-stars">';

	for ( $i = 1; $i <= 5; $i++ ) {
		if ( $i <= floor( $rating ) ) {
			echo '<span class="star filled"><i class="eicon-star"></i></span>';
		} elseif ( $i - 0.5 <= $rating ) {
			echo '<span class="star half"><i class="eicon-star-half"></i></span>';
		} else {
			echo '<span class="star empty"><i class="eicon-star-o"></i></span>';
		}
	}

	echo '</div>';

	if ( $rating > 0 ) {
		echo '<span class="rating-value">' . esc_html( number_format( $rating, 1 ) );
		if ( $rating_count > 0 ) {
			echo ' <span class="rating-count">(' . esc_html( $rating_count ) . ')</span>';
		}
		echo '</span>';
	} else {
		echo '<span class="rating-value no-rating">' . esc_html__( 'No reviews', 'ggm-commerce' ) . '</span>';
	}

	echo '</div>';
}
