<?php
/**
 * On-sale rule helper.
 *
 * @package PRECO
 */

namespace PRECO\Includes\Frontend\Core\Engine;

defined( 'ABSPATH' ) || exit;

/**
 * On-sale rule helper.
 */
class OnSaleRuleHelper {
	/**
	 * Detect whether rules explicitly exclude on-sale products.
	 *
	 * @param array $rules Rules to inspect.
	 * @return bool
	 */
	public function should_exclude_on_sale_from_rules( $rules ) {
		if ( ! is_array( $rules ) ) {
			return false;
		}
		foreach ( $rules as $rule ) {
			if ( ! is_array( $rule ) ) {
				continue;
			}
			if ( isset( $rule['enabled'] ) && false === $rule['enabled'] ) {
				continue;
			}
			if ( 'on_sale' !== ( $rule['triggerType'] ?? '' ) ) {
				continue;
			}
			return 'is_not' === ( $rule['relation'] ?? '' );
		}
		return false;
	}

	/**
	 * Filter out products that Woo considers on sale.
	 *
	 * @param int[] $ids Product IDs to filter.
	 * @return int[]
	 */
	public function filter_out_on_sale_products( $ids ) {
		if ( empty( $ids ) || ! is_array( $ids ) || ! function_exists( 'wc_get_products' ) ) {
			return is_array( $ids ) ? $ids : array();
		}

		$ids = array_values( array_filter( array_map( 'absint', $ids ) ) );
		if ( empty( $ids ) ) {
			return array();
		}

		// Batch-load all products in one query instead of per-ID calls (avoids N+1).
		$products = wc_get_products(
			array(
				'include' => $ids,
				'limit'   => count( $ids ),
				'status'  => 'any',
			)
		);

		$on_sale_ids = array();
		foreach ( $products as $product ) {
			if ( $product instanceof \WC_Product && $product->is_on_sale() ) {
				$on_sale_ids[] = $product->get_id();
			}
		}

		return array_values( array_diff( $ids, $on_sale_ids ) );
	}
}
