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

namespace PersonalizeWP\Segments;

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

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

/**
 * Product Segments
 *
 * Handles Activities with type `purchase`
 */
class Product extends Base {

	use Product_Trait;

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

	/**
	 * Sub-types of Activity, i.e. Specific plugins
	 *
	 * @var array
	 */
	protected $object_types = array( 'woocommerce' );

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

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

		// Check that the activity sub-type is on the allow list.
		if ( empty( $activity ) || ! in_array( $activity->object_type, $this->object_types, true ) ) {
			return;
		}

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

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

		$order = $this->get_order( $activity->object_type, $activity->object_id );
		if ( empty( $order ) ) {
			return;
		}

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

			if ( empty( $segment['conditions'] ) ) {
				// Simply tracking the submission of *any* purchase
				$this->assign_contact_to_segment( $segment['ID'], $activity->contact_id );
				continue;
			}

			$args = [
				'activity'   => $activity,
				'conditions' => json_decode( $segment['conditions'], true ),
				'operator'   => $segment['operator'],
				'order'      => $order,
			];
			if ( $this->activity_has_matched_conditions( $args ) ) {
				$this->assign_contact_to_segment( $segment['ID'], $activity->contact_id );
			}
		}
	}
}
