<?php

namespace CTXFeed\V5\Price;

class VariableProductPrice implements PriceInterface {

	/**
	 * @var \WC_Product_Variable $product WC Product.
	 */
	private $product;

	/**
	 * @var \CTXFeed\V5\Utility\Config $config Config.
	 */
	private $config;

	/**
	 * VariableProductPrice constructor.
	 *
	 * @param \WC_Product_Variable       $product WC Product.
	 * @param \CTXFeed\V5\Utility\Config $config  Config.
	 */
	public function __construct( $product, $config ) {
		$this->product = $product;
		$this->config  = $config;
	}

	/**
	 * Get Regular Price.
	 *
	 * @return float|int
	 */
	public function regular_price() {
		return $this->variation_price_by_type( 'regular_price' );
	}

	/**
	 * Get Price.
	 *
	 * @return float
	 */
	public function price() {
		return $this->variation_price_by_type( 'price' );
	}

	/**
	 * Get Sale Price.
	 *
	 * Returns sale price only if the product is currently on sale.
	 * If sale has a schedule and the schedule has expired, returns empty string.
	 *
	 * @return float|int|string
	 */
	public function sale_price() {
		// Check if product is currently on sale (respects scheduled dates)
		if ( ! $this->product->is_on_sale() ) {
			return '';
		}

		$sale_price = $this->variation_price_by_type( 'sale_price' );
		return apply_filters( 'woo_feed_parent_product_sale_price', $sale_price, $this->product, $this->config, false, 'sale_price' );
	}

	/**
	 * Get First Variation Price.
	 *
	 * @param string $price_type Price Type (regular_price|price|sale_price).
     * @return int
	 */
	private function variation_price_by_type( $price_type = 'price' ) {
		$price         = '';
		$min_max_first = $this->config->variable_price;
		$prices        = $this->product->get_variation_prices( true );

		if ( $price_type === 'sale_price' && $prices['sale_price'] === $prices['regular_price'] ) {
			return $price;
		}

		if ( empty( $prices[ $price_type ] ) ) {
			return $price;
		}

		$prices_by_type = $prices[ $price_type ];
		$prices_by_type = array_values( $prices_by_type );

		if ( $min_max_first === 'min' ) {
			return min( $prices_by_type );
		}

		if ( $min_max_first === 'max' ) {
			return max( $prices_by_type );
		}

		$prices_by_type = array_values( $prices_by_type );

		return $prices_by_type[0];
	}

}
