<?php
/**
 * WooCommerce total orders rule condition
 *
 * @link       https://personalizewp.com/
 * @since      3.2.0 Merged into PWP
 * @since      3.0.0
 *
 * @package    PersonalizeWP
 * @subpackage PersonalizeWP/Rule_Conditions/WooCommerce
 */

namespace PersonalizeWP\Rule_Conditions\WooCommerce;

use PersonalizeWP\Rule_Conditions\RuleCondition;
use PersonalizeWP\Rule_Conditions\Dependency\Woocommerce;

defined( 'ABSPATH' ) || exit; // Exit if accessed directly.

/**
 * Checks WooCommerce orders for total number of orders conditions
 */
class Total_Orders extends RuleCondition {

	/**
	 * Condition identifier
	 *
	 * @var string
	 */
	public string $identifier = 'woocommerce_total_orders';

	/**
	 * Constructor
	 */
	public function __construct() {
		parent::__construct();

		$this->category = __( 'WooCommerce', 'personalizewp' );

		$this->description = __( 'Total Orders', 'personalizewp' );

		$this->comparators = [
			'more_than' => _x( 'More Than', 'Comparator', 'personalizewp' ),
			'less_than' => _x( 'Less Than', 'Comparator', 'personalizewp' ),
			'equals'    => _x( 'Is Equal To', 'Comparator', 'personalizewp' ),
		];

		$this->comparison_values = [];

		$this->comparison_type = 'text';
	}

	/**
	 * Test total orders against condition
	 *
	 * @param string $comparator Comparator test to run
	 * @param string $value      Total orders to compare against
	 * @param string $action     Action to take, unused
	 * @param mixed  $meta       Additional meta data, unused
	 *
	 * @return bool
	 */
	public function matchesCriteria( $comparator, $value, $action, $meta = [] ): bool {

		if ( ! is_user_logged_in() ) {
			return false;
		}

		$user_id = get_current_user_id();

		// Get customer's completed orders count
		$order_count     = wc_get_customer_order_count( $user_id );
		$value_condition = is_numeric( $value ) ? absint( $value ) : 0;

		if ( empty( $value_condition ) ) {
			return false;
		}

		switch ( $comparator ) {
			case 'more_than':
				return $order_count > $value_condition;

			case 'less_than':
				return $order_count < $value_condition;

			case 'equals':
				return $order_count === $value_condition;
		}

		return false;
	}

	/**
	 * Array of dependencies for the condition to be used
	 *
	 * @return array
	 */
	public function dependencies(): array {
		return [
			Woocommerce::instance(),
		];
	}
}
