<?php
namespace Simple_Giveaways\AutomatorWP;

// Exit if accessed directly
use Simple_Giveaways\AutomatorWP_Base_Action;

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

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

	public $action = 'giveaway_subscribe_user';

	/**
	 * The new inserted user ID
	 *
	 * @since 1.0.0
	 *
	 * @var int|\WP_Error $subscriber_id
	 */
	public $subscriber_id = 0;

	public $errors = null;

	/**
	 * The post meta
	 *
	 * @since 1.0.0
	 *
	 * @var array $form_fields
	 */
	public $form_fields = array();

	public $posted_data = null;

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

		automatorwp_register_action(
			$this->action,
			array(
				'integration'   => $this->integration,
				'label'         => __( 'Subscribe a user', 'giveasap' ),
				'select_option' => __( 'Subscribe <strong>a user</strong>', 'giveasap' ),
				/* translators: %1$s: User. */
				'edit_label'    => sprintf( __( 'Subscribe a %1$s to %2$s', 'giveasap' ), '{user}', '{giveaway}' ),
				/* translators: %1$s: User. */
				'log_label'     => sprintf( __( 'Subscribe a %1$s to %2$s', 'giveasap' ), '{user}', '{giveaway}' ),
				'options'       => array(
					'user'     => array(
						'default' => __( 'user', 'automatorwp' ),
						'fields'  => array(
							'user_email'  => array(
								'name'     => __( 'Email:', 'automatorwp' ),
								'desc'     => __( 'The user email address.', 'automatorwp' ),
								'type'     => 'text',
								'required' => true,
								'default'  => '',
							),
							'form_fields' => array(
								'name'    => __( 'Form Fields:', 'automatorwp' ),
								'desc'    => __( 'The form fields in Giveaways that you are using.', 'automatorwp' ),
								'type'    => 'group',
								'classes' => 'automatorwp-fields-table',
								'options' => array(
									'add_button'    => __( 'Add field', 'automatorwp' ),
									'remove_button' => '<span class="dashicons dashicons-no-alt"></span>',
								),
								'fields'  => array(
									'meta_key'   => array(
										'name'    => __( 'Field Key:', 'automatorwp' ),
										'type'    => 'text',
										'default' => '',
									),
									'meta_value' => array(
										'name'    => __( 'Field Value:', 'automatorwp' ),
										'type'    => 'text',
										'default' => '',
									),
								),
							),
						),
					),
					'giveaway' => automatorwp_utilities_ajax_selector_option(
						array(
							'field'             => 'giveaway',
							'name'              => __( 'Giveaway:', 'giveasap' ),
							'option_none_value' => 'any',
							'option_none_label' => __( 'current active giveaways', 'giveasap' ),
							'action_cb'         => 'automatorwp_get_giveasap_giveaways',
							'options_cb'        => array( $this, 'get_giveaway_options' ),
							'default'           => 'any',
						)
					),
				),
			)
		);

	}

	/**
	 * Get Giveaway options
	 *
	 * @param object $field
	 *
	 * @return array
	 */
	public function get_giveaway_options( $field ) {

		// Setup vars.
		$value      = $field->escaped_value;
		$none_value = 'any';
		$none_label = __( 'any action', 'giveasap' );
		$options    = automatorwp_options_cb_none_option( $field, $none_value, $none_label );

		if ( ! empty( $value ) ) {
			if ( ! is_array( $value ) ) {
				$value = array( $value );
			}

			foreach ( $value as $giveaway_id ) {

				// Skip option none.
				if ( $giveaway_id === $none_value ) {
					continue;
				}

				$options[ $giveaway_id ] = get_the_title( $giveaway_id );
			}
		}

		return $options;

	}

	/**
	 * Action execution function
	 *
	 * @since 1.0.0
	 *
	 * @param stdClass $action             The action object
	 * @param int      $user_id            The user ID
	 * @param array    $action_options     The action's stored options (with tags already passed)
	 * @param stdClass $automation         The action's automation object
	 */
	public function execute( $action, $user_id, $action_options, $automation ) {

		// Setup user fields.
		$user_data = wp_parse_args(
			$action_options,
			array(
				'user_email'  => '',
				'giveaway'    => 0,
				'form_fields' => array(),
			)
		);

		if ( ! $user_data['user_email'] ) {
			return;
		}

		if ( ! $user_data['giveaway'] || 'any' === $user_data['giveaway'] ) {
			$giveaways = giveasap_get_giveaways( array( 'fields' => 'ids' ) );
		} else {
			$giveaways = array( $user_data['giveaway'] );
		}

		foreach ( $giveaways as $giveaway_id ) {
			$giveaway = giveasap_get_giveaway( $giveaway_id );
			if ( $giveaway->subscriber_exists( $user_data['user_email'] ) ) {
				continue;
			}

			// Let's fill the sg_form from data.
			$form_fields               = giveasap_get_form_fields( $giveaway_id );
			$_POST['giveasap_submit']  = true;
			$_POST['giveasap_consent'] = '1';
			$_POST['sg_giveaway_type'] = $giveaway->get_type();
			$posted_form               = array(
				'user_email' => $user_data['user_email'],
			);

			if ( is_array( $action_options['form_fields'] ) ) {

				foreach ( $action_options['form_fields'] as $i => $meta ) {

					// Parse automation tags replacements to both, key and value
					$meta_key   = automatorwp_parse_automation_tags( $automation->id, $user_id, $meta['meta_key'] );
					$meta_value = automatorwp_parse_automation_tags( $automation->id, $user_id, $meta['meta_value'] );

					// Sanitize
					$meta_key   = sanitize_text_field( $meta_key );
					$meta_value = sanitize_text_field( $meta_value );

					// Update action options to be passed on upcoming hooks
					$action_options['form_fields'][ $i ] = array(
						'meta_key'   => $meta_key,
						'meta_value' => $meta_value,
					);

					foreach ( $form_fields as $field_key => $form_field ) {
						if ( $field_key === $meta_key ) {
							$posted_form[ $field_key ] = $meta_value;
							break;
						}
					}
				}
			}

			$this->form_fields = $action_options['form_fields'];

			$_POST['sg_form'] = $posted_form;
			add_filter( 'giveasap_register_user_status', array( $this, 'set_active_status' ) );
			add_filter( 'sg_skip_form_fields_validation', '__return_true' );
			add_filter( 'sg_process_captcha', '__return_false' );
			$front = new \GiveASAP_Front( get_post( $giveaway_id ), false );
			$front->creating_steps( false );
			remove_filter( 'sg_skip_form_fields_validation', '__return_true' );
			remove_filter( 'giveasap_register_user_status', array( $this, 'set_active_status' ) );
			remove_filter( 'sg_process_captcha', '__return_false' );
			if ( $front->errors->get_error_messages() ) {
				$this->errors = $front->errors->get_error_messages();
			}
			if ( null !== $front->user ) {
				$this->subscriber_id = $front->user->id;
				giveasap_add_meta( $front->user->id, 'user_id', $user_id );
			}
		}
	}

	public function set_active_status() {
		return 'active';
	}

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

		// Log meta data
		add_filter( 'automatorwp_user_completed_action_log_meta', array( $this, 'log_meta' ), 10, 5 );

		// Log fields
		add_filter( 'automatorwp_log_fields', array( $this, 'log_fields' ), 10, 5 );

		parent::hooks();
	}

	/**
	 * Action custom log meta
	 *
	 * @since 1.0.0
	 *
	 * @param array    $log_meta           Log meta data
	 * @param stdClass $action             The action object
	 * @param int      $user_id            The user ID
	 * @param array    $action_options     The action's stored options (with tags already passed)
	 * @param stdClass $automation         The action's automation object
	 *
	 * @return array
	 */
	public function log_meta( $log_meta, $action, $user_id, $action_options, $automation ) {

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

		// Store user fields
		$user_fields = array(
			'user_email',
			'giveaway',
			'form_fields'
		);

		foreach ( $user_fields as $user_field ) {
			$log_meta[ $user_field ] = $action_options[ $user_field ];
		}

		// Store user meta
		$log_meta['form_fields'] = $this->form_fields;

		// Store result
		if ( $this->subscriber_id ) {
			$log_meta['result'] = __( 'User subscribed correctly', 'automatorwp' );
		} elseif ( $this->errors ) {
			$log_meta['result'] = $this->errors;
		} else {
			$log_meta['result'] = __( 'Could not subscribe the user', 'automatorwp' );
		}

		return $log_meta;
	}

	/**
	 * Action custom log fields
	 *
	 * @since 1.0.0
	 *
	 * @param array    $log_fields The log fields
	 * @param stdClass $log        The log object
	 * @param stdClass $object     The trigger/action/automation object attached to the log
	 *
	 * @return array
	 */
	public function log_fields( $log_fields, $log, $object ) {

		// Bail if log is not assigned to an action
		if ( $log->type !== 'action' ) {
			return $log_fields;
		}

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


		$log_fields['user_email'] = array(
			'name'    => __( 'Email:', 'automatorwp' ),
			'desc'    => __( 'The user email address.', 'automatorwp' ),
			'type'    => 'text',
			'default' => '',
		);

		$log_fields['form_fields'] = array(
			'name' => __( 'From Fields:', 'automatorwp' ),
			'desc' => __( 'The form fields data for the giveaway.', 'automatorwp' ),
			'type' => 'text',
		);

		$log_fields['result'] = array(
			'name' => __( 'Result:', 'automatorwp' ),
			'type' => 'text',
		);

		$log_fields['giveaway'] = array(
			'name' => __( 'Giveaway:', 'automatorwp' ),
			'type' => 'text',
		);

		return $log_fields;
	}

}

new Subscribe();
