<?php
/**
 * PersonalizeWP
 *
 * @link       https://personalizewp.com/
 * @since      3.2.0 Merged into PWP
 * @since      2.0.0
 *
 * @package    PersonalizeWP
 * @subpackage PersonalizeWP/Rule_Conditions
 */

namespace PersonalizeWP\Rule_Conditions;

use PersonalizeWP\Rule_Conditions\RuleCondition;
use PersonalizeWP\Model\Contact;

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

/**
 * Completed form submission type condition Rule
 *
 * Requires the Visitor Profile to have recorded a form submission
 */
class Completed_Form_Submission extends RuleCondition {

	/**
	 * Condition identifier
	 *
	 * @var string
	 */
	public string $identifier = 'completed_form_submission';

	/**
	 * Constructor
	 */
	public function __construct() {
		parent::__construct();

		$this->category = __( 'Forms', 'personalizewp' );

		$this->description = __( 'Submitted Form', 'personalizewp' );

		$this->comparators = [
			'equals' => _x( 'Is Equal To', 'Comparator', 'personalizewp' ),
		];

		$this->comparison_values = [
			'true'  => _x( 'True', 'Comparison value', 'personalizewp' ),
			'false' => _x( 'False', 'Comparison value', 'personalizewp' ),
		];
	}

	/**
	 * Test data against condition
	 *
	 * @param string $comparator Comparator test to run
	 * @param string $value      Comparison to check
	 * @param string $action     Action to take
	 * @param mixed  $meta       Additional meta data, unused
	 *
	 * @return bool
	 */
	public function matchesCriteria( $comparator, $value, $action, $meta = [] ): bool {
		switch ( $comparator ) {
			case 'equals':
				return $this->comparatorEquals( $value );
		}

		return false;
	}

	/**
	 * "Equal" test
	 *
	 * @param string $value Condition value to check against, could be true or false
	 *
	 * @return bool True if the current visitor matches the required condition value, false otherwise
	 */
	public function comparatorEquals( $value ): bool {

		// Convert to bool
		$value = (bool) ( 'true' === $value );

		// Set via main plugin within Public callback
		$uid = ! empty( $GLOBALS['PERSONALIZEWP_PARAMS']['uid'] ) ? sanitize_text_field( $GLOBALS['PERSONALIZEWP_PARAMS']['uid'] ) : false;

		if ( empty( $uid ) ) {
			// Return based on value, if condition was set to false this will return true.
			return false === $value;
		}

		// Get the Contact record, which might be an Anon user, do not create user.
		$contact = Contact::find_by_uid( $uid );
		if ( ! $contact ) {
			// Return based on value, if condition was set to false this will return true.
			return false === $value;
		}

		// Check for fixed meta data of 'has-completed-form';
		$possible_form = $contact->get_metadata( '_has-completed-form', true );
		// Match possible form submission against condition comparator value
		return $value === (bool) $possible_form;
	}
}
