<?php

namespace Simple_Giveaways;

/**
 * Class SG_AutomatorWP
 *
 * @package Simple_Giveaways
 */
class SG_AutomatorWP extends GA_Integration {

	/**
	 * Get Categories
	 *
	 * @return string[]
	 */
	public function get_categories() {
		return [
			'automation',
		];
	}

	/**
	 * Setting initial params
	 */
	public function __construct() {

		$this->title       = __( 'AutomatorWP', 'giveasap' );
		$this->settings_id = 'sg_automatorwp';
		$this->image       = untrailingslashit( GASAP_URI ) . '/includes/integrations/assets/automatorwp.svg';
		$this->desc        = __( 'Adds actions and triggers to AutomatorWP.', 'giveasap' );

		parent::__construct();

		if ( ! did_action( 'automatorwp_init' ) ) {
			// Default hook to register.
			add_action( 'automatorwp_init', array( $this, 'register_integration' ) );
		} else {
			// Hook for triggers registered from the theme's functions.
			add_action( 'after_setup_theme', array( $this, 'register_integration' ) );
		}

		$this->includes();

		add_action( 'admin_footer', array( $this, 'add_styles_on_automatorwp_pages' ) );
		add_action( 'automatorwp_automation_ui_after_integration_triggers_choices', array( $this, 'ui_integration_triggers_pro_choices' ), 10, 4 );

		add_filter( 'automatorwp_get_trigger_tag_replacement', array( $this, 'get_trigger_tag_replacement' ), 10, 6 );
		add_action( 'wp_ajax_automatorwp_get_giveasap_giveaways', array( $this, 'get_ajax_giveaways' ) );

	}

	/**
	 * Get Giveaways for EDD
	 */
	public function get_ajax_giveaways() {
		// Security check, forces to die if not security passed
		check_ajax_referer( 'automatorwp_admin', 'nonce' );

		// Pull back the search string.
		$search = isset( $_REQUEST['q'] ) ? esc_sql( $_REQUEST['q'] ) : '';

		$ids = giveasap_get_giveaways(
			array(
				's'              => $search,
				'posts_per_page' => 10,
				'fields'         => 'ids',
			)
		);

		$giveaways = array();

		foreach ( $ids as $id ) {
			$giveaway    = giveasap_get_giveaway( $id );
			$giveaways[] = array(
				'id'   => $id,
				'text' => rawurldecode( $giveaway->get_post()->post_title ),
			);
		}

		// Prepend option none.
		$results = automatorwp_ajax_parse_extra_options( $giveaways );

		// Return our results.
		wp_send_json_success( $results );
		die();
	}

	/**
	 * Adding styles for Giveaways Trigger or Action
	 *
	 * @return false|void
	 */
	public function add_styles_on_automatorwp_pages() {
		if ( ! is_admin() ) {
			return false;
		}

		if ( ! isset( $_GET['page'] ) ) {
			return;
		}

		if ( 'edit_automatorwp_automations' !== $_GET['page'] && 'add_automatorwp_automations' !== $_GET['page'] ) {
			return;
		}
		?>
		<style>
			.automatorwp-select2-dropdown-container .select2-results__option[aria-disabled="true"][id*="giveasap"]:before {
				content: 'Simple Giveaways Business';
				text-transform: uppercase;
				background: #a46497;
				font-size: 8px;
				line-height: 15px;
				vertical-align: middle;
			}
		</style>
		<?php
	}

	/**
	 * Adding Premium Triggers and Actions
	 *
	 * @param $integration_name
	 * @param $args
	 * @param $automation
	 * @param $item_type
	 */
	public function ui_integration_triggers_pro_choices( $integration_name, $args, $automation, $item_type ) {

		if ( 'giveasap' !== $integration_name ) {
			return;
		}

		if ( class_exists( '\Simple_Giveaways\Premium\SG_AutomatorWP' ) ) {
			return;
		}

		// Get the list of already listed triggers
		$choices = automatorwp_get_integration_triggers( $integration_name );

		$triggers = array(
			__( 'User has completed a giveaway action', 'giveasap' ),
		);
		foreach ( $triggers as $i => $trigger ) {

			$already_listed = false;

			foreach ( $choices as $choice ) {
				// Check if trigger has been already listed
				if ( $choice['label'] === $trigger ) {
					$already_listed = true;
					break;
				}
			}

			// Skip triggers already listed
			if ( $already_listed ) {
				continue;
			}
			?>
			<option value="<?php echo esc_attr( $integration_name ) . '_' . $i; ?>" disabled="disabled"><?php echo $trigger; ?></option>
			<?php
		}

	}

	/**
	 * Custom tags replacement
	 *
	 * @param string $replacement    The tag replacement
	 * @param string $tag_name       The tag name (without "{}")
	 * @param int    $automation_id  The automation ID
	 * @param int    $user_id        The user ID
	 * @param string $content        The content to parse
	 *
	 * @return string
	 */
	public function get_trigger_tag_replacement( $replacement, $tag_name, $trigger, $user_id, $content, $log ) {
		$trigger_args = automatorwp_get_trigger( $trigger->type );

		// Bail if no Giveaway data attached.
		if ( ! $trigger_args ) {
			return $replacement;
		}

		// Bail if trigger is not from this integration.
		if ( $trigger_args['integration'] !== 'giveasap' ) {
			return $replacement;
		}

		$tags = array_keys( self::get_tags() );

		// Bail if not order tags found.
		if ( ! in_array( $tag_name, $tags, true ) ) {
			return $replacement;
		}

		$subscriber_id = (int) automatorwp_get_log_meta( $log->id, 'subscriber_id', true );
		// Bail if no Subscriber ID attached.
		if ( $subscriber_id === 0 ) {
			return $replacement;
		}

		$subscriber = giveasap_get_subscriber( $subscriber_id );

		// Bail if subscriber can't be found.
		if ( ! $subscriber ) {
			return $replacement;
		}

		$function_name = str_replace( 'giveasap_subscriber_', '', $tag_name );

		// Dynamically, call to a order function to retrieve the tag value.
		if ( method_exists( $subscriber, 'get_' . $function_name ) ) {
			$replacement = call_user_func( array( $subscriber, 'get_' . $function_name ) );
		}

		// Format values for some tags.
		switch ( $tag_name ) {
			case 'giveasap_giveaway_link':
				$giveaway    = $subscriber->get_giveaway();
				$replacement = $giveaway->get_main_page_link();
				break;
			case 'giveasap_giveaway_total_entries':
				$giveaway    = $subscriber->get_giveaway();
				$replacement = $giveaway->get_total_entries();
				break;
		}

		return $replacement;
	}

	/**
	 * Return tags for AutomatorWP
	 *
	 * @return mixed|void
	 */
	public static function get_tags() {
		$tags = array(
			'giveasap_subscriber_id'            => array(
				'label'   => __( 'Subscriber ID', 'giveasap' ),
				'type'    => 'integer',
				'preview' => '123',
			),
			'giveasap_subscriber_giveaway_id'   => array(
				'label'   => __( 'Giveaway ID', 'giveasap' ),
				'type'    => 'integer',
				'preview' => '123',
			),
			'giveasap_subscriber_email'         => array(
				'label'   => __( 'Subscriber Email', 'giveasap' ),
				'type'    => 'text',
				'preview' => 'email@email.com',
			),
			'giveasap_subscriber_ref_id'        => array(
				'label'   => __( 'Subscriber Reference ID', 'giveasap' ),
				'type'    => 'text',
				'preview' => '2309jfm2fmfimdfmm9',
			),
			'giveasap_subscriber_wp_user_id'    => array(
				'label'   => __( 'Subscriber User ID', 'giveasap' ),
				'type'    => 'text',
				'preview' => '12',
			),
			'giveasap_subscriber_entries'       => array(
				'label'   => __( 'Subscriber Entries/Points', 'giveasap' ),
				'type'    => 'text',
				'preview' => '12',
			),
			'giveasap_subscriber_giveaway_link' => array(
				'label'   => __( 'Subscriber\'s Giveaway Link', 'giveasap' ),
				'type'    => 'text',
				'preview' => 'https://yoursite.com/giveaway/the-giveaway?ref=2nru3nu3rn34',
			),
			'giveasap_giveaway_link'            => array(
				'label'   => __( 'Giveaway Link', 'giveasap' ),
				'type'    => 'text',
				'preview' => 'https://yoursite.com/giveaway/the-giveaway',
			),
			'giveasap_giveaway_total_entries'   => array(
				'label'   => __( 'Giveaway Total Entries', 'giveasap' ),
				'type'    => 'text',
				'preview' => '3000',
			),
		);

		return apply_filters( 'giveasap_automatorwp_tags', $tags );
	}

	/**
	 * Return if we have AutomatorWP installed.
	 *
	 * @return bool
	 */
	public function automatorwp_installed() {
		return class_exists( '\AutomatorWP' );
	}

	/**
	 * Including files
	 */
	public function includes() {
		if ( ! $this->automatorwp_installed() ) {
			return;
		}
		include_once 'abstracts/class-automatorwp-base-action.php';
		include_once 'abstracts/class-automatorwp-base-trigger.php';
		include_once 'automatorwp/class-subscribed.php';
		include_once 'automatorwp/class-anonymous-subscribed.php';
		include_once 'automatorwp/class-anonymous-winners-notified.php';
		include_once 'automatorwp/class-winners-notified.php';
		include_once 'automatorwp/actions/class-subscribe.php';
	}

	/**
	 * Register integration
	 */
	public function register_integration() {
		automatorwp_register_integration(
			'giveasap',
			array(
				'label' => 'Simple Giveaways',
				'icon'  => trailingslashit( GASAP_URI ) . 'assets/images/logo-color.svg',
			)
		);
	}
}

add_filter( 'giveasap_integrations', '\Simple_Giveaways\sg_automatorwp_register' );

/**
 * Registering Math Captcha
 *
 * @return array
 */
function sg_automatorwp_register( $integrations ) {

	$integrations['sg_automatorwp'] = '\Simple_Giveaways\SG_AutomatorWP';

	return $integrations;
}
