<?php
/**
 * Expands product IDs into printable product/variation instances.
 *
 * @package PhoenixWP\PriceLabels
 */

declare(strict_types=1);

namespace PhoenixWP\PriceLabels\Labels;

use WC_Product;

defined( 'ABSPATH' ) || exit;

/**
 * Resolves user selection into WC_Product list for label generation.
 */
final class Variation_Resolver {

	/**
	 * @param int[] $product_ids Product or variation IDs from admin selection.
	 * @param bool  $expand_variations When true, variable products expand to all variations.
	 * @return WC_Product[]
	 */
	public function resolve( array $product_ids, bool $expand_variations = true ): array {
		$products = array();

		foreach ( array_unique( array_filter( array_map( 'absint', $product_ids ) ) ) as $product_id ) {
			$product = wc_get_product( $product_id );

			if ( ! $product instanceof WC_Product ) {
				continue;
			}

			if ( $product->is_type( 'variable' ) && $expand_variations ) {
				foreach ( $product->get_children() as $child_id ) {
					$variation = wc_get_product( $child_id );
					if ( $variation instanceof WC_Product ) {
						$products[] = $variation;
					}
				}
				continue;
			}

			$products[] = $product;
		}

		return $products;
	}
}
