<?php


namespace Simple_Giveaways\AutomatorWP;

use Simple_Giveaways\AutomatorWP_Base_Trigger;
use Simple_Giveaways\SG_AutomatorWP;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Anonymous_Subscribed
 *
 * @package Simple_Giveaways\AutomatorWP
 */
class Anonymous_Subscribed extends AutomatorWP_Base_Trigger {

	/**
	 * @var string
	 */
	public $trigger = 'giveasap_subscribed_anonymous';

	/**
	 * Register the trigger
	 *
	 * @since 1.0.0
	 */
	public function register() {

		$args = array(
			'integration'   => $this->integration,
			'anonymous'     => true,
			'label'         => __( 'User subscribed to a giveaway', 'giveasap' ),
			'select_option' => __( 'User subscribed to <strong>a giveaway</strong>', 'giveasap' ),
			'edit_label'    => __( 'User subscribed to a giveaway', 'giveasap' ),
			'log_label'     => __( 'User subscribed to a giveaway', 'giveasap' ),
			'action'        => 'giveasap_register_user',
			'function'      => array( $this, 'listener' ),
			'priority'      => 30,
			'accepted_args' => 4,
			'tags'          => array_merge(
				SG_AutomatorWP::get_tags()
			),
		);

		automatorwp_register_trigger(
			$this->trigger,
			$args
		);
	}

	/**
	 * Trigger listener
	 *
	 * @since 1.0.0
	 *
	 * @param int $order_id The order ID
	 */
	public function listener( $subscriber_id, $giveaway_id, $email, $entry ) {

		$subscriber = giveasap_get_subscriber( $subscriber_id );

		// Bail if not a valid order.
		if ( ! $subscriber ) {
			return;
		}

		automatorwp_trigger_event(
			array(
				'trigger'       => $this->trigger,
				'subscriber_id' => $subscriber_id,
				'giveaway_id'   => $giveaway_id,
			)
		);

	}

	/**
	 * Register the required hooks
	 *
	 * @since 1.0.0
	 */
	public function hooks() {

		// Log meta data
		add_filter( 'automatorwp_user_completed_trigger_log_meta', array( $this, 'log_meta' ), 10, 6 );

		parent::hooks();
	}

	/**
	 * Trigger custom log meta
	 *
	 * @since 1.0.0
	 *
	 * @param array    $log_meta           Log meta data
	 * @param stdClass $trigger            The trigger object
	 * @param int      $user_id            The user ID
	 * @param array    $event              Event information
	 * @param array    $trigger_options    The trigger's stored options
	 * @param stdClass $automation         The trigger's automation object
	 *
	 * @return array
	 */
	function log_meta( $log_meta, $trigger, $user_id, $event, $trigger_options, $automation ) {

		// Bail if action type don't match this action
		if ( $trigger->type !== $this->trigger ) {
			return $log_meta;
		}

		$log_meta['subscriber_id'] = ( isset( $event['subscriber_id'] ) ? $event['subscriber_id'] : 0 );
		$log_meta['giveaway_id']   = ( isset( $event['giveaway_id'] ) ? $event['giveaway_id'] : 0 );

		return $log_meta;

	}

}

new Anonymous_Subscribed();
