<?php
/**
 * Product Image Grid — Render Functions
 * Standalone functions converted from GGM_Commerce_Product_Image_Grid_Renderer.
 * All functions are prefixed ggmc_product_image_grid_.
 *
 * @package GGM_Commerce
 */

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

/**
 * Main render entry point called from the widget's render() method.
 *
 * Resolves the product ID, fetches images via the data handler, then
 * delegates to the appropriate layout renderer.
 *
 * @param \GGM_Commerce_Base_Widget $widget The widget instance.
 */
function ggmc_product_image_grid_render( $widget ) {
	$settings = $widget->get_settings_for_display();

	$data_handler = new GGM_Commerce_Product_Gallery_Data_Handler();

	// Resolve product ID (custom or context).
	$product_id = null;
	if ( isset( $settings['product_source'] ) && 'custom' === $settings['product_source'] ) {
		$product_id = ! empty( $settings['product_id'] ) ? absint( $settings['product_id'] ) : null;
	}
	if ( empty( $product_id ) ) {
		$product_id = $data_handler->get_current_product_id();
	}

	$images = $data_handler->get_product_images( $product_id );

	if ( empty( $images ) ) {
		ggmc_product_image_grid_render_empty_state();
		return;
	}

	$layout = $settings['layout_preset'] ?? 'standard-grid';

	switch ( $layout ) {
		case 'featured-grid':
			ggmc_product_image_grid_render_featured_grid( $images, $settings );
			break;
		case 'masonry':
			ggmc_product_image_grid_render_masonry( $images, $settings );
			break;
		case 'alternating':
			ggmc_product_image_grid_render_alternating( $images, $settings );
			break;
		case 'standard-grid':
		default:
			ggmc_product_image_grid_render_standard_grid( $images, $settings );
			break;
	}

	if ( ! empty( $settings['show_lightbox'] ) && 'yes' === $settings['show_lightbox'] ) {
		ggmc_product_image_grid_render_lightbox( $images, $settings );
	}
}

/**
 * Render standard grid layout.
 *
 * @param array $images   Image objects.
 * @param array $settings Widget settings.
 */
function ggmc_product_image_grid_render_standard_grid( $images, $settings ) {
	$ratio_class   = ggmc_product_image_grid_get_ratio_class( $settings );
	$lightbox      = ggmc_product_image_grid_is_lightbox_enabled( $settings );
	$visible_count = ggmc_product_image_grid_get_visible_count( $settings, count( $images ) );
	?>
	<div class="ggmc-image-grid ggmc-image-grid--standard <?php echo esc_attr( $ratio_class ); ?>" data-lightbox="<?php echo esc_attr( $lightbox ? 'true' : 'false' ); ?>">
		<div class="ggmc-image-grid__grid">
			<?php
			foreach ( $images as $index => $image ) {
				$hidden = $visible_count > 0 && $index >= $visible_count;
				ggmc_product_image_grid_render_grid_item( $image, $index, $settings, false, $hidden );
			}
			?>
		</div>
		<?php
		$hidden_count = $visible_count > 0 ? max( 0, count( $images ) - $visible_count ) : 0;
		ggmc_product_image_grid_render_load_more( $settings, $hidden_count );
		?>
	</div>
	<?php
}

/**
 * Render featured + grid layout.
 *
 * @param array $images   Image objects.
 * @param array $settings Widget settings.
 */
function ggmc_product_image_grid_render_featured_grid( $images, $settings ) {
	$ratio_class   = ggmc_product_image_grid_get_ratio_class( $settings );
	$featured_span = $settings['featured_span'] ?? '2x2';
	$lightbox      = ggmc_product_image_grid_is_lightbox_enabled( $settings );
	$visible_count = ggmc_product_image_grid_get_visible_count( $settings, count( $images ) );
	?>
	<div class="ggmc-image-grid ggmc-image-grid--featured featured-span-<?php echo esc_attr( $featured_span ); ?> <?php echo esc_attr( $ratio_class ); ?>" data-lightbox="<?php echo esc_attr( $lightbox ? 'true' : 'false' ); ?>">
		<div class="ggmc-image-grid__grid">
			<?php
			foreach ( $images as $index => $image ) {
				$is_featured = ( 0 === $index );
				$hidden      = $visible_count > 0 && $index >= $visible_count;
				ggmc_product_image_grid_render_grid_item( $image, $index, $settings, $is_featured, $hidden );
			}
			?>
		</div>
		<?php
		$hidden_count = $visible_count > 0 ? max( 0, count( $images ) - $visible_count ) : 0;
		ggmc_product_image_grid_render_load_more( $settings, $hidden_count );
		?>
	</div>
	<?php
}

/**
 * Render masonry layout.
 *
 * @param array $images   Image objects.
 * @param array $settings Widget settings.
 */
function ggmc_product_image_grid_render_masonry( $images, $settings ) {
	$lightbox      = ggmc_product_image_grid_is_lightbox_enabled( $settings );
	$visible_count = ggmc_product_image_grid_get_visible_count( $settings, count( $images ) );
	?>
	<div class="ggmc-image-grid ggmc-image-grid--masonry" data-lightbox="<?php echo esc_attr( $lightbox ? 'true' : 'false' ); ?>">
		<div class="ggmc-image-grid__grid">
			<?php
			foreach ( $images as $index => $image ) {
				$hidden = $visible_count > 0 && $index >= $visible_count;
				ggmc_product_image_grid_render_grid_item( $image, $index, $settings, false, $hidden );
			}
			?>
		</div>
		<?php
		$hidden_count = $visible_count > 0 ? max( 0, count( $images ) - $visible_count ) : 0;
		ggmc_product_image_grid_render_load_more( $settings, $hidden_count );
		?>
	</div>
	<?php
}

/**
 * Render alternating rows layout.
 *
 * @param array $images   Image objects.
 * @param array $settings Widget settings.
 */
function ggmc_product_image_grid_render_alternating( $images, $settings ) {
	$ratio_class   = ggmc_product_image_grid_get_ratio_class( $settings );
	$lightbox      = ggmc_product_image_grid_is_lightbox_enabled( $settings );
	$primary       = max( 1, absint( $settings['alternating_primary'] ?? 3 ) );
	$secondary     = max( 1, absint( $settings['alternating_secondary'] ?? 2 ) );
	$visible_count = ggmc_product_image_grid_get_visible_count( $settings, count( $images ) );

	$total      = count( $images );
	$img_index  = 0;
	$is_primary = true;
	?>
	<div class="ggmc-image-grid ggmc-image-grid--alternating <?php echo esc_attr( $ratio_class ); ?>" data-lightbox="<?php echo esc_attr( $lightbox ? 'true' : 'false' ); ?>">
		<div class="ggmc-image-grid__grid">
			<?php
			while ( $img_index < $total ) {
				$row_count = $is_primary ? $primary : $secondary;
				$row_class = $is_primary ? 'ggmc-image-grid__row--primary' : 'ggmc-image-grid__row--secondary';
				$remaining = $total - $img_index;
				$row_count = min( $row_count, $remaining );
				$hidden    = $visible_count > 0 && $img_index >= $visible_count;
				?>
				<div class="ggmc-image-grid__row <?php echo esc_attr( $row_class ); ?><?php echo $hidden ? ' ggmc-image-grid__row--hidden' : ''; ?>" style="grid-template-columns: repeat(<?php echo esc_attr( $row_count ); ?>, 1fr);">
					<?php
					for ( $i = 0; $i < $row_count; $i++ ) {
						$item_hidden = $visible_count > 0 && $img_index >= $visible_count;
						ggmc_product_image_grid_render_grid_item( $images[ $img_index ], $img_index, $settings, false, $item_hidden );
						$img_index++;
					}
					?>
				</div>
				<?php
				$is_primary = ! $is_primary;
			}
			?>
		</div>
		<?php
		$hidden_count = $visible_count > 0 ? max( 0, $total - $visible_count ) : 0;
		ggmc_product_image_grid_render_load_more( $settings, $hidden_count );
		?>
	</div>
	<?php
}

/**
 * Calculate the maximum number of visible images based on initial_rows and columns.
 *
 * @param array  $settings Widget settings.
 * @param int    $total    Total number of images.
 * @return int Number of images to show initially (0 = show all).
 */
function ggmc_product_image_grid_get_visible_count( $settings, $total ) {
	if ( empty( $settings['enable_load_more'] ) || 'yes' !== $settings['enable_load_more'] ) {
		return 0; // Show all
	}

	$initial_rows = max( 1, absint( $settings['initial_rows'] ?? 2 ) );
	$layout       = $settings['layout_preset'] ?? 'standard-grid';

	switch ( $layout ) {
		case 'standard-grid':
		case 'featured-grid':
			$columns = absint( $settings['grid_columns'] ?? 3 );
			return $initial_rows * $columns;

		case 'masonry':
			$columns = absint( $settings['masonry_columns'] ?? 3 );
			return $initial_rows * $columns;

		case 'alternating':
			$primary   = max( 1, absint( $settings['alternating_primary'] ?? 3 ) );
			$secondary = max( 1, absint( $settings['alternating_secondary'] ?? 2 ) );
			$count     = 0;
			for ( $r = 0; $r < $initial_rows; $r++ ) {
				$count += ( $r % 2 === 0 ) ? $primary : $secondary;
			}
			return $count;

		default:
			return $initial_rows * 3;
	}
}

/**
 * Render the "Load More" link after the grid.
 *
 * @param array $settings   Widget settings.
 * @param int   $hidden_count Number of hidden images.
 */
function ggmc_product_image_grid_render_load_more( $settings, $hidden_count ) {
	if ( $hidden_count <= 0 ) {
		return;
	}

	$text = $settings['load_more_text'] ?? __( 'SEE ALL HERE', 'ggm-commerce' );
	$icon = $settings['load_more_icon'] ?? [ 'value' => 'eicon-chevron-right', 'library' => 'eicons' ];
	?>
	<a href="#" class="ggmc-image-grid__load-more" role="button">
		<span class="ggmc-load-more-text"><?php echo esc_html( $text ); ?></span>
		<?php if ( ! empty( $icon['value'] ) ) : ?>
			<span class="ggmc-load-more-icon"><?php ggmc_render_icon( $icon, [ 'aria-hidden' => 'true' ] ); ?></span>
		<?php endif; ?>
	</a>
	<?php
}

/**
 * Render a single grid item.
 *
 * @param object $image       Image object from data handler.
 * @param int    $index       Image index.
 * @param array  $settings    Widget settings.
 * @param bool   $is_featured Whether this is the featured image.
 */
function ggmc_product_image_grid_render_grid_item( $image, $index, $settings, $is_featured = false, $hidden = false ) {
	$size     = ggmc_product_image_grid_get_image_size( $settings, $is_featured );
	$src      = ggmc_product_image_grid_get_image_url( $image, $size );
	$full_url = ggmc_product_image_grid_get_image_url( $image, 'full' );
	$srcset   = ggmc_product_image_grid_get_image_srcset( $image, $size );
	$alt      = ! empty( $image->alt ) ? $image->alt : ( $image->title ?? '' );
	$lazy     = ! empty( $settings['enable_lazy_loading'] ) && 'yes' === $settings['enable_lazy_loading'];

	$item_classes = [ 'ggmc-image-grid__item' ];
	if ( $is_featured ) {
		$item_classes[] = 'ggmc-image-grid__item--featured';
	}
	if ( $hidden ) {
		$item_classes[] = 'ggmc-image-grid__item--hidden';
	}

	// Build image inline styles from controls.
	$img_styles = [];
	$image_fit  = $settings['image_fit'] ?? 'cover';
	$img_styles[] = 'object-fit: ' . esc_attr( $image_fit );

	if ( in_array( $image_fit, [ 'cover', 'contain' ], true ) ) {
		$image_position = $settings['image_position'] ?? 'center center';
		$img_styles[]   = 'object-position: ' . esc_attr( $image_position );
	}

	$img_style = implode( '; ', $img_styles ) . ';';
	?>
	<div class="<?php echo esc_attr( implode( ' ', $item_classes ) ); ?>" data-index="<?php echo esc_attr( $index ); ?>" data-full-url="<?php echo esc_url( $full_url ); ?>">
		<img
			src="<?php echo esc_url( $src ); ?>"
			<?php if ( ! empty( $srcset ) ) : ?>
				srcset="<?php echo esc_attr( $srcset ); ?>"
			<?php endif; ?>
			alt="<?php echo esc_attr( $alt ); ?>"
			style="<?php echo esc_attr( $img_style ); ?>"
			<?php if ( $lazy ) : ?>
				loading="lazy"
			<?php endif; ?>
		/>
	</div>
	<?php
}

/**
 * Render lightbox markup.
 *
 * @param array $images   Image objects.
 * @param array $settings Widget settings.
 */
function ggmc_product_image_grid_render_lightbox( $images, $settings ) {
	$total = count( $images );
	?>
	<div class="ggmc-image-grid-lightbox" style="display: none;" data-total="<?php echo esc_attr( $total ); ?>">
		<div class="ggmc-image-grid-lightbox__overlay"></div>
		<div class="ggmc-image-grid-lightbox__container">
			<button class="ggmc-image-grid-lightbox__close" aria-label="<?php esc_attr_e( 'Close', 'ggm-commerce' ); ?>" type="button">
				<span class="dashicons dashicons-no-alt"></span>
			</button>
			<?php if ( $total > 1 ) : ?>
				<button class="ggmc-image-grid-lightbox__nav ggmc-image-grid-lightbox__prev" aria-label="<?php esc_attr_e( 'Previous', 'ggm-commerce' ); ?>" type="button">
					<span class="dashicons dashicons-arrow-left-alt2"></span>
				</button>
				<button class="ggmc-image-grid-lightbox__nav ggmc-image-grid-lightbox__next" aria-label="<?php esc_attr_e( 'Next', 'ggm-commerce' ); ?>" type="button">
					<span class="dashicons dashicons-arrow-right-alt2"></span>
				</button>
			<?php endif; ?>
			<div class="ggmc-image-grid-lightbox__image-container">
				<img class="ggmc-image-grid-lightbox__image" src="" alt="" />
			</div>
			<?php if ( $total > 1 ) : ?>
				<div class="ggmc-image-grid-lightbox__counter">
					<span class="current">1</span> / <span class="total"><?php echo esc_html( $total ); ?></span>
				</div>
			<?php endif; ?>
		</div>
	</div>
	<?php
}

/**
 * Render empty state placeholder (editor only).
 */
function ggmc_product_image_grid_render_empty_state() {
	if ( ggmc_is_editor_mode() ) {
		echo '<div class="ggmc-image-grid ggmc-image-grid--empty">';
		echo '<p>' . esc_html__( 'No product images found. Select a product with images or add images to the current product.', 'ggm-commerce' ) . '</p>';
		echo '</div>';
	}
}

/**
 * Get the CSS class for aspect ratio.
 *
 * @param array $settings Widget settings.
 * @return string CSS class.
 */
function ggmc_product_image_grid_get_ratio_class( $settings ) {
	$ratio = $settings['image_aspect_ratio'] ?? 'original';
	return 'ratio-' . $ratio;
}

/**
 * Check if lightbox is enabled.
 *
 * @param array $settings Widget settings.
 * @return bool
 */
function ggmc_product_image_grid_is_lightbox_enabled( $settings ) {
	return ! empty( $settings['show_lightbox'] ) && 'yes' === $settings['show_lightbox'];
}

/**
 * Get the image size key to use.
 *
 * @param array $settings    Widget settings.
 * @param bool  $is_featured Whether this is the featured image.
 * @return string Image size key.
 */
function ggmc_product_image_grid_get_image_size( $settings, $is_featured = false ) {
	if ( $is_featured ) {
		return 'large';
	}
	return $settings['image_size'] ?? 'medium';
}

/**
 * Get image URL for a given size.
 *
 * @param object $image Image object.
 * @param string $size  Size key (thumbnail, medium, large, full).
 * @return string Image URL.
 */
function ggmc_product_image_grid_get_image_url( $image, $size ) {
	$url_key = $size . '_url';
	if ( ! empty( $image->$url_key ) ) {
		return $image->$url_key;
	}
	return $image->url ?? '';
}

/**
 * Get image srcset for a given size.
 *
 * @param object $image Image object.
 * @param string $size  Size key.
 * @return string Srcset string.
 */
function ggmc_product_image_grid_get_image_srcset( $image, $size ) {
	$srcset_key = $size . '_srcset';
	return $image->$srcset_key ?? '';
}
