<?php
/**
 * Post Type 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.

/**
 * Post Type Segments
 *
 * Handles Activities with type 'post_type'.
 */
class Post_Type 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( 'post' );
	/**
	 * Types of Segment to process
	 *
	 * @var array
	 */
	protected $segment_types = array( 'post_type' );

	/**
	 * Process a `post_type` 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 Post Type criteria. Match activity object id with condition.
	 *
	 * @param array $args {
	 *     Array of args to use for matching the condition.
	 *
	 *     @type Activity $activity   Activity object - Unused
	 * }
	 *
	 * @return boolean
	 */
	protected function condition_has_matched_criteria( $args ) {

		list( 'activity' => $activity, 'options' => $post_type ) = $args;

		// Match Activity object ID to post type
		if ( get_post_type( $activity->object_id ) === $post_type ) {
			return true;
		}
		return false;
	}
}
