<?php
/**
 * Form 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;

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

/**
 * Form Segments
 *
 * Handles Activities with type `form`
 */
class Form extends Base {

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

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

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

		// Double check
		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'] ) ) {
				// Simply tracking the submission of *any* form
				$this->assign_contact_to_segment( $segment['ID'], $activity->contact_id );
				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 form criteria, searching for matching form ID and type.
	 *
	 * @since 2.3.0
	 *
	 * @param array $args {
	 *     Array of args to use for matching the condition.
	 *
	 *     @type Activity $activity   Activity object
	 *     @type mixed    $condition  Form ID to match
	 *     @type mixed    $options    Form/plugin type to match
	 * }
	 *
	 * @return boolean
	 */
	protected function condition_has_matched_criteria( $args ) {

		list( 'activity' => $activity, 'condition' => $form_id, 'options' => $form_type ) = $args;

		// Search for form ID match
		$has_same_form_id   = is_numeric( $form_id ) && (int) $activity->object_id === (int) $form_id;
		$has_same_form_type = ! empty( $activity->object_type ) && $form_type === $activity->object_type;

		// Matching form ID and from same plugin.
		if ( $has_same_form_id && $has_same_form_type ) {
			return true;
		}
		return false;
	}
}
