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

use Mewz\Framework\Base\Aspect;
use Mewz\WCAS\Aspects\Front\ProductLimits;

class AutoProductLimits extends Aspect
{
	public $enabled = 0;

	public function __hooks()
	{
		// enable product stock limits during certain hooks
		$hooks = apply_filters('mewz_wcas_limit_product_stock_auto_hooks', [
			'woocommerce_product_set_stock',
			'woocommerce_variation_set_stock',
			'woocommerce_product_set_stock_status',
			'woocommerce_variation_set_stock_status',
			'woocommerce_product_object_updated_props',
			'woocommerce_new_product',
			'woocommerce_update_product',
			'transition_post_status',
			//'updated_postmeta', // too broad?
		]);

		foreach ($hooks as $hook) {
			if (is_array($hook)) {
				if (!empty($hook[0])) add_filter($hook[0], [$this, 'enable_product_limits'], 0);
				if (!empty($hook[1])) add_filter($hook[1], [$this, 'disable_product_limits'], 999999);
			} else {
				add_filter($hook, [$this, 'enable_product_limits'], 0);
				add_filter($hook, [$this, 'disable_product_limits'], 999999);
			}
		}

		add_action('mewz_wcas_auto_product_limits_enable', [$this, 'enable_product_limits']);
		add_action('mewz_wcas_auto_product_limits_disable', [$this, 'disable_product_limits']);

		// ensure product stock limits are enabled during all action scheduler tasks
		add_action('action_scheduler_before_execute', [$this, 'action_scheduler_before_execute'], 0);
	}

	public function enable_product_limits($value = null)
	{
		if (!class_exists(ProductLimits::class, false)) {
			$this->plugin->aspects->load(ProductLimits::class);
		} elseif (!ProductLimits::$enabled) {
			ProductLimits::$enabled = true;
		} elseif ($this->enabled <= 0) {
			$this->enabled++;
		}

		$this->enabled++;

		return $value;
	}

	public function disable_product_limits($value = null)
	{
		$this->enabled--;

		if ($this->enabled <= 0) {
			ProductLimits::$enabled = false;
			$this->enabled = 0;
		}

		return $value;
	}

	public function action_scheduler_before_execute()
	{
		if (!class_exists(ProductLimits::class, false)) {
			$this->plugin->aspects->load(ProductLimits::class);
		}

		remove_action('action_scheduler_before_execute', [$this, 'action_scheduler_before_execute'], 0);
	}
}
