<?php
/**
 * Specific Country type condition Rules
 *
 * @link       https://personalizewp.com/
 * @since      1.0.0
 *
 * @package    PersonalizeWP
 * @subpackage PersonalizeWP/Rule_Conditions
 */

namespace PersonalizeWP\Rule_Conditions;

use PersonalizeWP\Geo_Service;

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

/**
 * Checks the current IP address of the user against known country conditions
 */
class Visitor_Country extends RuleCondition {

	public string $identifier = 'core_visitor_country';

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

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

		$this->description = __( 'User Location - Country', 'personalizewp' );

		$this->comparators = [
			'equals'         => _x( 'Is Equal To', 'Comparator', 'personalizewp' ),
			'does_not_equal' => _x( 'Does Not Equal', 'Comparator', 'personalizewp' ),
		];

		$this->comparison_values = \personalizewp()->get_countries();
	}

	/**
	 * Test data against condition
	 *
	 * @param  string $comparator
	 * @return bool
	 */
	public function matchesCriteria( $comparator, $value, $action, $meta = [] ): bool {
		switch ( $comparator ) {
			case 'equals':
				return $this->comparatorEquals( $value );
			case 'does_not_equal':
				return $this->comparatorDoesNotEqual( $value );
			case 'any':
				return $this->comparatorAny( $value );
		}

		return false;
	}

	/**
	 * "Equal" test
	 *
	 * @return bool
	 */
	public function comparatorEquals( $value ) {
		$country = Geo_Service::instance()->get_country();
		return ! empty( $country ) && $country === $value;
	}

	/**
	 * "Does not equal" test
	 *
	 * @return bool
	 */
	public function comparatorDoesNotEqual( $value ) {
		$country = Geo_Service::instance()->get_country();
		return ! empty( $country ) && $country !== $value;
	}

	/**
	 * "Any" test
	 *
	 * @return bool
	 */
	public function comparatorAny( $value ) {
		$country = Geo_Service::instance()->get_country();
		return ! empty( $country ) && in_array( $country, $value, true );
	}
}
