<?php
/**
 * WooCommerce product mapping helpers.
 *
 * @package CatalogFrameImageStudio
 */

namespace CatalogFrame_Image_Studio;

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

/**
 * Appends generated attachment IDs to matching product galleries.
 */
final class Product_Mapper {
	/**
	 * Returns whether WooCommerce product lookup is available.
	 *
	 * @return bool
	 */
	public function is_available() {
		return post_type_exists( 'product' ) && function_exists( 'wc_get_product_id_by_sku' );
	}

	/**
	 * Finds a product ID by SKU.
	 *
	 * @param string $sku Product SKU.
	 * @return int
	 */
	public function find_product_id_by_sku( $sku ) {
		$sku = trim( (string) $sku );
		if ( '' === $sku || ! $this->is_available() ) {
			return 0;
		}

		return max( 0, (int) wc_get_product_id_by_sku( $sku ) );
	}

	/**
	 * Appends an attachment to a product gallery without replacing existing media.
	 *
	 * @param string $sku           Product SKU.
	 * @param int    $attachment_id Attachment ID.
	 * @return array
	 */
	public function append_attachment_by_sku( $sku, $attachment_id ) {
		$product_id = $this->find_product_id_by_sku( $sku );
		if ( $product_id <= 0 ) {
			return array(
				'mapped'  => false,
				'message' => __( 'No matching product SKU was found.', 'catalogframe-image-studio' ),
			);
		}

		$attachment_id = (int) $attachment_id;
		$gallery       = get_post_meta( $product_id, '_product_image_gallery', true );
		$ids           = array_filter( array_map( 'absint', explode( ',', (string) $gallery ) ) );

		if ( ! in_array( $attachment_id, $ids, true ) ) {
			$ids[] = $attachment_id;
			update_post_meta( $product_id, '_product_image_gallery', implode( ',', $ids ) );
		}

		return array(
			'mapped'    => true,
			'productId' => $product_id,
			'message'   => __( 'Generated image appended to the product gallery.', 'catalogframe-image-studio' ),
		);
	}
}
