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

/**
 * Main render entry point for the Product Image widget.
 *
 * @param \GGM_Commerce_Base_Widget|GGMC_Block_Adapter $widget The widget instance.
 */
function ggmc_product_image_render( $widget ) {
	// Get product data (includes preview product support)
	$product_data = $widget->get_product_data();

	// Check if we're in an editor context (Elementor or Gutenberg)
	$is_editor = ggmc_is_editor_mode();

	// Placeholder image fallback
	$placeholder = '';
	if ( class_exists( '\Elementor\Utils' ) ) {
		$placeholder = \Elementor\Utils::get_placeholder_image_src();
	}
	if ( empty( $placeholder ) ) {
		$placeholder = includes_url( 'images/blank.gif' );
	}

	if ($product_data && isset($product_data->image_id) && $product_data->image_id > 0) {
		$image_html = $widget->get_product_image_html($product_data->image_id, 'large');
		if (!empty($image_html)) {
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- get_product_image_html() returns pre-escaped HTML
			echo $image_html;
		} else {
			// Image ID exists but attachment not found
			if ($is_editor) {
				echo '<div style="padding: 20px; background: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; color: #856404;">';
				echo '<strong>Image Not Found</strong><br>';
				echo 'Product has image_id: ' . esc_html($product_data->image_id) . ' but the attachment could not be loaded.';
				echo '</div>';
			} else {
				echo '<img src="' . esc_url( $placeholder ) . '">';
			}
		}
	} else {
		// No image_id set for this product
		if ($is_editor) {
			$message = 'No product image available.';
			if ($product_data) {
				$message = 'Product "' . esc_html($product_data->name ?? 'Unknown') . '" has no image assigned (image_id: ' . ($product_data->image_id ?? '0') . ').';
			}
			echo '<div style="padding: 20px; background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 4px; color: #6c757d; text-align: center;">';
			echo '<img src="' . esc_url( $placeholder ) . '" style="max-width: 200px; opacity: 0.5; margin-bottom: 10px;"><br>';
			echo '<span style="font-style: italic;">' . esc_html($message) . '</span>';
			echo '</div>';
		} else {
			echo '<img src="' . esc_url( $placeholder ) . '">';
		}
	}
}
