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

namespace PersonalizeWP\Scoring_Rules;

use PersonalizeWP\Scoring_Rules\Base;
use PersonalizeWP\Traits\Product_Trait;

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

/**
 * Product Scoring_Rules
 *
 * 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 $score_types = array( 'product' );

	/**
	 * Filter a `purchase` type Activity for Scoring rules
	 *
	 * @since 1.1.0
	 *
	 * @param array  $activity_args Activity arguments.
	 * @param string $type          Activity Type.
	 *
	 * @return array
	 */
	public function add_activity_score( $activity_args, $type ) {

		// Double check
		if ( ! in_array( $type, $this->activity_types, true ) || empty( $activity_args ) || ! isset( $activity_args['lead_score'] ) ) {
			return $activity_args;
		}

		// And check that the activity sub-type is on the allow list.
		if ( ! in_array( $activity_args['object_type'], $this->object_types, true ) ) {
			return $activity_args;
		}

		if ( ! isset( $this->scoring_rules ) ) {
			$this->scoring_rules = $this->get_scoring_rules();
		}

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

		$order = $this->get_order( $activity_args['object_type'], $activity_args['object_id'] );
		if ( empty( $order ) ) {
			return $activity_args;
		}

		foreach ( $this->scoring_rules as $scoring_rule ) {
			// Somehow no score to apply.
			if ( empty( $scoring_rule['lead_score'] ) ) {
				continue;
			}
			if ( empty( $scoring_rule['conditions'] ) ) {
				// Simply tracking the submission of *any* purchase
				$activity_args['lead_score'] += $scoring_rule['lead_score'];
				continue;
			}

			$args = [
				'activity'   => (object) $activity_args, // Need to convert to object for inherited functions
				'conditions' => json_decode( $scoring_rule['conditions'], true ),
				'operator'   => $scoring_rule['operator'],
				'order'      => $order,
			];
			if ( $this->activity_has_matched_conditions( $args ) ) {
				// Add our score to the Activity score.
				$activity_args['lead_score'] += $scoring_rule['lead_score'];
			}
		}

		// Always return activity args for Activity creation.
		return $activity_args;
	}
}
