<?php
namespace Mewz\WCAS\Aspects\Front;

use Mewz\Framework\Base\Aspect;
use Mewz\WCAS\Util\Attributes;
use Mewz\WCAS\Util\Products;

class VariableLimitsAjax extends Aspect
{
	public function __hooks()
	{
		add_filter('woocommerce_available_variation', [$this, 'available_variation'], 10, 3);
	}

	/**
	 * @param array $data
	 * @param \WC_Product_Variable $variable
	 * @param \WC_Product_Variation $variation
	 *
	 * @return array
	 */
	public function available_variation($data, $variable, $variation)
	{
		if (!isset($_POST['product_id']) || (int)$_POST['product_id'] !== $variable->get_id() || !Attributes::has_catchall($data['attributes'])) {
			return $data;
		}

		$attributes = Attributes::get_request_attributes();
		if (!$attributes) return $data;

		Products::set_prop($variation, 'variation', $attributes);

		// get stock data again with filters applied for current variation attributes
		$data['availability_html'] = wc_get_stock_html($variation);
		$data['is_in_stock'] = $variation->is_in_stock();
		$data['max_qty'] = ($max = $variation->get_max_purchase_quantity()) > 0 ? $max : '';

		return $data;
	}
}
