<?php
/**
 * Effective price resolver.
 *
 * @package PRECO
 */

namespace PRECO\Includes\Frontend\Engine\Filters\Price;

defined( 'ABSPATH' ) || exit;

/**
 * Effective price resolver.
 */
class EffectivePriceResolver {
	/**
	 * Get an effective numeric product price suitable for filtering/sorting.
	 *
	 * @param int $product_id Product ID.
	 * @return float|null
	 */
	public function resolve_for_product_id( $product_id ) {
		$product_id = absint( $product_id );
		if ( ! $product_id ) {
			return null;
		}

		if ( function_exists( 'wc_get_product' ) ) {
			$p = \wc_get_product( $product_id );
			if ( $p instanceof \WC_Product ) {
				if ( $p->is_type( 'variable' ) && method_exists( $p, 'get_variation_prices' ) ) {
					$prices = $p->get_variation_prices( true );
					$vals   = isset( $prices['price'] ) && is_array( $prices['price'] ) ? array_values( $prices['price'] ) : array();
					$nums   = array();
					foreach ( $vals as $v ) {
						if ( '' === $v || null === $v || false === $v || ! is_numeric( $v ) ) {
							continue;
						}
						$nums[] = (float) $v;
					}
					if ( ! empty( $nums ) ) {
						return (float) min( $nums );
					}

					$raw_min = \get_post_meta( $product_id, '_min_variation_price', true );
					if ( '' !== $raw_min && null !== $raw_min && false !== $raw_min && is_numeric( $raw_min ) ) {
						return (float) $raw_min;
					}
				}

				$raw_price = $p->get_price();
				if ( '' !== $raw_price && null !== $raw_price && false !== $raw_price && is_numeric( $raw_price ) ) {
					return (float) $raw_price;
				}
			}
		}

		$raw = \get_post_meta( $product_id, '_price', true );
		if ( '' !== $raw && null !== $raw && false !== $raw && is_numeric( $raw ) ) {
			return (float) $raw;
		}

		return null;
	}
}
