<?php
/**
 * Taxonomy assigned Segments
 *
 * @link       https://personalizewp.com/
 * @since      3.2.0 Merged into PWP
 * @since      2.7.0
 *
 * @package    PersonalizeWP
 * @subpackage PersonalizeWP/Segments
 */

namespace PersonalizeWP\Segments;

use PersonalizeWP\Segments\Base;
use PersonalizeWP\Model\Activity;

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

/**
 * Taxonomy Segments
 *
 * Handles Activites with type 'taxonomy'
 */
class Taxonomy extends Base {

	/**
	 * Used to store the Base plugin for repeated calls
	 *
	 * @var \PersonalizeWP
	 */
	protected $personalizewp;

	/**
	 * Types of Activity to process
	 *
	 * @var array
	 */
	protected $activity_types = array( 'tax' );

	/**
	 * Types of Segment to process
	 *
	 * @var array
	 */
	protected $segment_types = array( 'taxonomy' );

	/**
	 * Process a `taxonomy` type Activity for Segments
	 *
	 * @param Activity $activity Activity object
	 *
	 * @return void
	 */
	public function process_activity( $activity = '' ) {

		if ( ! empty( $activity ) && ! in_array( $activity->activity_type, $this->activity_types, true ) ) {
			return;
		}

		if ( ! isset( $this->segments ) ) {
			$this->segments = $this->get_segments();
		}

		if ( empty( $this->segments ) ) {
			return;
		}

		foreach ( $this->segments as $segment ) {

			if ( empty( $segment['conditions'] ) ) {
				continue;
			}

			$args = [
				'activity'   => $activity,
				'conditions' => json_decode( $segment['conditions'], true ),
				'operator'   => $segment['operator'],
			];

			if ( $this->activity_has_matched_conditions( $args ) ) {
				$this->assign_contact_to_segment( $segment['ID'], $activity->contact_id );
			}
		}
	}

	/**
	 * Test condition against Taxonomy criteria.
	 *
	 * @param array $args {
	 *     Array of args to use for matching the condition.
	 *
	 *     @type Activity $activity   Activity object
	 *     @type string   $condition  Taxonomy to match against
	 *     @type array    $options    Term IDs to match against, optional
	 * }
	 *
	 * @return boolean
	 */
	protected function condition_has_matched_criteria( $args ) {
		list( 'activity' => $activity, 'condition' => $taxonomy, 'options' => $term_ids ) = $args;

		// Sanitise term IDs.
		$term_ids = array_unique( array_filter( array_map( 'intval', $term_ids ) ) );
		// Quick check for current term ID within array of valid IDs. Skips taxonomy check.
		if ( ! empty( $term_ids ) && ! in_array( (int) $activity->object_id, $term_ids, true ) ) {
			return false;
		}

		// Check current term has the same taxonomy, also validates existing term ID.
		$term = get_term( $activity->object_id, $taxonomy );
		if ( is_a( $term, '\WP_Term' ) ) {
			return true;
		}

		return false;
	}
}
