<?php
/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and hooks to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    CartBounty Pro - Save and recover abandoned carts for WooCommerce
 * @subpackage CartBounty Pro - Save and recover abandoned carts for WooCommerce/admin
 * @author     Streamline.lv
 */
class CartBounty_Pro_Admin{

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * The public handler that manages the plugin's settings, options, and frontend functionality.
	 *
	 * @since    10.9
	 * @access   protected
	 * @var      CartBounty_Pro_Public    $public    Provides methods to control and extend the plugin's public area.
	 */
	protected $public = null;

	/**
	 * The coupons manager responsible for handling coupons.
	 *
	 * @since    10.9
	 * @access   protected
	 * @var      CartBounty_Pro_Coupons    $coupons    Provides methods to create, apply, and manage discount coupons.
	 */
	protected $coupons = null;

	/**
     * The automation handler that manages the plugin's abandoned cart reminder automation functionality.
     *
     * @since    10.9
     * @access   protected
     * @var      CartBounty_Pro_Automation    $automation    Provides methods to control and extend the plugin's automations.
     */
    protected $automation = null;

	/**
	 * The BulkGate handler that manages the plugin's settings, options, and backend functionality.
	 *
	 * @since    10.9
	 * @access   protected
	 * @var      CartBounty_Pro_BulkGate    $bulkgate    Provides methods to control and extend the plugin's BulkGate area.
	 */
	protected $bulkgate = null;

	/**
	 * The ActiveCampaign handler that manages the plugin's settings, options, and backend functionality.
	 *
	 * @since    10.9
	 * @access   protected
	 * @var      CartBounty_Pro_ActiveCampaign    $activecampaign    Provides methods to control and extend the plugin's ActiveCampaign area.
	 */
	protected $activecampaign = null;

	/**
	 * The GetResponse handler that manages the plugin's settings, options, and backend functionality.
	 *
	 * @since    10.9
	 * @access   protected
	 * @var      CartBounty_Pro_GetResponse    $getresponse    Provides methods to control and extend the plugin's GetResponse area.
	 */
	protected $getresponse = null;

	/**
	 * The Push Notification handler that manages the plugin's settings, options, and backend functionality.
	 *
	 * @since    10.9
	 * @access   protected
	 * @var      CartBounty_Pro_Push_Notification    $push_notification    Provides methods to control and extend the plugin's Puch Notification area.
	 */
	protected $push_notification = null;

	/**
	 * The WordPress handler that manages the plugin's settings, options, and backend functionality.
	 *
	 * @since    10.9
	 * @access   protected
	 * @var      CartBounty_Pro_WordPress    		$wordpress    Provides methods to control and extend the plugin's WordPress area.
	 */
	protected $wordpress = null;

	/**
	 * The MailChimp handler that manages the plugin's settings, options, and backend functionality.
	 *
	 * @since    10.9
	 * @access   protected
	 * @var      CartBounty_Pro_Mailchimp    		$mailchimp    Provides methods to control and extend the plugin's MailChimp area.
	 */
	protected $mailchimp = null;

	/**
	 * The Webhook handler that manages the plugin's settings, options, and backend functionality.
	 *
	 * @since    10.9
	 * @access   protected
	 * @var      CartBounty_Pro_Webhook    		$webhook    Provides methods to control and extend the plugin's Webhook area.
	 */
	protected $webhook = null;

	/**
	 * The reports handler that manages the plugin's settings, options, and backend functionality.
	 *
	 * @since    10.9
	 * @access   protected
	 * @var      CartBounty_Pro_Reports    		$reports    Provides methods to control and extend the plugin's Reports area.
	 */
	protected $reports  = null;

	/**
	 * The API connector responsible for handling communication with external services.
	 *
	 * @since    10.9
	 * @access   protected
	 * @var      CartBounty_Pro_API_Connector    $api    Provides methods to send and receive data via API requests.
	 */
	protected $api = null;

	/**
	 * The API access credentials used to authenticate requests with the external service.
	 *
	 * @since    10.9
	 * @access   protected
	 * @var      array    $api_access    Contains authentication data such as API key, token, or other required parameters.
	 */
	protected $api_access = null;

	/**
	 * Get the public handler (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return CartBounty_Pro_Public
	 */
	protected function public(){
		
		if( $this->public === null ){
			$this->public = new CartBounty_Pro_Public( CARTBOUNTY_PRO_PLUGIN_NAME_SLUG, CARTBOUNTY_PRO_VERSION_NUMBER );
		}

		return $this->public;
	}

	/**
	 * Get the coupon handler (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return CartBounty_Pro_Coupons
	 */
	protected function coupons(){
		
		if( $this->coupons === null ){
			$this->coupons = new CartBounty_Pro_Coupons();
		}

		return $this->coupons;
	}

	/**
	 * Get the admin handler (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return CartBounty_Pro_Automation
	 */
	protected function automation(){
		
		if( $this->automation === null ){
			$this->automation = new CartBounty_Pro_Automation();
		}

		return $this->automation;
	}

	/**
	 * Get the BulkGate handler (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return CartBounty_Pro_BulkGate
	 */
	protected function bulkgate(){
		
		if( $this->bulkgate === null ){
			$this->bulkgate = new CartBounty_Pro_BulkGate();
		}

		return $this->bulkgate;
	}

	/**
	 * Get the ActiveCampaign handler (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return CartBounty_Pro_ActiveCampaign
	 */
	protected function activecampaign(){
		
		if( $this->activecampaign === null ){
			$this->activecampaign = new CartBounty_Pro_ActiveCampaign();
		}

		return $this->activecampaign;
	}

	/**
	 * Get the GetResponse handler (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return CartBounty_Pro_GetResponse
	 */
	protected function getresponse(){
		
		if( $this->getresponse === null ){
			$this->getresponse = new CartBounty_Pro_GetResponse();
		}

		return $this->getresponse;
	}

	/**
	 * Get the Push Notification handler (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return CartBounty_Pro_Push_Notification
	 */
	protected function push_notification(){
		
		if( $this->push_notification === null ){
			$this->push_notification = new CartBounty_Pro_Push_Notification();
		}

		return $this->push_notification;
	}

	/**
	 * Get the WordPress handler (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return CartBounty_Pro_WordPress
	 */
	protected function wordpress(){
		
		if( $this->wordpress === null ){
			$this->wordpress = new CartBounty_Pro_WordPress();
		}

		return $this->wordpress;
	}

	/**
	 * Get the MailChimp handler (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return CartBounty_Pro_Mailchimp
	 */
	protected function mailchimp(){
		
		if( $this->mailchimp === null ){
			$this->mailchimp = new CartBounty_Pro_Mailchimp();
		}

		return $this->mailchimp;
	}

	/**
	 * Get the Webhook handler (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return CartBounty_Pro_Webhook
	 */
	protected function webhook(){
		
		if( $this->webhook === null ){
			$this->webhook = new CartBounty_Pro_Webhook();
		}

		return $this->webhook;
	}

	/**
	 * Get the Reports handler (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return CartBounty_Pro_Reports
	 */
	protected function reports(){
		
		if( $this->reports === null ){
			$this->reports = new CartBounty_Pro_Reports();
		}

		return $this->reports;
	}

	/**
	 * Get the API connector (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return CartBounty_Pro_API_Connector
	 */
	protected function api(){
		
		if( $this->api === null ){
			$this->api = new CartBounty_Pro_API_Connector();
		}

		return $this->api;
	}

	/**
	 * Get the API access creentials (lazy-loaded).
	 * Creates the connector on first use and then reuses the same instance.
	 *
	 * @since 10.9
	 * @access protected
	 * @return array
	 */
	protected function api_access(){
		
		if( $this->api_access === null ){
			$this->api_access = $this->get_api_access();
		}

		return $this->api_access;
	}

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0
	 * @param    string    $plugin_name       The name of this plugin.
	 * @param    string    $version    		  The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ){
		$this->plugin_name = $plugin_name;
		$this->version = $version;
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0
	 */
	public function enqueue_styles(){
		global $cartbounty_pro_admin_menu_page;
		$screen = get_current_screen();

		if( !is_object( $screen ) ) return;

		wp_enqueue_style( $this->plugin_name . '-global', plugin_dir_url( __FILE__ ) . 'css/cartbounty-pro-admin-global.css', $this->version ); //Global styles
		wp_style_add_data( $this->plugin_name . '-global', 'rtl', 'replace' );
		
		if( $screen->id == $cartbounty_pro_admin_menu_page ){
			wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/cartbounty-pro-admin.css', array('wp-color-picker'), $this->version );
			wp_style_add_data( $this->plugin_name, 'rtl', 'replace' );
		}
	}

	/**
	 * Register the javascripts for the admin area.
	 *
	 * @since    4.0
	 */
	public function enqueue_scripts(){
		global $cartbounty_pro_admin_menu_page;
		$screen = get_current_screen();
		
		//Do not continue if we are not on CartBounty Pro plugin page
		if( !is_object( $screen ) || $screen->id != $cartbounty_pro_admin_menu_page ) return;

		$data = array(
		    'ajaxurl' 		=> admin_url( 'admin-ajax.php' ),
		    'translations' 	=> array( //Necessary for emojis
		    	'search' 	=> __( 'Search', 'woo-save-abandoned-carts' ),
		    	'clear' 	=> __( 'Clear', 'woo-save-abandoned-carts' ),
		    	'notfound' 	=> __( 'No emoji found', 'woo-save-abandoned-carts' ),
		    	'results' 	=> __( 'Search results', 'woo-save-abandoned-carts' ),
		    	'recent' 	=> __( 'Frequently used', 'woo-save-abandoned-carts' ),
		    	'smileys' 	=> __( 'Smileys & emotion', 'woo-save-abandoned-carts' ),
		    	'people' 	=> __( 'People & body', 'woo-save-abandoned-carts' ),
		    	'nature' 	=> __( 'Animals & nature', 'woo-save-abandoned-carts' ),
		    	'foods' 	=> __( 'Food & drink', 'woo-save-abandoned-carts' ),
		    	'activity' 	=> __( 'Activity', 'woo-save-abandoned-carts' ),
		    	'places' 	=> __( 'Travel & places', 'woo-save-abandoned-carts' ),
		    	'objects' 	=> __( 'Objects', 'woo-save-abandoned-carts' ),
		    	'flags' 	=> __( 'Flags', 'woo-save-abandoned-carts' )
		    )
		);

		if( $screen->id == $cartbounty_pro_admin_menu_page ){ //Load report scripts only on Dashboard

			if( !isset( $_GET['tab'] ) || $_GET['tab'] == 'dashboard' ){
				wp_enqueue_script( $this->plugin_name . '-d3', plugin_dir_url( __FILE__ ) . 'js/d3.min.js', array( 'jquery' ), $this->version, false );
				wp_enqueue_script( $this->plugin_name . '-plot', plugin_dir_url( __FILE__ ) . 'js/plot.min.js', array( 'jquery' ), $this->version, false );
				wp_enqueue_script( $this->plugin_name . '-daypicker', plugin_dir_url( __FILE__ ) . 'js/daypicker.min.js', array( 'jquery' ), $this->version, false );
				wp_enqueue_script( $this->plugin_name . '-reports', plugin_dir_url( __FILE__ ) . 'js/cartbounty-pro-reports.js', array( 'jquery' ), $this->version, false );

				//Adding extra data related with daypicker calendar
				$reports = $this->reports();
				$data['daypicker'] = $reports->prepare_daypicker_data();
				$data['active_charts'] = $reports->get_active_reports( 'charts' );
				$data['chart_type'] = $reports->get_selected_chart_type();
				$data['currency_symbol'] = $reports->get_selected_currency_symbol();
				$data['locale'] = $this->get_locale_with_hyphen( get_user_locale() );
				$data['report_translations'] = array(
					'missing_chart_data' 	=> $reports->get_defaults( 'empty_chart_data' ),
				);
				$data['countries'] = plugin_dir_url( __FILE__ ) . 'assets/countries.json';
			}
		}

		wp_enqueue_script( $this->plugin_name . '-micromodal', plugin_dir_url( __FILE__ ) . 'js/micromodal.min.js', array( 'jquery' ), $this->version, false );
		wp_enqueue_script( $this->plugin_name . '-selectize', plugin_dir_url( __FILE__ ) . 'js/selectize.min.js', array( 'jquery' ), $this->version, false );
		wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/cartbounty-pro-admin.js', array( 'wp-color-picker', 'wp-element', 'jquery' ), $this->version, false );
		wp_localize_script( $this->plugin_name, 'cartbounty_pro_admin_data', $data ); //Sending data over to JS file
	}

	/**
	* Returning setting defaults
	*
	* @since    9.7
	* @return   array or string
	* @param    string     $value                Value to return
	*/
	public function get_defaults( $value = false ){
		$default_placeholders = $this->get_consent_default_placeholders();
		$checkout_consent = $default_placeholders['checkout_consent'];
		$tools_consent = $default_placeholders['tools_consent'];

		$defaults = array(
			'checkout_consent'				=> $checkout_consent,
			'checkout_consent_name'			=> 'Checkout consent label',
			'tools_consent'					=> $tools_consent,
			'tools_consent_name'			=> 'Tools consent notice',
			'hours_from'					=> 21,
			'hours_to'						=> 8
		);

		if($value){ //If a single value should be returned
			if(isset($defaults[$value])){ //Checking if value exists
				$defaults = $defaults[$value];
			}
		}

		return $defaults;
	}

	/**
	* Retrieve CartBounty settings
	*
	* @since    10.1
	* @return   array
	* @param    string     $section              Name of the section which options should be retrieved
	* @param    string     $value                Value to return
	*/
	public function get_settings( $section, $value = false ){

		$saved_options = array();
		$defaults = array();

		switch ( $section ) {

			case 'settings':
				$saved_options = get_option( 'cartbounty_pro_main_settings' );
				$defaults = array(
					'license_key' 				=> 'THANKSAN0',
					'exclude_anonymous_carts' 	=> false,
					'allowed_countries' 		=> array(),
					'delete_anonymous_carts' 	=> false,
					'excluded_emails_phones' 	=> '',
					'notification_email' 		=> '',
					'notification_frequency' 	=> 3600000,
					'gtranslate_key'		 	=> '',
					'exclude_recovered' 		=> false,
					'recaptcha' 				=> array(
						'status' 				=> false,
						'site_key' 				=> '',
						'secret_key' 			=> '',
					),
					'order_recovery'			=> false,
					'order_statuses'			=> array(),
					'international_phone'		=> false,
					'email_consent'				=> false,
					'phone_consent'				=> false,
					'checkout_consent'			=> '',
					'tools_consent'				=> '',
					'lift_email'				=> false,
					'lift_phone'				=> false,
					'hide_images'				=> false,
					'delete_coupons'			=> false,
					'logging_status'			=> false,
					'magic_login'				=> false,
					'magic_login_first_click'	=> false,
					'magic_login_window'		=> 172800000,
					'magic_login_roles'			=> array(),
				);
				break;

			case 'exit_intent':
				$saved_options = get_option( 'cartbounty_pro_exit_intent_settings' );
				$defaults = array(
					'status' 			=> false,
					'mobile_status' 	=> false,
					'field_type' 		=> 'email',
					'heading' 			=> '',
					'content' 			=> '',
					'style' 			=> 1,
					'main_color' 		=> '',
					'inverse_color' 	=> '',
					'image' 			=> '',
					'test_mode' 		=> false,
				);
				break;

			case 'early_capture':
				$saved_options = get_option( 'cartbounty_pro_early_capture_settings' );
				$defaults = array(
					'status' 			=> false,
					'mandatory' 		=> false,
					'field_type' 		=> 'email',
					'heading' 			=> '',
					'style' 			=> 1,
					'main_color' 		=> '',
					'inverse_color' 	=> '',
					'test_mode' 		=> false,
				);

				break;

			case 'tab_notification':
				$saved_options = get_option( 'cartbounty_pro_tab_notification_settings' );
				$defaults = array(
					'status' 			=> false,
					'check_cart' 		=> false,
					'interval' 			=> 2000,
					'content' 			=> '',
					'favicon' 			=> false,
					'favicon_image' 	=> '',
					'test_mode' 		=> false,
				);

				break;

			case 'submitted_warnings':
				$saved_options = get_option( 'cartbounty_pro_submitted_warnings' );
				$defaults = array(
					'mc_setup' 			=> false,
					'ac_setup' 			=> false,
					'gr_setup' 			=> false,
					'cron_warning' 		=> false,
				);

				break;

			case 'misc_settings':

				$saved_options = get_option( 'cartbounty_pro_misc_settings' );
				$defaults = array(
					'saved_license' 					=> 'THANKSAN0N',
					'license_code' 						=> 'THANKSAN0N',
					'version_number' 					=> '',
					'recoverable_carts' 				=> 0,
					'anonymous_carts' 					=> 0,
					'recovered_carts' 					=> 0,
					'times_review_declined' 			=> 0,
					'product_table_exists' 				=> false,
					'coupon_table_exists' 				=> false,
					'message_table_exists' 				=> false,
					'email_table_exists' 				=> false,
					'push_notification_table_exists' 	=> false,
					'carts_imported' 					=> false,
					'type_column_updated' 				=> false,
					'wpml_strings_registered' 			=> false,
					'converted_minutes_to_milliseconds' => false,
					'update_last_checked' 				=> '',
					'expiration_date' 					=> '',
				);

				break;
		}

		if( is_array( $saved_options ) ){
			$settings = array_merge( $defaults, $saved_options ); //Merging default settings with saved options
			
		}else{
			$settings = $defaults;
		}

		if( $value ){ //If a single value should be returned
			
			if( isset( $settings[$value] ) ){ //Checking if value exists
				$settings = $settings[$value];
			}
		}

		return $settings;
	}

	/**
	 * Method retrieves saved API credentials
	 *
	 * @since    10.9
	 * @return 	 Array
	 */
	public function get_api_access(){
		$api_access = array(
			'api_key' => '',
			'api_url' => $this->get_license_server_url()
		);

		return $api_access;
	}
	
	/**
	 * Register the menu under WooCommerce admin menu.
	 *
	 * @since    1.0
	 */
	function cartbounty_pro_menu(){
		global $cartbounty_pro_admin_menu_page;
		if(class_exists('WooCommerce')){ //Check if WooCommerce plugin is active
			$cartbounty_pro_admin_menu_page = add_submenu_page( 'woocommerce', CARTBOUNTY_PRO_PLUGIN_NAME, esc_html__('CartBounty Pro Abandoned carts', 'woo-save-abandoned-carts'), 'list_users', CARTBOUNTY_PRO, array( $this, 'display_page' ));//If the plugin is active - output menu under WooCommerce
		}else{
			$cartbounty_pro_admin_menu_page = add_menu_page( CARTBOUNTY_PRO_PLUGIN_NAME, esc_html__('CartBounty Pro Abandoned carts', 'woo-save-abandoned-carts'), 'list_users', CARTBOUNTY_PRO, array( $this,'display_page' ), 'dashicons-archive' ); //Else output the menu as a Page
		}
	}
	
	/**
	 * Adds newly abandoned, recoverable abandoned cart count to the menu
	 *
	 * @since    1.2
	 */
	function menu_abandoned_count(){
		global $wpdb, $submenu;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;

		if ( isset( $submenu['woocommerce'] ) ) { //If WooCommerce Menu exists
			$time = $this->get_time_intervals();
			$where_sentence = $this->get_where_sentence( 'recoverable' );

			$recoverable_new_cart_count = $wpdb->get_var( //Counting newly abandoned carts
				$wpdb->prepare(
					"SELECT COUNT(id)
					FROM $cart_table
					WHERE cart_contents != ''
					$where_sentence AND
					time > %s",
					$time['old_cart']
				)
			);

			foreach( $submenu['woocommerce'] as $key => $menu_item ){ //Go through all submenu sections of WooCommerce and look for CartBounty Pro Abandoned carts

				if( isset( $menu_item[0] ) ){
					if ( 0 === strpos( $menu_item[0], esc_html__( 'CartBounty Pro Abandoned carts', 'woo-save-abandoned-carts' ) ) ){
						$submenu['woocommerce'][$key][0] .= ' <span class="new-abandoned update-plugins count-' . esc_attr( $recoverable_new_cart_count ) . '">' . esc_html( $recoverable_new_cart_count ) .'</span>';
					}
				}
			}
		}
	}
	
	/**
	 * Adds Screen options tab and Help tab to plugin
	 *
	 * @since    1.0
	 */
	function register_admin_tabs(){
		global $cartbounty_pro_admin_menu_page;
		$screen = get_current_screen();
		$mailchimp = $this->mailchimp();
		$automation = $this->automation();
		$status = new CartBounty_Pro_System_Status(CARTBOUNTY_PRO_PLUGIN_NAME_SLUG, CARTBOUNTY_PRO_VERSION_NUMBER);
		$coupons = $this->coupons();
		
		// Check if we are on CartBounty Pro - Save and recover abandoned carts for WooCommerce page
		if(!is_object($screen) || $screen->id != $cartbounty_pro_admin_menu_page){
			return;

		}else{
			//Outputting how many rows we would like to see on the page
			$option = 'per_page';
			$args = array(
				'label' 	=> esc_html__('Carts per page:', 'woo-save-abandoned-carts'),
				'default' 	=> 10,
				'option' 	=> 'cartbounty_pro_carts_per_page'
			);

			//Adding screen options only on Abandoned cart page
			if(isset($_GET['tab'])){
				if($_GET['tab'] == 'carts'){
					add_screen_option( $option, $args );
				}
			}elseif(!isset($_GET['tab'])){
				add_screen_option( $option, $args );
			}

			$nonce = wp_create_nonce( 'get_system_status' );
			//Ads Help tab sections
			$cartbounty_pro_carts_help_support_content = '
				<h2>'. esc_html__('Need help or support?', 'woo-save-abandoned-carts') .'</h2>
				<p>'. sprintf(
					/* translators: %1$s - Plugin name */
					esc_html__('%1$s saves all activity in the WooCommerce checkout form before it is submitted. The plugin allows to see who abandons your shopping carts and get in touch with them.', 'woo-save-abandoned-carts'), esc_html( CARTBOUNTY_PRO_SHORT ) ) . '<br/>' .
					esc_html__('You will receive regular email notifications about newly abandoned shopping carts and will be able to remind about these carts either manually or automatically by sending automated abandoned cart recovery messages.', 'woo-save-abandoned-carts') .'</p>
				<p>'. sprintf(
					/* translators: %1$s - Link start, %2$s - Link end */
					esc_html__('If you have additional questions, please see the readme file, or look at %1$sfrequently asked questions%2$s.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( $this->get_trackable_link('' . 'faq', 'help_tab_faq') ) .'" target="_blank">', '</a>' ) .'</p>
				<div class="cartbounty-pro-button-row"><a href="'. esc_url( $this->get_trackable_link('' . 'faq', 'help_tab_faq_button') ) .'" class="cartbounty-pro-button" target="_blank">'. esc_html__('View FAQ', 'woo-save-abandoned-carts') .'</a><span class="cartbounty-pro-tooltip-container"><a href="#" id="cartbounty-pro-copy-system-status" class="cartbounty-pro-button cartbounty-pro-progress" data-nonce="' . esc_attr( $nonce ) . '">'. esc_html__('Copy system report', 'woo-save-abandoned-carts') .'</a><span class="cartbounty-pro-tooltip">'. esc_html__('Copied to clipboard', 'woo-save-abandoned-carts') .'</span></span><a href="'. esc_url( $this->get_trackable_link(CARTBOUNTY_PRO_SUPPORT_LINK, 'help_tab_support_button') ) .'" class="cartbounty-pro-button" target="_blank">'. esc_html__('Get support', 'woo-save-abandoned-carts') .'</a></div>';

			$screen->add_help_tab( array(
				'id'       =>	'cartbounty_pro_carts_help_support',
				'title'    =>	esc_html__('Need help?', 'woo-save-abandoned-carts'),
				'content'  =>	$cartbounty_pro_carts_help_support_content
			));

			$license_valid = $this->check_license();

			//Outputs Report bug info and button as well as Export tables button.
			//The Export tables button is available if the license key is valid and MailChimp is connected to a list. We are using conditional statement (conditional expression) ? (true) : (false)
			$cartbounty_pro_carts_help_report_bug = '
				<h2>'. esc_html__('Export data', 'woo-save-abandoned-carts') .'</h2>
				<p>'. esc_html__('You can export your abandoned carts as well as data related to MailChimp synchronization.', 'woo-save-abandoned-carts') . '<br/>' . esc_html__('This data can be also very useful when it comes to debugging abandoned cart synchronization issues.', 'woo-save-abandoned-carts') . '</p>
				<div class="cartbounty-pro-button-row">
					'. ( $license_valid && $this->get_cart_count( 'all' ) != 0 ? '<form method="post"><input type="hidden" name="cartbounty_pro_export_carts" value="cartbounty_pro_export_c" /><button type="submit" id="export-carts" class="cartbounty-pro-button cartbounty-pro">'. esc_html__('Export carts', 'woo-save-abandoned-carts') .'</button></form>': '').
					( $license_valid && $automation->get_stats( 'wordpress', 'send' ) > 0 ? '<form method="post"><input type="hidden" name="cartbounty_pro_export_emails" value="cartbounty_pro_export_e" /><button type="submit" id="export-emails" class="cartbounty-pro-button">'. esc_html__('Export email log', 'woo-save-abandoned-carts') .'</button></form>' : '').
					( $license_valid && $automation->get_stats( 'bulkgate', 'send' ) > 0 ? '<form method="post"><input type="hidden" name="cartbounty_pro_export_messages" value="cartbounty_pro_export_sms" /><button type="submit" id="export-messages" class="cartbounty-pro-button">'. esc_html__('Export SMS log', 'woo-save-abandoned-carts') .'</button></form>' : '').
					( $license_valid && $this->product_count() > 0 ? '<form method="post"><input type="hidden" name="cartbounty_pro_export_products" value="cartbounty_pro_export_p" /><button type="submit" id="export-products" class="cartbounty-pro-button">'. esc_html__('Export products', 'woo-save-abandoned-carts') .'</button></form>' : '').
					( $license_valid && $coupons->coupon_count() > 0 ? '<form method="post"><input type="hidden" name="cartbounty_pro_export_coupons" value="cartbounty_pro_export_cp" /><button type="submit" id="export-coupons" class="cartbounty-pro-button">'. esc_html__('Export coupons', 'woo-save-abandoned-carts') .'</button></form>' : '').
					( $license_valid && $mailchimp->store_connected() ? '<form method="post"><input type="hidden" name="cartbounty_pro_export_mailchimp" value="cartbounty_pro_export_m" /><button type="submit" id="export-mailchimp" class="cartbounty-pro-button">'. esc_html__('Export last MailChimp sync status', 'woo-save-abandoned-carts') .'</button></form>': '').
					( $license_valid && ( $automation->get_stats( 'push_notification', 'send' ) > 0 || $automation->get_stats( 'push_notification', 'send_failed' ) > 0 ) ? '<form method="post"><input type="hidden" name="cartbounty_pro_export_push_notifications" value="cartbounty_pro_export_pn" /><button type="submit" id="export-push-notifications" class="cartbounty-pro-button">'. esc_html__('Export notification log', 'woo-save-abandoned-carts') .'</button></form>' : '').
					'
				</div>';

			$screen->add_help_tab( array(
				'id'       =>	'cartbounty_pro_carts_report_bug',
				'title'    =>	esc_html__('Export data', 'woo-save-abandoned-carts'),
				'content'  =>	$cartbounty_pro_carts_help_report_bug
			));

			if($this->get_free_version_carts()){
				$nonce = wp_create_nonce( 'import_carts' );
				$cartbounty_pro_import_carts = '
					<h2>'. esc_html__("Leave no abandoned cart behind!", 'woo-save-abandoned-carts') .'</h2>
					<p>'. sprintf(
						/* translators: %1$s - Plugin name */
						esc_html__('Import your abandoned carts captured by our free version of %s and increase your sales using the power of automated abandoned cart recovery emails.', 'woo-save-abandoned-carts'), esc_html( CARTBOUNTY_PRO_SHORT ) ) . '<br/>' . sprintf( esc_html__('Please note that carts older than %d days will not be imported.', 'woo-save-abandoned-carts'), CARTBOUNTY_PRO_MAX_SYNC_PERIOD ) .'</p>
					<div class="cartbounty-pro-button-row">
						'. ( $license_valid && !$this->import_complete() ? '
							<button type="submit" class="import-carts cartbounty-pro-button" data-nonce="' . esc_attr( $nonce ) . '">'. esc_html__('Import carts', 'woo-save-abandoned-carts') .'</button>': '
							<button type="submit" class="import-carts cartbounty-pro-button" disabled>'. esc_html__('Import carts', 'woo-save-abandoned-carts') .'</button><span id="cartbounty-pro-import-carts-response">'. esc_html__("Captain, we have already done this.", 'woo-save-abandoned-carts') .'</span>
						').'
					</div>';
				$screen->add_help_tab( array(
					'id'       =>	'cartbounty_pro_import_carts',
					'title'    =>	esc_html__('Import carts', 'woo-save-abandoned-carts'),
					'content'  =>	$cartbounty_pro_import_carts
				));
			}

			$cartbounty_pro_carts_help_request_feature = '
				<h2>'. esc_html__("Have a new feature in mind? That's awesome!", 'woo-save-abandoned-carts') .'</h2>
				<p>'. sprintf(
					/* translators: %s - Plugin name */
					esc_html__('We always welcome suggestions from our users and will evaluate each new idea to improve %s. In fact, many of the features you are currently using have arrived from users like yourself.', 'woo-save-abandoned-carts'), esc_html( CARTBOUNTY_PRO_ABBREVIATION ) ) .'</p>
				<div class="cartbounty-pro-button-row"><a href="'. esc_url( $this->get_trackable_link(CARTBOUNTY_PRO_FEATURE_LINK, 'help_tab_suggest_feature') ) .'" class="cartbounty-pro-button" target="_blank">'. esc_html__('Suggest a feature', 'woo-save-abandoned-carts') .'</a>
				</div>';
			$screen->add_help_tab( array(
				'id'       =>	'cartbounty_pro_carts_request_feature',
				'title'    =>	esc_html__('Suggest a feature', 'woo-save-abandoned-carts'),
				'content'  =>	$cartbounty_pro_carts_help_request_feature
			));
		}
	}

	/**
	 * Saves settings displayed under Screen options
	 *
	 * @since    1.0
	 */
	function save_page_options( $status, $option, $value ){
		return $value;
	}
	
	/**
	 * Display the abandoned carts and settings under admin page
	 *
	 * @since    1.0
	 */
	function display_page(){
		global $pagenow;
	
		if( !$this->user_is_shop_manager() ){
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'woo-save-abandoned-carts'));
		}?>
		
		<div id="cartbounty-pro-page-wrapper" class="wrap<?php if( $this->get_settings( 'settings', 'hide_images' ) ) {echo " cartbounty-pro-without-thumbnails";}?>">
			<h1><?php esc_html_e( CARTBOUNTY_PRO_ABBREVIATION ); ?></h1>
			<?php do_action( 'cartbounty_pro_after_page_title' ); 
			$active_tab = $this->get_default_open_tab();
			
			if( isset( $_GET['tab'] ) ){
				$active_tab = $_GET['tab'];
			}

			$this->create_admin_tabs( $active_tab );
			
			if( $pagenow == 'admin.php' && $_GET['page'] == CARTBOUNTY_PRO ){
				$tab = $this->get_open_tab();
				$current_section = $this->get_open_section();

				if($current_section): //If one of the sections has been opened

					$sections = $this->get_sections( $tab );
					foreach( $sections as $key => $section ){
						if($current_section == $key): //Determine which section is open to output correct contents ?>
							<div id="cartbounty-pro-content-container">
								<div class="cartbounty-pro-row">
									<div class="cartbounty-pro-sidebar cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3"><?php $this->display_sections( $current_section, $tab ); ?></div>
									<div class="cartbounty-pro-content cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
										<div class="cartbounty-pro-settings-container">
											<h2 class="cartbounty-pro-section-title"><?php esc_html_e( $section['name'] ); ?></h2>
											<?php $this->section_contents( $key ); ?>
										</div>
									</div>
								</div>
							</div>
						<?php endif;
					}?>

				<?php elseif( $tab == 'dashboard' ): //Dashboard tab ?>

					<?php
					$reports = $this->reports();
					$nonce = wp_create_nonce('cartbounty_pro_report_period');
					$reports->update_currency_rates();
					?>

					<div id="cartbounty-pro-content-container" class="cartbounty-pro-dashboard">
						<div class="cartbounty-pro-row cartbounty-pro-flex">
							<div class="cartbounty-col-xs-6 cartbounty-col-sm-6 cartbounty-pro-dashboard-title-column">
								<h2 id="cartbounty-pro-dashboard-title" class="cartbounty-pro-section-title"><?php esc_html_e( 'Welcome to Dashboard', 'woo-save-abandoned-carts' ); ?></h2>
							</div>
							<div class="cartbounty-col-xs-6 cartbounty-col-sm-6 cartbounty-pro-calendar-column">
								<div id="cartbounty-pro-calendar-container">
									<div id="cartbounty-pro-period-dropdown-container">
										<?php echo $reports->display_period_dropdown(); ?>
									</div>
									<div id="cartbounty-pro-daypicker-container">
										<form method="post">
											<input type="hidden" name="cartbounty_pro_apply_period" value="cartbounty_pro_apply_period_c" />
											<input type="hidden" name="cartbounty_pro_report_period" value="<?php echo $nonce; ?>">
											<div id='cartbounty-daypicker-container'></div>
										</form>
									</div>
								</div>
							</div>
							<div class="cartbounty-col-xs-12 cartbounty-col-md-6 cartbounty-col-lg-7">
								<div class="cartbounty-pro-abandoned-cart-stats-block cartbounty-pro-report-widget">
									<div class="cartbounty-pro-stats-header cartbounty-pro-report-content">
										<h3>
											<i class="cartbounty-pro-widget-icon cartbounty-pro-abandoned-cart-stats-icon">
												<img src="<?php echo esc_url( plugins_url( 'assets/reports-icon.svg', __FILE__ ) ) ?>" />
											</i><?php esc_html_e( 'Abandoned cart reports', 'woo-save-abandoned-carts' ); ?>
										</h3>
										<?php echo $reports->edit_options( 'reports' ); ?>
									</div>
									<?php echo $reports->display_reports(); ?>
								</div>
							</div>
							<div class="cartbounty-col-xs-12 cartbounty-col-md-6 cartbounty-col-lg-5">
								<?php echo $this->display_dashboard_notices(); ?>
								<div class="cartbounty-pro-abandoned-carts-by-country cartbounty-pro-report-widget">
									<div class="cartbounty-pro-stats-header cartbounty-pro-report-content">
										<h3 id="cartbounty-pro-abandoned-carts-by-country-report-name-container">
											<i class="cartbounty-pro-widget-icon cartbounty-pro-top-abandoned-products-icon">
												<img src="<?php echo esc_url( plugins_url( 'assets/world-map-icon.svg', __FILE__ ) ) ?>" />
											</i>
											<span id="cartbounty-pro-abandoned-carts-by-country-report-name"><?php echo $reports->get_selected_map_report_name(); ?></span>
										</h3>
										<?php echo $reports->edit_options( 'carts-by-country' ); ?>
									</div>
									<div id="cartbounty-pro-abandoned-carts-by-country-container" class="cartbounty-pro-loading-skeleton-screen">
										<?php echo $reports->display_report_skeleton( 'map' ); ?>
									</div>
								</div>
								<div class="cartbounty-pro-top-abandoned-products cartbounty-pro-report-widget">
									<div class="cartbounty-pro-stats-header cartbounty-pro-report-content">
										<h3>
											<i class="cartbounty-pro-widget-icon cartbounty-pro-top-abandoned-products-icon">
												<img src="<?php echo esc_url( plugins_url( 'assets/top-products-icon.svg', __FILE__ ) ) ?>" />
											</i>
											<?php esc_html_e( 'Top abandoned products', 'woo-save-abandoned-carts' ); ?>
										</h3>
										<?php echo $reports->edit_options( 'top-products' ); ?>
									</div>
									<div id="cartbounty-pro-top-abandoned-products-container">
										<div id="cartbounty-pro-cart-top-products" class="cartbounty-pro-dashboard-table cartbounty-pro-loading-skeleton-screen">
											<?php echo $reports->display_report_skeleton( 'top_products' ); ?>
										</div>
									</div>
								</div>
								<?php $active_features = $this->display_active_features();
								if( !empty( trim( $active_features ) ) ) : ?>
								<div class="cartbounty-pro-active-features">
									<h3><?php esc_html_e( 'Active features', 'woo-save-abandoned-carts' ); ?></h3>
									<div class="cartbounty-pro-row cartbounty-pro-flex">
										<?php echo $active_features; ?>
									</div>
								</div>
								<?php endif; ?>
							</div>
						</div>
					</div>

				<?php elseif( $tab == 'carts' ): //Abandoned carts tab ?>

					<?php
						require_once plugin_dir_path( __FILE__ ) . 'class-cartbounty-pro-admin-table.php';
						$table = new CartBounty_Pro_Table();
						$table->prepare_items();
						$current_action = $table->current_action();

						//Output table contents
						$message = '';
						
						if( $current_action ){

							if( !empty( $_REQUEST['id'] ) ){ //In case we have a row selected, process the message output
								$processed_rows = 0;
								$action_message = esc_html__( 'Carts deleted: %d', 'woo-save-abandoned-carts' );

								if( isset( $_REQUEST['processed_rows'] ) ){
									$processed_rows = esc_html( $_REQUEST['processed_rows'] );
								}

								if( $current_action === 'pause' ){
									$action_message = esc_html__( 'Carts paused: %d', 'woo-save-abandoned-carts' );

								}elseif( $current_action === 'resume' ){
									$action_message = esc_html__( 'Carts resumed: %d', 'woo-save-abandoned-carts' );
								
								}elseif( $current_action === 'restart' ){
									$action_message = esc_html__( 'Carts restarted: %d', 'woo-save-abandoned-carts' );
								}

								$message = '<div class="updated below-h2" id="message"><p>' . sprintf(
									/* translators: %d - Item count */
									$action_message, esc_html( $processed_rows )
								) . '</p></div>';
							}
						}

						$cart_status = 'all';
						if (isset($_GET['cart-status'])){
							$cart_status = $_GET['cart-status'];
						}
					?>
					<?php echo $message;
					if ($this->get_cart_count( 'all' ) == 0): //If no abandoned carts, then output this note ?>
						<p id="cartbounty-pro-no-carts-message">
							<?php echo wp_kses_post( __( 'Looks like you do not have any saved Abandoned carts yet.<br/>But do not worry, as soon as someone fills the <strong>Email</strong> or <strong>Phone number</strong> fields of your WooCommerce Checkout form and abandons the cart, it will automatically appear here.', 'woo-save-abandoned-carts') ); ?>
						</p>
						<?php if($this->get_free_version_carts() && !$this->import_complete() ){
							$nonce = wp_create_nonce( 'import_carts' );
							$cartbounty_pro_import_carts = '
								<p>'. sprintf( esc_html__('Ahh, magnificent! You have already saved some abandoned carts using our free version of %s. Why not importing them?', 'woo-save-abandoned-carts'), esc_html( CARTBOUNTY_PRO_SHORT ) ) . '<br/>' . sprintf( esc_html__('Please note that carts older than %d days will not be imported.', 'woo-save-abandoned-carts'), CARTBOUNTY_PRO_MAX_SYNC_PERIOD ) .'</p>
								<div class="cartbounty-pro-button-row">
									<button type="submit" class="cartbounty-pro-button import-carts button button-primary cartbounty-pro-progress" data-nonce="' . esc_attr( $nonce ) . '">'. esc_html__('Import carts', 'woo-save-abandoned-carts') .'</button>
								</div>';
							echo $cartbounty_pro_import_carts;
						} ?>
					<?php else: ?>
						<?php $nonce = wp_create_nonce( 'search_carts' ); ?>
						<?php
						$action_url = admin_url( 'admin.php' );
						$search_phrase = '';
						if(isset($_GET['cartbounty-pro-search'])){
							$search_phrase = $_GET['cartbounty-pro-search'];
							if(!empty($search_phrase)){
								$searching_for_phrase = '
								<p id="cartbounty-search-phrase">
									'. esc_html__('Search results for ', 'woo-save-abandoned-carts') . '"' . esc_html__( stripslashes( $search_phrase ) ) . '"' .'
								</p>';
								echo $searching_for_phrase;
							}
						}?>
					
						<form id="cartbounty-pro-table" method="GET" action="<?php echo esc_url( $action_url ); ?>">
							<div class="cartbounty-pro-row">
								<div class="cartbounty-col-sm-6">
									<?php $this->display_cart_statuses( $cart_status, $tab);?>
								</div>
								<div class="cartbounty-col-sm-6">
									<div id="cartbounty-pro-cart-search">
										<label class="screen-reader-text" for="post-search-input"><?php esc_html_e('Search carts', 'woo-save-abandoned-carts'); ?> :</label>
										<input type="search" id="cartbounty-pro-cart-search-input" class="cartbounty-pro-text" name="cartbounty-pro-search" value="<?php echo esc_attr( stripslashes( $search_phrase ) ); ?>"><button type="submit" id="cartbounty-pro-search-submit" class="cartbounty-pro-button button button-secondary cartbounty-pro-progress"><i class="cartbounty-pro-icon cartbounty-pro-visible-xs"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70.06 70"><path d="M30,60a29.9,29.9,0,0,0,16.64-5.06L60.7,69a3.58,3.58,0,0,0,5,0L69,65.64a3.57,3.57,0,0,0,0-5l-14.13-14A30,30,0,1,0,30,60Zm0-48.21A18.23,18.23,0,1,1,11.76,30,18.24,18.24,0,0,1,30,11.76Zm0,0" transform="translate(0)"/></svg></i><i class='cartbounty-pro-hidden-xs'><?php esc_html_e('Search carts', 'woo-save-abandoned-carts'); ?></i>
										</button>
									</div>
								</div>
							</div>
							<input type="hidden" name="cart-status" value="<?php echo esc_attr( $cart_status ); ?>">
							<input type="hidden" name="search-nonce" value="<?php echo esc_attr( $nonce ); ?>">
							<input type="hidden" name="page" value="<?php echo esc_attr( $_REQUEST['page'] ); ?>"/>
							<input type="hidden" name="tab" value="<?php echo esc_attr( $tab ); ?>"/>
							<input type="hidden" name="nonce" value="<?php echo wp_create_nonce( 'bulk_action_nonce' ); ?>"/>
							<?php $table->display(); ?>
						</form>
					<?php endif; ?>

				<?php elseif( $tab == 'recovery' ): //Recovery tab ?>

					<div id="cartbounty-pro-content-container">
						<div class="cartbounty-pro-row">
							<div class="cartbounty-pro-sidebar cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3"><?php $this->display_sections( $current_section, $tab ); ?></div>
							<div class="cartbounty-pro-content cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
								<h2 class="cartbounty-pro-section-title"><?php esc_html_e('Recovery', 'woo-save-abandoned-carts'); ?></h2>
								<div class="cartbounty-pro-section-intro"><?php esc_html_e('Automate your abandoned cart recovery by sending automated recovery emails, SMS text messages and web push notifications to your visitors.', 'woo-save-abandoned-carts'); ?><br/><?php esc_html_e('Connect and build your perfect abandoned cart recovery process.', 'woo-save-abandoned-carts'); ?></div>
								<div class="cartbounty-pro-row cartbounty-pro-flex">
									<?php
									$recovery_items = $this->get_sections( $tab );
									foreach( $recovery_items as $key => $item ): ?>
										<?php $button = esc_html__('Connect', 'woo-save-abandoned-carts'); 
											if($item['connected']){
												$button = esc_html__('Edit', 'woo-save-abandoned-carts');
											}
										?>
										<div class="cartbounty-pro-section-item-container cartbounty-col-sm-6 cartbounty-col-lg-4">
											<div class="cartbounty-pro-section-item<?php if($item['connected']){echo ' cartbounty-pro-connected'; }?>">
												<?php $link = '?page='. CARTBOUNTY_PRO .'&tab='. $tab .'&section='. $key; ?>
												<div class="cartbounty-pro-section-image">
													<?php echo $this->get_connection( $item['connected'], true, $tab ); ?>
													<a href="<?php echo esc_url( $link ); ?>" title="<?php echo esc_attr( $item['name'] ); ?>"><?php echo $this->get_icon( $key, false, false, true ); ?></a>
												</div>
												<div class="cartbounty-pro-section-content">
													<h3><a href="<?php echo esc_url( $link ); ?>" title="<?php echo esc_attr( $item['name'] ); ?>"><?php echo esc_html( $item['name'] ); ?></a></h3>
													<?php echo wp_kses_post( $item['description'] ); ?>
													<a class="button cartbounty-pro-button" href="<?php echo esc_url( $link ); ?>"><?php echo esc_html( $button ); ?></a>
												</div>
											</div>
										</div>
									<?php endforeach; ?>
								</div>
							</div>
						</div>
					</div>

				<?php elseif( $tab == 'tools' ): //Tools tab ?>

					<div id="cartbounty-pro-content-container">
						<div class="cartbounty-pro-row">
							<div class="cartbounty-pro-sidebar cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3"><?php $this->display_sections( $current_section, $tab ); ?></div>
							<div class="cartbounty-pro-content cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
								<h2 class="cartbounty-pro-section-title"><?php esc_html_e('Tools', 'woo-save-abandoned-carts'); ?></h2>
								<div class="cartbounty-pro-section-intro"><?php esc_html_e('Here you will find some special tools that will enable you to discover even more bounty. Increase your chances of getting more recoverable abandoned carts. You can enable one or all of them, just make sure not to overwhelm your visitors with information :)', 'woo-save-abandoned-carts'); ?></div>
								<div class="cartbounty-pro-row cartbounty-pro-flex">
									<?php
									$tools_items = $this->get_sections( $tab );
									foreach( $tools_items as $key => $item ): ?>
										<?php $button = esc_html__('Enable', 'woo-save-abandoned-carts'); 
											if($item['connected']){
												$button = esc_html__('Edit', 'woo-save-abandoned-carts');
											}
										?>
										<div class="cartbounty-pro-section-item-container cartbounty-col-sm-6 cartbounty-col-lg-4">
											<div class="cartbounty-pro-section-item<?php if($item['connected']){echo ' cartbounty-pro-connected'; }?>">
												<?php $link = '?page='. CARTBOUNTY_PRO .'&tab='. $tab .'&section='. $key; ?>
												<div class="cartbounty-pro-section-image">
													<?php echo $this->get_connection( $item['connected'], true, $tab ); ?>
													<a href="<?php echo esc_url( $link ); ?>" title="<?php echo esc_attr( $item['name'] ); ?>"><?php echo $this->get_icon( $key, false, false, true ); ?></a>
												</div>
												<div class="cartbounty-pro-section-content">
													<h3><a href="<?php echo esc_url( $link ); ?>" title="<?php echo esc_attr( $item['name'] ); ?>"><?php echo esc_html( $item['name'] ); ?></a></h3>
													<?php echo wp_kses_post( $item['description'] ); ?>
													<a class="button cartbounty-pro-button" href="<?php echo esc_url( $link ); ?>"><?php echo esc_html( $button ); ?></a>
												</div>
											</div>
										</div>
									<?php endforeach; ?>
								</div>
							</div>
						</div>
					</div>

				<?php elseif( $tab == 'settings' ): //Settings tab ?>

					<div id="cartbounty-pro-content-container">
						<div class="cartbounty-pro-settings-container">
							<form method="post" action="options.php">
								<?php
									$settings = $this->get_settings( 'settings' );
									$exclude_anonymous_carts = $settings['exclude_anonymous_carts'];
									$allowed_countries = $settings['allowed_countries'];
									$excluded_emails_phones = $settings['excluded_emails_phones'];
									$notification_email = $settings['notification_email'];
									$gtranslate_key = $settings['gtranslate_key'];
									$exclude_recovered = $settings['exclude_recovered'];
									$email_consent = $settings['email_consent'];
									$phone_consent = $settings['phone_consent'];
									$checkout_consent = $settings['checkout_consent'];
									$tools_consent = $settings['tools_consent'];
									$lift_email = $settings['lift_email'];
									$lift_phone = $settings['lift_phone'];
									$hide_images = $settings['hide_images'];
									$delete_coupons = $settings['delete_coupons'];
									$logging_status = $settings['logging_status'];
									$magic_login = $settings['magic_login'];
									$magic_login_first_click = $settings['magic_login_first_click'];
									$license = $this->activate_license(); //Check license key and output message
									$license_active = $this->check_license();
									$consent_nonce = wp_create_nonce( 'consent_nonce' );

									//Handling reCAPTCHA field array
									$recaptcha = $this->get_recaptcha();
									$gtranslate = new CartBounty_Pro_GTranslate();
								?>
								<div class="cartbounty-pro-row">
									<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
										<h4><?php esc_html_e('License & Activation', 'woo-save-abandoned-carts'); ?></h4>
										<p class="cartbounty-pro-titles-column-description">
											<?php esc_html_e('To get product updates and premium support.', 'woo-save-abandoned-carts'); ?>
										</p>
									</div>
									<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9">
										<div class="cartbounty-pro-settings-group">
											<label for="cartbounty_pro_license_key"><?php esc_html_e('License key', 'woo-save-abandoned-carts'); ?>
												<?php echo $this->output_connection_message( $license ); ?>
											</label>
											<input id="cartbounty_pro_license_key" class="cartbounty-pro-text" type="text" name="cartbounty_pro_main_settings[license_key]" value="<?php echo esc_attr( $settings['license_key'] ); ?>" <?php echo $this->disable_field(); ?> />
											<?php 
											if(!$license_active && $license['status'] != '3'){
												echo '<p class="cartbounty-pro-additional-information">'. esc_html__('Plugin will not function unless a valid license key is provided.', 'woo-save-abandoned-carts') .'</p>';
											}elseif( $license['status'] == '3' ){ //If License expired
												echo '<p class="cartbounty-pro-additional-information cartbounty-pro-expired-notice"><i class="license-status-icon"><img src="'. esc_url( plugins_url( 'assets/expired-license-icon.svg', __FILE__ ) ) .'" /></i>'. $license['expired_message'] .'</p>';
											}?>
										</div>
									</div>
								</div>
								<div class="cartbounty-pro-row">
									<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
										<h4><?php esc_html_e( 'Abandoned carts', 'woo-save-abandoned-carts' ); ?></h4>
										<p class="cartbounty-pro-titles-column-description">
											<?php esc_html_e( 'Manage shopping cart exclusions. Specify emails or phone numbers to prevent them from being saved as abandoned carts by CartBounty.', 'woo-save-abandoned-carts' ); ?>
										</p>
									</div>
									<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9<?php if( $exclude_anonymous_carts ){ echo ' cartbounty-pro-checked-parent'; }?>">
										<div class="cartbounty-pro-settings-group cartbounty-pro-toggle<?php if( $exclude_anonymous_carts ){ echo ' cartbounty-pro-checked'; }?>">
											<label for="cartbounty-pro-exclude-anonymous-carts" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
												<input id="cartbounty-pro-exclude-anonymous-carts" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[exclude_anonymous_carts]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $exclude_anonymous_carts, false ); ?> autocomplete="off" />
												<span class="cartbounty-pro-slider round"></span>
											</label>
											<label for="cartbounty-pro-exclude-anonymous-carts" class="cartbounty-pro-control-visibility">
												<?php esc_html_e( 'Exclude anonymous carts', 'woo-save-abandoned-carts' ); ?>
											</label>
										</div>
										<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
											<label for="cartbounty_pro_allowed_countries"><?php esc_html_e('Exclude from all countries except these', 'woo-save-abandoned-carts'); ?></label>
											<?php $this->display_countries( 'settings' ); ?>
										</div>
										<div class="cartbounty-pro-settings-group">
											<?php $this->display_time_intervals( 'cartbounty_pro_main_settings[delete_anonymous_carts]' ); ?>
										</div>
										<div class="cartbounty-pro-settings-group">
											<label for="cartbounty-pro-excluded-emails-phones"><?php esc_html_e( 'Exclude carts containing any of these emails and phone numbers', 'woo-save-abandoned-carts' ); ?></label>
											<input id="cartbounty-pro-excluded-emails-phones" class="cartbounty-pro-text cartbounty-pro-display-emails" type="text" name="cartbounty_pro_main_settings[excluded_emails_phones]" value="<?php echo esc_attr( $excluded_emails_phones ); ?>" <?php echo $this->disable_field(); ?> />
											<p class='cartbounty-pro-additional-information'>
												<?php esc_html_e( 'You can add multiple emails and phone numbers separated by a comma.', 'woo-save-abandoned-carts' ); ?> <?php esc_html_e( 'You can also use an asterisk (*) to match parts of an email. For example, "*@gmail.com" would match all Gmail addresses.', 'woo-save-abandoned-carts' ); ?>
											</p>
										</div>
										<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
											<label for="cartbounty-pro-hide-images" class="cartbounty-pro-switch">
												<input id="cartbounty-pro-hide-images" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[hide_images]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $hide_images, false ); ?> autocomplete="off" />
												<span class="cartbounty-pro-slider round"></span>
											</label>
											<label for="cartbounty-pro-hide-images"><?php esc_html_e('Display abandoned cart contents in a list', 'woo-save-abandoned-carts'); ?></label>
											<p class='cartbounty-pro-additional-information'>
												<?php esc_html_e('This will only affect how abandoned cart contents are displayed in the list of abandoned carts.', 'woo-save-abandoned-carts'); ?>
											</p>
										</div>
									</div>
								</div>
								<div class="cartbounty-pro-row">
									<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
										<h4><?php esc_html_e('Notifications', 'woo-save-abandoned-carts'); ?></h4>
										<p class="cartbounty-pro-titles-column-description">
											<?php esc_html_e('Receive email notifications about newly abandoned and recovered carts. Please note, that you will not get emails about anonymous carts.', 'woo-save-abandoned-carts'); ?>
										</p>
									</div>
									<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9">
										<div class="cartbounty-pro-settings-group">
											<label for="cartbounty_pro_notification_email"><?php esc_html_e('Admin email', 'woo-save-abandoned-carts'); ?></label>
											<input id="cartbounty_pro_notification_email" class="cartbounty-pro-text cartbounty-pro-display-emails" type="email" name="cartbounty_pro_main_settings[notification_email]" value="<?php echo esc_attr( $notification_email ); ?>" placeholder="<?php echo esc_attr( get_option( 'admin_email' ) );?>" <?php echo $this->disable_field(); ?> multiple />
											<p class='cartbounty-pro-additional-information'>
												<?php esc_html_e('You can add multiple emails separated by a comma.', 'woo-save-abandoned-carts'); ?>
											</p>
										</div>
										<div class="cartbounty-pro-settings-group">
											<?php $this->display_time_intervals( 'cartbounty_pro_main_settings[notification_frequency]' ); ?>
										</div>
										<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
											<label for="cartbounty-pro-exclude-recovered" class="cartbounty-pro-switch">
												<input id="cartbounty-pro-exclude-recovered" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[exclude_recovered]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $exclude_recovered, false ); ?> autocomplete="off" />
												<span class="cartbounty-pro-slider round"></span>
											</label>
											<label for="cartbounty-pro-exclude-recovered">
												<?php esc_html_e('Exclude recovered carts from notifications', 'woo-save-abandoned-carts'); ?>
											</label>
										</div>
									</div>
								</div>
								<?php if( $gtranslate->is_active() ): ?>
								<div class="cartbounty-pro-row">
									<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
										<h4><?php esc_html_e( 'GTranslate', 'woo-save-abandoned-carts' ); ?></h4>
										<p class="cartbounty-pro-titles-column-description">
											<?php echo sprintf(
											/* translators: %s - Link tags */
											esc_html__( 'Translate abandoned cart reminder messages using GTranslate API. %sSee this%s to learn how to configure translations.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( $this->get_trackable_link( '' . 'translations', 'gtranslate_configuration', '#gtranslate' ) ) .'" title="'. esc_attr__( 'Configure translations with GTranslate', 'woo-save-abandoned-carts' ) .'" target="_blank">', '</a>' ); ?>
										</p>
									</div>
									<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9">
										<div class="cartbounty-pro-settings-group">
											<label for="cartbounty_pro_gtranslate_key"><?php esc_html_e( 'API Key', 'woo-save-abandoned-carts' ); ?></label>
											<input id="cartbounty_pro_gtranslate_key" class="cartbounty-pro-text" type="text" name="cartbounty_pro_main_settings[gtranslate_key]" value="<?php echo esc_attr( $gtranslate_key ); ?>" <?php echo $this->disable_field(); ?> />
											<p class='cartbounty-pro-additional-information'>
												<?php echo sprintf(
												/* translators: %s - Link tags */
												esc_html__( 'You can sign up for a free API key %shere%s.', 'woo-save-abandoned-carts' ), '<a href="https://translatex.com" target="_blank">', '</a>' ); ?>
											</p>
										</div>
									</div>
								</div>
							<?php endif; ?>
								<div class="cartbounty-pro-row">
									<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
										<h4><?php esc_html_e('Protection', 'woo-save-abandoned-carts'); ?></h4>
										<p class="cartbounty-pro-titles-column-description">
											<?php echo sprintf(
											/* translators: %s - Link tags */
											esc_html__('In case you feel that bots might be leaving recoverable abandoned carts. Please %sview this%s to learn how to prevent bots from leaving anonymous carts.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( $this->get_trackable_link( '' . 'abandoned-carts', 'anonymous_bots', '#prevent-bots-from-leaving-abandoned-carts' ) ) .'" title="'. esc_attr__('Prevent bots from leaving anonymous carts', 'woo-save-abandoned-carts') .'" target="_blank">', '</a>' ); ?>
										</p>
									</div>
									<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9<?php if($recaptcha['status']){ echo ' cartbounty-pro-checked-parent'; }?>">
										<div class="cartbounty-pro-settings-group cartbounty-pro-toggle<?php if($recaptcha['status']){ echo ' cartbounty-pro-checked'; }?>">
											<label for="cartbounty_pro_recaptcha[status]" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
												<input id="cartbounty_pro_recaptcha[status]" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[recaptcha][status]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $recaptcha['status'], false ); ?> autocomplete="off" />
												<span class="cartbounty-pro-slider round"></span>
											</label>
											<label for="cartbounty_pro_recaptcha[status]" class="cartbounty-pro-control-visibility"><?php esc_html_e('Enable reCAPTCHA v3', 'woo-save-abandoned-carts'); ?></label>
											<p class='cartbounty-pro-additional-information'>
												<i class='cartbounty-pro-hidden'>
												<?php echo sprintf(
													/* translators: %s - URL link */
													esc_html__('Make sure to enter your Site and Secret keys below and save them. You can %2$sget them here%1$s. Learn %3$show to adjust the sensitivity%1$s in case you are still bothered by bots. Check your current score in this %4$sreCAPTCHA demo%1$s.', 'woo-save-abandoned-carts'), '</a>', '<a href="'. esc_url( RECAPTCHA_SITE ) .'" title="'. esc_attr__('Get reCAPTCHA Site and Secret keys', 'woo-save-abandoned-carts') .'" target="_blank">', '<a href="'. esc_url( $this->get_trackable_link('' . 'actions-and-filters', 'recaptcha_score', '#adjust-google-recaptcha-sensitivity') ) .'" title="'. esc_attr__('How to adjust the minimum allowed score for the abandoned cart to be saved', 'woo-save-abandoned-carts') .'" target="_blank">', '<a href="'. esc_url( RECAPTCHA_DEMO_LINK ) .'" title="'. esc_attr__('reCAPTCHA demo link', 'woo-save-abandoned-carts') .'" target="_blank">'); ?>
												</i>
											</p>
										</div>
										<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
											<label for="cartbounty_pro_recaptcha[site_key]"><?php esc_html_e('Site key', 'woo-save-abandoned-carts'); ?></label>
											<input id="cartbounty_pro_recaptcha[site_key]" class="cartbounty-pro-text" type="text" name="cartbounty_pro_main_settings[recaptcha][site_key]" value="<?php echo esc_attr( $recaptcha['site_key'] ); ?>" <?php echo $this->disable_field(); ?> />
										</div>
										<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
											<label for="cartbounty_pro_recaptcha[secret_key]"><?php esc_html_e('Secret key', 'woo-save-abandoned-carts'); ?></label>
											<input id="cartbounty_pro_recaptcha[secret_key]" class="cartbounty-pro-text" type="text" name="cartbounty_pro_main_settings[recaptcha][secret_key]" value="<?php echo esc_attr($recaptcha['secret_key']); ?>" <?php echo $this->disable_field(); ?> />
										</div>
									</div>
								</div>
								<div class="cartbounty-pro-row">
									<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
										<h4><?php esc_html_e('Unfinished orders', 'woo-save-abandoned-carts'); ?></h4>
										<p class="cartbounty-pro-titles-column-description">
											<?php esc_html_e('Send reminders about WooCommerce orders that have been abandoned.', 'woo-save-abandoned-carts'); ?>
										</p>
									</div>
									<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9">
										<div class="cartbounty-pro-settings-group-container<?php if( $this->recover_orders_enabled() ){ echo ' cartbounty-pro-checked-parent'; }?>">
											<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
												<label for="cartbounty-pro-order-recovery" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
													<input id="cartbounty-pro-order-recovery" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[order_recovery]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $this->recover_orders_enabled(), false ); ?> autocomplete="off" />
													<span class="cartbounty-pro-slider round"></span>
												</label>
												<label for="cartbounty-pro-order-recovery" class="cartbounty-pro-control-visibility"><?php esc_html_e('Enable unfinished order recovery', 'woo-save-abandoned-carts'); ?></label>
											</div>
											<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
												<label for="cartbounty-pro-order-statuses"><?php esc_html_e( 'Recover orders with status', 'woo-save-abandoned-carts' ); ?></label>
												<?php $this->display_order_statuses(); ?>
											</div>
										</div>
									</div>
								</div>
								<div class="cartbounty-pro-row">
									<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
										<h4><?php esc_html_e( 'Consent', 'woo-save-abandoned-carts' ); ?></h4>
										<p class="cartbounty-pro-titles-column-description">
											<?php esc_html_e( 'Settings related to the collection of visitor consent for phone and email in compliance with data protection laws.', 'woo-save-abandoned-carts' ); ?>
										</p>
									</div>
									<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9">
										<div id="cartbounty-pro-consent-settings" class="cartbounty-pro-select-multiple<?php if( $email_consent || $phone_consent ){ echo ' cartbounty-pro-checked-parent'; }?>">
											<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
												<label for="cartbounty-pro-email-consent" class="cartbounty-pro-switch">
													<input id="cartbounty-pro-email-consent" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[email_consent]" value="1" data-type="email" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $email_consent, false ); ?> data-nonce="<?php echo esc_attr( $consent_nonce ); ?>" autocomplete="off" />
													<span class="cartbounty-pro-slider round"></span>
												</label>
												<label for="cartbounty-pro-email-consent"><?php esc_html_e('Enable email consent', 'woo-save-abandoned-carts'); ?></label>
											</div>
											<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
												<label for="cartbounty-pro-phone-consent" class="cartbounty-pro-switch">
													<input id="cartbounty-pro-phone-consent" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[phone_consent]" value="1" data-type="phone" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $phone_consent, false ); ?> data-nonce="<?php echo esc_attr( $consent_nonce ); ?>" autocomplete="off" />
													<span class="cartbounty-pro-slider round"></span>
												</label>
												<label for="cartbounty-pro-phone-consent"><?php esc_html_e('Enable phone number consent', 'woo-save-abandoned-carts'); ?></label>
											</div>
											<div class="cartbounty-pro-toggle-content">
												<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
													<label for="cartbounty-pro-checkout-consent"><?php esc_html_e( 'Checkout consent label', 'woo-save-abandoned-carts' ); ?></label>
													<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
														<input id="cartbounty-pro-checkout-consent" class="cartbounty-pro-text" type="text" name="cartbounty_pro_main_settings[checkout_consent]" value="<?php echo esc_attr( $checkout_consent ); ?>" placeholder="<?php echo esc_attr($this->get_defaults( 'checkout_consent' ) ); ?>" /><?php $this->add_emojis(); ?>
													</div>
												</div>
												<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
													<label for="cartbounty-pro-tools-consent"><?php esc_html_e( 'Tools consent notice', 'woo-save-abandoned-carts' ); ?></label>
													<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
														<input id="cartbounty-pro-tools-consent" class="cartbounty-pro-text" type="text" name="cartbounty_pro_main_settings[tools_consent]" value="<?php echo esc_attr( $tools_consent ); ?>" placeholder="<?php echo esc_attr($this->get_defaults( 'tools_consent' ) ); ?>" /><?php $this->add_emojis(); ?>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
								<div class="cartbounty-pro-row">
									<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
										<h4><?php esc_html_e( 'Magic login', 'woo-save-abandoned-carts' ); ?></h4>
										<p class="cartbounty-pro-titles-column-description">
											<?php esc_html_e( 'Automatically sign in registered customers when they open their recovery link. Make sure the Cart, Checkout and My account pages bypass all caches (CDN and caching plugins).', 'woo-save-abandoned-carts' ); ?>
										</p>
									</div>
									<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9">
										<div class="cartbounty-pro-settings-group-container<?php if( $magic_login ){ echo ' cartbounty-pro-checked-parent'; }?>">
											<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
												<label for="cartbounty-pro-magic-login" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
													<input id="cartbounty-pro-magic-login" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[magic_login]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $magic_login, false ); ?> autocomplete="off" />
													<span class="cartbounty-pro-slider round"></span>
												</label>
												<label for="cartbounty-pro-magic-login" class="cartbounty-pro-control-visibility"><?php esc_html_e('Enable Magic login', 'woo-save-abandoned-carts'); ?></label>
											</div>
											<div class="cartbounty-pro-settings-group cartbounty-pro-toggle cartbounty-pro-hidden">
												<label for="cartbounty-pro-magic-login-first-click" class="cartbounty-pro-switch">
													<input id="cartbounty-pro-magic-login-first-click" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[magic_login_first_click]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $magic_login_first_click, false ); ?> autocomplete="off" />
													<span class="cartbounty-pro-slider round"></span>
												</label>
												<label for="cartbounty-pro-magic-login-first-click"><?php esc_html_e( 'Automatically sign in only on first link click', 'woo-save-abandoned-carts'); ?></label>
												<p class='cartbounty-pro-additional-information'>
													<?php esc_html_e( 'On the first recovery link click, the customer is auto-signed in. Subsequent clicks only restore the cart.', 'woo-save-abandoned-carts' ); ?>
												</p>
											</div>
											<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
												<label for="cartbounty-pro-magic-login-roles"><?php esc_html_e( 'Allowed user roles', 'woo-save-abandoned-carts' ); ?></label>
												<?php $this->display_magic_login_roles(); ?>
											</div>
											<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
												<?php $this->display_time_intervals( 'cartbounty_pro_main_settings[magic_login_window]' ); ?>
												<p class='cartbounty-pro-additional-information'>
													<?php esc_html_e( 'Sets how long after sending a reminder its recovery link can automatically sign the customer in. After this window, the link still restores the cart - automatic sign in is disabled.', 'woo-save-abandoned-carts' ); ?>
												</p>
											</div>
										</div>
									</div>
								</div>
								<div class="cartbounty-pro-row">
									<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
										<h4><?php esc_html_e('Miscellaneous', 'woo-save-abandoned-carts'); ?></h4>
										<p class="cartbounty-pro-titles-column-description">
											<?php esc_html_e('Other settings that may be useful.', 'woo-save-abandoned-carts');?>
										</p>
									</div>
									<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9">
										<div class="cartbounty-pro-settings-group cartbounty-pro-toggle<?php if($lift_email){ echo ' cartbounty-pro-checked'; }?>">
											<label for="cartbounty-pro-lift-email" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
												<input id="cartbounty-pro-lift-email" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[lift_email]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $lift_email, false ); ?> autocomplete="off" />
												<span class="cartbounty-pro-slider round"></span>
											</label>
											<label for="cartbounty-pro-lift-email" class="cartbounty-pro-control-visibility"><?php esc_html_e('Lift email field', 'woo-save-abandoned-carts'); ?></label>
											<p class='cartbounty-pro-additional-information'>
												<?php esc_html_e('You could increase the chances of saving recoverable abandoned carts by moving the email field to the top of your checkout form.', 'woo-save-abandoned-carts');
												echo " <i class='cartbounty-pro-hidden'>". esc_html__('Please test the checkout after enabling this, as sometimes it can cause issues or not raise the field if you have a custom checkout.', 'woo-save-abandoned-carts') ."</i>";
												 ?>
											</p>
										</div>
										<div class="cartbounty-pro-settings-group cartbounty-pro-toggle<?php if($lift_phone){ echo ' cartbounty-pro-checked'; }?>">
											<label for="cartbounty-pro-lift-phone" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
												<input id="cartbounty-pro-lift-phone" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[lift_phone]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $lift_phone, false ); ?> autocomplete="off" />
												<span class="cartbounty-pro-slider round"></span>
											</label>
											<label for="cartbounty-pro-lift-phone" class="cartbounty-pro-control-visibility"><?php esc_html_e('Lift phone field', 'woo-save-abandoned-carts'); ?></label>
											<p class='cartbounty-pro-additional-information'>
												<?php esc_html_e('You could increase the chances of saving recoverable abandoned carts by moving the phone field to the top of your checkout form.', 'woo-save-abandoned-carts');
												echo " <i class='cartbounty-pro-hidden'>". esc_html__('Please test the checkout after enabling this, as sometimes it can cause issues or not raise the field if you have a custom checkout.', 'woo-save-abandoned-carts') ."</i>";
												 ?>
											</p>
										</div>
										<div class="cartbounty-pro-settings-group-container">
											<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
												<label for="cartbounty-pro-international-phone" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
													<input id="cartbounty-pro-international-phone" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[international_phone]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $this->international_phone_enabled(), false ); ?> autocomplete="off" />
													<span class="cartbounty-pro-slider round"></span>
												</label>
												<label for="cartbounty-pro-international-phone" class="cartbounty-pro-control-visibility"><?php esc_html_e('Enable easy international phone input', 'woo-save-abandoned-carts'); ?></label>
											</div>
										</div>
										<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
											<label for="cartbounty-pro-delete-coupons" class="cartbounty-pro-switch">
												<input id="cartbounty-pro-delete-coupons" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[delete_coupons]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $delete_coupons, false ); ?> autocomplete="off" />
												<span class="cartbounty-pro-slider round"></span>
											</label>
											<label for="cartbounty-pro-delete-coupons"><?php esc_html_e('Enable expired coupon deletion', 'woo-save-abandoned-carts'); ?></label>
											<p class='cartbounty-pro-additional-information'>
												<?php echo sprintf(
													/* translators: %s - Plugin name */
													esc_html__('Automatically delete expired and unused coupons generated by %s.', 'woo-save-abandoned-carts'), esc_html( CARTBOUNTY_PRO_ABBREVIATION ) );
												?>
											</p>
										</div>
										<div class="cartbounty-pro-settings-group cartbounty-pro-toggle<?php if($logging_status){ echo ' cartbounty-pro-checked'; }?>">
											<label for="cartbounty-pro-log" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
												<input id="cartbounty-pro-log" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_main_settings[logging_status]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $logging_status, false ); ?> autocomplete="off" />
												<span class="cartbounty-pro-slider round"></span>
											</label>
											<label for="cartbounty-pro-log" class="cartbounty-pro-control-visibility"><?php esc_html_e('Enable logging', 'woo-save-abandoned-carts'); ?></label>
											<p class='cartbounty-pro-additional-information'>
												<?php esc_html_e('These logs can be helpful while troubleshooting issues related to different actions and connections.', 'woo-save-abandoned-carts'); 
													echo " <i class='cartbounty-pro-hidden'>". sprintf( esc_html__('To view the log file, please go to WooCommerce > Status > Logs and from the dropdown list pick a file that starts with "%s".', 'woo-save-abandoned-carts'), esc_html( CARTBOUNTY_PRO_PLUGIN_NAME_SLUG ) ) ."</i>";
												?>
											</p>
										</div>
									</div>
								</div>
								<div class='cartbounty-pro-button-row'>
									<?php
									settings_fields( 'cartbounty-pro-settings-group' );
									do_settings_sections( 'cartbounty-pro-settings-group' );
									
									if( $this->user_is_admin() ){
										echo "<button type='submit' class='cartbounty-pro-button button-primary cartbounty-pro-progress'>". esc_html__('Save settings', 'woo-save-abandoned-carts') ."</button>";
										
										if( $license_active ){
											$nonce = wp_create_nonce( 'deactivate_cartbounty_license' );
											echo "<a id='disconnect_cartbounty' class='cartbounty-pro-button button button-secondary' href='#' data-action='disconnect_cartbounty' data-nonce='" . esc_attr( $nonce ) . "'>". esc_html__('Deactivate license', 'woo-save-abandoned-carts') ."</a>";
										}
									}?>
								</div>
							</form>
						</div>
					</div>
				<?php endif;
			}?>
		</div>
	<?php
	}

	/**
	 * Method creates tabs on plugin page
	 *
	 * @since    1.4.3
	 * @param    $current    Currently open tab - string
	 */
	function create_admin_tabs( $current ){
		$tabs = array(
			'dashboard' => esc_html__( 'Dashboard', 'woo-save-abandoned-carts' ),
			'carts' 	=> esc_html__( 'Abandoned carts', 'woo-save-abandoned-carts' ),
			'recovery' 	=> esc_html__( 'Recovery', 'woo-save-abandoned-carts' ),
			'tools' 	=> esc_html__( 'Tools', 'woo-save-abandoned-carts' ),
			'settings' 	=> esc_html__( 'Settings', 'woo-save-abandoned-carts' )
		);
		echo '<h2 class="nav-tab-wrapper">';
		
		foreach( $tabs as $tab => $name ){
			$class = ( $tab == $current ) ? ' nav-tab-active' : ''; //if the tab is open, an additional class, nav-tab-active, is added
			echo "<a class='cartbounty-pro-tab nav-tab$class' href='". esc_url( "?page=". esc_html( CARTBOUNTY_PRO ) ."&tab=$tab" ) ."'>". $this->get_icon( $tab, $current, false, false ) ."<span class='cartbounty-pro-tab-name'>". esc_html( $name ) ."</span></a>";
		}
		echo '</h2>';
	}

	/**
	 * Get default open CartBounty tab
	 *
	 * @since    10.5
	 */
	function get_default_open_tab(){
		return apply_filters( 'cartbounty_pro_default_open_tab', 'dashboard' );
	}

	/**
	 * Method returns icons as SVG code
	 *
	 * @since    9.0
	 * @return 	 String
	 * @param    $icon 		Icon to get - string
	 * @param    $current 	Current active tab - string
	 * @param    $section 	Whether the icon is located in sections - boolean
	 * @param    $grid 		Whether the icon is located section items grid - boolean
	 */
	public function get_icon( $icon, $current, $section, $grid ){

		$color = '#555'; //Default icon color
		$svg = '';
		
		if( $current == $icon ){ //If the icon is active in tabs
			$color = '#000';
		}

		if( $grid ){ //If the icon is in the item grid
			$color = '#000';
		}

		if( $current == $icon && $section ){ //If the icon is active in sections
			$color = '#976dfb';
		}

		if( $icon == 'dashboard' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 92.73 65"><path d="M61.2,2.41C29.21-7.79,0,15.85,0,46.45,0,50.63,1.11,65,4.71,65H88.56c2.82,0,4.17-14.37,4.17-18.55C92.73,26.52,80.21,8.43,61.2,2.41Zm-45.58,50a5.58,5.58,0,1,1,5.57-5.58A5.58,5.58,0,0,1,15.62,52.38Zm8.46-22.9a5.58,5.58,0,1,1,5.57-5.58A5.57,5.57,0,0,1,24.08,29.48ZM46.37,9.12a5.57,5.57,0,1,1-5.58,5.57A5.57,5.57,0,0,1,46.37,9.12Zm4.69,46.15a5.57,5.57,0,0,1-9-6.55l3-4.09c1.81-2.48,23.85-28.58,26.34-26.77S55.83,48.69,54,51.18Zm26.05-3.59a5.57,5.57,0,1,1,5.58-5.57A5.57,5.57,0,0,1,77.11,51.68Z"/></svg>';

		}elseif( $icon == 'carts' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 26.34 29.48"><path d="M7.65,24c-2.43,0-3.54-1.51-3.54-2.91V3.44C3.77,3.34,3,3.15,2.48,3L.9,2.59A1.28,1.28,0,0,1,0,1.15,1.32,1.32,0,0,1,1.34,0a1.52,1.52,0,0,1,.42.06l.68.2c1.38.41,2.89.85,3.25,1A1.72,1.72,0,0,1,6.79,2.8V5.16L24.67,7.53a1.75,1.75,0,0,1,1.67,2v6.1a3.45,3.45,0,0,1-3.59,3.62h-16v1.68c0,.14,0,.47,1.07.47H21.13a1.32,1.32,0,0,1,1.29,1.38,1.35,1.35,0,0,1-.25.79,1.18,1.18,0,0,1-1,.5Zm-.86-7.5,15.76,0c.41,0,1.11,0,1.11-1.45V10c-3-.41-13.49-1.69-16.87-2.11Z"/><path d="M21.78,29.48a4,4,0,1,1,4-4A4,4,0,0,1,21.78,29.48Zm0-5.37a1.35,1.35,0,1,0,1.34,1.34A1.35,1.35,0,0,0,21.78,24.11ZM10.14,29.48a4,4,0,1,1,4-4A4,4,0,0,1,10.14,29.48Zm0-5.37a1.35,1.35,0,1,0,1.34,1.34A1.34,1.34,0,0,0,10.14,24.11Z"/><path d="M18.61,18.91a1.34,1.34,0,0,1-1.34-1.34v-9a1.34,1.34,0,1,1,2.67,0v9A1.34,1.34,0,0,1,18.61,18.91Z"/><path d="M12.05,18.87a1.32,1.32,0,0,1-1.34-1.29v-10a1.34,1.34,0,0,1,2.68,0v10A1.32,1.32,0,0,1,12.05,18.87Z"/></svg>';
		
		}elseif( $icon == 'recovery' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 66.07 49.48"><path d="M28.91,26.67A7.62,7.62,0,0,0,33,28a7,7,0,0,0,4.16-1.37c.77-.46,23.19-17.66,26.05-20s1.06-4.9,1.06-4.9S63.51,0,60.64,0H6.08c-3.83,0-4.5,2-4.5,2S0,4.49,3.28,7Z"/><path d="M40.84,32.14A13.26,13.26,0,0,1,33,34.9a13,13,0,0,1-7.77-2.76C24.33,31.55,1.11,14.49,0,13.25V43a6.52,6.52,0,0,0,6.5,6.5H59.57a6.51,6.51,0,0,0,6.5-6.5V13.25C65,14.46,41.74,31.55,40.84,32.14Z"/></svg>';
		
		}elseif( $icon == 'settings' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 69.95 69.95"><path d="M64,34.83a20.36,20.36,0,0,0,5.2-20A2.49,2.49,0,0,0,65,13.79L56.61,22.2a6.25,6.25,0,0,1-8.85,0h0a6.26,6.26,0,0,1,0-8.86l8.4-8.41a2.49,2.49,0,0,0-1-4.16A20.4,20.4,0,0,0,30.26,27a2.16,2.16,0,0,1-.54,2.22L2.27,56.71a7.76,7.76,0,0,0,0,11h0a7.77,7.77,0,0,0,11,0L40.7,40.23a2.18,2.18,0,0,1,2.22-.54A20.38,20.38,0,0,0,64,34.83Z"/></svg>';
		
		}elseif( $icon == 'exit_intent' || $icon == 'tools' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 65.5 70"><path d="M29,7.23A7.23,7.23,0,1,1,21.75,0,7.23,7.23,0,0,1,29,7.23Z"/><path d="M17.32,70a5.73,5.73,0,0,1-4.78-2.6,4.85,4.85,0,0,1-.18-4.84q1-2.12,2-4.25c1.33-2.8,2.71-5.68,4.14-8.5,1.33-2.6,5-5.49,11.29-8.81-2.17-4.18-4.25-8-6.35-11.61a21.16,21.16,0,0,1-5.12.66C11.6,30.05,5.59,26.63,1,20.18a4.58,4.58,0,0,1-.48-4.86,5.76,5.76,0,0,1,5.06-3,5.28,5.28,0,0,1,4.39,2.29c2.32,3.26,5.1,4.92,8.26,4.92A13.46,13.46,0,0,0,25,17.43c.18-.12.63-.36,1.12-.64l.31-.17,1.36-.78a23.44,23.44,0,0,1,12-3.55c6.76,0,12.77,3.42,17.39,9.89A4.56,4.56,0,0,1,57.58,27,5.76,5.76,0,0,1,52.52,30a5.26,5.26,0,0,1-4.38-2.28c-2.33-3.26-5.11-4.91-8.27-4.91a10.63,10.63,0,0,0-1.66.14c2.44,4.4,6.53,12.22,7.08,13.58,2.23,4.07,4.78,7.82,8.25,7.82A7,7,0,0,0,57,43.23a5.68,5.68,0,0,1,2.85-.81,5.85,5.85,0,0,1,5.41,4.43A5.27,5.27,0,0,1,62.74,53a18,18,0,0,1-9.08,2.68c-5,0-9.91-2.61-14.08-7.55-2.93,1.44-8.65,4.38-11.3,6.65-.53.87-4.4,8.16-6.4,12.29A5,5,0,0,1,17.32,70Z"/></svg>';
		
		}elseif( $icon == 'early_capture' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 38.87 70"><path d="M38.53,32.71,23,67.71A3.89,3.89,0,0,1,19.43,70a5.56,5.56,0,0,1-.81-.08,3.87,3.87,0,0,1-3.07-3.81V42.78H3.88A3.89,3.89,0,0,1,.34,37.3l15.55-35A3.88,3.88,0,0,1,23.32,3.9V27.23H35a3.9,3.9,0,0,1,3.54,5.48Zm0,0"/></svg>';
		
		}elseif( $icon == 'tab_notification' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 67.5 70"><path d="M55.38,41V28.11A19.19,19.19,0,0,0,55.21,25l0-.27C54.12,16.29,47.66,9.48,38.72,7.34l-1.29-.29V5.3a3.87,3.87,0,1,0-7.73,0V7.06A21.9,21.9,0,0,0,11.75,27.94c-.07,2.61-.07,8.9-.06,13a9.82,9.82,0,0,0-6.33,9.33c0,5.44,4.16,9.86,9.29,9.86H33.32v.48a9.38,9.38,0,0,0,18.75,0v-.48h.36c5.12,0,9.29-4.42,9.29-9.86A9.84,9.84,0,0,0,55.38,41ZM19.44,28.67a15.16,15.16,0,0,1,.29-3A14.06,14.06,0,0,1,33.54,14.44a14.53,14.53,0,0,1,4.77.81,14,14,0,0,1,9.34,12.46c0,.45,0,.53,0,.56a3.91,3.91,0,0,1,0,.51c0,1,0,7.44,0,11.66H19.42C19.42,36.37,19.42,30.92,19.44,28.67ZM42.7,62.92a2.47,2.47,0,0,1-2.47-2.46,3,3,0,0,1,0-.31h4.87a3,3,0,0,1,0,.31A2.46,2.46,0,0,1,42.7,62.92Zm9.62-10.16H14.75c-.92,0-1.67-1.11-1.67-2.47s.75-2.46,1.67-2.46H52.32c.92,0,1.67,1.1,1.67,2.46S53.24,52.76,52.32,52.76Z"/><path d="M11.31.8A34.14,34.14,0,0,0,.24,15.73a3.82,3.82,0,0,0,3.61,5.11h0A3.78,3.78,0,0,0,7.4,18.43,26.5,26.5,0,0,1,16,6.87a3.81,3.81,0,0,0,1.47-3v0A3.83,3.83,0,0,0,11.31.8Z"/><path d="M56.19.8A34.14,34.14,0,0,1,67.26,15.73a3.82,3.82,0,0,1-3.61,5.11h0a3.8,3.8,0,0,1-3.56-2.41A26.4,26.4,0,0,0,51.5,6.87a3.78,3.78,0,0,1-1.47-3v0A3.83,3.83,0,0,1,56.19.8Z"/></svg>';
		
		}elseif( $icon == 'activecampaign' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13.24 20"><path d="M12.52,8.69C12.23,8.45.76,0.44,0.24,0.12L0.08,0V2A1.32,1.32,0,0,0,.8,3.14l0.08,0L10.7,10c-1.09.76-9.38,6.52-9.9,6.84a1.16,1.16,0,0,0-.68,1.25V20s12.19-8.49,12.43-8.69h0a1.52,1.52,0,0,0,.68-1.25V9.82A1.4,1.4,0,0,0,12.52,8.69Z"/><path d="M5.35,10.91a1.61,1.61,0,0,0,1-.36L7.08,10,7.2,9.94,7.08,9.86s-5.39-3.74-6-4.1A0.7,0.7,0,0,0,.36,5.63,0.71,0.71,0,0,0,0,6.28V7.53l0,0s3.7,2.58,4.43,3.06A1.63,1.63,0,0,0,5.35,10.91Z"/></svg>';
		
		}elseif( $icon == 'getresponse' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70 44.54"><path d="M35,35a29,29,0,0,1-17.22-5.84A28.38,28.38,0,0,1,6.89,11.35c-.07-.47-.15-.94-.21-1.33A3.2,3.2,0,0,1,9.86,6.36h1.48a23.94,23.94,0,0,0,8.4,13.76A24.74,24.74,0,0,0,34.91,25.5C48.16,25.78,61.05,14,69.31,1.15A3,3,0,0,0,67,0H3A3,3,0,0,0,0,3V41.55a3,3,0,0,0,3,3H67a3,3,0,0,0,3-3V8.5C59.14,27.59,46.65,35,35,35Z"/></svg>';
		
		}elseif( $icon == 'mailchimp' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 65.96 70"><path d="M49.61,33.08a5.41,5.41,0,0,1,1.45,0,4.92,4.92,0,0,0,.07-2.75c-.34-1.66-.82-2.67-1.79-2.52s-1,1.37-.66,3a5.7,5.7,0,0,0,.93,2.24Z"/><path d="M41.26,34.4c.69.3,1.12.5,1.29.33s.07-.32-.09-.59a4,4,0,0,0-1.8-1.45,4.88,4.88,0,0,0-4.78.57c-.47.34-.91.81-.84,1.1,0,.09.09.16.25.19a27.75,27.75,0,0,1,3.27-.73,5.65,5.65,0,0,1,2.7.58Z"/><path d="M39.85,35.2a3.23,3.23,0,0,0-1.72.72,1.1,1.1,0,0,0-.45.69.19.19,0,0,0,.07.16.2.2,0,0,0,.15.06,2.81,2.81,0,0,0,.67-.18,5.74,5.74,0,0,1,2.92-.31c.45,0,.67.08.77-.07a.26.26,0,0,0,0-.29,2.62,2.62,0,0,0-2.38-.78Z"/><path d="M46.79,38.13a1.13,1.13,0,0,0,1.52-.26c.22-.45-.1-1.06-.72-1.37a1.13,1.13,0,0,0-1.52.27,1.11,1.11,0,0,0,.72,1.36Z"/><path d="M50.75,34.67c-.5,0-.92.54-.93,1.23s.39,1.25.89,1.26.91-.55.93-1.23-.39-1.25-.89-1.26Z"/><path d="M17.14,47c-.12-.15-.33-.1-.53-.06a2.11,2.11,0,0,1-.46.07,1,1,0,0,1-.86-.44,1.59,1.59,0,0,1,0-1.47,2,2,0,0,1,.12-.26c.4-.9,1.07-2.41.31-3.85a3.38,3.38,0,0,0-2.6-1.89,3.34,3.34,0,0,0-2.87,1,4.14,4.14,0,0,0-1.07,3.47c.08.22.2.28.29.29s.47-.11.64-.58a.86.86,0,0,0,0-.15,5,5,0,0,1,.46-1.08,2,2,0,0,1,1.26-.87,2,2,0,0,1,1.53.29,2,2,0,0,1,.74,2.36A5.58,5.58,0,0,0,13.8,46a2.11,2.11,0,0,0,1.87,2.16,1.59,1.59,0,0,0,1.5-.75.31.31,0,0,0,0-.37Z"/><path d="M24.76,19.66a31,31,0,0,1,8.71-7.12.11.11,0,0,1,.15.15,8.56,8.56,0,0,0-.81,2,.12.12,0,0,0,.18.12,17,17,0,0,1,7.65-2.7.13.13,0,0,1,.08.22,6.6,6.6,0,0,0-1.21,1.21.12.12,0,0,0,.1.18A15.09,15.09,0,0,1,46,15.38c.12.06,0,.3-.1.27a25.86,25.86,0,0,0-11.58,0,26.57,26.57,0,0,0-9.41,4.15.11.11,0,0,1-.15-.17Zm13,29.25Zm10.78,1.27a.21.21,0,0,0,.12-.2.2.2,0,0,0-.22-.18,24.86,24.86,0,0,1-10.84-1.1c.57-1.87,2.1-1.19,4.4-1a32.17,32.17,0,0,0,10.64-1.15,24.28,24.28,0,0,0,8-3.95,16,16,0,0,1,1.11,3.78,1.86,1.86,0,0,1,1.17.22c.5.31.87.95.62,2.61a14.39,14.39,0,0,1-4,7.93,16.67,16.67,0,0,1-4.86,3.63,20,20,0,0,1-3.17,1.34c-8.35,2.73-16.9-.27-19.65-6.71a9.46,9.46,0,0,1-.55-1.52,13.36,13.36,0,0,1,2.93-12.54h0a1.09,1.09,0,0,0,.39-.75,1.27,1.27,0,0,0-.3-.7c-1.09-1.59-4.86-4.28-4.11-9.49C30.68,26.64,34,24,37,24.16l.77,0c1.33.08,2.48.25,3.57.3a7.19,7.19,0,0,0,5.41-1.81,4.13,4.13,0,0,1,2.07-1.17,2.71,2.71,0,0,1,.79-.08,2.68,2.68,0,0,1,1.33.43c1.56,1,1.78,3.55,1.86,5.38,0,1.05.17,3.58.21,4.31.1,1.67.54,1.9,1.42,2.19.5.17,1,.29,1.65.48a9.31,9.31,0,0,1,4,1.92,2.56,2.56,0,0,1,.74,1.45c.24,1.77-1.38,4-5.67,5.95a28.69,28.69,0,0,1-14.3,2.29l-1.37-.15c-3.15-.43-4.94,3.63-3,6.42,1.21,1.79,4.52,3,7.84,3,7.59,0,13.43-3.24,15.6-6l.17-.24c.11-.16,0-.25-.11-.16-1.77,1.21-9.66,6-18.08,4.58a11.38,11.38,0,0,1-2-.53c-.75-.29-2.3-1-2.49-2.6,6.8,2.1,11.09.11,11.09.11ZM11.18,34a9.06,9.06,0,0,0-5.72,3.65A15.45,15.45,0,0,1,3,35.33C1,31.46,5.24,24,8.22,19.7c7.35-10.49,18.86-18.43,24.19-17,.86.25,3.73,3.58,3.73,3.58a74.88,74.88,0,0,0-10.26,7.07A46.63,46.63,0,0,0,11.18,34Zm4,17.73a5,5,0,0,1-1.09.08c-3.56-.09-7.41-3.3-7.79-7.1-.42-4.2,1.72-7.43,5.52-8.2a6.67,6.67,0,0,1,1.6-.11c2.13.11,5.27,1.75,6,6.39.64,4.11-.37,8.29-4.22,8.94Zm48.22-7.43c0-.11-.23-.84-.51-1.71a13.28,13.28,0,0,0-.55-1.49,5.47,5.47,0,0,0,1-3.94,5,5,0,0,0-1.45-2.81,11.64,11.64,0,0,0-5.11-2.53l-1.3-.36c0-.06-.07-3.07-.13-4.37a15,15,0,0,0-.57-3.84,10.35,10.35,0,0,0-2.66-4.74c3.24-3.36,5.27-7.06,5.26-10.24,0-6.11-7.51-8-16.76-4.13l-2,.83L35,1.47c-10.54-9.2-43.51,27.44-33,36.34l2.31,1.95A11.32,11.32,0,0,0,3.71,45,10.3,10.3,0,0,0,7.27,51.6a10.86,10.86,0,0,0,7,2.81C18.35,63.86,27.72,69.66,38.71,70c11.78.35,21.68-5.18,25.82-15.11A20.84,20.84,0,0,0,66,48.26c0-2.79-1.58-3.94-2.58-3.94Z"/></svg>';
		
		}elseif( $icon == 'wordpress' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70 70"><path d="M35,0A35,35,0,1,0,70,35,35,35,0,0,0,35,0M3.53,35A31.33,31.33,0,0,1,6.26,22.19l15,41.13A31.48,31.48,0,0,1,3.53,35M35,66.47a31.42,31.42,0,0,1-8.89-1.28l9.44-27.44,9.67,26.5a3.45,3.45,0,0,0,.23.43A31.21,31.21,0,0,1,35,66.47m4.34-46.22c1.89-.1,3.6-.3,3.6-.3a1.3,1.3,0,0,0-.2-2.6s-5.1.4-8.39.4c-3.09,0-8.29-.4-8.29-.4a1.3,1.3,0,0,0-.2,2.6s1.61.2,3.3.3l4.91,13.43L27.18,54.33,15.72,20.25c1.9-.1,3.6-.3,3.6-.3a1.3,1.3,0,0,0-.2-2.6s-5.1.4-8.39.4c-.59,0-1.28,0-2,0a31.46,31.46,0,0,1,47.54-5.92l-.41,0a5.44,5.44,0,0,0-5.28,5.58c0,2.6,1.49,4.79,3.09,7.38a16.66,16.66,0,0,1,2.59,8.68c0,2.69-1,5.82-2.39,10.17L50.71,54.07Zm23.27-.35A31.46,31.46,0,0,1,50.82,62.2l9.61-27.79a29.62,29.62,0,0,0,2.39-11.27,23.42,23.42,0,0,0-.21-3.24"/></svg>';
		
		}elseif( $icon == 'bulkgate' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70 53.8"><g id="g3418"><path id="path3420" d="M35,12.83c11.44,7.83,19.44,17.88,22.73,41H70C68.8,30.78,55,11,35,0,15,11,1.29,30.78,0,53.8H12.29S34,54.61,48.41,32c0,0-14.44,7.68-22.94,4.49-8-3-4.15-10-3.71-10.72A48,48,0,0,1,35,12.83"/></g></svg>';
		
		}elseif( $icon == 'push_notification' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70 67"><path d="M50.84,67a6.26,6.26,0,0,1-4.27-1.68L34,53.58H12.45A12.4,12.4,0,0,1,0,41.26V12.32A12.4,12.4,0,0,1,12.45,0h45.1A12.4,12.4,0,0,1,70,12.32V41.26A12.4,12.4,0,0,1,57.55,53.58h-.43l-.07,7.3A6.22,6.22,0,0,1,50.84,67ZM12.45,6.53a5.87,5.87,0,0,0-5.92,5.79V41.26a5.87,5.87,0,0,0,5.92,5.79H36.62l13.91,13,.12-13h6.9a5.87,5.87,0,0,0,5.92-5.79V12.32a5.87,5.87,0,0,0-5.92-5.79Z"/><rect x="14.47" y="16.99" width="41.06" height="6.53" rx="3.27"/><rect x="14.47" y="30.01" width="31.06" height="6.53" rx="3.27"/></svg>';
		
		}elseif( $icon == 'webhook' ){
			$svg = '<svg style="fill: '. esc_attr( $color ) .';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72.88 68"><path d="M17.52,68a17.68,17.68,0,0,1-1.78-.09A17.49,17.49,0,0,1,.09,52.27a17.3,17.3,0,0,1,2.8-11.41,3.15,3.15,0,0,1,2.63-1.42,3.08,3.08,0,0,1,2.35,1.07,3.24,3.24,0,0,1,.2,3.82,11.28,11.28,0,0,0,9.45,17.44,12.63,12.63,0,0,0,4.56-.9,11,11,0,0,0,6.72-10,3.59,3.59,0,0,1,3.52-3.65H51l.3-.38a5.17,5.17,0,1,1,0,6.4l-.3-.38H37.47a3.24,3.24,0,0,0-3.1,2.37A17.58,17.58,0,0,1,17.52,68Z"/><path d="M55.39,67.57c-.36,0-.72,0-1.08,0a3.12,3.12,0,0,1-2.79-4.14,3.23,3.23,0,0,1,3-2.08h.18l.64,0A11.26,11.26,0,0,0,66.6,50.87a11.52,11.52,0,0,0-4.53-9.95,10.39,10.39,0,0,0-6.51-2.23,11.85,11.85,0,0,0-5.49,1.38l-.09,0a3.75,3.75,0,0,1-1.79.46,3.44,3.44,0,0,1-3-1.73L35.85,22.68l-.48-.07a5.17,5.17,0,0,1,.74-10.28,5.17,5.17,0,0,1,4.81,7.09l-.18.45,6.73,11.7a3.23,3.23,0,0,0,2.8,1.61,3.58,3.58,0,0,0,.8-.1,17.51,17.51,0,1,1,4.32,34.49Z"/><path d="M17.51,55.6a5.17,5.17,0,0,1-.73-10.29l.48-.07L24,33.57a3.25,3.25,0,0,0-.49-3.88A17.5,17.5,0,0,1,36.18,0a17.1,17.1,0,0,1,7.14,1.54,17.34,17.34,0,0,1,8.47,8.15,3.13,3.13,0,0,1,0,2.8,3.1,3.1,0,0,1-2.21,1.68,3.31,3.31,0,0,1-.55.05,3.24,3.24,0,0,1-2.84-1.8,11.32,11.32,0,0,0-21.34,3.83,11,11,0,0,0,5.26,10.82,3.58,3.58,0,0,1,1.39,4.86L22.14,48.07l.18.45A5.13,5.13,0,0,1,22,53a5.19,5.19,0,0,1-4.48,2.58Z"/></svg>';
		}

		return "<span class='cartbounty-pro-icon-container cartbounty-pro-icon-$icon'><img src='data:image/svg+xml;base64," . esc_attr( base64_encode( $svg ) ) . "' alt='" . esc_attr( $icon ) . "' /></span>";
	}

	/**
	 * Method returns current open tab. Default tab - Dashboard
	 *
	 * @since    9.3.5
	 */
	function get_open_tab(){
		$tab = $this->get_default_open_tab();

		if( isset( $_GET['tab'] ) ){
			$tab = $_GET['tab'];
		}

		return $tab;
	}

	/**
	 * Method returns current open section. Default - empty section
	 *
	 * @since    9.3.5
	 */
	function get_open_section(){
		$section = '';

		if( isset( $_GET['section'] ) ){
			$section = $_GET['section'];
		}

		return $section;
	}

	/**
     * Method displays available sections
     *
     * @since    9.0
     * @return   string
     * @param 	 string    $active_section    	Currently open section item
     * @param    string    $tab    		  		Tab name
     */
    function display_sections( $active_section, $tab ){
    	$sections = $this->get_sections( $tab );
    	$all_title = esc_html__('All integrations', 'woo-save-abandoned-carts');

    	if($tab == 'tools'){
    		$all_title = esc_html__('All tools', 'woo-save-abandoned-carts');
    	}

    	//Generating sections for large screens
    	echo '<ul id="cartbounty-pro-sections" class="cartbounty-pro-hidden-xs">';
    	foreach( $sections as $key => $section ){
    		$class = ( $key == $active_section ) ? 'current' : '';
    		$link = "?page=". CARTBOUNTY_PRO ."&tab=$tab&section=$key";
	    	echo "<li><a href='". esc_url( $link ) ."' title='". esc_attr( $section['name'] ) . "' class='". esc_attr( $class ) ."'>". $this->get_icon( $key, $active_section, true, false) ." <span class='cartbounty-pro-section-name'>". esc_html( $section['name'] ) . "</span>". $this->get_connection( $section['connected'], $text = false, false ) ."</a></li>";
    	}
    	echo '</ul>';

    	//Generating sections for small screens
    	echo '<select id="cartbounty-pro-mobile-sections" class="cartbounty-pro-select" onchange="window.location.href=this.value" style="display: none;">';
    		echo "<option value='". esc_url( "?page=". esc_html( CARTBOUNTY_PRO ) ."&tab=$tab" ) ."'>". esc_html( $all_title ) ."</option>";
	    	foreach( $sections as $key => $section ){
	    		$link = "?page=". CARTBOUNTY_PRO ."&tab=$tab&section=$key";
		    	echo "<option value='". esc_url( $link ) ."' ". selected( $active_section, $key, false ) .">". esc_html( $section['name'] ). "</option>";
	    	}
    	echo '</select>';
    }

    /**
	 * Method displays a dropdown field of available time intervals for a given option name
	 *
	 * @since    9.9.3
	 * @return   HTML
	 * @param    string     $option				Name of the option field used for storing time in database
     * @param    integer    $automation			Automation number
     * @param    string     $automation_name    Automation name
     * @param    string     $recovery           Recovery type e.g. ActiveCampaign, WordPress, MailChimp
     * @param    string     $field_type         Information about field type that needs to be prepared
	 */
	public function display_time_intervals( $option, $automation = NULL, $automation_name = '', $recovery = '', $field_type = NULL ) {
		$data = $this->get_interval_data( $option, $automation, false, $automation_name,  $recovery, $field_type );
		$storage_array = '[interval]';
		$step_nr = '';
		$step_array = '';
		
		if( !empty( $field_type ) ){
			$storage_array = '['. $field_type .']';
		}

		if( $option == 'cartbounty_pro_automation_steps' || $option == 'cartbounty_pro_bulkgate_steps' || $option == 'cartbounty_pro_push_notification_steps' ){
			$step_nr = '_' . $automation;
			$step_array = '[' . $automation . ']';
		}

		if( $option == 'cartbounty_pro_tab_notification_settings[interval]' ||
			$option == 'cartbounty_pro_main_settings[notification_frequency]' ||
			$option == 'cartbounty_pro_main_settings[magic_login_window]' ||
			$option == 'cartbounty_pro_main_settings[delete_anonymous_carts]' ){
			$storage_array = '';
		}

		echo '<label for="' . $option . $step_nr . ( isset( $field_type ) ? '_' . esc_attr( $field_type ) : '' ) . '">' . $data['name'] . '</label>';
		echo '<select id="' . $option . $step_nr . ( isset( $field_type ) ? '_' . esc_attr( $field_type ) : '' ) . '" class="cartbounty-pro-select" name="' . $option . $step_array . $storage_array .'" autocomplete="off" ' . $this->disable_field() . '>';
		foreach( $this->prepare_time_intervals( $data['interval'], $data['zero_name'], $option ) as $key => $milliseconds ) {
			echo '<option value="' . esc_attr( $key ) . '" ' . selected( $data['selected'], $key, false ) . '>' . esc_html( $milliseconds ) . '</option>';
		}
		echo '</select>';
	}

	/**
	 * Method returns existing time intervals for a given option
	 *
	 * @since    9.9.3
	 * @return   array or string
	 * @param    string     $option					Name of the option field saved in database
     * @param    integer    $automation				Automation number
     * @param    boolean    $just_selected_value	Should only the selected Interval value be returned
     * @param    string     $automation_name    	Automation name
     * @param    string     $recovery           	Recovery type e.g. ActiveCampaign, WordPress, MailChimp. Used for coupon dropdown generation
     * @param    string     $field_type         	Information about field type that needs to be prepared
	 */
	public function get_interval_data( $option, $automation = false, $just_selected_value = false, $automation_name = '', $recovery = '', $field_type = '' ){
		$option_value = get_option( $option );

		switch( $option ) {

			case 'cartbounty_pro_main_settings[delete_anonymous_carts]':
				$name = esc_html__( 'Automatically delete anonymous carts older than', 'woo-save-abandoned-carts' );
				$zero_name = esc_html__( 'Disable deletion', 'woo-save-abandoned-carts' );
				$milliseconds = array( 0, 86400000, 172800000, 259200000, 345600000, 432000000, 518400000, 604800000, 1209600000, 1814400000, 2419200000, 4838400000, 7257600000, 9676800000, 12096000000, 14515200000 );
				$selected_interval = 0;
				$delete_anonymous_carts = $this->get_settings( 'settings', 'delete_anonymous_carts' );

				if( isset( $delete_anonymous_carts ) ){ //If interval has been set - use it
					$selected_interval = $delete_anonymous_carts;
				}

				break;

			case 'cartbounty_pro_tab_notification_settings[interval]':
				$name = esc_html__( 'Notification interval', 'woo-save-abandoned-carts' );
				$zero_name = '';
				$milliseconds = array( 1000, 1500, 2000, 2500, 3000, 3500, 4000, 5000, 10000 );
				$selected_interval = $this->get_tools_defaults( 'interval', 'tab_notification' );
				$tn_interval = $this->get_settings( 'tab_notification', 'interval' );

				if( $tn_interval ){ //If interval has been set - use it
					$selected_interval = $tn_interval;
				}

				break;

			case 'cartbounty_pro_main_settings[notification_frequency]':
				$name = esc_html__( 'Check for new abandoned carts', 'woo-save-abandoned-carts' );
				$zero_name = esc_html__( 'Disable notifications', 'woo-save-abandoned-carts' );
				$milliseconds = array( 0, 600000, 1200000, 1800000, 3600000, 7200000, 10800000, 14400000, 18000000, 21600000, 43200000, 86400000, 172800000, 604800000, 2419200000 );
				$selected_interval = 3600000;
				$notification_frequency = $this->get_settings( 'settings', 'notification_frequency' );

				if( isset( $notification_frequency ) ){ //If interval has been set - use it
					$selected_interval = $notification_frequency;
				}

				break;

			case 'cartbounty_pro_main_settings[magic_login_window]':
				$name = esc_html__( 'Magic login expires after', 'woo-save-abandoned-carts' );
				$zero_name = esc_html__( 'Unlimited period of time', 'woo-save-abandoned-carts' );
				$milliseconds = array( 0, 3600000, 7200000, 10800000, 14400000, 18000000, 21600000, 43200000, 86400000, 172800000, 259200000, 345600000, 432000000, 518400000, 604800000, 1209600000, 1814400000, 2419200000, 4838400000, 7257600000, 9676800000, 12096000000, 14515200000 );
				$selected_interval = 172800000;
				$magic_login_window = $this->get_settings( 'settings', 'magic_login_window' );

				if( isset( $magic_login_window ) ){ //If interval has been set - use it
					$selected_interval = $magic_login_window;
				}

				break;

			case 'cartbounty_pro_automation_steps':
			case 'cartbounty_pro_bulkgate_steps':
			case 'cartbounty_pro_push_notification_steps':
			case 'cartbounty_pro_mailchimp_coupon':
			case 'cartbounty_pro_getresponse_coupon':
			case 'cartbounty_pro_activecampaign_coupon':
			case 'cartbounty_pro_webhook_coupon':
			case 'cartbounty_pro_exit_intent_coupon':
			case 'cartbounty_pro_early_capture_coupon':

				if( $field_type == 'coupon_expiry' ){ //Handling coupon expiration dropdown fields
					$coupons = $this->coupons();
					$name = esc_html__( 'Coupon expires after', 'woo-save-abandoned-carts' );
					$zero_name = esc_html__( 'Never expires', 'woo-save-abandoned-carts' );
					$milliseconds = array( 0, 86400000, 172800000, 259200000, 345600000, 432000000, 518400000, 604800000, 1209600000, 1814400000, 2419200000, 4838400000, 7257600000, 9676800000, 12096000000, 14515200000 );
					$selected_interval = $coupons->get_coupon_settings( $recovery, $option, $automation, $field_type );

				}else{ //Handling other dropdown fields
					$name = esc_html__( 'Send message after', 'woo-save-abandoned-carts' );
					$zero_name = '';
					$milliseconds = array( 300000, 600000, 900000, 1200000, 1500000, 1800000, 2400000, 3000000, 3600000, 7200000, 10800000, 14400000, 18000000, 21600000, 25200000, 28800000, 32400000, 36000000, 39600000, 43200000, 64800000, 86400000, 172800000, 259200000, 345600000, 432000000, 518400000, 604800000, 1209600000, 1814400000, 2419200000, 4838400000, 7257600000 );
					
					if( $option == 'cartbounty_pro_automation_steps'){
						$name = esc_html__( 'Send email after', 'woo-save-abandoned-carts' );
						$wordpress = $this->wordpress();
						$selected_interval = $wordpress->get_defaults( 'interval', $automation );

					}elseif( $option == 'cartbounty_pro_bulkgate_steps' ){
						$bulkgate = $this->bulkgate();
						$selected_interval = $bulkgate->get_defaults( 'interval', $automation );
					
					}elseif( $option == 'cartbounty_pro_push_notification_steps' ){
						$name = esc_html__( 'Send notification after', 'woo-save-abandoned-carts' );
						$push_notification = $this->push_notification();
						$selected_interval = $push_notification->get_defaults( 'interval', $automation );
					}

					if( isset( $option_value[$automation] ) ){
						$automation_step = $option_value[$automation];
					}

					if( !empty( $automation_step['interval'] ) ){ //If interval has been set - use it
						$selected_interval = $automation_step['interval'];
					}
				}

				break;
		}

		if( $just_selected_value ){ //In case just the selected value is requested
			$prepared_interval_array = $this->prepare_time_intervals( array( $selected_interval ) );

			if( isset( $prepared_interval_array[$selected_interval] ) ){
				return $prepared_interval_array[$selected_interval];
			}

		}else{
			return array(
				'name'  		=> $name,
				'zero_name'		=> $zero_name,
				'interval'		=> $milliseconds,
				'selected'		=> $selected_interval
			);
		}
	}

	/**
     * Prepare time intervals from milliseconds
     *
     * @since    9.0
     * @return   array
     * @param 	 array    $milliseconds    	Array of milliseconds
     * @param 	 string   $zero_value    	Content for zero value
     * @param    string   $option			Name of the option field used for storing time in database
     */
	function prepare_time_intervals( $milliseconds = array(), $zero_value = '', $option = '' ){
		$intervals = array();
		$alternative_options = array( 'cartbounty_pro_main_settings[notification_frequency]' );

		if( is_array( $milliseconds ) ){

			foreach( $milliseconds as $milisecond ){
				
				if( $milisecond == 0 ) {
					$intervals[$milisecond] = $zero_value;

				}elseif( $milisecond < 60000 ){ //Generate seconds
					$seconds = $milisecond / 1000;
					$intervals[$milisecond] = sprintf(
						esc_html( _n( '%s second', '%s seconds', esc_html( $seconds ), 'woo-save-abandoned-carts' ) ), esc_html( $seconds )
					);

				}elseif( $milisecond < 3600000 ){ //Generate minutes
					$minutes = $milisecond / 60000;
					$intervals[$milisecond] = sprintf(
						esc_html( _n( '%s minute', '%s minutes', esc_html( $minutes ), 'woo-save-abandoned-carts' ) ), esc_html( $minutes )
					);

					if( in_array( $option, $alternative_options ) ){ //To display alternative frequencies like "Every minute" or "Once a day"
						$intervals[$milisecond] = sprintf(
							esc_html( _n( 'Every minute', 'Every %s minutes', esc_html( $minutes ), 'woo-save-abandoned-carts' ) ), esc_html( $minutes )
						);
					}

				}elseif( $milisecond < 86400000 ){ //Generate hours
					$hours = $milisecond / 3600000;
					$intervals[$milisecond] = sprintf(
						esc_html( _n( '%s hour', '%s hours', esc_html( $hours ), 'woo-save-abandoned-carts' ) ), esc_html( $hours )
					);

					if( in_array( $option, $alternative_options ) ){ //To display alternative frequencies like "Every minute" or "Once a day"
						$intervals[$milisecond] = sprintf(
							esc_html( _n( 'Every hour', 'Every %s hours', esc_html( $hours ), 'woo-save-abandoned-carts' ) ), esc_html( $hours )
						);
					}

					if( $hours == 12 && in_array( $option, $alternative_options ) ){ //To display alternative frequencies like "Every minute" or "Once a day"
						$intervals[$milisecond] = esc_html__( 'Twice daily', 'woo-save-abandoned-carts' );
					}

				}elseif( $milisecond < 604800000 ){ //Generate days
					$days = $milisecond / 86400000;
					$intervals[$milisecond] = sprintf(
						esc_html( _n( '%s day', '%s days', esc_html( $days ), 'woo-save-abandoned-carts' ) ), esc_html( $days )
					);

					if( $days == 1 && in_array( $option, $alternative_options ) ){ //To display alternative frequencies like "Every minute" or "Once a day"
						$intervals[$milisecond] = esc_html__( 'Once daily', 'woo-save-abandoned-carts' );
					}

					if( $days == 2 && in_array( $option, $alternative_options ) ){ //To display alternative frequencies like "Every minute" or "Once a day"
						$intervals[$milisecond] = esc_html__( 'Once every 2 days', 'woo-save-abandoned-carts' );
					}

				}elseif( $milisecond < 2419200000 ){ //Generate weeks
					$weeks = $milisecond / 604800000;
					$intervals[$milisecond] = sprintf(
						esc_html( _n( '%s week', '%s weeks', esc_html( $weeks ), 'woo-save-abandoned-carts' ) ), esc_html( $weeks )
					);

					if( $weeks == 1 && in_array( $option, $alternative_options ) ){ //To display alternative frequencies like "Every minute" or "Once a day"
						$intervals[$milisecond] = esc_html__( 'Once weekly', 'woo-save-abandoned-carts' );
					}

				}else{ //Generate months
					$months = $milisecond / 2419200000;
					$intervals[$milisecond] = sprintf(
						esc_html( _n( '%s month', '%s months', esc_html( $months ), 'woo-save-abandoned-carts' ) ), esc_html( $months )
					);

					if( $months == 1 && in_array( $option, $alternative_options ) ){ //To display alternative frequencies like "Every minute" or "Once a day"
						$intervals[$milisecond] = esc_html__( 'Once monthly', 'woo-save-abandoned-carts' );
					}
				}
			}
		}

		return $intervals;
	}
	
	/**
     * Method displays available countries that can be selected
     *
     * @since    9.2
     * @return   string
     * @param    string    $section				Section identifier
     */
    function display_countries( $section ){
    	if(!class_exists('WooCommerce')){ //Check if WooCommerce plugin is active
    		return;
    	}

    	if( $section == 'settings' ){
    		$option_name = 'cartbounty_pro_main_settings[allowed_countries]';
    		$allowed_countries = $this->get_settings( 'settings', 'allowed_countries' );
    		$select_name = $option_name . '[]';

    	}elseif( $section == 'bulkgate' ){
    		$option_name = 'cartbounty_pro_bulkgate_settings';
    		$bulkgate_settings = get_option( $option_name );
    		$allowed_countries = array();

			if( isset( $bulkgate_settings['countries'] ) ){
				$allowed_countries = $bulkgate_settings['countries'];
			}
    		
    		$select_name = $option_name . '[countries][]';
    	}

    	if(!$allowed_countries){
    		$allowed_countries = array();
    	}
    	$countries = new WC_Countries(); //Creating WooCommerce country object

    	echo '<select id="cartbounty-pro-allowed-countries" class="cartbounty-pro-select cartbounty-pro-multiple" name="'. $select_name .'" multiple placeholder="'. esc_attr__('Choose countries / regions…', 'woo-save-abandoned-carts') .'" '. $this->disable_field() .' autocomplete="off">';
	    	foreach( $countries->get_countries() as $key => $country ){
	    		$selected = '';
	    		if(in_array($key, $allowed_countries)){
	    			$selected = 'selected';
	    		}
		    	echo "<option value='". esc_attr( $key ) ."' ". esc_attr( $selected ) .">". esc_html( $country ) ."</option>";
	    	}
    	echo '</select>';
    	echo '<button id="cartbounty-pro-add-all-countries" class="cartbounty-pro-button button button-secondary cartbounty-pro-progress" type="button">'. esc_html__('Select all', 'woo-save-abandoned-carts') .'</button>';
    	echo '<button id="cartbounty-pro-remove-all-countries" class="cartbounty-pro-button button button-secondary" type="button">'. esc_html__('Select none', 'woo-save-abandoned-carts') .'</button>';
    }

    /**
	 * Method returns sections
	 *
	 * @since    9.0
	 * @return   array
	 * @param    string    $tab    		  Tab name
	 */
	function get_sections( $tab ){
		$sections = array();

		if($tab == 'recovery'){

			$activecampaign = $this->activecampaign();
			$getresponse = $this->getresponse();
			$mailchimp = $this->mailchimp();
			$automation = $this->automation();
			$webhook = $this->webhook();

			$sections = array(
				'activecampaign'	=> array(
					'name'				=> 'ActiveCampaign',
					'connected'			=> $activecampaign->store_connected() ? true : false,
					'description'		=> '<p>' . esc_html__("ActiveCampaign is an awesome platform that enable you to set up advanced rules for sending abandoned cart recovery emails tailored to customer behavior.", 'woo-save-abandoned-carts') . '</p>'
				),
				'getresponse'	=> array(
					'name'				=> 'GetResponse',
					'connected'			=> $getresponse->store_connected() ? true : false,
					'description'		=> '<p>' . esc_html__("GetResponse offers efficient and beautifully designed email marketing platform to recover abandoned carts. It is a professional email marketing system with awesome email design options and beautifully pre-designed email templates.", 'woo-save-abandoned-carts') . '</p>'
				),
				'mailchimp'	=> array(
					'name'				=> 'MailChimp',
					'connected'			=> $mailchimp->store_connected() ? true : false,
					'description'		=> '<p>' . esc_html__("MailChimp allows to send personalized reminder emails to your customers, either as one-time messages or a series of follow-up emails, such as sending the first email within an hour of cart abandonment, the second one after 24 hours, and so on.", 'woo-save-abandoned-carts') . '</p>'
				),
				'wordpress'	=> array(
					'name'				=> 'WordPress',
					'connected'			=> $automation->automation_enabled( 'wordpress' ) ? true : false,
					'description'		=> '<p>' . esc_html__("A simple solution for sending abandoned cart reminder emails using WordPress mail server. This recovery option works best if you have a small to medium number of abandoned carts.", 'woo-save-abandoned-carts') . '</p>'
				),
				'bulkgate'	=> array(
					'name'				=> 'BulkGate',
					'connected'			=> $automation->automation_enabled( 'bulkgate' ) ? true : false,
					'description'		=> '<p>' . esc_html__("A perfect channel for sending personalized SMS text messages like abandoned cart reminders.", 'woo-save-abandoned-carts') . '</p><p>' . esc_html__("Recover more sales by sending a personal SMS message along with other abandoned cart reminders.", 'woo-save-abandoned-carts') . '</p>'
				),
				'push_notification'	=> array(
					'name'				=> esc_html__( 'Push notifications', 'woo-save-abandoned-carts' ),
					'connected'			=> $automation->automation_enabled( 'push_notification' ) ? true : false,
					'description'		=> '<p>' . esc_html__("Web push notifications offer a low-friction, real-time way to send cart reminders - no email or phone necessary. They can reach users even after they have left your store, increasing the chance of cart recovery.", 'woo-save-abandoned-carts') . '</p>'
				),
				'webhook'	=> array(
					'name'				=> 'Webhook',
					'connected'			=> $webhook->api_valid() ? true : false,
					'description'		=> '<p>' . sprintf(
						/* translators: %1$s - Link start, %2$s - Link start, %3$s - Link end */
						esc_html__( 'Webhook offers an easy way of sending event-based data about abandoned carts to applications like %1$sMake (former Integromat)%3$s, %2$sPabbly%3$s, Zapier or other. A great way for building powerful automations and advanced marketing processes.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( CARTBOUNTY_PRO_MAKE_LINK ) .'" target="_blank">', '<a href="'. esc_url( CARTBOUNTY_PRO_PABBLY_LINK ) .'" target="_blank">', '</a>' ) . '</p>'
				)
			);
		}

		if($tab == 'tools'){
			$sections = array(
				'exit_intent'	=> array(
					'name'				=> esc_html__('Exit Intent', 'woo-save-abandoned-carts'),
					'connected'			=> $this->get_settings( 'exit_intent', 'status' ) ? true : false,
					'description'		=> '<p>' . esc_html__("Save more recoverable abandoned carts by showcasing a popup message right before your customer tries to leave and offer an option to save his shopping cart by entering his email.", 'woo-save-abandoned-carts') . '</p>'
				),
				'early_capture'	=> array(
					'name'				=> esc_html__('Early capture', 'woo-save-abandoned-carts'),
					'connected'			=> $this->get_settings( 'early_capture', 'status' ) ? true : false,
					'description'		=> '<p>' . esc_html__('Try saving more recoverable abandoned carts by enabling Early capture to collect customer’s email or phone right after the "Add to cart" button is clicked.', 'woo-save-abandoned-carts') . '</p>'
				),
				'tab_notification'	=> array(
					'name'				=> esc_html__('Tab notification', 'woo-save-abandoned-carts'),
					'connected'			=> $this->get_settings( 'tab_notification', 'status' ) ? true : false,
					'description'		=> '<p>' . esc_html__('Decrease shopping cart abandonment by grabbing customer attention and returning them to your store after they have switched to a new browser tab with Tab notification.', 'woo-save-abandoned-carts') . '</p>'
				)
			);
		}
		
		return $sections;
	}

	/**
	 * Method returns section contents
	 *
	 * @since    9.0
	 * @return   array
	 * @param    string    $active_section    	Currently open section item
	 */
	function section_contents( $active_section ){
		$coupons = $this->coupons();
		$automation = $this->automation();

		switch ( $active_section ) {

			case 'activecampaign':

				$activecampaign = $this->activecampaign(); 
				$api_valid = $activecampaign->api_valid();

				if(!class_exists('WooCommerce')){ //If WooCommerce is not active
					$this->missing_woocommerce_notice( $active_section ); 
					return;
				}?>

				<div class="cartbounty-pro-section-intro">
					<?php echo sprintf(
						/* translators: %1$s - Link start, %2$s - Link start, %3$s - Link end */
						esc_html__('If you would like to integrate with %1$sActiveCampaign%3$s and automate your abandoned cart recovery process, please enter your ActiveCampaign API key and URL below. See %2$sthis video tutorial%3$s for additional information.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( CARTBOUNTY_PRO_ACTIVECAMPAIGN_TRIAL_LINK ) .'" target="_blank">', '<a href="'. esc_url( CARTBOUNTY_PRO_ACTIVECAMPAIGN_SETUP_TUTORIAL_LINK ) .'" target="_blank">', '</a>' );

						if( !$api_valid ){
							echo ' ' . sprintf(
								/* translators: %s - URL link */
								esc_html__('If you do not have an ActiveCampaign account yet, you can %ssign up for a free trial period here%s.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( CARTBOUNTY_PRO_ACTIVECAMPAIGN_TRIAL_LINK ) .'" target="_blank">', '</a>' );
						}
					?>
				</div>

				<form method="post" action="options.php">
					<?php
						settings_fields( 'cartbounty-pro-activecampaign-settings' );
						do_settings_sections( 'cartbounty-pro-activecampaign-settings' );
						$activecampaign->run();							
						$ac_settings = $activecampaign->get_settings();						
						$api_access = $activecampaign->get_api_access();
						$api_status = $activecampaign->api_status();
						$fields = array( $api_access['api_url'], $api_access['api_key']);
					?>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('API Access', 'woo-save-abandoned-carts'); ?></h4>
							<?php if(!$api_valid):?>
								<p class="cartbounty-pro-titles-column-description">
									<?php echo sprintf(
									/* translators: %s - URL link */
									esc_html__('Please look at this guide on %show to get ActiveCampaign URL and API key%s.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( CARTBOUNTY_PRO_ACTIVECAMPAIGN_API_TUTORIAL ) .'" target="_blank">', '</a>' ); ?>
								</p>
							<?php else: ?>
								<p class="cartbounty-pro-titles-column-description">
									<?php esc_html_e('Synchronizes your abandoned carts with ActiveCampaign.', 'woo-save-abandoned-carts'); ?>
								</p>
							<?php endif; ?>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty_pro_activecampaign_key"><?php esc_html_e('API key', 'woo-save-abandoned-carts'); ?><?php echo $this->output_connection_message( $api_status, $fields ); ?></label>
								<input id="cartbounty_pro_activecampaign_key" class="cartbounty-pro-text" type="text" name="cartbounty_pro_activecampaign_settings[key]" value="<?php echo esc_attr( $ac_settings['key'] ); ?>" <?php echo $this->disable_field(); ?> />
							</div>
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty_pro_activecampaign_url"><?php esc_html_e('URL', 'woo-save-abandoned-carts'); ?></label>
								<input id="cartbounty_pro_activecampaign_url" class="cartbounty-pro-text" type="text" name="cartbounty_pro_activecampaign_settings[url]" value="<?php echo esc_attr( $ac_settings['url'] ); ?>" <?php echo $this->disable_field(); ?> />
							</div>
							<?php if($api_valid): ?>
								<div class="cartbounty-pro-settings-group">
									<label for="cartbounty_pro_activecampaign_automation_id"><?php esc_html_e('Automation', 'woo-save-abandoned-carts'); ?></label><?php $activecampaign->display_automations(); ?>
								</div>
							<?php endif; ?>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<?php $coupons->display_coupon_settings( $active_section, 'cartbounty_pro_activecampaign_coupon' ); ?>
					</div>
					<div class="cartbounty-pro-row">
						<?php $this->display_exclusion_settings( $active_section ); ?>
					</div>
					<div class='cartbounty-pro-button-row'>
						<?php
						if( $this->user_is_admin() ){
							echo "<button type='submit' class='cartbounty-pro-button button-primary cartbounty-pro-progress'>". esc_html__('Save settings', 'woo-save-abandoned-carts') ."</button>";
						}
						if($this->check_license() && $activecampaign->store_connected()){
							echo $this->display_force_sync_button( $active_section );
						}?>
					</div>
				</form>
				<?php
				break;

			case 'getresponse':

				$getresponse = $this->getresponse();
				$api_valid = $getresponse->api_valid();

				if(!class_exists('WooCommerce')){ //If WooCommerce is not active
					$this->missing_woocommerce_notice( $active_section ); 
					return;
				}?>

				<div class="cartbounty-pro-section-intro">
					<?php echo sprintf(
						/* translators: %s - URL link */
						esc_html__('Please enter your %sGetResponse API key%s below to integrate with GetResponse and automate your abandoned cart recovery process.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( CARTBOUNTY_PRO_GETRESPONSE_API_LINK ) .'" target="_blank">', '</a>' );

						if( !$api_valid ){
							echo ' ' . sprintf(
								/* translators: %s - URL link */
								esc_html__('If you do not have an account on GetResponse yet, you can %ssign up for a free trial period here%s.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( CARTBOUNTY_PRO_GETRESPONSE_TRIAL_LINK ) .'" target="_blank">', '</a>' );
						}
					?>
				</div>

				<form method="post" action="options.php">
					<?php
						settings_fields( 'cartbounty-pro-getresponse-settings' );
						do_settings_sections( 'cartbounty-pro-getresponse-settings' );
						$settings = $getresponse->get_settings();
						$api_status = $getresponse->api_status();
						$api_access = $getresponse->get_api_access();
						$fields = array( $api_access['api_key'] );
					?>

					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('API Access', 'woo-save-abandoned-carts'); ?></h4>
							<?php if(!$api_valid):?>
								<p class="cartbounty-pro-titles-column-description">
									<?php echo sprintf(
									/* translators: %s - URL link */
									esc_html__('Please look at this guide on %show to get GetResponse API key%s.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( CARTBOUNTY_PRO_GETRESPONSE_API_LINK ) .'" target="_blank">', '</a>' ); ?>
								</p>
							<?php else: ?>
								<p class="cartbounty-pro-titles-column-description">
									<?php esc_html_e('Synchronizes your abandoned carts with GetResponse.', 'woo-save-abandoned-carts'); ?>
								</p>
							<?php endif; ?>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty_pro_getresponse_key"><?php esc_html_e('API key', 'woo-save-abandoned-carts'); ?><?php echo $this->output_connection_message( $api_status, $fields ); ?></label>
								<input id="cartbounty_pro_getresponse_key" class="cartbounty-pro-text" type="text" name="cartbounty_pro_getresponse_settings[key]" value="<?php echo esc_attr( $settings['key'] ); ?>" <?php echo $this->disable_field(); ?> />
							</div>
							<?php if($api_valid): ?>
								<div class="cartbounty-pro-settings-group">
									<label for="cartbounty_pro_getresponse_store_id"><?php esc_html_e('Store to sync with', 'woo-save-abandoned-carts'); ?></label><?php $getresponse->display_stores(); ?>
								</div>
								<div class="cartbounty-pro-settings-group">
									<label for="cartbounty_pro_getresponse_list_id"><?php esc_html_e('List to sync with', 'woo-save-abandoned-carts'); ?></label><?php $getresponse->display_lists(); ?>
								</div>
							<?php endif; ?>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<?php $coupons->display_coupon_settings( $active_section, 'cartbounty_pro_getresponse_coupon' ); ?>
					</div>
					<div class="cartbounty-pro-row">
						<?php $this->display_exclusion_settings( $active_section ); ?>
					</div>
					<div class='cartbounty-pro-button-row'>
						<?php
						if( $this->user_is_admin() ){
							echo "<button type='submit' class='cartbounty-pro-button button-primary cartbounty-pro-progress'>". esc_html__('Save settings', 'woo-save-abandoned-carts') ."</button>";
						}
						if($this->check_license() && $getresponse->store_connected()){
							echo $this->display_force_sync_button( $active_section );
						}?>
					</div>
				</form>
				<?php
				break;

			case 'mailchimp':

				if(!class_exists('WooCommerce')){ //If WooCommerce is not active
					$this->missing_woocommerce_notice( $active_section ); 
					return;
				}?>

				<div class="cartbounty-pro-section-intro">
					<?php echo sprintf(
						/* translators: %1$s - Link start, %2$s - Link start, %3$s - Link end */
						esc_html__('Please enter your %1$sMailChimp%3$s API key below to integrate with MailChimp and automate your abandoned cart recovery process. Please see %2$sthis video tutorial%3$s for additional information.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( CARTBOUNTY_PRO_MAILCHIMP_LINK ) .'" target="_blank">' , '<a href="'. esc_url( CARTBOUNTY_PRO_MAILCHIMP_SETUP_TUTORIAL_LINK ) .'" target="_blank">', '</a>' );
					?>
				</div>

				<form method="post" action="options.php">
					<?php 
						settings_fields( 'cartbounty-pro-mailchimp-settings' );
						do_settings_sections( 'cartbounty-pro-mailchimp-settings' );
						$mailchimp = $this->mailchimp();
						$mailchimp->run();
						$api_valid = $mailchimp->api_valid();
						$api_status = $mailchimp->api_status();
						$api_access = $mailchimp->get_api_access();
						$fields = array( $api_access['api_key'] );
						$settings = $mailchimp->get_settings();
					?>

					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('API Access', 'woo-save-abandoned-carts'); ?></h4>
							<?php if(!$api_valid):?>
								<p class="cartbounty-pro-titles-column-description">
									<?php echo sprintf(
									/* translators: %s - URL link */
									esc_html__('Please look at this guide on %show to get MailChimp API key%s.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( CARTBOUNTY_PRO_MAILCHIMP_API_LINK ) .'" target="_blank">', '</a>'); ?>
								</p>
							<?php else: ?>
								<p class="cartbounty-pro-titles-column-description">
									<?php esc_html_e('Synchronizes your abandoned carts with MailChimp.', 'woo-save-abandoned-carts'); ?>
								</p>
							<?php endif; ?>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty_pro_mailchimp_key"><?php esc_html_e('API key', 'woo-save-abandoned-carts'); ?><?php echo $this->output_connection_message( $api_status, $fields ); ?></label>
								<input id="cartbounty_pro_mailchimp_key" class="cartbounty-pro-text" type="text" name="cartbounty_pro_mailchimp_settings[key]" value="<?php echo esc_attr( $settings['key'] ); ?>" <?php echo $this->disable_field(); ?> />
							</div>
							<?php if( $api_valid ): ?>
								<div class="cartbounty-pro-settings-group">
									<?php $mailchimp->display_lists(); ?>
								</div>
							<?php endif; ?>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<?php $coupons->display_coupon_settings( $active_section, 'cartbounty_pro_mailchimp_coupon' ); ?>
					</div>
					<div class="cartbounty-pro-row">
						<?php $this->display_exclusion_settings( $active_section ); ?>
					</div>
					<div class='cartbounty-pro-button-row'>
						<?php
						if( $this->user_is_admin() ){
							echo "<button type='submit' class='cartbounty-pro-button button-primary cartbounty-pro-progress'>". esc_html__('Save settings', 'woo-save-abandoned-carts') ."</button>";
						}
						if($this->check_license() && $mailchimp->store_connected()){
							echo $this->display_force_sync_button( $active_section );
						}?>
					</div>
				</form>
				<?php
				break;

			case 'wordpress':

				if(!class_exists('WooCommerce')){ //If WooCommerce is not active
					$this->missing_woocommerce_notice( $active_section ); 
					return;
				}?>

				<div class="cartbounty-pro-section-intro">
					<?php esc_html_e('A simple solution for sending abandoned cart reminder emails using WordPress mail server. This recovery option works best if you have a small to medium number of abandoned carts.', 'woo-save-abandoned-carts'); ?> <?php esc_html_e('If you are looking for something more advanced and powerful, please consider connecting with ActiveCampaign, GetResponse or MailChimp.', 'woo-save-abandoned-carts'); ?>
				</div>

				<form method="post" action="options.php">
					<?php
						global $wpdb;
						settings_fields( 'cartbounty-pro-wordpress-settings' );
						do_settings_sections( 'cartbounty-pro-wordpress-settings' );
						$wordpress = $this->wordpress();
						$settings = $wordpress->get_settings();
						$automation_steps = get_option('cartbounty_pro_automation_steps');
					?>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-pro-full-width cartbounty-col-sm-12 cartbounty-col-md-12 cartbounty-col-lg-12">
							<h4><?php esc_html_e('Automation process', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e('Configure your abandoned cart reminder emails, how they look, when to send them, include coupons, etc. You can choose to enable just one or all of them creating a 4-step automation process. The countdown of the next step starts right after the previous one is finished.', 'woo-save-abandoned-carts'); ?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-pro-full-width cartbounty-col-sm-12 cartbounty-col-md-12 cartbounty-col-lg-12">
							<div class="cartbounty-pro-settings-group">
								<div class="cartbounty-pro-stairway">
									<?php if( !empty( $automation_steps ) ){
										foreach( $automation_steps as $key => $step ){
											$step = (object)$step;
											$enabled = ( isset($step->enabled) ) ? $step->enabled : false;
											$subject = ( isset($step->subject) ) ? $step->subject : '';
											$heading = ( isset($step->heading) ) ? $step->heading : '';
											$content = ( isset($step->content) ) ? $step->content : '';
											$template = ( isset($step->template) ) ? $step->template : $wordpress->get_defaults( 'template', $key ); 
											$main_color = ( isset($step->main_color) ) ? $step->main_color : false;
											$button_color = ( isset($step->button_color) ) ? $step->button_color : false;
											$text_color = ( isset($step->text_color) ) ? $step->text_color : false;
											$background_color = ( isset($step->background_color) ) ? $step->background_color : false;
											$include_image = ( isset($step->include_image) ) ? $step->include_image : false;
											$main_image = ( isset($step->main_image) ) ? $step->main_image : false;
											$time_interval_name = $this->get_interval_data( 'cartbounty_pro_automation_steps', $key, $just_selected_value = true );
											$preview_email_nonce = wp_create_nonce( 'preview_email' );
											$test_email_nonce = wp_create_nonce( 'test_email' ); 
											$coupon_status = $automation->display_coupon_status( 'wordpress', $key );
											$automation_status = $automation->display_automation_status( $enabled ); ?>

											<div class="cartbounty-pro-step<?php esc_attr( $automation->check_if_accessible( 'wordpress', $key ) ); ?>" data-automation-step="<?php echo esc_attr( $key ); ?>">
												<div class="cartbounty-pro-step-opener">
													<div class="cartbounty-pro-row">
														<div class="cartbounty-pro-titles-column cartbounty-col-xs-12 cartbounty-col-sm-4 cartbounty-col-lg-3">
															<div class="cartbounty-pro-automation-number"><?php echo esc_html( $key ) + 1; ?></div>
															<div class="cartbounty-pro-automation-name">
																<h3><?php echo esc_html( $wordpress->get_defaults( 'name', $key ) ); ?></h3>
																<p><?php echo sprintf(
																	/* translators: %s - Time, e.g. 10 minutes */
																	 esc_html__('Sends after %s', 'woo-save-abandoned-carts'), esc_html( $time_interval_name ) );?></p>
																<div class="cartbounty-pro-automation-status">
																	<?php echo $automation_status . $coupon_status; ?>
																</div>
															</div>
															<div class="cartbounty-pro-step-trigger"></div>
														</div>
														<div class="cartbounty-pro-settings-column cartbounty-col-xs-12 cartbounty-col-sm-8 cartbounty-col-lg-9">
															<div class="cartbounty-pro-row">
																<div class="cartbounty-pro-stats-container cartbounty-col-sm-12 cartbounty-col-lg-9">
																	<div class="cartbounty-pro-stats cartbounty-pro-percentage-switcher">
																		<div class="cartbounty-pro-stats-percentage">
																			<i><?php esc_html_e( 'Queue', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_queue( 'wordpress', $key ) ); ?></p>
																		</div>
																		<div class="cartbounty-pro-stats-count">
																			<i><?php esc_html_e( 'Sends', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats( 'wordpress', 'send', $key, $single = true ) ); ?></p>
																		</div>
																	</div>
																	<div class="cartbounty-pro-stats cartbounty-pro-percentage-switcher">
																		<div class="cartbounty-pro-stats-percentage">
																			<i><?php esc_html_e( 'Open rate', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats_percentage( 'wordpress', 'open', $key ) ); ?></p>
																		</div>
																		<div class="cartbounty-pro-stats-count">
																			<i><?php esc_html_e( 'Opens', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats( 'wordpress', 'open', $key, $single = true ) ); ?></p>
																		</div>
																	</div>
																	<div class="cartbounty-pro-stats cartbounty-pro-percentage-switcher">
																		<div class="cartbounty-pro-stats-percentage">
																			<i><?php esc_html_e( 'Click rate', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats_percentage( 'wordpress', 'click', $key ) ); ?></p>
																		</div>
																		<div class="cartbounty-pro-stats-count">
																			<i><?php esc_html_e( 'Clicks', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats( 'wordpress', 'click', $key, $single = true ) ); ?></p>
																		</div>
																	</div>
																	<div class="cartbounty-pro-stats cartbounty-pro-percentage-switcher">
																		<div class="cartbounty-pro-stats-percentage">
																			<i><?php esc_html_e( 'Recovery rate', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats_percentage( 'wordpress', 'recovered', $key ) ); ?></p>
																		</div>
																		<div class="cartbounty-pro-stats-count">
																			<i><?php esc_html_e( 'Recovered', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats( 'wordpress', 'recovered', $key, $single = true ) ); ?></p>
																		</div>
																	</div>
																	<div class="cartbounty-pro-stats cartbounty-pro-percentage-switcher">
																		<div class="cartbounty-pro-stats-percentage">
																			<i><?php esc_html_e( 'Unsubscribe rate', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats_percentage( 'wordpress', 'unsubscribed', $key ) ); ?></p>
																		</div>
																		<div class="cartbounty-pro-stats-count">
																			<i><?php esc_html_e( 'Unsubscribes', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats( 'wordpress', 'unsubscribed', $key, $single = true ) ); ?></p>
																		</div>
																	</div>
																</div>
																<div class="cartbounty-pro-trigger-container cartbounty-col-sm-12 cartbounty-col-lg-3">
																	<div class="cartbounty-pro-automation-status">
																		<?php echo $coupon_status . $automation_status; ?>
																	</div>
																	<div class="cartbounty-pro-step-trigger"></div>
																</div>
															</div>
														</div>
													</div>
												</div>
												<div class="cartbounty-pro-step-contents">
													<div class="cartbounty-pro-row">
														<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
															<h4><?php esc_html_e('General', 'woo-save-abandoned-carts'); ?></h4>
															<p class="cartbounty-pro-titles-column-description">
																<?php esc_html_e('Enable email sending to start this automated abandoned cart recovery step.', 'woo-save-abandoned-carts');
																	echo ' ' . sprintf(
																	/* translators: %s - Link tags */
																	 esc_html__('Learn how to use %spersonalization tags%s.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( $this->get_trackable_link( '' . 'personalization-tags', 'wp_personalization' ) ) .'" target="_blank">', '</a>');?>
															</p>
														</div>
														<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9<?php if($enabled){ echo ' cartbounty-pro-checked-parent'; }?>">
															<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
																<label for="cartbounty-pro-automation-status-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-switch cartbounty-pro-control-visibility cartbounty-pro-step-controller">
																	<input id="cartbounty-pro-automation-status-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][enabled]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $enabled, false ); ?> autocomplete="off" />
																	<span class="cartbounty-pro-slider round"></span>
																</label>
																<label for="cartbounty-pro-automation-status-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-control-visibility cartbounty-pro-step-controller"><?php esc_html_e('Enable email', 'woo-save-abandoned-carts'); ?></label>
															</div>
															<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
																<?php $this->display_time_intervals( 'cartbounty_pro_automation_steps', $key ); ?>
																<p class='cartbounty-pro-additional-information'>
																	<?php echo sprintf(
																	/* translators: %s - Link tags */
																	esc_html__( 'Please %ssee this%s to learn how reminder sending works and when it will be delivered.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( $this->get_trackable_link( '' . 'abandoned-carts', 'wp_is_it_abandoned', '#when-is-the-cart-abandoned' ) ) .'" target="_blank">', '</a>'); ?>
																</p>
															</div>
															<div class="cartbounty-pro-settings-group">
																<label for="cartbounty-pro-automation-subject-<?php echo esc_attr( $key ); ?>"><?php esc_html_e('Email subject', 'woo-save-abandoned-carts'); ?></label>
																<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
																	<input id="cartbounty-pro-automation-subject-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-text" type="text" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][subject]" value="<?php echo esc_attr( stripslashes( $subject ) ); ?>" placeholder="<?php echo esc_attr( $wordpress->get_defaults( 'subject', $key ) ); ?>" /><?php $this->add_emojis(); ?><?php $this->add_tags( array( 'recovery_link', 'unsubscribe_link' ) ); ?>
																</div>
																<p class='cartbounty-pro-additional-information'>
																	<?php esc_html_e('Subject line has a huge impact on email open rate.', 'woo-save-abandoned-carts'); ?>
																</p>
															</div>
															<div class="cartbounty-pro-settings-group">
																<label for="cartbounty-pro-automation-heading-<?php echo esc_attr( $key ); ?>"><?php esc_html_e('Main title', 'woo-save-abandoned-carts'); ?></label>
																<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
																	<input id="cartbounty-pro-automation-heading-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-text" type="text" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][heading]" value="<?php echo esc_attr( stripslashes( $heading ) ); ?>" placeholder="<?php echo esc_attr( $wordpress->get_defaults( 'heading', $key ) ); ?>" /><?php $this->add_emojis(); ?><?php $this->add_tags(); ?>
																</div>
															</div>
															<div class="cartbounty-pro-settings-group">
																<label for="cartbounty-pro-automation-content-<?php echo esc_attr( $key ); ?>"><?php esc_html_e('Content', 'woo-save-abandoned-carts'); ?></label>
																<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
																	<textarea id="cartbounty-pro-automation-content-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-text" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][content]" placeholder="<?php echo esc_attr( $wordpress->get_defaults( 'content', $key ) ); ?>" rows="4"><?php echo esc_html( stripslashes( $content ) ); ?></textarea><?php $this->add_emojis(); ?><?php $this->add_tags(); ?>
																</div>
															</div>
														</div>
													</div>
													<div class="cartbounty-pro-row">
														<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
															<h4><?php esc_html_e('Appearance', 'woo-save-abandoned-carts'); ?></h4>
															<p class="cartbounty-pro-titles-column-description">
																<?php esc_html_e( 'Choose a template that will be used to display the abandoned cart reminder email.', 'woo-save-abandoned-carts' ); ?> <?php echo sprintf(
																	/* translators: %s - Link tags */
																	 esc_html__( 'Look here to see advanced %stemplate customization%s options.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( $this->get_trackable_link( '' . 'templates', 'wp_template_customization' ) ) .'" target="_blank">', '</a>');?>
															</p>
														</div>
														<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9<?php if($include_image){ echo ' cartbounty-pro-checked-parent'; }?>">
															<div class="cartbounty-pro-settings-group">
																<h4><?php esc_html_e('Template', 'woo-save-abandoned-carts'); ?></h4>
																<div class="cartbounty-pro-flex-container">
																	<div id="cartbounty-pro-automation-template-light-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-type cartbounty-pro-email-template cartbounty-pro-email-template-light <?php if($template == 1){ echo "cartbounty-pro-radio-active";} ?>">
																		<label class="cartbounty-pro-image" for="cartbounty-pro-template-light-<?php echo esc_attr( $key ); ?>">
																			<em>
																				<i>
																					<span class="cartbounty-pro-template-top-image"></span>
																					<img src="<?php echo esc_url( plugins_url( 'assets/template-light.svg', __FILE__ ) ); ?>" title="<?php esc_attr_e('Light', 'woo-save-abandoned-carts'); ?>" alt="<?php esc_attr_e('Light', 'woo-save-abandoned-carts'); ?>"/>
																				</i>
																			</em>
																			<input id="cartbounty-pro-template-light-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][template]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $template, false ); ?> autocomplete="off" />
																			<?php esc_html_e('Light', 'woo-save-abandoned-carts'); ?>
																		</label>
																	</div>
																	<div id="cartbounty-pro-automation-template-rows-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-type cartbounty-pro-email-template cartbounty-pro-email-template-rows <?php if($template == 2){ echo "cartbounty-pro-radio-active";} ?>">
																		<label class="cartbounty-pro-image" for="cartbounty-pro-template-rows-<?php echo esc_attr( $key ); ?>">
																			<em>
																				<i>
																					<span class="cartbounty-pro-template-top-image"></span>
																					<img src="<?php echo esc_url( plugins_url( 'assets/template-rows.svg', __FILE__ ) ); ?>" title="<?php esc_attr_e('With cart contents', 'woo-save-abandoned-carts'); ?>" alt="<?php esc_attr_e('With cart contents', 'woo-save-abandoned-carts'); ?>"/>
																				</i>
																			</em>
																			<input id="cartbounty-pro-template-rows-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][template]" value="2" <?php echo $this->disable_field(); ?> <?php echo checked( 2, $template, false ); ?> autocomplete="off" />
																			<?php esc_html_e('With cart contents', 'woo-save-abandoned-carts'); ?>
																		</label>
																	</div>
																	<div id="cartbounty-pro-automation-template-columns-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-type cartbounty-pro-email-template cartbounty-pro-email-template-columns <?php if($template == 3){ echo "cartbounty-pro-radio-active";} ?>">
																		<label class="cartbounty-pro-image" for="cartbounty-pro-template-columns-<?php echo esc_attr( $key ); ?>">
																			<em>
																				<i>
																					<span class="cartbounty-pro-template-top-image"></span>
																					<img src="<?php echo esc_url( plugins_url( 'assets/template-columns.svg', __FILE__ ) ); ?>" title="<?php esc_attr_e('With cart contents in columns', 'woo-save-abandoned-carts'); ?>" alt="<?php esc_attr_e('With cart contents in columns', 'woo-save-abandoned-carts'); ?>"/>
																				</i>
																			</em>
																			<input id="cartbounty-pro-template-columns-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][template]" value="3" <?php echo $this->disable_field(); ?> <?php echo checked( 3, $template, false ); ?> autocomplete="off" />
																			<?php esc_html_e('With cart contents in columns', 'woo-save-abandoned-carts'); ?>
																		</label>
																	</div>
																</div>
															</div>
															<div class="cartbounty-pro-settings-group">
																<h4><?php esc_html_e('Colors', 'woo-save-abandoned-carts'); ?></h4>
																<p class='cartbounty-pro-additional-information'>
																	<?php esc_html_e('Look at the default email colors and adjust them to fit your design requirements.', 'woo-save-abandoned-carts'); ?>
																</p>
																<div class="cartbounty-pro-colors">
																	<label for="cartbounty-pro-template-main-color-<?php echo esc_attr( $key ); ?>"><?php esc_html_e('Main:', 'woo-save-abandoned-carts'); ?></label>
																	<input id="cartbounty-pro-template-main-color-<?php echo esc_attr( $key ); ?>" type="text" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][main_color]" class="cartbounty-pro-color-picker cartbounty-pro-text" value="<?php echo esc_attr( $main_color ); ?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
																</div>
																<div class="cartbounty-pro-colors">
																	<label for="cartbounty-pro-template-inverse-color-<?php echo esc_attr( $key ); ?>"><?php esc_html_e('Button:', 'woo-save-abandoned-carts'); ?></label>
																	<input id="cartbounty-pro-template-button-color-<?php echo esc_attr( $key ); ?>" type="text" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][button_color]" class="cartbounty-pro-color-picker cartbounty-pro-text" value="<?php echo esc_attr( $button_color ); ?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
																</div>
																<div class="cartbounty-pro-colors">
																	<label for="cartbounty-pro-template-text-color-<?php echo esc_attr( $key ); ?>"><?php esc_html_e('Text:', 'woo-save-abandoned-carts'); ?></label>
																	<input id="cartbounty-pro-template-text-color-<?php echo esc_attr( $key ); ?>" type="text" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][text_color]" class="cartbounty-pro-color-picker cartbounty-pro-text" value="<?php echo esc_attr( $text_color ); ?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
																</div>
																<div class="cartbounty-pro-colors">
																	<label for="cartbounty-pro-template-background-color-<?php echo esc_attr( $key ); ?>"><?php esc_html_e('Backdrop:', 'woo-save-abandoned-carts'); ?></label>
																	<input id="cartbounty-pro-template-background-color-<?php echo esc_attr( $key ); ?>" type="text" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][background_color]" class="cartbounty-pro-color-picker cartbounty-pro-text" value="<?php echo esc_attr( $background_color ); ?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
																</div>
															</div>
															<div class="cartbounty-pro-settings-group cartbounty-pro-toggle <?php if($include_image){ echo ' cartbounty-pro-checked'; }?>">
																<label for="cartbounty-pro-automation-include-image-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
																	<input id="cartbounty-pro-automation-include-image-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][include_image]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $include_image, false ); ?> autocomplete="off" />
																	<span class="cartbounty-pro-slider round"></span>
																</label>
																<label for="cartbounty-pro-automation-include-image-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-control-visibility"><?php esc_html_e('Include image', 'woo-save-abandoned-carts'); ?></label>
															</div>
															<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
																<?php
																	if(!did_action('wp_enqueue_media')){
																		wp_enqueue_media();
																	}
																	$image = wp_get_attachment_image_src( $main_image );
																?>
																<h4><?php esc_html_e('Custom image', 'woo-save-abandoned-carts'); ?></h4>
																<p class='cartbounty-pro-additional-information'>
																	<?php esc_html_e('Recommended dimensions:', 'woo-save-abandoned-carts'); ?> 900 x 300 px.
																</p>
																<div class="cartbounty-pro-action-container">
																	<p id="cartbounty-pro-upload-custom-image-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-upload-image" data-automation="<?php echo esc_attr( $key ); ?>">
																		<?php if($image):?>
																			<img src="<?php echo esc_url( $image[0] ); ?>" />
																		<?php else: ?>
																			<input type="button" value="<?php esc_attr_e('Add a custom image', 'woo-save-abandoned-carts'); ?>" class="cartbounty-pro-button button-secondary button" <?php echo $this->disable_field(); ?> />
																		<?php endif;?>
																	</p>
																	<a href="#" id="cartbounty-pro-remove-custom-image-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-remove-image" data-automation="<?php echo esc_attr( $key ); ?>" <?php if(!$image){echo 'style="display:none"';}?>></a>
																</div>
																<input id="cartbounty-pro-custom-image-<?php echo esc_attr( $key ); ?>" type="hidden" name="cartbounty_pro_automation_steps[<?php echo esc_attr( $key ); ?>][main_image]" value="<?php if($main_image){echo esc_attr( $main_image );}?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
															</div>
														</div>
													</div>
													<div class="cartbounty-pro-row">
														<?php $coupons->display_coupon_settings( $active_section, 'cartbounty_pro_automation_steps', $key ); ?>
													</div>
													<div class="cartbounty-pro-row">
														<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
															<h4><?php esc_html_e('Test email', 'woo-save-abandoned-carts'); ?></h4>
															<p class="cartbounty-pro-titles-column-description">
																<?php esc_html_e('Before activating this automation, you might want to test your email.', 'woo-save-abandoned-carts'); ?>
															</p>
														</div>
														<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
															<div class="cartbounty-pro-settings-group">
																<h4><?php esc_html_e('Preview', 'woo-save-abandoned-carts'); ?></h4>
																<button type="button" class='cartbounty-pro-button button-secondary cartbounty-pro-progress cartbounty-pro-preview-email' data-automation='<?php echo esc_attr( $key ); ?>' data-nonce='<?php echo esc_attr( $preview_email_nonce ); ?>' <?php echo $this->disable_field(); ?>><?php esc_html_e('Preview email', 'woo-save-abandoned-carts'); ?></button>
																<?php echo $this->output_modal_container( $key ); ?>
															</div>
															<div class="cartbounty-pro-settings-group">
																<label for="cartbounty-pro-send-test-<?php echo esc_attr( $key ); ?>"><?php esc_html_e('Send a test email to', 'woo-save-abandoned-carts'); ?></label>
																<div class="cartbounty-pro-input-with-button">
																	<input id="cartbounty-pro-send-test-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-text cartbounty-pro-disable-submit" type="email"  placeholder="<?php echo esc_attr( get_option( 'admin_email' ) );?>" <?php echo $this->disable_field(); ?> />
																	<button type="button" class='cartbounty-pro-button button-secondary cartbounty-pro-progress cartbounty-pro-send-email' data-automation='<?php echo esc_attr( $key ); ?>' data-nonce='<?php echo esc_attr( $test_email_nonce ); ?>' <?php echo $this->disable_field(); ?>><?php esc_html_e('Send', 'woo-save-abandoned-carts'); ?></button>
																</div>
															</div>
														</div>
													</div>
												</div>
											</div>
										<?php }} ?>
								</div>
							</div>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('General email settings', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e('"From" name tells your recipients who sent them the message. It is just as important as your subject line and can impact whether your email is opened, or not.', 'woo-save-abandoned-carts'); ?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty-pro-automation-from-name"><?php esc_html_e('"From" name', 'woo-save-abandoned-carts'); ?></label>
								<input id="cartbounty-pro-automation-from-name" class="cartbounty-pro-text" type="text" name="cartbounty_pro_automation_settings[from_name]" value="<?php echo esc_attr( stripslashes( $settings['from_name'] ) ); ?>" placeholder="<?php echo esc_attr( get_option( 'blogname' ) );?>" <?php echo $this->disable_field(); ?> />
							</div>
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty-pro-automation-from-email"><?php esc_html_e('"From" email', 'woo-save-abandoned-carts'); ?></label>
								<input id="cartbounty-pro-automation-from-email" class="cartbounty-pro-text" type="email" name="cartbounty_pro_automation_settings[from_email]" value="<?php echo sanitize_email( $settings['from_email'] ); ?>" placeholder="<?php echo esc_attr( get_option( 'admin_email' ) );?>" <?php echo $this->disable_field(); ?> />
							</div>
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty-pro-automation-reply-email"><?php esc_html_e('Reply-to address', 'woo-save-abandoned-carts'); ?></label>
								<input id="cartbounty-pro-automation-reply-email" class="cartbounty-pro-text" type="email" name="cartbounty_pro_automation_settings[reply_email]" value="<?php echo sanitize_email( $settings['reply_email'] ); ?>" <?php echo $this->disable_field(); ?> />
							</div>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<?php $this->display_exclusion_settings( $active_section ); ?>
					</div>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('Miscellaneous', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e('Other settings that may be useful.', 'woo-save-abandoned-carts');?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group">
								<h4><?php esc_html_e('Reset stats', 'woo-save-abandoned-carts'); ?></h4>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e('Reset automation process email send, open, and click statistics.', 'woo-save-abandoned-carts'); ?>
								</p>
								<div class="cartbounty-pro-action-container">
									<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( 'handle', 'cartbounty_pro_reset_stats' ), 'cartbounty-pro-reset-stats-nonce', 'cartbounty_pro_reset_stats' ) ); ?>" class='cartbounty-pro-button button-secondary cartbounty-pro-progress'><?php esc_html_e('Reset', 'woo-save-abandoned-carts'); ?></a>
								</div>
							</div>
						</div>
					</div>
					<div class='cartbounty-pro-button-row'>
						<?php
						if( $this->user_is_admin() ){
							echo "<button type='submit' class='cartbounty-pro-button button-primary cartbounty-pro-progress'>". esc_html__('Save settings', 'woo-save-abandoned-carts') ."</button>";
						}
						if( $this->check_license() && $automation->automation_enabled( 'wordpress' ) ){
							echo $this->display_force_sync_button( $active_section );
						}
						?>
					</div>
				</form>

				<?php
				break;

			case 'bulkgate':

				$bulkgate = $this->bulkgate();
				$api_valid = $bulkgate->api_valid();

				if(!class_exists('WooCommerce')){ //If WooCommerce is not active
					$this->missing_woocommerce_notice( $active_section ); 
					return;
				}?>

				<div class="cartbounty-pro-section-intro">
					<?php echo esc_html__( 'A perfect channel for sending personalized, time-sensitive SMS text messages like abandoned cart reminders.', 'woo-save-abandoned-carts' ) . ' ' . esc_html__( 'Please connect your BulkGate account using API and start using 4-step automation process for sending automated abandoned cart reminder text messages.', 'woo-save-abandoned-carts' );
						echo ' ' . sprintf(
							/* translators: %s - URL link */
							esc_html__('Take a %slook at our docs%s to learn more about available features.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( $this->get_trackable_link( '' . 'bulkgate-sms-text-message-abandoned-cart-recovery', 'bk_features' ) ) .'" target="_blank">', '</a>' );

						if( !$api_valid ){
							echo ' ' . sprintf(
								/* translators: %s - URL link */
								esc_html__('If you do not have an account on BulkGate yet, you can %ssign up for a free account here%s.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( CARTBOUNTY_PRO_BULKGATE_TRIAL_LINK ) .'" target="_blank">', '</a>' );
						}
					?>
				</div>
				<form method="post" action="options.php">
					<?php
						settings_fields( 'cartbounty-pro-bulkgate-settings' );
						do_settings_sections( 'cartbounty-pro-bulkgate-settings' );
						$bulkgate_settings = get_option('cartbounty_pro_bulkgate_settings');
						$bulkgate_steps = get_option('cartbounty_pro_bulkgate_steps');
						$api_access = $bulkgate->get_api_access();
						$api_status = $bulkgate->api_status();
						$tcpa_gdpr_nonce = wp_create_nonce( 'save_tcpa_gdpr' );
						$api_key = '';
						$api_id = '';
						$enable_countries = '';
						$enable_quiet_hours = '';

						if( isset( $api_access['api_key'] ) ){
							$api_key = $api_access['api_key'];
						}

						if( isset( $api_access['api_id'] ) ){
							$api_id = $api_access['api_id'];
						}

						if( isset( $bulkgate_settings['enable_countries'] ) ){
							$enable_countries = $bulkgate_settings['enable_countries'];
						}

						if( isset( $bulkgate_settings['enable_quiet_hours'] ) ){
							$enable_quiet_hours = $bulkgate_settings['enable_quiet_hours'];
						}
					?>

					<div class="cartbounty-pro-bulkgate-automation-settings<?php if( !$api_valid ){ echo ' cartbounty-pro-hidden'; } ?>">
						<div class="cartbounty-pro-row">
							<div class="cartbounty-pro-titles-column cartbounty-pro-full-width cartbounty-col-sm-12 cartbounty-col-md-12 cartbounty-col-lg-12">
								<h4><?php esc_html_e('Automation process', 'woo-save-abandoned-carts'); ?></h4>
								<p class="cartbounty-pro-titles-column-description">
									<?php esc_html_e('Configure your abandoned cart reminder text messages, when to send them, include coupons, etc. You can choose to enable just one or all of them creating a 4-step automation process. The countdown of the next step starts right after the previous one is finished.', 'woo-save-abandoned-carts'); ?>
								</p>
							</div>
							<?php if( !$this->tcpa_gdpr_confirmed( 'bulkgate' ) ): ?>
								<div id="cartbounty-pro-tcpa-gdpr-notice" class="cartbounty-pro-settings-column cartbounty-pro-full-width cartbounty-col-sm-12 cartbounty-col-md-12 cartbounty-col-lg-12">
									<div class="cartbounty-pro-settings-group">
										<div class="cartbounty-pro-step cartbounty-pro-step-active cartbounty-pro-step-single">
											<div class="cartbounty-pro-step-contents">
												<div class="cartbounty-pro-row">
													<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
														<h4><?php esc_html_e( 'GDPR / TCPA compliance', 'woo-save-abandoned-carts' ); ?></h4>
														<p class="cartbounty-pro-titles-column-description">
															<?php esc_html_e( 'Europe, United States, and other countries require companies to be mindful when using personal data and sending text messages.', 'woo-save-abandoned-carts' ); ?>
														</p>
													</div>
													<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
														<div class="cartbounty-pro-settings-group">
															<h4><?php esc_html_e( 'Review compliance', 'woo-save-abandoned-carts' ); ?></h4>
															<p class='cartbounty-pro-additional-information'>
																<?php echo sprintf(
																/* translators: %s - URL link */
																 esc_html__( 'Please %sfollow this guide%s to comply with the laws and mark it as completed once done. %s will not send any text messages until this has been finished.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( $this->get_trackable_link( '' . 'gdpr-tcpa-compliance', 'bk_tcpa_gdpr' ) ) .'" target="_blank">', '</a>', esc_html( CARTBOUNTY_PRO_SHORT ) ); ?>
															</p>
															<div class="cartbounty-pro-action-container">
																<button id="cartbounty-pro-save-tcpa-gdpr" type="button" class='cartbounty-pro-button button-secondary cartbounty-pro-progress' data-recovery='bulkgate' data-nonce='<?php echo esc_attr( $tcpa_gdpr_nonce ); ?>' <?php echo $this->disable_field(); ?>><?php esc_html_e( 'Mark as completed', 'woo-save-abandoned-carts' ); ?></button>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							<?php endif; ?>
							<div class="cartbounty-pro-settings-column cartbounty-pro-full-width cartbounty-col-sm-12 cartbounty-col-md-12 cartbounty-col-lg-12">
								<div class="cartbounty-pro-settings-group">
									<div class="cartbounty-pro-stairway">
										<?php if( !empty( $bulkgate_steps ) ){
											foreach ( $bulkgate_steps as $key => $step ){
												$step = ( object )$step;
												$enabled = ( isset( $step->enabled ) ) ? $step->enabled : false;
												$content = ( isset( $step->content ) ) ? $step->content : '';
												$time_interval_name = $this->get_interval_data( 'cartbounty_pro_bulkgate_steps', $key, $just_selected_value = true );
												$test_sms_nonce = wp_create_nonce( 'test_sms' );
												$coupon_status = $automation->display_coupon_status( 'bulkgate', $key );
												$automation_status = $automation->display_automation_status( $enabled ); ?>

												<div class="cartbounty-pro-step<?php esc_attr( $automation->check_if_accessible( 'bulkgate', $key ) ); ?>" data-automation-step="<?php echo esc_attr( $key ); ?>">
													<div class="cartbounty-pro-step-opener">
														<div class="cartbounty-pro-row">
															<div class="cartbounty-pro-titles-column cartbounty-col-xs-12 cartbounty-col-sm-4 cartbounty-col-lg-3">
																<div class="cartbounty-pro-automation-number"><?php echo esc_html( $key ) + 1; ?></div>
																<div class="cartbounty-pro-automation-name">
																	<h3><?php echo esc_html( $bulkgate->get_defaults( 'name', $key ) ); ?></h3>
																	<p><?php echo sprintf(
																		/* translators: %s - Time, e.g. 10 minutes */
																		 esc_html__( 'Sends after %s', 'woo-save-abandoned-carts' ), esc_html( $time_interval_name ) );?></p>
																	<div class="cartbounty-pro-automation-status">
																		<?php echo $automation_status . $coupon_status; ?>
																	</div>
																</div>
																<div class="cartbounty-pro-step-trigger"></div>
															</div>
															<div class="cartbounty-pro-settings-column cartbounty-col-xs-12 cartbounty-col-sm-8 cartbounty-col-lg-9">
																<div class="cartbounty-pro-row">
																	<div class="cartbounty-pro-stats-container cartbounty-col-sm-12 cartbounty-col-lg-9">
																		<div class="cartbounty-pro-stats cartbounty-pro-percentage-switcher">
																			<div class="cartbounty-pro-stats-percentage">
																				<i><?php esc_html_e( 'Queue', 'woo-save-abandoned-carts' ); ?></i>
																				<p><?php echo esc_html( $automation->get_queue( 'bulkgate', $key ) ); ?></p>
																			</div>
																			<div class="cartbounty-pro-stats-count">
																				<i><?php esc_html_e( 'Sends', 'woo-save-abandoned-carts' ); ?></i>
																				<p><?php echo esc_html( $automation->get_stats( 'bulkgate', 'send', $key, $single = true ) ); ?></p>
																			</div>
																		</div>
																		<div class="cartbounty-pro-stats cartbounty-pro-percentage-switcher">
																			<div class="cartbounty-pro-stats-percentage">
																				<i><?php esc_html_e( 'Click rate', 'woo-save-abandoned-carts' ); ?></i>
																				<p><?php echo esc_html( $automation->get_stats_percentage( 'bulkgate', 'click', $key ) ); ?></p>
																			</div>
																			<div class="cartbounty-pro-stats-count">
																				<i><?php esc_html_e( 'Clicks', 'woo-save-abandoned-carts' ); ?></i>
																				<p><?php echo esc_html( $automation->get_stats( 'bulkgate', 'click', $key, $single = true ) ); ?></p>
																			</div>
																		</div>
																		<div class="cartbounty-pro-stats cartbounty-pro-percentage-switcher">
																			<div class="cartbounty-pro-stats-percentage">
																				<i><?php esc_html_e( 'Recovery rate', 'woo-save-abandoned-carts' ); ?></i>
																				<p><?php echo esc_html( $automation->get_stats_percentage( 'bulkgate', 'recovered', $key ) ); ?></p>
																			</div>
																			<div class="cartbounty-pro-stats-count">
																				<i><?php esc_html_e( 'Recovered', 'woo-save-abandoned-carts' ); ?></i>
																				<p><?php echo esc_html( $automation->get_stats( 'bulkgate', 'recovered', $key, $single = true ) ); ?></p>
																			</div>
																		</div>
																		<div class="cartbounty-pro-stats cartbounty-pro-percentage-switcher">
																			<div class="cartbounty-pro-stats-percentage">
																				<i><?php esc_html_e( 'Unsubscribe rate', 'woo-save-abandoned-carts' ); ?></i>
																				<p><?php echo esc_html( $automation->get_stats_percentage( 'bulkgate', 'unsubscribed', $key ) ); ?></p>
																			</div>
																			<div class="cartbounty-pro-stats-count">
																				<i><?php esc_html_e( 'Unsubscribes', 'woo-save-abandoned-carts' ); ?></i>
																				<p><?php echo esc_html( $automation->get_stats( 'bulkgate', 'unsubscribed', $key, $single = true ) ); ?></p>
																			</div>
																		</div>
																	</div>
																	<div class="cartbounty-pro-trigger-container cartbounty-col-sm-12 cartbounty-col-lg-3">
																		<div class="cartbounty-pro-automation-status">
																			<?php echo $coupon_status . $automation_status; ?>
																		</div>
																		<div class="cartbounty-pro-step-trigger"></div>
																	</div>
																</div>
															</div>
														</div>
													</div>
													<div class="cartbounty-pro-step-contents">
														<div class="cartbounty-pro-row">
															<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
																<h4><?php esc_html_e( 'Message settings', 'woo-save-abandoned-carts' ); ?></h4>
																<p class="cartbounty-pro-titles-column-description">
																	<?php esc_html_e( 'Enable this text message to start this automated abandoned cart recovery step.', 'woo-save-abandoned-carts' );
																		echo ' ' . sprintf(
																		/* translators: %s - Link tags */
																		 esc_html__( 'Learn how to use %spersonalization tags%s.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( $this->get_trackable_link( '' . 'personalization-tags', 'bk_personalization' ) ) .'" target="_blank">', '</a>');?>
																</p>
															</div>
															<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9<?php if( $enabled ){ echo ' cartbounty-pro-checked-parent'; }?>">
																<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
																	<label for="cartbounty-pro-automation-status-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-switch cartbounty-pro-control-visibility cartbounty-pro-step-controller">
																		<input id="cartbounty-pro-automation-status-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_bulkgate_steps[<?php echo esc_attr( $key ); ?>][enabled]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $enabled, false ); ?> autocomplete="off" />
																		<span class="cartbounty-pro-slider round"></span>
																	</label>
																	<label for="cartbounty-pro-automation-status-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-control-visibility cartbounty-pro-step-controller"><?php esc_html_e( 'Enable text message', 'woo-save-abandoned-carts' ); ?></label>
																</div>
																<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
																	<?php $this->display_time_intervals( 'cartbounty_pro_bulkgate_steps', $key ); ?>
																	<p class='cartbounty-pro-additional-information'>
																		<?php echo sprintf(
																		/* translators: %s - Link tags */
																		esc_html__( 'Please %ssee this%s to learn how reminder sending works and when it will be delivered.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( $this->get_trackable_link( '' . 'abandoned-carts', 'bk_is_it_abandoned', '#when-is-the-cart-abandoned' ) ) .'" target="_blank">', '</a>'); ?>
																	</p>
																</div>
																<div class="cartbounty-pro-settings-group">
																	<label for="cartbounty-pro-automation-content-<?php echo esc_attr( $key ); ?>"><?php esc_html_e( 'Content', 'woo-save-abandoned-carts' ); ?></label>
																	<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
																		<textarea id="cartbounty-pro-automation-content-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-text" name="cartbounty_pro_bulkgate_steps[<?php echo esc_attr( $key ); ?>][content]" placeholder="<?php echo esc_attr( $bulkgate->get_defaults( 'content', $key ) ); ?>" rows="4"><?php echo esc_html( stripslashes( $content ) ); ?></textarea><?php $this->add_emojis(); ?><?php $this->add_tags(); ?>
																	</div>
																</div>
															</div>
														</div>
														<div class="cartbounty-pro-row">
															<?php $coupons->display_coupon_settings( $active_section, 'cartbounty_pro_bulkgate_steps', $key ); ?>
														</div>
														<div class="cartbounty-pro-row">
															<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
																<h4><?php esc_html_e( 'Test message', 'woo-save-abandoned-carts' ); ?></h4>
																<p class="cartbounty-pro-titles-column-description">
																	<?php esc_html_e( 'Before activating this automation, you might want to test your message.', 'woo-save-abandoned-carts' ); ?>
																</p>
															</div>
															<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
																<div class="cartbounty-pro-settings-group">
																	<label for="cartbounty-pro-send-test-<?php echo esc_attr( $key ); ?>"><?php esc_html_e( 'Send a test message to', 'woo-save-abandoned-carts' ); ?></label>
																	<div class="cartbounty-pro-input-with-button">
																		<input id="cartbounty-pro-send-test-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-text cartbounty-pro-disable-submit" type="tel" value="<?php echo esc_attr( $this->get_phone_area_code_from_country() );?>" placeholder="<?php echo esc_attr( $this->get_phone_area_code_from_country() );?>" <?php echo $this->disable_field(); ?> />
																		<button type="button" class='cartbounty-pro-button button-secondary cartbounty-pro-progress cartbounty-pro-send-sms' data-automation='<?php echo esc_attr( $key ); ?>' data-nonce='<?php echo esc_attr( $test_sms_nonce ); ?>' <?php echo $this->disable_field(); ?>><?php esc_html_e( 'Send', 'woo-save-abandoned-carts' ); ?></button>
																	</div>
																</div>
															</div>
														</div>
													</div>
												</div>
											<?php }} ?>
									</div>
								</div>
							</div>
						</div>
						<div class="cartbounty-pro-row">
							<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
								<h4><?php esc_html_e( 'Sender settings', 'woo-save-abandoned-carts' ); ?></h4>
								<p class="cartbounty-pro-titles-column-description">
									<?php esc_html_e( 'Set sender type you will use to deliver text messages.', 'woo-save-abandoned-carts' ); ?>
								</p>
							</div>
							<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9">
								<div class="cartbounty-pro-settings-group">
									<label for="cartbounty-pro-automation-sender-id"><?php esc_html_e( 'Sender type', 'woo-save-abandoned-carts' ); ?></label>
									<?php $bulkgate->display_sender_types(); ?>
								</div>
								<?php $bulkgate->display_sender_names(); ?>
							</div>
						</div>
						<div class="cartbounty-pro-row">
							<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
								<h4><?php esc_html_e( 'Countries', 'woo-save-abandoned-carts' ); ?></h4>
								<p class="cartbounty-pro-titles-column-description">
									<?php esc_html_e( 'By default, abandoned cart reminder text messages are sent to all countries.', 'woo-save-abandoned-carts' ); ?>
								</p>
							</div>
							<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9<?php if( $enable_countries ){ echo ' cartbounty-pro-checked-parent'; }?>">
								<div class="cartbounty-pro-settings-group cartbounty-pro-toggle<?php if( $enable_countries ){ echo ' cartbounty-pro-checked'; }?>">
									<label for="cartbounty-pro-bulkgate-enable-countries" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
										<input id="cartbounty-pro-bulkgate-enable-countries" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_bulkgate_settings[enable_countries]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $enable_countries, false ); ?> autocomplete="off" />
										<span class="cartbounty-pro-slider round"></span>
									</label>
									<label for="cartbounty-pro-bulkgate-enable-countries" class="cartbounty-pro-control-visibility">
										<?php esc_html_e( 'Limit countries', 'woo-save-abandoned-carts' ); ?>
									</label>
								</div>
								<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
									<label for="cartbounty_pro_allowed_countries"><?php esc_html_e( 'Send text messages only to these countries', 'woo-save-abandoned-carts' ); ?></label>
									<?php $this->display_countries( 'bulkgate' ); ?>
								</div>
							</div>
						</div>
						<div class="cartbounty-pro-row">
							<div class="cartbounty-pro-titles-column cartbounty-col-sm-4 cartbounty-col-lg-3">
								<h4><?php esc_html_e( 'Quiet hours', 'woo-save-abandoned-carts' ); ?></h4>
								<p class="cartbounty-pro-titles-column-description">
									<?php esc_html_e( "Customers will not receive any text messages during these hours. Messages will be sent after quiet hours are over. Works based on the recipient's local time zone.", 'woo-save-abandoned-carts' ); ?>
								</p>
							</div>
							<div class="cartbounty-pro-settings-column cartbounty-col-sm-8 cartbounty-col-lg-9<?php if( $enable_quiet_hours ){ echo ' cartbounty-pro-checked-parent'; }?>">
								<div class="cartbounty-pro-settings-group cartbounty-pro-toggle<?php if( $enable_quiet_hours ){ echo ' cartbounty-pro-checked'; }?>">
									<label for="cartbounty-pro-bulkgate-enable-quiet-hours" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
										<input id="cartbounty-pro-bulkgate-enable-quiet-hours" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_bulkgate_settings[enable_quiet_hours]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $enable_quiet_hours, false ); ?> autocomplete="off" />
										<span class="cartbounty-pro-slider round"></span>
									</label>
									<label for="cartbounty-pro-bulkgate-enable-quiet-hours" class="cartbounty-pro-control-visibility">
										<?php esc_html_e( 'Enable', 'woo-save-abandoned-carts' ); ?>
									</label>
								</div>
								<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
									<?php $this->display_quiet_hours( 'bulkgate' ); ?>
								</div>
							</div>
						</div>
						<div class="cartbounty-pro-row">
							<?php $this->display_exclusion_settings( $active_section ); ?>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('API Access', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php echo esc_html__( 'To initiate the setup, please enter your API token and ID.', 'woo-save-abandoned-carts' );
								if( !$api_valid ){
									echo ' ' . sprintf(
										/* translators: %s - URL link */
										esc_html__( 'Login to your %sBulkGate account%s to obtain this.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( CARTBOUNTY_PRO_BULKGATE_TRIAL_LINK ) .'" target="_blank">', '</a>'
									);
								}?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty_pro_bulkgate_api_token"><?php esc_html_e('Application token', 'woo-save-abandoned-carts'); ?><?php echo $this->output_connection_message( $api_status, array( $api_key, $api_id ) ); ?></label>
								<input id="cartbounty_pro_bulkgate_api_token" class="cartbounty-pro-text" type="text" name="cartbounty_pro_bulkgate_settings[api_token]" value="<?php echo esc_attr( $api_key ); ?>" <?php echo $this->disable_field(); ?> />
							</div>
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty_pro_bulkgate_api_id"><?php esc_html_e('Application ID', 'woo-save-abandoned-carts'); ?></label>
								<input id="cartbounty_pro_bulkgate_api_id" class="cartbounty-pro-text" type="text" name="cartbounty_pro_bulkgate_settings[api_id]" value="<?php echo esc_attr( $api_id ); ?>" <?php echo $this->disable_field(); ?> />
							</div>
						</div>
					</div>
					<div class="cartbounty-pro-row<?php if( !$api_valid ){ echo ' cartbounty-pro-hidden'; } ?>">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('Miscellaneous', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e('Other settings that may be useful.', 'woo-save-abandoned-carts');?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group">
								<h4><?php esc_html_e('Reset stats', 'woo-save-abandoned-carts'); ?></h4>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e('Reset automation process message send and click statistics.', 'woo-save-abandoned-carts'); ?>
								</p>
								<div class="cartbounty-pro-action-container">
									<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( 'handle', 'cartbounty_pro_reset_stats' ), 'cartbounty-pro-reset-stats-nonce', 'cartbounty_pro_reset_stats' ) ); ?>" class='cartbounty-pro-button button-secondary cartbounty-pro-progress'><?php esc_html_e('Reset', 'woo-save-abandoned-carts'); ?></a>
								</div>
							</div>
						</div>
					</div>
					<div class='cartbounty-pro-button-row'>
						<?php
						if(  $this->user_is_admin() ){
							echo "<button type='submit' class='cartbounty-pro-button button-primary cartbounty-pro-progress'>". esc_html__('Save settings', 'woo-save-abandoned-carts') ."</button>";
						}
						if( $this->check_license() && $automation->automation_enabled( 'bulkgate' ) ){
							echo $this->display_force_sync_button( $active_section );
						}?>
					</div>
				</form>
				<?php
				break;

			case 'push_notification':

				if(!class_exists('WooCommerce')){ //If WooCommerce is not active
					$this->missing_woocommerce_notice( $active_section ); 
					return;
				}?>

				<div class="cartbounty-pro-section-intro">
					<?php esc_html_e('With no requirement for an email or phone number, web push notifications provide a low-friction, real-time, personal and efficient channel for sending abandoned cart reminders.', 'woo-save-abandoned-carts'); ?> <?php esc_html_e('Additionally, notifications can be sent even after the user has closed the website, providing a higher chance of engaging them to complete their purchase.', 'woo-save-abandoned-carts'); ?> <?php echo sprintf(
							/* translators: %s - URL link */
							esc_html__('Take a look at our docs to learn more about %spush notification settings and browser support%s.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( $this->get_trackable_link( '' . 'web-push-notifications-abandoned-cart-recovery', 'pn_features' ) ) .'" target="_blank">', '</a>'
						);?>
				</div>

				<form method="post" action="options.php">
					<?php
						global $wpdb;
						settings_fields( 'cartbounty-pro-push-notification-settings' );
						do_settings_sections( 'cartbounty-pro-push-notification-settings' );
						$push_notification = $this->push_notification();
						$automation_steps = get_option( 'cartbounty_pro_push_notification_steps' );
					?>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-pro-full-width cartbounty-col-sm-12 cartbounty-col-md-12 cartbounty-col-lg-12">
							<h4><?php esc_html_e( 'Automation process', 'woo-save-abandoned-carts' ); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e( 'Configure your abandoned cart reminder push notifications, how they look, when to send them, include coupons, etc. You can choose to enable just one or all of them creating a 4-step automation process. The countdown of the next step starts right after the previous one is finished.', 'woo-save-abandoned-carts' ); ?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-pro-full-width cartbounty-col-sm-12 cartbounty-col-md-12 cartbounty-col-lg-12">
							<div class="cartbounty-pro-settings-group">
								<div class="cartbounty-pro-stairway">
									<?php if( !empty( $automation_steps ) ){
										foreach( $automation_steps as $key => $step ){
											$step = (object)$step;
											$enabled = ( isset( $step->enabled ) ) ? $step->enabled : false;
											$heading = ( isset( $step->heading ) ) ? $step->heading : '';
											$content = ( isset( $step->content ) ) ? $step->content : '';
											$include_icon = ( isset( $step->include_icon ) ) ? $step->include_icon : false;
											$include_image = ( isset( $step->include_image ) ) ? $step->include_image : false;
											$main_icon = ( isset( $step->main_icon ) ) ? $step->main_icon : false;
											$main_image = ( isset( $step->main_image ) ) ? $step->main_image : false;
											$preview_notification_nonce = wp_create_nonce( 'test_push_notification' );
											$time_interval_name = $this->get_interval_data( 'cartbounty_pro_push_notification_steps', $key, $just_selected_value = true );
											$coupon_status = $automation->display_coupon_status( 'push_notification', $key );
											$automation_status = $automation->display_automation_status( $enabled ); ?>

											<div class="cartbounty-pro-step<?php esc_attr( $automation->check_if_accessible( 'push_notification', $key ) ); ?>" data-automation-step="<?php echo esc_attr( $key ); ?>">
												<div class="cartbounty-pro-step-opener">
													<div class="cartbounty-pro-row">
														<div class="cartbounty-pro-titles-column cartbounty-col-xs-12 cartbounty-col-sm-5 cartbounty-col-lg-4">
															<div class="cartbounty-pro-automation-number"><?php echo esc_html( $key ) + 1; ?></div>
															<div class="cartbounty-pro-automation-name">
																<h3><?php echo esc_html( $push_notification->get_defaults( 'name', $key ) ); ?></h3>
																<p><?php echo sprintf(
																	/* translators: %s - Time, e.g. 10 minutes */
																	 esc_html__( 'Sends after %s', 'woo-save-abandoned-carts' ), esc_html( $time_interval_name ) );?></p>
																<div class="cartbounty-pro-automation-status">
																	<?php echo $automation_status . $coupon_status; ?>
																</div>
															</div>
															<div class="cartbounty-pro-step-trigger"></div>
														</div>
														<div class="cartbounty-pro-settings-column cartbounty-col-xs-12 cartbounty-col-sm-7 cartbounty-col-lg-8">
															<div class="cartbounty-pro-row">
																<div class="cartbounty-pro-stats-container cartbounty-col-sm-12 cartbounty-col-lg-9">
																	<div class="cartbounty-pro-stats cartbounty-pro-percentage-switcher">
																		<div class="cartbounty-pro-stats-percentage">
																			<i><?php esc_html_e( 'Queue', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_queue( 'push_notification', $key ) ); ?></p>
																		</div>
																		<div class="cartbounty-pro-stats-count">
																			<i><?php esc_html_e( 'Sends', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats( 'push_notification', 'send', $key, $single = true ) ); ?></p>
																		</div>
																	</div>
																	<div class="cartbounty-pro-stats cartbounty-pro-percentage-switcher">
																		<div class="cartbounty-pro-stats-percentage">
																			<i><?php esc_html_e( 'Click rate', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats_percentage( 'push_notification', 'click', $key ) ); ?></p>
																		</div>
																		<div class="cartbounty-pro-stats-count">
																			<i><?php esc_html_e( 'Clicks', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats( 'push_notification', 'click', $key, $single = true ) ); ?></p>
																		</div>
																	</div>
																	<div class="cartbounty-pro-stats cartbounty-pro-percentage-switcher">
																		<div class="cartbounty-pro-stats-percentage">
																			<i><?php esc_html_e( 'Recovery rate', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats_percentage( 'push_notification', 'recovered', $key ) ); ?></p>
																		</div>
																		<div class="cartbounty-pro-stats-count">
																			<i><?php esc_html_e( 'Recovered', 'woo-save-abandoned-carts' ); ?></i>
																			<p><?php echo esc_html( $automation->get_stats( 'push_notification', 'recovered', $key, $single = true ) ); ?></p>
																		</div>
																	</div>
																</div>
																<div class="cartbounty-pro-trigger-container cartbounty-col-sm-12 cartbounty-col-lg-3">
																	<div class="cartbounty-pro-automation-status">
																		<?php echo $coupon_status . $automation_status; ?>
																	</div>
																	<div class="cartbounty-pro-step-trigger"></div>
																</div>
															</div>
														</div>
													</div>
												</div>
												<div class="cartbounty-pro-step-contents">
													<div class="cartbounty-pro-row">
														<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
															<h4><?php esc_html_e( 'General', 'woo-save-abandoned-carts' ); ?></h4>
															<p class="cartbounty-pro-titles-column-description">
																<?php esc_html_e( 'Enable notification sending to start this automated abandoned cart recovery step.', 'woo-save-abandoned-carts' );
																	echo ' ' . sprintf(
																	/* translators: %s - Link tags */
																	 esc_html__( 'Learn how to use %spersonalization tags%s.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( $this->get_trackable_link( '' . 'personalization-tags', 'pn_personalization' ) ) .'" target="_blank">', '</a>' ); ?>
															</p>
														</div>
														<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9<?php if( $enabled ){ echo ' cartbounty-pro-checked-parent'; } ?>">
															<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
																<label for="cartbounty-pro-automation-status-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-switch cartbounty-pro-control-visibility cartbounty-pro-step-controller">
																	<input id="cartbounty-pro-automation-status-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_push_notification_steps[<?php echo esc_attr( $key ); ?>][enabled]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $enabled, false ); ?> autocomplete="off" />
																	<span class="cartbounty-pro-slider round"></span>
																</label>
																<label for="cartbounty-pro-automation-status-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-control-visibility cartbounty-pro-step-controller"><?php esc_html_e( 'Enable notification', 'woo-save-abandoned-carts' ); ?></label>
															</div>
															<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
																<?php $this->display_time_intervals( 'cartbounty_pro_push_notification_steps', $key ); ?>
																<p class='cartbounty-pro-additional-information'>
																	<?php echo sprintf(
																	/* translators: %s - Link tags */
																	esc_html__( 'Please %ssee this%s to learn how reminder sending works and when it will be delivered.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( $this->get_trackable_link( '' . 'abandoned-carts', 'pn_is_it_abandoned', '#when-is-the-cart-abandoned' ) ) .'" target="_blank">', '</a>' ); ?>
																</p>
															</div>
															<div class="cartbounty-pro-settings-group">
																<label for="cartbounty-pro-automation-heading-<?php echo esc_attr( $key ); ?>"><?php esc_html_e( 'Title', 'woo-save-abandoned-carts' ); ?></label>
																<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
																	<input id="cartbounty-pro-automation-heading-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-text" type="text" name="cartbounty_pro_push_notification_steps[<?php echo esc_attr( $key ); ?>][heading]" value="<?php echo esc_attr( stripslashes( $heading ) ); ?>" placeholder="<?php echo esc_attr( $push_notification->get_defaults( 'heading', $key ) ); ?>" /><?php $this->add_emojis(); ?><?php $this->add_tags( array( 'recovery_link', 'unsubscribe_link', 'coupon', 'coupon_expiry' ) ); ?>
																</div>
															</div>
															<div class="cartbounty-pro-settings-group">
																<label for="cartbounty-pro-automation-content-<?php echo esc_attr( $key ); ?>"><?php esc_html_e( 'Content', 'woo-save-abandoned-carts' ); ?></label>
																<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
																	<textarea id="cartbounty-pro-automation-content-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-text" name="cartbounty_pro_push_notification_steps[<?php echo esc_attr( $key ); ?>][content]" placeholder="<?php echo esc_attr( $push_notification->get_defaults( 'content', $key ) ); ?>" rows="4"><?php echo esc_html( stripslashes( $content ) ); ?></textarea><?php $this->add_emojis(); ?><?php $this->add_tags( array( 'recovery_link', 'unsubscribe_link' ) ); ?>
																</div>
															</div>
														</div>
													</div>
													<div class="cartbounty-pro-row">
														<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
															<h4><?php esc_html_e( 'Appearance', 'woo-save-abandoned-carts' ); ?></h4>
															<p class="cartbounty-pro-titles-column-description">
																<?php esc_html_e( 'Adjust the visual appearance of your notification.', 'woo-save-abandoned-carts' ); ?>
															</p>
														</div>
														<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
															<div class="cartbounty-pro-row cartbounty-pro-settings-columns">
																<div class="cartbounty-col-md-12 cartbounty-col-lg-6<?php if( $include_icon ){ echo ' cartbounty-pro-checked-parent'; }?>">
																	<div class="cartbounty-pro-settings-group cartbounty-pro-toggle <?php if( $include_icon ){ echo ' cartbounty-pro-checked'; }?>">
																		<label for="cartbounty-pro-automation-include-icon-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
																			<input id="cartbounty-pro-automation-include-icon-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_push_notification_steps[<?php echo esc_attr( $key ); ?>][include_icon]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $include_icon, false ); ?> autocomplete="off" />
																			<span class="cartbounty-pro-slider round"></span>
																		</label>
																		<label for="cartbounty-pro-automation-include-icon-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-control-visibility"><?php esc_html_e( 'Use product image as icon', 'woo-save-abandoned-carts' ); ?></label>
																		<p class='cartbounty-pro-additional-information'>First product image from the shopping cart will be used in the notification to increase engagement.</p>
																	</div>
																	<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
																		<?php
																			if( !did_action( 'wp_enqueue_media' ) ){
																				wp_enqueue_media();
																			}
																			$image = wp_get_attachment_image_src( $main_icon );
																		?>
																		<h4><?php esc_html_e( 'Custom icon', 'woo-save-abandoned-carts' ); ?></h4>
																		<p class='cartbounty-pro-additional-information'>
																			<?php esc_html_e( 'Recommended dimensions:', 'woo-save-abandoned-carts' ); ?> 256 x 256 px.
																		</p>
																		<div class="cartbounty-pro-action-container">
																			<p id="cartbounty-pro-upload-custom-icon-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-upload-icon" data-automation="<?php echo esc_attr( $key ); ?>">
																				<?php if( $image ):?>
																					<img src="<?php echo esc_url( $image[0] ); ?>" />
																				<?php else: ?>
																					<input type="button" value="<?php esc_attr_e( 'Add a custom icon', 'woo-save-abandoned-carts' ); ?>" class="cartbounty-pro-button button-secondary button" <?php echo $this->disable_field(); ?> />
																				<?php endif;?>
																			</p>
																			<a href="#" id="cartbounty-pro-remove-custom-icon-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-remove-icon" data-automation="<?php echo esc_attr( $key ); ?>" <?php if( !$image ){ echo 'style="display:none"'; }?>></a>
																		</div>
																		<input id="cartbounty-pro-custom-icon-<?php echo esc_attr( $key ); ?>" type="hidden" name="cartbounty_pro_push_notification_steps[<?php echo esc_attr( $key ); ?>][main_icon]" value="<?php if( $main_icon ){echo esc_attr( $main_icon );}?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
																	</div>
																</div>
																<div class="cartbounty-col-md-12 cartbounty-col-lg-6<?php if( $include_image ){ echo ' cartbounty-pro-checked-parent'; }?>">
																	<div class="cartbounty-pro-settings-group cartbounty-pro-toggle <?php if( $include_image ){ echo ' cartbounty-pro-checked'; }?>">
																		<label for="cartbounty-pro-automation-include-image-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
																			<input id="cartbounty-pro-automation-include-image-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_push_notification_steps[<?php echo esc_attr( $key ); ?>][include_image]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $include_image, false ); ?> autocomplete="off" />
																			<span class="cartbounty-pro-slider round"></span>
																		</label>
																		<label for="cartbounty-pro-automation-include-image-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-control-visibility"><?php esc_html_e( 'Include image', 'woo-save-abandoned-carts' ); ?></label>
																	</div>
																	<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
																		<?php
																			if( !did_action( 'wp_enqueue_media' ) ){
																				wp_enqueue_media();
																			}
																			$image = wp_get_attachment_image_src( $main_image );
																		?>
																		<h4><?php esc_html_e( 'Custom image', 'woo-save-abandoned-carts' ); ?></h4>
																		<p class='cartbounty-pro-additional-information'>
																			<?php esc_html_e( 'Recommended dimensions:', 'woo-save-abandoned-carts' ); ?> 1024 x 512 px. <?php esc_html_e( 'Please note that this feature is not supported by all browsers.', 'woo-save-abandoned-carts' ); ?>
																		</p>
																		<div class="cartbounty-pro-action-container">
																			<p id="cartbounty-pro-upload-custom-image-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-upload-image" data-automation="<?php echo esc_attr( $key ); ?>">
																				<?php if( $image ):?>
																					<img src="<?php echo esc_url( $image[0] ); ?>" />
																				<?php else: ?>
																					<input type="button" value="<?php esc_attr_e( 'Add a custom image', 'woo-save-abandoned-carts' ); ?>" class="cartbounty-pro-button button-secondary button" <?php echo $this->disable_field(); ?> />
																				<?php endif;?>
																			</p>
																			<a href="#" id="cartbounty-pro-remove-custom-image-<?php echo esc_attr( $key ); ?>" class="cartbounty-pro-remove-image" data-automation="<?php echo esc_attr( $key ); ?>" <?php if( !$image ){ echo 'style="display:none"'; }?>></a>
																		</div>
																		<input id="cartbounty-pro-custom-image-<?php echo esc_attr( $key ); ?>" type="hidden" name="cartbounty_pro_push_notification_steps[<?php echo esc_attr( $key ); ?>][main_image]" value="<?php if( $main_image ){echo esc_attr( $main_image );}?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
																	</div>
																</div>
															</div>
														</div>
													</div>
													<div class="cartbounty-pro-row">
														<?php $coupons->display_coupon_settings( $active_section, 'cartbounty_pro_push_notification_steps', $key ); ?>
													</div>
													<div class="cartbounty-pro-row">
														<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
															<h4><?php esc_html_e( 'Test notification', 'woo-save-abandoned-carts' ); ?></h4>
															<p class="cartbounty-pro-titles-column-description">
																<?php echo sprintf(
																	/* translators: %s - Link tags */
																	 esc_html__( 'If you are having trouble previewing your notifications, check out our %stroubleshooting guide%s for push notifications.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( $this->get_trackable_link( '' . 'web-push-notifications-abandoned-cart-recovery', 'pn_troubleshooting', '#troubleshooting-push-notifications' ) ) .'" target="_blank">', '</a>' ); ?>
															</p>
														</div>
														<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
															<div class="cartbounty-pro-settings-group">
																<div class="cartbounty-pro-settings-group">
																	<h4><?php esc_html_e('Preview', 'woo-save-abandoned-carts'); ?></h4>
																	<button type="button" class='cartbounty-pro-button button-secondary cartbounty-pro-progress cartbounty-pro-test-push-notification' data-automation='<?php echo esc_attr( $key ); ?>' data-action='send_test_push_notification' data-nonce='<?php echo esc_attr( $preview_notification_nonce ); ?>' <?php echo $this->disable_field(); ?>><?php esc_html_e( 'Show notification', 'woo-save-abandoned-carts' ); ?></button>
																</div>
															</div>
														</div>
													</div>
												</div>
											</div>
										<?php }} ?>
								</div>
							</div>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-sm-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e( 'Notification consent', 'woo-save-abandoned-carts' ); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e( 'Customize notification permission request contents, appearance and settings.', 'woo-save-abandoned-carts' ); ?> <?php echo sprintf(
								/* translators: %s - Link tags */
								 esc_html__( 'Look here to see advanced %stemplate customization%s options.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( $this->get_trackable_link( '' . 'actions-and-filters', 'pn_template_customization', '#push-notification-hooks' ) ) .'" target="_blank">', '</a>');?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group">
								<h4><?php esc_html_e('Message', 'woo-save-abandoned-carts'); ?></h4>
								<label for="cartbounty-pro-push-notification-permission-heading"><?php esc_html_e( 'Title', 'woo-save-abandoned-carts' ); ?></label>
								<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
									<input id="cartbounty-pro-push-notification-permission-heading" class="cartbounty-pro-text" type="text" name="cartbounty_pro_push_notification_settings[permission_heading]" value="<?php echo esc_attr( $push_notification->get_settings( 'permission_heading' ) ); ?>" placeholder="<?php echo esc_attr( $this->get_tools_defaults( 'permission_heading', 'push_notification' ) ); ?>" /><?php $this->add_emojis(); ?>
								</div>
							</div>
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty-pro-push-notification-permission-content"><?php esc_html_e( 'Content', 'woo-save-abandoned-carts' ); ?></label>
								<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
									<textarea id="cartbounty-pro-push-notification-permission-content" class="cartbounty-pro-text" name="cartbounty_pro_push_notification_settings[permission_content]" placeholder="<?php echo esc_attr( $this->get_tools_defaults( 'permission_content', 'push_notification' ) ); ?>" rows="4"><?php echo esc_html( $push_notification->get_settings( 'permission_content' ) ); ?></textarea><?php $this->add_emojis(); ?>
								</div>
							</div>
							<div class="cartbounty-pro-settings-group">
								<h4><?php esc_html_e( 'Style', 'woo-save-abandoned-carts' ); ?></h4>
								<div class="cartbounty-pro-flex-container">
									<div id="cartbounty-pro-push-notification-permission-center" class="cartbounty-pro-type <?php if( $push_notification->get_settings( 'permission_style' ) == 1 ){ echo "cartbounty-pro-radio-active";} ?>">
										<label class="cartbounty-pro-image" for="cartbounty-pro-radiobutton-center">
											<em>
												<i>
													<img src="<?php echo esc_url( plugins_url( 'assets/template-light.svg', __FILE__ ) ); ?>" title="<?php esc_attr_e( 'Appear in center', 'woo-save-abandoned-carts' ); ?>" alt="<?php esc_attr_e( 'Appear in center', 'woo-save-abandoned-carts' ); ?>"/>
												</i>
											</em>
											<input id="cartbounty-pro-radiobutton-center" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_push_notification_settings[permission_style]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $push_notification->get_settings( 'permission_style' ), false ); ?> autocomplete="off" />
											<?php esc_html_e( 'Appear in center', 'woo-save-abandoned-carts' ); ?>
										</label>
									</div>
									<div id="cartbounty-pro-push-notification-permission-left" class="cartbounty-pro-type <?php if( $push_notification->get_settings( 'permission_style' ) == 2 ){ echo "cartbounty-pro-radio-active";} ?>">
										<label class="cartbounty-pro-image" for="cartbounty-pro-radiobutton-left">
											<em>
												<i>
													<img src="<?php echo esc_url( plugins_url( 'assets/template-light.svg', __FILE__ ) ); ?>" title="<?php esc_attr_e( 'Slide in from left', 'woo-save-abandoned-carts' ); ?>" alt="<?php esc_attr_e( 'Slide in from left', 'woo-save-abandoned-carts' ); ?>"/>
												</i>
											</em>
											<input id="cartbounty-pro-radiobutton-left" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_push_notification_settings[permission_style]" value="2" <?php echo $this->disable_field(); ?> <?php echo checked( 2, $push_notification->get_settings( 'permission_style' ), false ); ?> autocomplete="off" />
											<?php esc_html_e( 'Slide in from left', 'woo-save-abandoned-carts' ); ?>
										</label>
									</div>
									<div id="cartbounty-pro-push-notification-permission-top" class="cartbounty-pro-type <?php if( $push_notification->get_settings( 'permission_style' ) == 3 ){ echo "cartbounty-pro-radio-active";} ?>">
										<label class="cartbounty-pro-image" for="cartbounty-pro-radiobutton-top">
											<em>
												<i>
													<img src="<?php echo esc_url( plugins_url( 'assets/push-notification-permission.svg', __FILE__ ) ); ?>" title="<?php esc_attr_e( 'Top bar', 'woo-save-abandoned-carts' ); ?>" alt="<?php esc_attr_e( 'Top bar', 'woo-save-abandoned-carts' ); ?>"/>
												</i>
											</em>
											<input id="cartbounty-pro-radiobutton-top" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_push_notification_settings[permission_style]" value="3" <?php echo $this->disable_field(); ?> <?php echo checked( 3, $push_notification->get_settings( 'permission_style' ), false ); ?> autocomplete="off" />
											<?php esc_html_e( 'Top bar', 'woo-save-abandoned-carts' ); ?>
										</label>
									</div>
								</div>
							</div>
							<div class="cartbounty-pro-settings-group">
								<h4><?php esc_html_e( 'Colors', 'woo-save-abandoned-carts' ); ?></h4>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e( 'If you leave the Inverse color empty, it will automatically use the inverse color of the main color you have picked. Clear both colors to use the default colors.', 'woo-save-abandoned-carts' ); ?>
								</p>
								<div class="cartbounty-pro-colors">
									<label for="cartbounty-pro-push-notification-permission-main-color"><?php esc_html_e( 'Main:', 'woo-save-abandoned-carts' ); ?></label>
									<input id="cartbounty-pro-push-notification-permission-main-color" type="text" name="cartbounty_pro_push_notification_settings[main_color]" class="cartbounty-pro-color-picker cartbounty-pro-text" value="<?php echo esc_attr( $push_notification->get_settings( 'main_color' ) ); ?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
								</div>
								<div class="cartbounty-pro-colors">
									<label for="cartbounty-pro-push-notification-permission-inverse-color"><?php esc_html_e( 'Inverse:', 'woo-save-abandoned-carts' ); ?></label>
									<input id="cartbounty-pro-push-notification-permission-inverse-color" type="text" name="cartbounty_pro_push_notification_settings[inverse_color]" class="cartbounty-pro-color-picker cartbounty-pro-text" value="<?php echo esc_attr( $push_notification->get_settings( 'inverse_color' ) ); ?>" <?php echo $this->disable_field(); ?> autocomplete="off" /> 
								</div>
							</div>
							<div class="cartbounty-pro-settings-group">
								<?php
									if( !did_action( 'wp_enqueue_media' ) ){
										wp_enqueue_media();
									}
									$image = wp_get_attachment_image_src( $push_notification->get_settings( 'permission_image' ) );
								?>
								<h4><?php esc_html_e( 'Custom image', 'woo-save-abandoned-carts' ); ?></h4>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e( 'Recommended dimensions:', 'woo-save-abandoned-carts' ); ?> 1024 x 600 px.
								</p>
								<div class="cartbounty-pro-action-container">
									<p id="cartbounty-pro-upload-custom-image" class="cartbounty-pro-upload-image">
										<?php if( $image ):?>
											<img src="<?php echo esc_url( $image[0] ); ?>" />
										<?php else: ?>
											<input type="button" value="<?php esc_attr_e( 'Add a custom image', 'woo-save-abandoned-carts' ); ?>" class="cartbounty-pro-button button-secondary button" <?php echo $this->disable_field(); ?> />
										<?php endif;?>
									</p>
									<a href="#" id="cartbounty-pro-remove-custom-image" class="cartbounty-pro-remove-image" <?php if( !$image ){echo 'style="display:none"'; }?>></a>
								</div>
								<input id="cartbounty-pro-custom-image" type="hidden" name="cartbounty_pro_push_notification_settings[permission_image]" value="<?php if( $push_notification->get_settings( 'permission_image' ) ){echo esc_attr( $push_notification->get_settings( 'permission_image' ) );} ?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
							</div>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<?php $this->display_exclusion_settings( $active_section ); ?>
					</div>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e( 'Miscellaneous', 'woo-save-abandoned-carts' ); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e( 'Enable test mode to see how the notification permission request looks like.', 'woo-save-abandoned-carts' );?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group">
								<h4><?php esc_html_e( 'Reset stats', 'woo-save-abandoned-carts' ); ?></h4>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e( 'Reset automation process notification send and click statistics.', 'woo-save-abandoned-carts' ); ?>
								</p>
								<div class="cartbounty-pro-action-container">
									<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( 'handle', 'cartbounty_pro_reset_stats' ), 'cartbounty-pro-reset-stats-nonce', 'cartbounty_pro_reset_stats' ) ); ?>" class='cartbounty-pro-button button-secondary cartbounty-pro-progress'><?php esc_html_e( 'Reset', 'woo-save-abandoned-carts' ); ?></a>
								</div>
							</div>
							<div class="cartbounty-pro-settings-group cartbounty-pro-toggle<?php if( $push_notification->get_settings( 'test_mode' ) ){ echo ' cartbounty-pro-checked'; }?>">
								<label for="cartbounty-pro-push-notification-permission-test-mode" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
									<input id="cartbounty-pro-push-notification-permission-test-mode" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_push_notification_settings[test_mode]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $push_notification->get_settings( 'test_mode' ), false ); ?> autocomplete="off" />
									<span class="cartbounty-pro-slider round"></span>
								</label>
								<label for="cartbounty-pro-push-notification-permission-test-mode" class="cartbounty-pro-control-visibility"><?php esc_html_e( 'Enable test mode', 'woo-save-abandoned-carts' ); ?></label>
								<p class='cartbounty-pro-additional-information'>
									<i class='cartbounty-pro-hidden'>
										<?php esc_html_e( 'Now open your store, add a product to the cart and try refreshing the page or opening a product page. Please note that while this is enabled, only users with Admin rights will be able to see the Push notification permission request and appearance limitations have been removed which means that you will see the request each time you the page is refreshed. Do not forget to disable this after you have done testing.', 'woo-save-abandoned-carts' ); ?>
									</i>
								</p>
							</div>
						</div>
					</div>
					<div class='cartbounty-pro-button-row'>
						<?php
						if( $this->user_is_admin() ){
							echo "<button type='submit' class='cartbounty-pro-button button-primary cartbounty-pro-progress'>". esc_html__( 'Save settings', 'woo-save-abandoned-carts' ) ."</button>";
						}
						if( $this->check_license() && $automation->automation_enabled( 'push_notification' ) ){
							echo $this->display_force_sync_button( $active_section );
						}
						?>
					</div>
				</form>

				<?php
				break;

			case 'webhook':

				$webhook = $this->webhook();
				$api_valid = $webhook->api_valid();

				if( !class_exists( 'WooCommerce' ) ){ //If WooCommerce is not active
					$this->missing_woocommerce_notice( $active_section ); 
					return;
				}?>

				<div class="cartbounty-pro-section-intro">
					<?php echo sprintf(
						/* translators: %1$s - Link start, %2$s - Link start, %3$s - Link end */
						esc_html__( 'Webhook offers an easy way of sending event-based data about abandoned carts to applications like %1$sMake (former Integromat)%3$s, %2$sPabbly%3$s, Zapier or other. A great way for building powerful automations and advanced marketing processes.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( CARTBOUNTY_PRO_MAKE_LINK ) .'" target="_blank">', '<a href="'. esc_url( CARTBOUNTY_PRO_PABBLY_LINK ) .'" target="_blank">', '</a>' );
					?>
				</div>
				<form method="post" action="options.php">
					<?php
						settings_fields( 'cartbounty-pro-webhook-settings' );
						do_settings_sections( 'cartbounty-pro-webhook-settings' );
						$webhook_url = $webhook->get_webhook_url();
						$api_status = $webhook->api_status();
						$fields = array( $webhook_url );
					?>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('General', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php echo sprintf(
									/* translators: %s - URL link */
									esc_html( 'Enable webhook by providing webhook URL. Use our Docs to see %swebhook setup tutorial and example use%s.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( $this->get_trackable_link( '' . 'webhook-make-integromat-pabbly-abandoned-cart-recovery-automation', 'wh_setup_tutorial' ) ) .'" target="_blank">', '</a>'
								); ?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9<?php if($api_valid){ echo ' cartbounty-pro-checked-parent'; }?>">
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty_pro_webhook_url"><?php esc_html_e( 'Webhook URL', 'woo-save-abandoned-carts' ); ?><?php echo $this->output_connection_message( $api_status, $fields ); ?></label>
								<input id="cartbounty_pro_webhook_url" class="cartbounty-pro-text" type="url" name="cartbounty_pro_webhook_url" value="<?php echo esc_attr( $webhook_url ); ?>" <?php echo $this->disable_field(); ?> />
								<?php if( !$api_valid ){
									echo "<p class='cartbounty-pro-additional-information'>" . sprintf(
										/* translators: %s - URL link */
										esc_html__( 'Sign up for a Free account on %1$sMake%3$s or %2$sPabbly%3$s to get webhook URL and create powerful abandoned cart automations.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( CARTBOUNTY_PRO_MAKE_LINK ) .'" target="_blank">', '<a href="'. esc_url( CARTBOUNTY_PRO_PABBLY_LINK ) .'" target="_blank">', '</a>' ) . "</p>";
								}?>
							</div>
							<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
								<h4><?php esc_html_e( 'Webhook test', 'woo-save-abandoned-carts' ); ?></h4>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e( 'Send sample abandoned cart data to your integration.', 'woo-save-abandoned-carts' ); ?>
								</p>
								<div class="cartbounty-pro-action-container">
									<?php $actions = $webhook->get_webhook_actions();
									foreach ( $actions as $key => $action ): ?>
										<button type="button" class='cartbounty-pro-button button-secondary cartbounty-pro-progress cartbounty-pro-test-webhook' data-action='test_webhook' data-operation='<?php echo esc_attr( $key );?>' data-nonce='<?php echo esc_attr( wp_create_nonce( $key ) ); ?>' <?php echo $this->disable_field(); ?>><?php esc_html_e( $action); ?></button>
									<?php endforeach; ?>
								</div>
							</div>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<?php $coupons->display_coupon_settings( $active_section, 'cartbounty_pro_webhook_coupon' ); ?>
					</div>
					<div class="cartbounty-pro-row">
						<?php $this->display_exclusion_settings( $active_section ); ?>
					</div>
					<div class='cartbounty-pro-button-row'>
						<?php
						if( $this->user_is_admin() ){
							echo "<button type='submit' class='cartbounty-pro-button button-primary cartbounty-pro-progress'>". esc_html__( 'Save settings', 'woo-save-abandoned-carts' ) ."</button>";
						}
						if( $this->check_license() && $api_valid ){
							echo $this->display_force_sync_button( $active_section );
						}?>
					</div>
				</form>
				<?php
				break;

			case 'exit_intent':

				if(!class_exists('WooCommerce')){ //If WooCommerce is not active
					$this->missing_woocommerce_notice( $active_section ); 
					return;
				}?>

				<div class="cartbounty-pro-section-intro">
					<?php echo sprintf(
						/* translators: %s - Link */
						 esc_html__('With the help of Exit Intent, you can capture even more abandoned carts by displaying a message including an email or phone field that the customer can fill to save his shopping cart. You can even offer to send a discount code. Please note that the Exit Intent will only be showed to unregistered users once every 60 minutes after they have added an item to their cart and try to leave your store. Learn how to %scustomize contents%s of Exit Intent popup.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( $this->get_trackable_link( '' . 'exit-intent-popup-technology', 'ei_modify_content' ) ) .'" target="_blank" title="'. esc_html__( 'How to customize contents of Exit Intent', 'woo-save-abandoned-carts' ) .'">', '</a>' );
					?>
				</div>
				<form method="post" action="options.php">
					<?php
						settings_fields( 'cartbounty-pro-settings-exit-intent' );
						do_settings_sections( 'cartbounty-pro-settings-exit-intent' );
						$ei_settings = $this->get_settings( 'exit_intent' );
						$ei_status = $ei_settings['status'];
						$ei_mobile_status = $ei_settings['mobile_status'];
						$ei_field_type = $ei_settings['field_type'];
						$ei_heading = $ei_settings['heading'];
						$ei_content = $ei_settings['content'];
						$ei_style = $ei_settings['style'];
						$ei_main_color = $ei_settings['main_color'];
						$ei_inverse_color = $ei_settings['inverse_color'];
						$ei_image = $ei_settings['image'];
						$ei_test_mode = $ei_settings['test_mode'];
					?>

					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('General', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e('Enable email or phone request before leaving your store.', 'woo-save-abandoned-carts'); ?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9<?php if($ei_status){ echo ' cartbounty-pro-checked-parent'; }?>">
							<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
								<label for="cartbounty-pro-exit-intent-status" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
									<input id="cartbounty-pro-exit-intent-status" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_exit_intent_settings[status]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $ei_status, false ); ?> autocomplete="off" />
									<span class="cartbounty-pro-slider round"></span>
								</label>
								<label for="cartbounty-pro-exit-intent-status" class="cartbounty-pro-control-visibility"><?php esc_html_e('Enable Exit Intent', 'woo-save-abandoned-carts'); ?></label>
							</div>
							<div class="cartbounty-pro-settings-group cartbounty-pro-toggle cartbounty-pro-hidden">
								<label for="cartbounty-pro-exit-intent-mobile-status" class="cartbounty-pro-switch">
									<input id="cartbounty-pro-exit-intent-mobile-status" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_exit_intent_settings[mobile_status]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $ei_mobile_status, false ); ?> autocomplete="off" />
									<span class="cartbounty-pro-slider round"></span>
								</label>
								<label for="cartbounty-pro-exit-intent-mobile-status"><?php esc_html_e('Enable mobile Exit Intent', 'woo-save-abandoned-carts'); ?></label>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e('Will trigger on a quick page scroll-up or the "Back" button.', 'woo-save-abandoned-carts'); ?>
								</p>
							</div>
							<div class="cartbounty-pro-settings-group">
								<h4><?php esc_html_e('Field type', 'woo-save-abandoned-carts'); ?></h4>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e('Choose which input field should be collected in the popup.', 'woo-save-abandoned-carts'); ?>
								</p>
								<label for="cartbounty-pro-exit-intent-field-type-email" class="cartbounty-pro-radiobutton-label">
									<input id="cartbounty-pro-exit-intent-field-type-email" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_exit_intent_settings[field_type]" value="email" <?php echo $this->disable_field(); ?> <?php echo checked( $ei_field_type, 'email', false ); ?> autocomplete="off" />
										<?php esc_html_e('Email', 'woo-save-abandoned-carts'); ?>
								</label>
								<label for="cartbounty-pro-exit-intent-field-type-phone" class="cartbounty-pro-radiobutton-label">
									<input id="cartbounty-pro-exit-intent-field-type-phone" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_exit_intent_settings[field_type]" value="phone" <?php echo $this->disable_field(); ?> <?php echo checked( $ei_field_type, 'phone', false ); ?> autocomplete="off" />
										<?php esc_html_e('Phone', 'woo-save-abandoned-carts'); ?>
								</label>
								<label for="cartbounty-pro-exit-intent-field-type-phone-and-email" class="cartbounty-pro-radiobutton-label">
									<input id="cartbounty-pro-exit-intent-field-type-phone-and-email" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_exit_intent_settings[field_type]" value="phone-and-email" <?php echo $this->disable_field(); ?> <?php echo checked( $ei_field_type, 'phone-and-email', false ); ?> autocomplete="off" />
										<?php esc_html_e('Both', 'woo-save-abandoned-carts'); ?>
								</label>
							</div>
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty-pro-exit-intent-heading"><?php esc_html_e('Main title', 'woo-save-abandoned-carts'); ?></label>
								<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
									<input id="cartbounty-pro-exit-intent-heading" class="cartbounty-pro-text" type="text" name="cartbounty_pro_exit_intent_settings[heading]" value="<?php echo esc_attr( $ei_heading ); ?>" placeholder="<?php echo esc_attr( $this->get_tools_defaults('heading', 'exit_intent') ); ?>" /><?php $this->add_emojis(); ?>
								</div>
							</div>
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty-pro-exit-intent-content"><?php esc_html_e('Content', 'woo-save-abandoned-carts'); ?></label>
								<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
									<textarea id="cartbounty-pro-exit-intent-content" class="cartbounty-pro-text" name="cartbounty_pro_exit_intent_settings[content]" placeholder="<?php echo esc_attr( $this->get_tools_defaults('content', 'exit_intent') ); ?>" rows="4"><?php echo esc_html( $ei_content ); ?></textarea><?php $this->add_emojis(); ?>
								</div>
							</div>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('Appearance', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e('Adjust the visual appearance of your Exit Intent popup.', 'woo-save-abandoned-carts'); ?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group">
								<h4><?php esc_html_e('Style', 'woo-save-abandoned-carts'); ?></h4>
								<div class="cartbounty-pro-flex-container">
									<div id="cartbounty-pro-exit-intent-center" class="cartbounty-pro-type <?php if($ei_style == 1){ echo "cartbounty-pro-radio-active";} ?>">
										<label class="cartbounty-pro-image" for="cartbounty-pro-radiobutton-center">
											<em>
												<i>
													<img src="<?php echo esc_url( plugins_url( 'assets/exit-intent-form.svg', __FILE__ ) ); ?>" title="<?php esc_attr_e('Appear in center', 'woo-save-abandoned-carts'); ?>" alt="<?php esc_attr_e('Appear in center', 'woo-save-abandoned-carts'); ?>"/>
												</i>
											</em>
											<input id="cartbounty-pro-radiobutton-center" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_exit_intent_settings[style]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $ei_style, false ); ?> autocomplete="off" />
											<?php esc_html_e('Appear in center', 'woo-save-abandoned-carts'); ?>
										</label>
									</div>
									<div id="cartbounty-pro-exit-intent-left" class="cartbounty-pro-type <?php if($ei_style == 2){ echo "cartbounty-pro-radio-active";} ?>">
										<label class="cartbounty-pro-image" for="cartbounty-pro-radiobutton-left">
											<em>
												<i>
													<img src="<?php echo esc_url( plugins_url( 'assets/exit-intent-form.svg', __FILE__ ) ); ?>" title="<?php esc_attr_e('Slide in from left', 'woo-save-abandoned-carts'); ?>" alt="<?php esc_attr_e('Slide in from left', 'woo-save-abandoned-carts'); ?>"/>
												</i>
											</em>
											<input id="cartbounty-pro-radiobutton-left" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_exit_intent_settings[style]" value="2" <?php echo $this->disable_field(); ?> <?php echo checked( 2, $ei_style, false ); ?> autocomplete="off" />
											<?php esc_html_e('Slide in from left', 'woo-save-abandoned-carts'); ?>
										</label>
									</div>
									<div id="cartbounty-pro-exit-intent-fullscreen" class="cartbounty-pro-type <?php if($ei_style == 3){ echo "cartbounty-pro-radio-active";} ?>">
										<label class="cartbounty-pro-image" for="cartbounty-pro-radiobutton-fullscreen">
											<em>
												<i>
													<img src="<?php echo esc_url( plugins_url( 'assets/exit-intent-form.svg', __FILE__ ) ); ?>" title="<?php esc_attr_e('Fullscreen', 'woo-save-abandoned-carts'); ?>" alt="<?php esc_attr_e('Fullscreen', 'woo-save-abandoned-carts'); ?>"/>
												</i>
											</em>
											<input id="cartbounty-pro-radiobutton-fullscreen" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_exit_intent_settings[style]" value="3" <?php echo $this->disable_field(); ?> <?php echo checked( 3, $ei_style, false ); ?> autocomplete="off" />
											<?php esc_html_e('Fullscreen', 'woo-save-abandoned-carts'); ?>
										</label>
									</div>
								</div>
							</div>
							<div class="cartbounty-pro-settings-group">
								<h4><?php esc_html_e('Colors', 'woo-save-abandoned-carts'); ?></h4>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e('If you leave the Inverse color empty, it will automatically use the inverse color of the main color you have picked. Clear both colors to use the default colors.', 'woo-save-abandoned-carts'); ?>
								</p>
								<div class="cartbounty-pro-colors">
									<label for="cartbounty-pro-exit-intent-main-color"><?php esc_html_e('Main:', 'woo-save-abandoned-carts'); ?></label>
									<input id="cartbounty-pro-exit-intent-main-color" type="text" name="cartbounty_pro_exit_intent_settings[main_color]" class="cartbounty-pro-color-picker cartbounty-pro-text" value="<?php echo esc_attr( $ei_main_color ); ?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
								</div>
								<div class="cartbounty-pro-colors">
									<label for="cartbounty-pro-exit-intent-inverse-color"><?php esc_html_e('Inverse:', 'woo-save-abandoned-carts'); ?></label>
									<input id="cartbounty-pro-exit-intent-inverse-color" type="text" name="cartbounty_pro_exit_intent_settings[inverse_color]" class="cartbounty-pro-color-picker cartbounty-pro-text" value="<?php echo esc_attr( $ei_inverse_color ); ?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
								</div>
							</div>
							<div class="cartbounty-pro-settings-group">
								<?php
									if(!did_action('wp_enqueue_media')){
										wp_enqueue_media();
									}
									$image = wp_get_attachment_image_src( $ei_image );
								?>
								<h4><?php esc_html_e('Custom image', 'woo-save-abandoned-carts'); ?></h4>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e('Recommended dimensions:', 'woo-save-abandoned-carts'); ?> 1024 x 600 px.
								</p>
								<div class="cartbounty-pro-action-container">
									<p id="cartbounty-pro-upload-custom-image" class="cartbounty-pro-upload-image">
										<?php if($image):?>
											<img src="<?php echo esc_url( $image[0] ); ?>" />
										<?php else: ?>
											<input type="button" value="<?php esc_attr_e('Add a custom image', 'woo-save-abandoned-carts'); ?>" class="cartbounty-pro-button button-secondary button" <?php echo $this->disable_field(); ?> />
										<?php endif;?>
									</p>
									<a href="#" id="cartbounty-pro-remove-custom-image" class="cartbounty-pro-remove-image" <?php if(!$image){echo 'style="display:none"';}?>></a>
								</div>
								<input id="cartbounty-pro-custom-image" type="hidden" name="cartbounty_pro_exit_intent_settings[image]" value="<?php if($ei_image){echo esc_attr( $ei_image );}?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
							</div>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<?php $coupons->display_coupon_settings( $active_section, 'cartbounty_pro_exit_intent_coupon' ); ?>
					</div>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('Miscellaneous', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e('Enable test mode to see how the Exit Intent popup looks like.', 'woo-save-abandoned-carts');?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group cartbounty-pro-toggle<?php if($ei_test_mode){ echo ' cartbounty-pro-checked'; }?>">
								<label for="cartbounty-pro-exit-intent-test-mode" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
									<input id="cartbounty-pro-exit-intent-test-mode" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_exit_intent_settings[test_mode]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $ei_test_mode, false ); ?> autocomplete="off" />
									<span class="cartbounty-pro-slider round"></span>
								</label>
								<label for="cartbounty-pro-exit-intent-test-mode" class="cartbounty-pro-control-visibility"><?php esc_html_e('Enable test mode', 'woo-save-abandoned-carts'); ?></label>
								<p class='cartbounty-pro-additional-information'>
									<i class='cartbounty-pro-hidden'>
										<?php esc_html_e('Now open your store, add a product to the cart and try leaving it. Please note that while this is enabled, only users with Admin rights will be able to see the Exit Intent and appearance limitations have been removed which means that you will see the popup each time you try to leave your store. Do not forget to disable this after you have done testing.', 'woo-save-abandoned-carts'); ?>
									</i>
								</p>
							</div>
						</div>
					</div>
					<div class='cartbounty-pro-button-row'>
						<?php
						if( $this->user_is_admin() ){
							echo "<button type='submit' class='cartbounty-pro-button button-primary cartbounty-pro-progress'>". esc_html__('Save settings', 'woo-save-abandoned-carts') ."</button>";
						}?>
					</div>
				</form>
				<?php
				break;

			case 'early_capture':

				if(!class_exists('WooCommerce')){ //If WooCommerce is not active
					$this->missing_woocommerce_notice( $active_section ); 
					return;
				}?>

				<div class="cartbounty-pro-section-intro">
					<?php echo sprintf(
						/* translators: %s - Link */
						 esc_html__('Try saving more recoverable abandoned carts by enabling Early capture to collect customer’s email or phone right after the "Add to cart" button is clicked. You can also enable mandatory input to make sure guest visitors are not able to add anything to their carts until a valid email or phone is provided. Please note that Early capture will only be presented to unregistered visitors once every 60 minutes. Learn how to %scustomize contents%s of Early capture request.', 'woo-save-abandoned-carts'), '<a href="'. esc_url( $this->get_trackable_link( '' . 'early-capture-add-to-cart-popup', 'ec_modify_content' ) ) .'" target="_blank" title="'. esc_html__( 'How to customize contents of Early capture', 'woo-save-abandoned-carts' ) .'">', '</a>' );
					?>
				</div>
				<form method="post" action="options.php">
					<?php 
						settings_fields( 'cartbounty-pro-early-capture-settings' );
						do_settings_sections( 'cartbounty-pro-early-capture-settings' );
						$ec_settings = $this->get_settings( 'early_capture' );
						$ec_status = $ec_settings['status'];
						$ec_mandatory = $ec_settings['mandatory'];
						$ec_field_type = $ec_settings['field_type'];
						$ec_heading = $ec_settings['heading'];
						$ec_style = $ec_settings['style'];
						$ec_main_color = $ec_settings['main_color'];
						$ec_inverse_color = $ec_settings['inverse_color'];
						$ec_test_mode = $ec_settings['test_mode'];
					?>

					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('General', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e('Enable email or phone request before adding an item to the cart.', 'woo-save-abandoned-carts'); ?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
								<label for="cartbounty-pro-early-capture-status" class="cartbounty-pro-switch">
									<input id="cartbounty-pro-early-capture-status" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_early_capture_settings[status]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $ec_status, false ); ?> autocomplete="off" />
									<span class="cartbounty-pro-slider round"></span>
								</label>
								<label for="cartbounty-pro-early-capture-status"><?php esc_html_e('Enable Early capture', 'woo-save-abandoned-carts'); ?></label>
							</div>
							<div class="cartbounty-pro-settings-group cartbounty-pro-toggle<?php if($ec_mandatory){ echo ' cartbounty-pro-checked'; }?>">
								<label for="cartbounty-pro-early-capture-mandatory" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
									<input id="cartbounty-pro-early-capture-mandatory" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_early_capture_settings[mandatory]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $ec_mandatory, false ); ?> autocomplete="off" />
									<span class="cartbounty-pro-slider round"></span>
								</label>
								<label for="cartbounty-pro-early-capture-mandatory" class="cartbounty-pro-control-visibility"><?php esc_html_e('Enable mandatory input', 'woo-save-abandoned-carts'); ?></label>
								<p class='cartbounty-pro-additional-information'>
									<i class='cartbounty-pro-hidden'>
										<?php esc_html_e('Your guest visitors will not be able to add anything to their carts until a valid email or phone is provided.', 'woo-save-abandoned-carts'); ?>
									</i>
								</p>
							</div>
							<div class="cartbounty-pro-settings-group">
								<h4><?php esc_html_e('Field type', 'woo-save-abandoned-carts'); ?></h4>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e('Choose which input field should be collected in the request.', 'woo-save-abandoned-carts'); ?>
								</p>
								<label for="cartbounty-pro-early-capture-field-type-email" class="cartbounty-pro-radiobutton-label">
									<input id="cartbounty-pro-early-capture-field-type-email" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_early_capture_settings[field_type]" value="email" <?php echo $this->disable_field(); ?> <?php echo checked( $ec_field_type, 'email', false ); ?> autocomplete="off" />
										<?php esc_html_e('Email', 'woo-save-abandoned-carts'); ?>
								</label>
								<label for="cartbounty-pro-early-capture-field-type-phone" class="cartbounty-pro-radiobutton-label">
									<input id="cartbounty-pro-early-capture-field-type-phone" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_early_capture_settings[field_type]" value="phone" <?php echo $this->disable_field(); ?> <?php echo checked( $ec_field_type, 'phone', false ); ?> autocomplete="off" />
										<?php esc_html_e('Phone', 'woo-save-abandoned-carts'); ?>
								</label>
							</div>
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty-pro-early-capture-heading"><?php esc_html_e('Main title', 'woo-save-abandoned-carts'); ?></label>
								<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
									<input id="cartbounty-pro-early-capture-heading" class="cartbounty-pro-text" type="text" name="cartbounty_pro_early_capture_settings[heading]" value="<?php echo esc_attr( $ec_heading ); ?>" placeholder="<?php echo esc_attr( $this->get_tools_defaults('heading', 'early_capture') ); ?>" /><?php $this->add_emojis(); ?>
								</div>
							</div>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('Appearance', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e('Adjust the visual appearance of your Early capture request.', 'woo-save-abandoned-carts'); ?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group">
								<h4><?php esc_html_e('Style', 'woo-save-abandoned-carts'); ?></h4>
								<div class="cartbounty-pro-flex-container">
									<div id="cartbounty-pro-early-capture-near-button" class="cartbounty-pro-type <?php if($ec_style == 1){ echo "cartbounty-pro-radio-active";} ?>">
										<label class="cartbounty-pro-image" for="cartbounty-pro-radiobutton-center">
											<em>
												<i>
													<svg viewBox="0 0 61 35">
														<g id="cartbounty-pro-early-capture-popup-group">
															<path id="cartbounty-pro-near-button-1" d="M58,35H3a3,3,0,0,1-3-3V20a3,3,0,0,1,3-3H9l3-4,3,4H58a3,3,0,0,1,3,3V32A3,3,0,0,1,58,35Z"/>
															<path id="cartbounty-pro-near-button-2" d="M38.88,27.33H12a1.86,1.86,0,0,1-2-1.67V25.5a1.86,1.86,0,0,1,2-1.67H38.88Z"/>
															<path id="cartbounty-pro-near-button-3" d="M49.38,27.33H38.5v-3.5H49.38a1.86,1.86,0,0,1,2,1.67v.16A1.86,1.86,0,0,1,49.38,27.33Z"/>
														</g>
														<rect id="cartbounty-pro-near-button-4" width="42" height="12" rx="3"/>
													</svg>
												</i>
											</em>
											<input id="cartbounty-pro-radiobutton-center" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_early_capture_settings[style]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $ec_style, false ); ?> autocomplete="off" />
											<?php esc_html_e('Next to button', 'woo-save-abandoned-carts'); ?>
										</label>
									</div>
									<div id="cartbounty-pro-early-capture-center" class="cartbounty-pro-type <?php if($ec_style == 2){ echo "cartbounty-pro-radio-active";} ?>">
										<label class="cartbounty-pro-image" for="cartbounty-pro-radiobutton-left">
											<em>
												<i>
													<img src="<?php echo esc_url( plugins_url( 'assets/early-capture-form-popup.svg', __FILE__ ) ); ?>" title="<?php esc_attr_e('Popup overlay', 'woo-save-abandoned-carts'); ?>" alt="<?php esc_attr_e('Popup overlay', 'woo-save-abandoned-carts'); ?>"/>
												</i>
											</em>
											<input id="cartbounty-pro-radiobutton-left" class="cartbounty-pro-radiobutton" type="radio" name="cartbounty_pro_early_capture_settings[style]" value="2" <?php echo $this->disable_field(); ?> <?php echo checked( 2, $ec_style, false ); ?> autocomplete="off" />
											<?php esc_html_e('Popup overlay', 'woo-save-abandoned-carts'); ?>
										</label>
									</div>
								</div>
							</div>
							<div class="cartbounty-pro-settings-group">
								<h4><?php esc_html_e('Colors', 'woo-save-abandoned-carts'); ?></h4>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e('If you leave the Inverse color empty, it will automatically use the inverse color of the main color you have picked. Clear both colors to use the default colors.', 'woo-save-abandoned-carts'); ?>
								</p>
								<div class="cartbounty-pro-colors">
									<label for="cartbounty-pro-early-capture-main-color"><?php esc_html_e('Main:', 'woo-save-abandoned-carts'); ?></label>
									<input id="cartbounty-pro-early-capture-main-color" type="text" name="cartbounty_pro_early_capture_settings[main_color]" class="cartbounty-pro-color-picker cartbounty-pro-text" value="<?php echo esc_attr( $ec_main_color ); ?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
								</div>
								<div class="cartbounty-pro-colors">
									<label for="cartbounty-pro-early-capture-inverse-color"><?php esc_html_e('Inverse:', 'woo-save-abandoned-carts'); ?></label>
									<input id="cartbounty-pro-early-capture-inverse-color" type="text" name="cartbounty_pro_early_capture_settings[inverse_color]" class="cartbounty-pro-color-picker cartbounty-pro-text" value="<?php echo esc_attr( $ec_inverse_color ); ?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
								</div>
							</div>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<?php $coupons->display_coupon_settings( $active_section, 'cartbounty_pro_early_capture_coupon' ); ?>
					</div>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('Miscellaneous', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e('Enable test mode to see how the Early capture looks like.', 'woo-save-abandoned-carts');?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group cartbounty-pro-toggle<?php if($ec_test_mode){ echo ' cartbounty-pro-checked'; }?>">
								<label for="cartbounty-pro-early-capture-test-mode" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
									<input id="cartbounty-pro-early-capture-test-mode" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_early_capture_settings[test_mode]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $ec_test_mode, false ); ?> autocomplete="off" />
									<span class="cartbounty-pro-slider round"></span>
								</label>
								<label for="cartbounty-pro-early-capture-test-mode" class="cartbounty-pro-control-visibility"><?php esc_html_e('Enable test mode', 'woo-save-abandoned-carts'); ?></label>
								<p class='cartbounty-pro-additional-information'>
									<i class='cartbounty-pro-hidden'>
										<?php esc_html_e('Now open your store and try adding a product to your cart. Please note that while this is enabled, only users with Admin rights will be able to see the Early capture request and appearance limitations have been removed which means that you will see the request each time you try to add an item to your cart. Do not forget to disable this after you have done testing.', 'woo-save-abandoned-carts'); ?>
									</i>
								</p>
							</div>
						</div>
					</div>
					<div class='cartbounty-pro-button-row'>
						<?php
						if( $this->user_is_admin() ){
							echo "<button type='submit' class='cartbounty-pro-button button-primary cartbounty-pro-progress'>". esc_html__('Save settings', 'woo-save-abandoned-carts') ."</button>";
						}?>
					</div>
				</form>
				<?php
				break;

			case 'tab_notification':

				if(!class_exists('WooCommerce')){ //If WooCommerce is not active
					$this->missing_woocommerce_notice( $active_section ); 
					return;
				}?>

				<div class="cartbounty-pro-section-intro">
					<?php echo esc_html__( "Decrease shopping cart abandonment by grabbing customer attention and returning them to your store after they have switched to a new browser tab with Tab notification.", 'woo-save-abandoned-carts') . ' ' . sprintf( 
						/* translators: %s - Link */
						esc_html__( "Remind your customers that their shopping cart is craving for some love and attention :). Learn more about %sTab notification%s.", 'woo-save-abandoned-carts'), '<a href="'. esc_url( $this->get_trackable_link( '' . 'dynamic-browser-tab-notification', 'tn_learn_more' ) ) .'" target="_blank" title="'. esc_html__( 'Tab notification', 'woo-save-abandoned-carts' ) .'">', '</a>'
					); ?>
				</div>
				<form method="post" action="options.php">
					<?php 
						settings_fields( 'cartbounty-pro-tab-notification-settings' );
						do_settings_sections( 'cartbounty-pro-tab-notification-settings' );
						$tn_settings = $this->get_settings( 'tab_notification' );
						$tn_status = $tn_settings['status'];
						$tn_check_cart = $tn_settings['check_cart'];
						$tn_content = $tn_settings['content'];
						$tn_favicon = $tn_settings['favicon'];
						$tn_favicon_image = $tn_settings['favicon_image'];
						$tn_test_mode = $tn_settings['test_mode'];
					?>

					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('General', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e('Enable Tab notification and set the speed at which tab Title and Favicon will change.', 'woo-save-abandoned-carts'); ?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9<?php if($tn_status){ echo ' cartbounty-pro-checked-parent'; }?>">
							<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
								<label for="cartbounty-pro-tab-notification-status" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
									<input id="cartbounty-pro-tab-notification-status" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_tab_notification_settings[status]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $tn_status, false ); ?> autocomplete="off" />
									<span class="cartbounty-pro-slider round"></span>
								</label>
								<label for="cartbounty-pro-tab-notification-status" class="cartbounty-pro-control-visibility"><?php esc_html_e('Enable Tab notification', 'woo-save-abandoned-carts'); ?></label>
							</div>
							<div class="cartbounty-pro-settings-group cartbounty-pro-toggle cartbounty-pro-hidden">
								<label for="cartbounty-pro-tab-notification-check-cart" class="cartbounty-pro-switch">
									<input id="cartbounty-pro-tab-notification-check-cart" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_tab_notification_settings[check_cart]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $tn_check_cart, false ); ?> autocomplete="off" />
									<span class="cartbounty-pro-slider round"></span>
								</label>
								<label for="cartbounty-pro-tab-notification-check-cart"><?php esc_html_e('Check for empty cart', 'woo-save-abandoned-carts'); ?></label>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e('If enabled, will show Tab notification only when shopping cart is not empty.', 'woo-save-abandoned-carts'); ?>
								</p>
							</div>
							
							<div class="cartbounty-pro-settings-group">
								<?php $this->display_time_intervals( 'cartbounty_pro_tab_notification_settings[interval]' ); ?>
							</div>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e('Notification content', 'woo-save-abandoned-carts'); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e('Customize the message that will appear in the Tab title and enable Favicon.', 'woo-save-abandoned-carts'); ?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9<?php if($tn_favicon){ echo ' cartbounty-pro-checked-parent'; }?>">
							<div class="cartbounty-pro-settings-group">
								<label for="cartbounty-pro-tab-notification-content"><?php esc_html_e('Message', 'woo-save-abandoned-carts'); ?></label>
								<div class="cartbounty-pro-content-creation cartbounty-pro-flex">
									<input id="cartbounty-pro-tab-notification-content" class="cartbounty-pro-text" type="text" name="cartbounty_pro_tab_notification_settings[content]" value="<?php echo esc_attr( $tn_content ); ?>" placeholder="<?php echo esc_attr( $this->get_tools_defaults( 'content', 'tab_notification' ) ); ?>" /><?php $this->add_emojis(); ?>
								</div>
							</div>
							<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
								<label for="cartbounty-pro-tab-notification-favicon-status" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
									<input id="cartbounty-pro-tab-notification-favicon-status" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_tab_notification_settings[favicon]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $tn_favicon, false ); ?> autocomplete="off" />
									<span class="cartbounty-pro-slider round"></span>
								</label>
								<label for="cartbounty-pro-tab-notification-favicon-status" class="cartbounty-pro-control-visibility"><?php esc_html_e('Enable Favicon change', 'woo-save-abandoned-carts'); ?></label>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e('A Favicon is a small image displayed next to the page title in the browser tab.', 'woo-save-abandoned-carts'); ?>
								</p>
							</div>
							<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
								<?php
									if(!did_action('wp_enqueue_media')){
										wp_enqueue_media();
									}
									$image = wp_get_attachment_image_src( $tn_favicon_image );
								?>
								<h4><?php esc_html_e('Custom Favicon', 'woo-save-abandoned-carts'); ?></h4>
								<p class='cartbounty-pro-additional-information'>
									<?php esc_html_e('Recommended dimensions:', 'woo-save-abandoned-carts'); ?> 32 x 32 px.
								</p>
								<div class="cartbounty-pro-action-container">
									<p id="cartbounty-pro-upload-custom-image" class="cartbounty-pro-upload-image">
										<?php if($image):?>
											<img src="<?php echo esc_url( $image[0] ); ?>" />
										<?php else: ?>
											<input type="button" value="<?php esc_attr_e('Add a custom image', 'woo-save-abandoned-carts'); ?>" class="cartbounty-pro-button button-secondary button" <?php echo $this->disable_field(); ?> />
										<?php endif;?>
									</p>
									<a href="#" id="cartbounty-pro-remove-custom-image" class="cartbounty-pro-remove-image" <?php if(!$image){echo 'style="display:none"';}?>></a>
								</div>
								<input id="cartbounty-pro-custom-image" type="hidden" name="cartbounty_pro_tab_notification_settings[favicon_image]" value="<?php if( $tn_favicon_image ){echo esc_attr( $tn_favicon_image );}?>" <?php echo $this->disable_field(); ?> autocomplete="off" />
							</div>
						</div>
					</div>
					<div class="cartbounty-pro-row">
						<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
							<h4><?php esc_html_e( 'Miscellaneous', 'woo-save-abandoned-carts' ); ?></h4>
							<p class="cartbounty-pro-titles-column-description">
								<?php esc_html_e( 'Enable test mode to see how Tab notification works.', 'woo-save-abandoned-carts' );?>
							</p>
						</div>
						<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9">
							<div class="cartbounty-pro-settings-group cartbounty-pro-toggle<?php if( $tn_test_mode ){ echo ' cartbounty-pro-checked'; }?>">
								<label for="cartbounty-pro-tab-notification-test-mode" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
									<input id="cartbounty-pro-tab-notification-test-mode" class="cartbounty-pro-checkbox" type="checkbox" name="cartbounty_pro_tab_notification_settings[test_mode]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $tn_test_mode, false ); ?> autocomplete="off" />
									<span class="cartbounty-pro-slider round"></span>
								</label>
								<label for="cartbounty-pro-tab-notification-test-mode" class="cartbounty-pro-control-visibility"><?php esc_html_e( 'Enable test mode', 'woo-save-abandoned-carts' ); ?></label>
								<p class='cartbounty-pro-additional-information'>
									<i class='cartbounty-pro-hidden'>
										<?php esc_html_e( 'Now open your store, add a product to the cart and switch to a new browser tab. Please note that while this is enabled, only users with Admin rights will be able to see the Tab notification. Do not forget to disable this after you have done testing.', 'woo-save-abandoned-carts' ); ?>
									</i>
								</p>
							</div>
						</div>
					</div>
					<div class='cartbounty-pro-button-row'>
						<?php
						if( $this->user_is_admin() ){
							echo "<button type='submit' class='cartbounty-pro-button button-primary cartbounty-pro-progress'>". esc_html__( 'Save settings', 'woo-save-abandoned-carts' ) ."</button>";
						}?>
					</div>
				</form>
				<?php
				break;
		}
	}

	/**
	 * Method displays notice of a missing WooCommerce plugin
	 *
	 * @since    9.0
	 * @param    string    $current_section    	Currently open section
	 */
	function missing_woocommerce_notice( $current_section ){
		$sections = $this->get_sections( 'recovery' );
		$name = '';
		foreach ($sections as $key => $section) { //Getting integration name from array
			if($key == $current_section){
				$name = $section['name'];
			}
		}
		echo '<p class="cartbounty-pro-description">' . sprintf(
			/* translators: %s - Gets replaced by an integration name, e.g. MailChimp */
			esc_html__('Not so fast, sailor! You must enable WooCommerce before we can set sail or this %s boat gets us nowhere.', 'woo-save-abandoned-carts'), esc_html( $name ) ) . '</p>';
	}

	/**
	 * Method returns connection status message
	 *
	 * @since    9.0
	 * @param    array    $api_status    	API response
	 * @param    array    $fields    		API fields
	 */
	function output_connection_message( $api_status, $fields = array()){
		$empty = false;
		$message = esc_html__('Not connected', 'woo-save-abandoned-carts');
		$direction = is_rtl() ? 'rtl' : 'ltr';

		if(!empty($api_status['message'])){
			$message = $api_status['message'];
		}
		
		foreach ($fields as $key => $field) { //Check if at least one of the fields in an aray is empty
			if (empty($field)) {
				$empty = true;
			}
		}

		if($api_status['status'] == 3){ //If License key expired (Settings page)
			echo '<span class="license-status license-active license-expired" dir="'. $direction .'"><i class="license-status-icon"><img src="'. esc_url( plugins_url( 'assets/expired-icon.svg', __FILE__ ) ) .'" /></i>'. esc_html( $message ) .'</span>';
		
		}elseif($api_status['status'] == 1){ //If API key is valid
			echo '<span class="license-status license-active" dir="'. $direction .'"><i class="license-status-icon"><img src="'. esc_url( plugins_url( 'assets/active-icon.svg', __FILE__ ) ) .'" /></i>'. esc_html( $message ) .'</span>';

		}elseif($api_status['status'] == 0 && !$empty){ //If license is not active and none of the input fields are empty
			echo '<span class="license-status license-inactive" dir="'. $direction .'"><i class="license-status-icon"><img src="'. esc_url( plugins_url( 'assets/invalid-icon.svg', __FILE__ ) ) .'" /></i>'. esc_html( $message ) .'</span>';

		}else{ //If key not provided
			echo '<span class="license-status license-missing" dir="'. $direction .'"><i class="license-status-icon"><img src="'. esc_url( plugins_url( 'assets/inactive-icon.svg', __FILE__ ) ) .'" /></i>'. esc_html( $message ) .'</span>';
		}
	}

	/**
	 * Method returns visual status indiciator if the item has been connected
	 *
	 * @since    9.0
	 * @return   string
	 * @param    boolean    $connected    	Whether the item is connected or not
	 * @param    boolean    $text    		Should the text be displayed or just the green status
	 * @param    string    	$tab    		Tab section, used to determine which type of text should be returned
	 */
	function get_connection( $connected, $text, $tab ){
		$status = '';
		if($connected){
			if($text){
				$text = esc_html__('Enabled', 'woo-save-abandoned-carts');

				if($tab == 'recovery'){
					$text = esc_html__('Connected', 'woo-save-abandoned-carts');
				}
				
			}
			$status = '<em class="cartbounty-pro-connection">'. esc_html( $text ) .'</em>';
		}
		return $status;
	}

	/**
	* Check if WooCommerce Action scheduler library exists
	*
	* @since    9.9.3
	* @return   boolean
	*/
	function action_scheduler_enabled(){
		$status = false;

		if( class_exists( 'ActionScheduler_Store' ) ){
			$status = true;
		}

		return $status;
	}

	/**
	 * Schedules WordPress events
	 * By default trying to use WooCommerce Action Scheduler library to schedule events.
	 * Documentation: https://actionscheduler.org/api/
	 * Fallback to WP Cron
	 * Moved outside of Plugin activation class in v.9.4 since there were many ocurances when events were not scheduled after plugin activation
	 *
	 * @since    1.1
	 */
	function schedule_events(){
		$settings = $this->get_settings( 'settings' );
		$notification_frequency = $settings['notification_frequency'];
		$delete_anonymous_carts = $settings['delete_anonymous_carts'];
		$delete_coupons = $settings['delete_coupons'];

		if ( empty( $notification_frequency ) ){ //Making sure that if the value is an empty string, we do not get a fatal error
			$notification_frequency = 0;
		}

		$hooks = array(
			'cartbounty_pro_sync_hook' 					=> array( 
				'interval'			=> 5 * 60, //Every 5 minutes
				'wp_cron_interval'	=> 'cartbounty_pro_sync_interval',
				'enabled'			=> true
			),
			'cartbounty_pro_remove_empty_carts_hook' 	=> array(
				'interval'			=> 12 * 60 * 60, //Twice Daily
				'wp_cron_interval'	=> 'cartbounty_pro_twice_daily_interval',
				'enabled'			=> true
			),
			'cartbounty_pro_notification_sendout_hook' 	=> array(
				'interval'			=> $notification_frequency / 1000,
				'wp_cron_interval'	=> 'cartbounty_pro_notification_sendout_interval',
				'enabled'			=> ( $notification_frequency == 0 ) ? false : true
			),
			'cartbounty_pro_delete_anonymous_carts_hook' 	=> array(
				'interval'			=> 12 * 60 * 60, //Twice Daily
				'wp_cron_interval'	=> 'cartbounty_pro_twice_daily_interval',
				'enabled'			=> ( $delete_anonymous_carts == 0 ) ? false : true
			),
			'cartbounty_pro_delete_coupons_hook' 		=> array(
				'interval'			=> 12 * 60 * 60, //Twice Daily
				'wp_cron_interval'	=> 'cartbounty_pro_twice_daily_interval',
				'enabled'			=> ( !$delete_coupons ) ? false : true
			)
		);

		foreach( $hooks as $hook_name => $hook_data ){

			if( $this->action_scheduler_enabled() ){ //Check if WooCommerce Action scheduler library exists

				if( $hook_data['enabled'] ){ //If action should be scheduled

					if ( !as_next_scheduled_action( $hook_name ) ){ //Validate if action has not already been scheduled
						as_schedule_recurring_action( time(), $hook_data['interval'], $hook_name, array(), CARTBOUNTY_PRO );
					}

				}else{ //Unschedule action
					as_unschedule_action( $hook_name, array(), CARTBOUNTY_PRO );
				}

				wp_clear_scheduled_hook( $hook_name ); //Removing any WP Cron events in case they were scheduled previously

			}else{ //Falling back to using WP Cron in case Action Scheduler not available
				
				if( $hook_data['enabled'] ){ //If action should be scheduled

					if ( !wp_next_scheduled( $hook_name ) ){ //Validate if action has not already been scheduled
						wp_schedule_event( time(), $hook_data['wp_cron_interval'], $hook_name );
					}

				}else{ //Unschedule action
					wp_clear_scheduled_hook( $hook_name );
				}
			}
		}
	}

	/**
	* Unschedule email notification sendout hook in case the interval gets changed and Action Scheduler is being used
	*
	* @since    9.9.3
	*/
	function unschedule_notification_sendout_hook(){

		if( $this->action_scheduler_enabled() ){
			as_unschedule_action( 'cartbounty_pro_notification_sendout_hook', array(), CARTBOUNTY_PRO );
		}
	}

	/**
	 * Method adds additional intervals to default WordPress Cron intervals
	 * Interval provided in minutes
	 *
	 * @since    1.1
	 * @param    array    $intervals    Existing Array of intervals
	 */
	function add_custom_wp_cron_intervals( $intervals ){
		$notification_frequency = $this->get_interval_data( 'cartbounty_pro_main_settings[notification_frequency]' );
		$interval_name = $this->prepare_time_intervals( $notification_frequency['interval'], $zero_value = '', 'cartbounty_pro_main_settings[notification_frequency]' );
		$interval = $notification_frequency['selected'];

		$intervals['cartbounty_pro_notification_sendout_interval'] = array( //Defining cron Interval for sending out email notifications about abandoned carts
			'interval' 	=> $interval / 1000,
			'display' 	=> $interval_name[$interval]
		);

		$intervals['cartbounty_pro_sync_interval'] = array( //Defining cron Interval for sending out abandoned carts
			'interval' 	=> 5 * 60,
			'display' 	=> 'Every 5 minutes'
		);

		$intervals['cartbounty_pro_twice_daily_interval'] = array(
			'interval' 	=> 12 * 60 * 60,
			'display' 	=> 'Twice Daily'
		);

		return $intervals;
	}
	
	/**
	 * Method that activates license that has been entered or deactivates license if the license deleted or changed
	 *
	 * @since    1.1
	 */
	function activate_license(){
		$settings = $this->get_settings( 'settings' );
		$misc_settings = $this->get_settings( 'misc_settings' );
		$newly_submited_license_key = $settings['license_key']; //License key entered in the form
		$saved_license_key = $misc_settings['saved_license']; //Previously saved license key
		$license_active = $this->is_license_active();
		$license_expired = $this->is_license_expired();
		$license = array();
		$expression = $this->get_expressions();
		$saved_cart_count = $this->get_closest_lowest_integer( $this->total_cartbounty_recoverable_cart_count() );

		$status = array(
			'invalid'	=> '0',
			'valid'		=> '1',
			'missing'	=> '2',
			'expired'	=> '3'
		);

		//If license field is empty or does not exist
		if($newly_submited_license_key == '' || $newly_submited_license_key == NULL){	
			//Deactivate previous license key if it was active or expired
			if( $license_active || $license_expired ){
				//Deactivate license key. Run deactivation function
				$this->deactivate_license();
				$license['status'] = $status['missing'];
				$license['result'] = 'error';
				$license['message'] = esc_html__('Not activated', 'woo-save-abandoned-carts');
				$this->log('info', CARTBOUNTY_PRO_SHORT . ': ' . esc_html__('License key has been deactivated', 'woo-save-abandoned-carts'));

			}else{
				$license['status'] = $status['missing'];
				$license['result'] = 'error';
				$license['message'] = esc_html__('Not activated', 'woo-save-abandoned-carts');
			}

			$misc_settings['saved_license'] = '';
			$misc_settings['license_code'] = '';
			update_option( 'cartbounty_pro_misc_settings', $misc_settings );

		}else{
			//If license field is not empty we are checking license			
			//Check if newly entered license key is different from previously activated
			if($saved_license_key != $newly_submited_license_key){				
				//Deactivate previous license key if it was active or expired
				if( $license_active || $license_expired ){
					//Deactivate license key. Run deactivation function
					$this->deactivate_license();
				}

				$misc_settings['saved_license'] = '';
				$misc_settings['license_code'] = '';
				update_option( 'cartbounty_pro_misc_settings', $misc_settings );
				
				$api_params = array(
					'slm_action' => 'slm_activate',
					'secret_key' => CARTBOUNTY_PRO_SECRET_KEY,
					'license_key' => sanitize_key($newly_submited_license_key),
					'registered_domain' => $this->get_current_domain_name(),
					'item_reference' => urlencode(CARTBOUNTY_PRO_PLUGIN_NAME),
				);				

				$api = $this->api();
				$result = $api->connect( 'cartbounty', $this->api_access(), '', 'GET', $api_params );
				$response = $result['response'];

				if( $result['status_code'] == 200 ){
					//If Success was returned for the license activation						
					if( $response->result == 'success'){
						$misc_settings['saved_license'] = $newly_submited_license_key;
						$misc_settings['license_code'] = CARTBOUNTY_PRO_LICENSE_CODE;
						update_option( 'cartbounty_pro_misc_settings', $misc_settings );
						$license['status'] = $status['valid'];
						$license['result'] = $response->result;
						$license['message'] = $response->message;
						$this->clear_notice( 'license_expired' );
						$this->clear_notice( 'license_about_to_expire' );
						$this->log('info', CARTBOUNTY_PRO_SHORT . ': ' . $response->message);

					}else{
						//If license activation encounters error. Probably entered incorrect license key
						$misc_settings['saved_license'] = $newly_submited_license_key;
						$misc_settings['license_code'] = '';
						update_option( 'cartbounty_pro_misc_settings', $misc_settings );
						
						$license['status'] = $status['invalid'];
						$license['result'] = $response->result;
						$license['message'] = $response->message;
						
						//In some cases the license might be already active therefore we must check error codes
						//Error code 20  = License blocked
						//Error code 30  = License has expired
						//Error code 40  = License already in use on current domain
						//Error code 110 = Reached maximum activation and license key already in use on current domain
						if($response->error_code == 30){
							$misc_settings['license_code'] = CARTBOUNTY_PRO_EXPIRED_LICENSE_CODE;
							update_option( 'cartbounty_pro_misc_settings', $misc_settings );
							$license['status'] = $status['expired'];
							$license['result'] = 'success';
							$license['message'] = esc_html__('Active (Expired)', 'woo-save-abandoned-carts');

							$license['expired_message'] = $this->get_expired_license_message( 'expired_settings' );

							$this->log('info', CARTBOUNTY_PRO_SHORT . ': ' . esc_html__('License key activated but has expired.', 'woo-save-abandoned-carts'));

						}elseif($response->error_code == 40 || $response->error_code == 110){
							$misc_settings['license_code'] = CARTBOUNTY_PRO_LICENSE_CODE;
							update_option( 'cartbounty_pro_misc_settings', $misc_settings );
							$license['status'] = $status['valid'];
							$license['result'] = 'success';
							$license['message'] = esc_html__( 'Active', 'woo-save-abandoned-carts' );
							$this->clear_notice( 'license_expired' );
							$this->clear_notice( 'license_about_to_expire' );
							$this->log('info', CARTBOUNTY_PRO_SHORT . ': ' . esc_html__('License key is already in use on current domain.', 'woo-save-abandoned-carts'));

						}else{
							$this->log('info', 'License activation error: ' . print_r($result, 1));
						}
					}

				}else{

					if(is_object($response_body)){
						$license['status'] = $status['invalid'];
						$license['result'] = $response->result;
						$license['message'] = esc_html__('Something went wrong. The license server might be down. Please try again.', 'woo-save-abandoned-carts');
						$this->log('info', CARTBOUNTY_PRO_SHORT . ': ' . esc_html__('Something went wrong. The license server might be down. Please try again.', 'woo-save-abandoned-carts'));
					}else{
						$license['status'] = $status['invalid'];
						$license['result'] = '';
						$license['message'] = esc_html__('Failed to reach the license server.', 'woo-save-abandoned-carts');
						$this->log('info', CARTBOUNTY_PRO_SHORT . ': ' . esc_html__('Failed to reach the license server.', 'woo-save-abandoned-carts'));
					}
				}

			}else{
				//If newly entered license key is equal to previously entered key				
				//Check if previously we had an activated license
				if( $license_active ){
					$license['status'] = $status['valid'];
					$license['result'] = 'success';
					$license['message'] = esc_html__( 'Active', 'woo-save-abandoned-carts' );
				
				}elseif( $license_expired ){
					//If the license has expired
					$license['status'] = $status['expired'];
					$license['result'] = 'success';
					$license['message'] = esc_html__('Active (Expired)', 'woo-save-abandoned-carts');
					$license['expired_message'] = $this->get_expired_license_message( 'expired_settings' );

				}else{
					//If previously license was not valid
					$license['status'] = $status['invalid'];
					$license['result'] = 'error';
					$license['message'] = esc_html__('Invalid license key', 'woo-save-abandoned-carts');
				}
			}
		}
		return $license;
	}
	
	/**
	 * Method that handles license deactivation
	 *
	 * @since    1.1
	 * @return   string
	 */
	function deactivate_license(){
		$status = '';
		$data = $_POST;
		$misc_settings = $this->get_settings( 'misc_settings' );
		$saved_license = $misc_settings['saved_license'];
		$api_params = array(
			'slm_action' => 'slm_deactivate',
			'secret_key' => CARTBOUNTY_PRO_SECRET_KEY,
			'license_key' => sanitize_key( $saved_license ),
			'registered_domain' => $this->get_current_domain_name(),
			'item_reference' => urlencode(CARTBOUNTY_PRO_PLUGIN_NAME),
		);

		$api = $this->api();
		$result = $api->connect( 'cartbounty', $this->api_access(), '', 'GET', $api_params );
		$response = $result['response'];

		if( $result['status_code'] == 200 ){

			if($response->result == 'success' || $response->error_code == 80){ //Error code 80 means that the license key on this domain is already inactive
				$settings = $this->get_settings( 'settings' );
				$settings['license_key'] = '';
				$misc_settings['saved_license'] = '';
				$misc_settings['license_code'] = '';
				//If license successfully deactivated
				update_option( 'cartbounty_pro_main_settings', $settings ); //Clearing Input data
				update_option( 'cartbounty_pro_misc_settings', $misc_settings );

				$status = esc_html__('License successfully deactivated', 'woo-save-abandoned-carts');
				if(!empty($data['action'])){ //Necessary when Ajax deactivation button pressed
					wp_send_json_success( $status );
				}
			} else{
				//If license activation encounters error. Probably entered incorrect license key
				$status = esc_html__('Error deactivating license', 'woo-save-abandoned-carts');
				if(!empty($data['action'])){ //Necessary when Ajax deactivation button pressed
					wp_send_json_error( $status );
				}
			}

		}else{
			//If errors in response from the license server we output error message
			$status = esc_html__('Error deactivating license', 'woo-save-abandoned-carts');
			if(!empty($data['action'])){ //Necessary when Ajax deactivation button pressed
				wp_send_json_error( $status );
			}
		}

		return $status;
	}

	/**
	 * Check if license key is active or not
	 *
	 * @since    10.0
	 * @return   boolean
	 */
	function is_license_active(){
		return true;
	}

	/**
	 * Check if license key has expired or not
	 *
	 * @since    10.0
	 * @return   boolean
	 */
	function is_license_expired(){
		return false;
	}

	/**
	 * Output admin notices
	 *
	 * @since    9.2.1
	 */
	function display_notices(){
		$this->activate_license_notice();
		$this->display_wp_cron_warnings();
		$this->display_automation_notices();
	}
	
	/**
	 * Output notice in case the license key is not active or has expired
	 *
	 * @since    1.1
	 */
	function activate_license_notice(){

		if( $this->should_display_notice( 'missing_license' ) ){
			
			if ( isset( $_GET['tab'] ) ){
				
				if( $_GET['tab'] == 'settings' ){ //Do not display notice on Settings page
					return;
				}
			}
			
			$notice_contents = $this->get_notice_contents( 'missing_license' );
			$message = $notice_contents['description'];
			echo $this->get_notice_output( $message );

		}elseif( $this->should_display_notice( 'license_expired' ) ){
			$saved_cart_count = $this->get_closest_lowest_integer( $this->total_cartbounty_recoverable_cart_count() );
			$handle = 'cartbounty_pro_expired_notice';
			$message = $this->get_expired_license_message( 'expired_header_notice' );
			echo $this->get_notice_output( $message, $handle, $class = 'automation', true, 'close', $user_specific = true );
		
		}elseif( $this->should_display_notice( 'license_about_to_expire' ) ){
			$handle = 'cartbounty_pro_license_about_to_expire_notice';
			$message = $this->get_license_about_to_expire_message( 'license_about_to_expire_header_notice' );
			echo $this->get_notice_output( $message, $handle, $class = 'automation', true, 'close', $user_specific = true );
		}
	}

	/**
	 * Method shows warnings if any of the WP Cron events not scheduled or if the WP Cron has been disabled
	 *
	 * @since    3.3
	 */
	function display_wp_cron_warnings(){

		if( $this->action_scheduler_enabled() ) return; //Do not display WP Cron related messages in case WooCommerce Action scheduler is enabled

		$mailchimp = $this->mailchimp();
		$activecampaign = $this->activecampaign();
		$getresponse = $this->getresponse();
		$automation = $this->automation();
		$webhook = $this->webhook();

		if( $mailchimp->store_connected() || $activecampaign->store_connected() || $getresponse->store_connected() || $automation->automation_enabled( 'wordpress' ) || $automation->automation_enabled( 'bulkgate' ) || $automation->automation_enabled( 'push_notification' ) || $webhook->api_valid() ){ //Check if we have connected to MailChimp, ActiveCampaign, GetResponse, WordPress, BulkGate, Push notifications or Webhook automation
			//Checking if WP Cron hooks are scheduled
			$missing_hooks = array();
			$settings = $this->get_settings( 'settings' );
			$notification_frequency = $settings['notification_frequency'];
			$delete_anonymous_carts = $settings['delete_anonymous_carts'];
			$delete_coupons = $settings['delete_coupons'];

			if( wp_next_scheduled( 'cartbounty_pro_notification_sendout_hook' ) === false && $notification_frequency != 0 ){ //If we havent scheduled email notifications and notifications have not been disabled
				$missing_hooks[] = 'cartbounty_pro_notification_sendout_hook';
			}

			if( wp_next_scheduled( 'cartbounty_pro_delete_anonymous_carts_hook' ) === false && $delete_anonymous_carts != 0 ){ //If we havent scheduled email notifications and notifications have not been disabled
				$missing_hooks[] = 'cartbounty_pro_delete_anonymous_carts_hook';
			}

			if( wp_next_scheduled( 'cartbounty_pro_sync_hook' ) === false ){
				$missing_hooks[] = 'cartbounty_pro_sync_hook';
			}

			if( wp_next_scheduled( 'cartbounty_pro_delete_coupons_hook' ) === false && $delete_coupons ){ //If automated coupon deletion is enabled, but the hook is not scheduled, remove the hook
				$missing_hooks[] = 'cartbounty_pro_delete_coupons_hook';
			}

			if ( !empty( $missing_hooks ) ) { //If we have hooks that are not scheduled
				$hooks = '';
				$current = 1;
				$total = count( $missing_hooks );

				foreach( $missing_hooks as $missing_hook ){
					$hooks .= $missing_hook;
					
					if ( $current != $total ){
						$hooks .= ', ';
					}
					$current++;
				}

				$message = sprintf(
					/* translators: %s - Cron event name */
					wp_kses( _n( 'It seems that WP Cron event <strong>%s</strong> required for automation is not scheduled.', 'It seems that WP Cron events <strong>%s</strong> required for automation are not scheduled.', esc_html( $total ), 'woo-save-abandoned-carts' ), 'data' ), esc_html( $hooks ) ) . ' ' .
					sprintf(
					/* translators: %1$s - Plugin name, %2$s - Link start, %3$s - Link end */
					esc_html__( 'Please try disabling and enabling %1$s plugin. If this notice does not go away after that, please %2$sget in touch with us%3$s.', 'woo-save-abandoned-carts' ), esc_html( CARTBOUNTY_PRO_ABBREVIATION ), '<a href="'. esc_url( $this->get_trackable_link( CARTBOUNTY_PRO_SUPPORT_LINK, 'wp_cron_disabled' ) ) .'" target="_blank">', '</a>' );
				echo $this->get_notice_output( $message, $handle = '', 'warning' );
			}
		}

		//Checking if WP Cron is enabled
		if( defined( 'DISABLE_WP_CRON' ) ){
			
			if( DISABLE_WP_CRON == true ){
				$handle = 'cron_warning';
				$message = esc_html__( "WP Cron has been disabled. Several WordPress core features, such as checking for updates or sending notifications utilize this function. Please enable it or contact your system administrator to help you with this.", 'woo-save-abandoned-carts' );
				echo $this->get_notice_output( $message, $handle, $class = 'warning', true, 'close' );
			}
		}
	}

	/**
	 * Method shows next steps notice after connecting to an external recovery integration
	 *
	 * @since    9.2.1
	 */
	function display_automation_notices(){
		
		if( !$this->check_license() ){ //Exit in case license key is not activated
			return;
		}

		$activecampaign = $this->activecampaign();
		$getresponse = $this->getresponse();
		$mailchimp = $this->mailchimp();
		$integrations = array();

		if( $mailchimp->store_connected() ){
			$integrations[] = array(
				'handle'	=> 'mc_setup',
				'message'	=> sprintf(
					/* translators: %s - URL placeholder */
					esc_html__( 'Awesome! Now get back to MailChimp and setup your %sabandoned cart recovery automation processes%s and turn your visitors into customers :)', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( CARTBOUNTY_PRO_MAILCHIMP_SETUP_AUTOMATION_LINK ) .'" target="_blank" title="'. esc_attr__( 'Abandoned cart recovery automation process on MailChimp', 'woo-save-abandoned-carts' ) .'">', '</a>' )
			);
		}

		if( $activecampaign->store_connected() ){
			$api_access = $activecampaign->get_api_access();
			$url = $api_access['api_url'];
			$url = preg_match( '/https:\/\/(.+?)\./', $url, $first_part ); //Retrieving first part of the users account entered URL

			$integrations[] = array(
				'handle'	=> 'ac_setup',
				'message'	=> sprintf(
					/* translators: %s - URL placeholder */
					esc_html__( 'Excellent! Now return to ActiveCampaign to setup your %sabandoned cart recovery automation process%s and turn your visitors into customers :)', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( $first_part[0] ."activehosted.com/app/automations") .'" target="_blank" title="'. esc_attr__( 'Abandoned cart recovery automation process', 'woo-save-abandoned-carts' ) .'">', '</a>' )
			);
		}

		if( $getresponse->store_connected() ){
			$integrations[] = array(
				'handle'	=> 'gr_setup',
				'message'	=> sprintf(
					/* translators: %s - URL placeholder */
					esc_html__( 'Superb! You are just about ready to start sending out automated abandoned cart recovery reminders via GetResponse. Please get back to GetResponse to setup your %sabandoned cart recovery automation process%s and turn your visitors into customers :)', 'woo-save-abandoned-carts'), '<a href="'. esc_url( CARTBOUNTY_PRO_GETRESPONSE_SETUP_LINK ) .'" target="_blank" title="'. esc_attr__( 'Abandoned cart recovery automation process', 'woo-save-abandoned-carts' ) .'">', '</a>' )
			);
		}

		foreach ( $integrations as $key => $integration ) {
			echo $this->get_notice_output( $integration['message'], $integration['handle'], $class = 'automation', true, 'done' );
		}
	}

	/**
	 * Handling notice output
	 *
	 * @since    9.2.1
	 * @return   string
	 * @param    string   	$message   		Content of the message
	 * @param    string   	$handle   		Unique ID for the notice. Default empty
	 * @param    string   	$class   		Additional classes required for the notice. Default empty
	 * @param    boolean   	$submit   		Should a submit button be added or not. Default false
	 * @param    string   	$button_type    Type of the button (done or close). Default done
	 * @param    boolean   	$user_specific  Weather notice is saved in the user or global site level
	 */
	function get_notice_output( $message, $handle = '', $class = '', $submit = false, $button_type = 'done', $user_specific = false ){
		$closed = false;

		if( $user_specific ){

			if( isset( $_GET[$handle] ) ){ //Check if we should update the option and close the notice
				check_admin_referer( 'cartbounty-pro-notice-nonce', $handle ); //Exit in case security check is not passed
				update_user_meta( get_current_user_id(), $handle, 1 );
			}
			$closed = get_user_meta( get_current_user_id(), $handle, false );

		}else{

			$notice_options = $this->get_settings( 'submitted_warnings' );

			if( isset( $_GET[$handle] ) ){ //Check if we should update the option and close the notice
				check_admin_referer( 'cartbounty-pro-notice-nonce', $handle ); //Exit in case security check is not passed
				$notice_options[$handle] = true;
				update_option( 'cartbounty_pro_submitted_warnings', $notice_options );
			}

			if( isset( $notice_options[$handle] ) ){
				$closed = $notice_options[$handle];
			}
		}

		if( $closed ){ //Exit if notice previously has been already closed
			return;
		}

		$button = false;
		$button_text = esc_html__( 'Done', 'woo-save-abandoned-carts' );
		
		if( $button_type == 'close' ){
			$button_text = esc_html__( 'Close', 'woo-save-abandoned-carts' );
		}

		if( $submit ){
			$button = '<span class="cartbounty-pro-button-container"><a class="cartbounty-pro-close-header-notice cartbounty-pro-button button button-secondary cartbounty-pro-progress" href="'. esc_url( wp_nonce_url( add_query_arg( 'handle', $handle ), 'cartbounty-pro-notice-nonce', $handle ) ) .'">'. esc_html( $button_text ) .'</a></span>';
		}

		$output = '<div class="cartbounty-pro-notification notice updated '. esc_attr( $class ) .'">
			<p>'. $message .'</p>'. $button .'
		</div>';

		return $output;
	}

	/**
	 * Method for sending out email notification in order to notify about new abandoned carts and recovered
	 *
	 * @since    1.1
	 */
	function send_email(){
		if( !$this->check_license() ) return; //Exit if license key not valid

		$exclude_recovered_carts = $this->get_settings( 'settings', 'exclude_recovered' );
		$this->prepare_email( 'recoverable' );
		
		if( !$exclude_recovered_carts ){ //If we do not exclude recovered carts from emails
			$this->prepare_email( 'recovered' );
		}
	}

	/**
	 * Method prepares and sends the email
	 *
	 * @since    8.1
	 * @param    string   	$type   	The type of notification email
	 */
	private function prepare_email( $type ){
		global $wpdb;
		$public = $this->public();
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
		$time_intervals = $this->get_time_intervals();
		$time = $time_intervals['cart_abandoned'];
		$where_sentence = $this->get_where_sentence( $type );

		if($type == 'recovered'){
			$time = $time_intervals['cart_recovered'];
		}

		//Retrieve from database rows that have not been emailed and are older than 60 minutes
		$carts = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT email, phone, pn_subscription, cart_contents, cart_total, currency
				FROM $cart_table
				WHERE mail_sent = %d
				$where_sentence AND
				cart_contents != '' AND
				time < %s",
				0,
				$time
			)
		);

		$cart_count = count($carts);
		if(!$cart_count){
			return;
		}

		$to = esc_html(get_option( 'admin_email' ));
		$user_settings_email = $this->get_settings( 'settings', 'notification_email' ); //Retrieving email address if the user has entered one
		
		if(!empty($user_settings_email)){
			$to = esc_html($user_settings_email);
			$to_without_spaces = str_replace(' ', '', $to);
			$to = explode(',', $to_without_spaces);
		}
		
		$blog_name = get_option( 'blogname' );
		$admin_link = get_admin_url() .'admin.php?page='. CARTBOUNTY_PRO;

		if($type == 'recovered'){ //In case if we are sending notification email about newly recovered carts
			$subject = '['.$blog_name.'] '. esc_html( _n('Bounty! Cart recovered! 🤟', 'Bounty! Carts recovered! 🤑', $cart_count, 'woo-save-abandoned-carts') );
			$heading = esc_html( _n('Cart recovered! 🤟', 'Carts recovered! 🤑', $cart_count, 'woo-save-abandoned-carts') );
			$content = sprintf(
			/* translators: %1$d - Abandoned cart count, %2$s - Plugin name */
			esc_html( _n('Excellent, you have recovered an abandoned cart using %2$s.', 'Amazing, you have recovered %1$d abandoned carts using %2$s.', $cart_count, 'woo-save-abandoned-carts') ), esc_html( $cart_count ), esc_html( CARTBOUNTY_PRO_SHORT ) );
			$content .= ' ' . sprintf(
				/* translators: %s - Link tags */
				esc_html__('Please use %sthis link%s to see full information about your carts.', 'woo-save-abandoned-carts'), '<a href="' . esc_url( $admin_link ) . '">', '</a>');
			$button_color = '#20bca0';

		}else{
			$subject = '['.$blog_name.'] '. esc_html( _n('New abandoned cart saved! 🛒', 'New abandoned carts saved! 🛒', $cart_count, 'woo-save-abandoned-carts') );
			$heading = esc_html( _n('New abandoned cart!', 'New abandoned carts!', $cart_count, 'woo-save-abandoned-carts') );
			$content = sprintf(
			/* translators: %1$d - Abandoned cart count, %2$s - Plugin name */
			esc_html( _n('Great, you have saved a new recoverable abandoned cart using %2$s.', 'Congratulations, you have saved %1$d new recoverable abandoned carts using %2$s.', $cart_count, 'woo-save-abandoned-carts') ), esc_html( $cart_count ), esc_html( CARTBOUNTY_PRO_SHORT ) );
			$content .= ' ' . sprintf(
			/* translators: %s - Link tags */
			esc_html__('Please use %sthis link%s to see full information about your carts.', 'woo-save-abandoned-carts'), '<a href="' . esc_url( $admin_link ) . '">', '</a>');
			$button_color = '#aa88fc';
		}

		$main_color = '#ffffff';
		$text_color = '#000000';
		$background_color = '#f2f2f2';
		$footer_color = '#353535';
		$border_color = '#e9e8e8';
		
		$args = apply_filters(
			'cartbounty_pro_admin_notification_args',
			array(
				'carts'					=> $this->prepare_cart_rows($carts),
				'main_color'			=> $main_color,
				'button_color'			=> $button_color,
				'text_color'			=> $text_color,
				'background_color'		=> $background_color,
				'footer_color'			=> $footer_color,
				'border_color'			=> $border_color,
				'heading'				=> $heading,
				'content'				=> $content,
				'carts_link'			=> $admin_link
			)
		);

		ob_start();
		echo $public->get_template( 'cartbounty-pro-admin-email-notification.php', $args, false, plugin_dir_path( __FILE__ ) . '../templates/emails/');
		$message = ob_get_contents();
		ob_end_clean();

		$sender = 'WordPress@' . preg_replace( '#^www.#', '', $this->get_current_domain_name() );
		$header = array(
			'from' 			=> 'From: ' . esc_html( CARTBOUNTY_PRO_SHORT ) . ' <' . apply_filters( 'cartbounty_pro_from_email', esc_html( $sender ) ) . '>',
			'content-type'	=> 'Content-Type: text/html; charset="' . esc_attr( get_option( 'blog_charset' ) ) . '"'
		);

		$cc = apply_filters( 'cartbounty_pro_admin_notification_cc', '' );
		$bcc = apply_filters( 'cartbounty_pro_admin_notification_bcc', '' );
		
		if( !empty( $cc ) ){ //Add cc email address in case it is not empty
			$header['cc'] = 'Cc: ' . esc_html( $cc );
		}

		if( !empty( $bcc ) ){ //Add bcc email address in case it is not empty
			$header['bcc'] = 'Bcc: ' . esc_html( $bcc );
		}

		wp_mail( $to, esc_html($subject), $message, $header ); //Sending out email

		//Update mail_sent status to true with mail_status = 0 and are older than 60 minutes
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE $cart_table
				SET mail_sent = %d 
				WHERE mail_sent = %d
				$where_sentence AND
				cart_contents != '' AND
				time < %s",
				1,
				0,
				$time
			)
		);
	}

	/**
	 * Method retrieves Settings tab url
	 *
	 * @since    1.1
	 */
	public static function get_settings_tab_url(){
		$url = menu_page_url( CARTBOUNTY_PRO, false );
		$url = $url . '&tab=settings';
		return $url;
	}

	/**
	 * Method retrieves Carts tab url
	 *
	 * @since    10.0.2
	 */
	public static function get_carts_tab_url(){
		$url = menu_page_url( CARTBOUNTY_PRO, false );
		$url = $url . '&tab=carts';
		return $url;
	}

	/**
	 * Count products
	 *
	 * @since    4.0
	 */
	function product_count(){
		global $wpdb;
		if( $this->table_exists( 'product_table_exists' ) ){
	        $cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME_PRODUCTS;
	        $total_items = $wpdb->get_var("SELECT COUNT(product_id) FROM $cart_table");
	        return $total_items;
	    }else{
	    	return false;
	    }
	}

	/**
	 * Method checks if license is activated
	 *
	 * @since    1.2
	 * @return 	 Boolean
	 */
	public function check_license(){
		return true;
	}
	/**
	 * Retrieving plugin updates
	 * Checking for plugin updates every 12 hours
	 *
	 * @since    1.3
	 */
	function check_for_updates(){
		return;
	}

	/**
	 * Adds aditional arguments to check_for_updates() function
	 *
	 * @since    4.3
	 * @param    $queryArgs    Query arguments
	 */
	function add_license_to_update_request( $queryArgs ){
		$license = $this->get_settings( 'settings', 'license_key' );

	    if ( !empty( $license ) ) {
	    	$license = base64_encode( openssl_encrypt( $license, 'aes-128-ctr', CARTBOUNTY_PRO_LICENSE_ENCRYPTION_KEY, false, '1f5bcPa858kabNzc' ) ); //Encrypting the license key
	        $queryArgs['cartbounty_pro_license_key'] = esc_attr( $license );
	        $queryArgs['cartbounty_pro_server_name'] = esc_attr( $this->get_current_domain_name() );
	    }

	    return $queryArgs;
	}

	/**
	 * Adds custom action link on Plugin page under plugin name
	 *
	 * @since    1.2
	 * @param    $actions        Action
	 * @param    $plugin_file    Location of the plugin
	 */
	function add_plugin_action_links( $actions, $plugin_file ) {
		
		if ( !is_array( $actions ) ){
			return $actions;
		}

		$carts_tab = $this->get_carts_tab_url();
		
		$action_links = array();
		$action_links['cartbounty_pro_settings'] = array(
			'label' => esc_html__( 'Carts', 'woo-save-abandoned-carts' ),
			'url'   => $carts_tab
		);
		$action_links['cartbounty_pro_carts'] = array(
			'label' => esc_html__( 'Dashboard', 'woo-save-abandoned-carts' ),
			'url'   => menu_page_url( CARTBOUNTY_PRO, false )
		);

		return $this->add_display_plugin_action_links( $actions, $plugin_file, $action_links, 'before' );
	}

	/**
	 * Method that merges the links on Plugin page under plugin name
	 *
	 * @since    1.2
	 * @return   array
	 * @param    $actions        Action
	 * @param    $plugin_file    Location of the plugin
	 * @param    $action_links   Action links - array
	 * @param    $position       Position
	 */
	function add_display_plugin_action_links( $actions, $plugin_file, $action_links = array(), $position = 'after' ){
		static $plugin;
		if ( ! isset( $plugin ) ) {
			$plugin = CARTBOUNTY_PRO_BASENAME;
		}
		if ( $plugin === $plugin_file && ! empty( $action_links ) ) {
			foreach ( $action_links as $key => $value ) {
				$link = array( $key => '<a href="' . esc_url( $value['url'] ) . '">' . esc_html( $value['label'] ) . '</a>' );
				if ( 'after' === $position ) {
					$actions = array_merge( $actions, $link );
				} else {
					$actions = array_merge( $link, $actions );
				}
			}
		}
		return $actions;
	}

	/**
	 * Method checks the current plugin version with the one saved in database in order to handle database update when plugin is activated
	 * since WordPress doesn't run the database update function automatically on plugin update
	 *
	 * @since    1.4.1
	 */
	 
	function check_version(){
		$misc_settings = $this->get_settings( 'misc_settings' );

		if( CARTBOUNTY_PRO_VERSION_NUMBER == $misc_settings['version_number'] ){ //If database version is equal to plugin version. Not updating database
			return;

		}else{ //Versions are different and we must update the database
			$misc_settings['version_number'] = CARTBOUNTY_PRO_VERSION_NUMBER;
			update_option( 'cartbounty_pro_misc_settings', $misc_settings );
			activate_cartbounty_pro(); //Function that updates the database
			return;
		}
	}

	/**
	 * Sets the path to language folder for internationalization
	 *
	 * @since    1.4.1
	 */
	function cartbounty_pro_text_domain(){
		return load_plugin_textdomain( 'woo-save-abandoned-carts', false, basename( plugin_dir_path( __DIR__ ) ) . '/languages' );
	}
	
	/**
	 * Checks if we have to disable input field or not because of the users access right to save data
	 *
	 * @since    2.0.2
	 * @return   string
	 * @param    $options    Options
	 */
	function disable_field( $options = array() ){
		$status = '';
		if($options){
			if($options['forced'] == true){
				$status = 'disabled=""';
			}
		}
		elseif( !$this->user_is_admin() ){
			$status = 'disabled=""';
		}
		return $status;
	}

	/**
	 * Check if notice has been submitted or not
	 *
	 * @since    10.0
	 * @return   boolean
	 * @param    string    		$notice_type        Notice type
	 */
	function is_notice_submitted( $notice_type ){
		$result = false;
		$submitted_notices = get_option( 'cartbounty_pro_submitted_notices' );

		if( isset( $submitted_notices[$notice_type] ) ){
			$result = true;
		}

		return $result;
	}

	/**
	 * Method outputs bubble content
	 *
	 * @since    3.1.0
	 */
	function output_bubble_content(){
		$tab = $this->get_open_tab();

		if( $tab == 'carts' ){ //If we should display this bubble
			$review_bubble = $this->draw_bubble( 'review' );
			echo $content = $this->prepare_notice( 'review' );

			if( $review_bubble ){ //If we should display this bubble
				echo $review_bubble;
			}
		}
	}

	/**
	 * Show bubble slide-out window
	 *
	 * @since    3.1.0
	 * @return   false / HTML
	 * @param    string    	$notice_type        Notice type
	 */
	function draw_bubble( $notice_type ){
		$result = false;

		if( $this->should_display_notice( $notice_type ) ){ //Checking if we should display the bubble
			$notice_id = '#cartbounty-pro-notice-' . $notice_type;
			ob_start(); ?>
			<script>
				jQuery(document).ready(function($) {
					var bubble = $(<?php echo "'". $notice_id ."'"; ?>);
					var close = $('.cartbounty-pro-close, .cartbounty-pro-notice-done');
					
					//Function loads the bubble after a given time period in seconds	
					setTimeout(function() {
						bubble.addClass('cartbounty-pro-show-bubble');
					}, 2500);
				});
			</script>
			<?php
			$result .= ob_get_contents();
			ob_end_clean();
		}

		return $result;
	}

	/**
	 * Handles notice actions (dashboard and bubble notices)
	 *
	 * @since    9.3.1
	 */
	function handle_notices(){

		if ( check_ajax_referer( 'notice_nonce', 'nonce', false ) == false ) { //If the request does not include our nonce security check, stop executing function
			wp_send_json_error(esc_html__( 'Looks like you are not allowed to do this.', 'woo-save-abandoned-carts' ) );
		}

		if( !( isset( $_POST['type'] ) && isset( $_POST['operation'] ) ) ){ //Stop if missing necessary data
			wp_send_json_error(esc_html__( 'Something is wrong.', 'woo-save-abandoned-carts' ) );
		}

		$notice_type = sanitize_text_field( $_POST['type'] );
		$operation = sanitize_text_field( $_POST['operation'] );
		$submitted_notices = get_option( 'cartbounty_pro_submitted_notices' );
		$misc_settings = $this->get_settings( 'misc_settings' );
		
		if( empty( $submitted_notices ) ){
			$submitted_notices = array();
		}

		switch( $notice_type ){
			case 'license_expired':
			case 'license_about_to_expire':

				if( $operation == 'declined' ){
					$submitted_notices[$notice_type] = 1;
					update_option( 'cartbounty_pro_submitted_notices', $submitted_notices ); //Update option that the review has been added
					wp_send_json_success();

				}
				break;

			case 'review':

				if( $operation == 'submitted' ){
					$submitted_notices[$notice_type] = 1;
					update_option( 'cartbounty_pro_submitted_notices', $submitted_notices ); //Update option that the review has been added
					wp_send_json_success();

				}elseif( $operation == 'declined' ){
					$level = $this->get_achieved_review_level();
					
					if( $level > 0 ){
						$misc_settings['times_review_declined'] = $level;
						update_option( 'cartbounty_pro_misc_settings', $misc_settings ); //Update declined count according to the current level
						wp_send_json_success();
					}
				}
				break;
		}
	}

	/**
	 * Clear notice
	 *
	 * @since    10.1
	 * @param    string    			$notice_type        		Notice type
	 */
	function clear_notice( $notice_type ){

		$submitted_notices = get_option( 'cartbounty_pro_submitted_notices', array() );

		switch( $notice_type ){

			case 'license_expired':
			case 'license_about_to_expire':
				unset( $submitted_notices[$notice_type] );
				update_option( 'cartbounty_pro_submitted_notices', $submitted_notices ); //Update option that the review has been added

				//Clearing all user specific notifications for Administrators and Shop managers
				$user_ids = get_users( array(
					'role__in' => array( 'administrator', 'shop_manager' ),
					'fields'   => 'ID',
				) );

				foreach ( $user_ids as $user_id ) {
					delete_metadata( 'user', $user_id, 'cartbounty_pro_expired_notice', '', true );
					delete_metadata( 'user', $user_id, 'cartbounty_pro_license_about_to_expire_notice', '', true );
				}
					
				break;
		}
	}

	/**
	 * Returns the count of total captured abandoned carts
	 *
	 * @since    3.3
	 * @return 	 integer
	 */
	function total_cartbounty_recoverable_cart_count(){
		$count = $this->get_settings( 'misc_settings', 'recoverable_carts' );
		return $count;
	}

	/**
	 * Retrieves the closest and lowest rounded integer number
	 * If number is 1, return 1
	 * If number is smaller than 5, output number - 1
	 * If number is smaller than 10, output 5
	 * If number is anything else, output lowest integer
	 *
	 * @since    9.7.4.3
	 * @return 	 integer
	 */
	function get_closest_lowest_integer( $number ){

		if( empty( $number ) ){
			$number = 0;

		}elseif( $number == 1 ){
			$number = 1;

		}elseif( $number <= 5 ){
			$number = $number - 1;

		}elseif( $number <= 10 ){
			$number = 5;

		}else{
			$number = floor( ( $number - 1 ) / 10 ) * 10;
		}

		return $number;
	}

	/**
	 * Method exports plugin abandoned cart table to a CSV file
	 *
	 * @since    3.2
	 */
	function export_cartbounty_pro_carts(){

		//Checking if the Export carts button was submited and the user has rights to do that
		if( empty( $_POST['cartbounty_pro_export_carts']) || 'cartbounty_pro_export_c' != $_POST['cartbounty_pro_export_carts']) return;

		if( !$this->user_is_admin() ) return; //Checking if the user has rights to Export tables

		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
		$columns = apply_filters( 'cartbounty_pro_export_columns', '*' );
		$delimiter = apply_filters( 'cartbounty_pro_export_delimiter', '^' );
		
		$rows = $wpdb->get_results(
			"SELECT $columns
			FROM $cart_table"
		);

		$serialized_data = array(
			'cart_contents',
			'location',
			'other_fields',
			'pn_subscription',
			'coupons',
			'refferals',
		);

		if( $rows ){ //If we have rows in the table
			$csv_rows = array();

			//Building CSV file header
			foreach( $rows as $row => $values ){
			    $csv_header_row = array();

				foreach( $values as $key => $value ){ //Looping through object values to build CSV header
					$csv_header_row[] = $key;
				}

				if( $this->check_columns( $columns, array( 'id', 'session_id', 'email' ) ) ){ //Add recovery_link to exported file only in case id, session_id and email fields are present
					$csv_header_row[] = 'recovery_link'; //Inserting virtual column for exporting abandoned cart recovery link
				}
				
			    break; //Break foreach loop after first row is ready as this is our header
			}

			//Looping through the row contents necessary for CSV body
			foreach( $rows as $row => $values ){
				$csv_output = array();

				foreach( $values as $key => $value ){ //Looping through object values to build CSV body

					$currency = $values->currency;

					if( in_array( $key, $serialized_data ) && is_serialized( $value ) ){ //Converting serialized contents to a CSV friendly format
					
						$value = maybe_unserialize( $value );
						
						if( empty( $value ) ){
							$csv_output[] = '';

						}else{
							
							$output = '';

							if( !apply_filters( 'cartbounty_pro_export_raw_data', false ) ){ //Export data as stored in DB or in a more user friendly manner

								if( $key == 'cart_contents' ){ //In case exporting cart contents
									$cart_contents = $this->get_saved_cart_contents( $value );
									$total_products = count( $cart_contents );
									$i = 0;

									foreach( $cart_contents as $product ){

										if( is_array( $product ) ){

											if( isset( $product['product_title'] ) ){
												$product_title = esc_html( $product['product_title'] );
												$quantity = " (". $product['quantity'] .")"; //Enclose product quantity in brackets
												$product_price = $this->get_product_price( $product );
												$price = ', ' . $product_price . ' ' . esc_html( $currency );
												$product_title_line = $product_title . $price . $quantity;
												$output .= esc_html( $product_title_line );

												$i++;

												if( $total_products > $i ){
													$output .= $delimiter;
												}
											}
										}
									}

								}else{ //In case exporting any other serialized data like location, other_fields etc.
									$formatted_data = array();

									if( is_array( $value ) ){
										
										foreach( $value as $key => $item ){

											if( is_array( $item ) ){
												$item = json_encode( $item, JSON_UNESCAPED_UNICODE );
											}

											$formatted_data[] = $key . '=' . $item;
										}

										$comma_delimited_string = implode( $delimiter, $formatted_data );
										$output = $comma_delimited_string;
									}
								}

							}else{
								$output = json_encode( $value, JSON_UNESCAPED_UNICODE ); //Using JSON_UNESCAPED_UNICODE because otherwise UTF-8 characters would be converted to hexadecimal values
							}

							$csv_output[] = $output;
						}
						
					}else{
						$csv_output[] = $value;
					}
				}

				if( $this->check_columns( $columns, array( 'id', 'session_id', 'email' ) ) ){ //Add recovery_link to exported file only in case id, session_id and email fields are present
					$csv_output[] = $this->create_cart_url( $values->email, $values->session_id, $values->id ); //Inserting virtual column at the end of the row for exporting abandoned cart recovery link
				}

				$csv_rows[] = $csv_output;
			}

			$this->generate_csv_file( $csv_header_row, $csv_rows, 'carts' );
		}
	}

	/**
	 * Method exports plugin products or coupon table to a CSV file
	 *
	 * @since    9.2.3
	 */
	function export_cartbounty_meta(){
		if( !$this->user_is_admin() ) //Checking if the user has rights to Export tables
			return;

		global $wpdb;
		if( isset($_POST['cartbounty_pro_export_products']) ){
			$table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME_PRODUCTS;
			$name = 'products';
		}elseif( isset($_POST['cartbounty_pro_export_coupons']) ){
			$table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME_COUPONS;
			$name = 'coupons';
		}elseif( isset($_POST['cartbounty_pro_export_emails']) ){
			$table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME_EMAILS;
			$name = 'emails';
		}elseif( isset($_POST['cartbounty_pro_export_messages']) ){
			$table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME_MESSAGES;
			$name = 'text_messages';
		}elseif( isset($_POST['cartbounty_pro_export_push_notifications']) ){
			$table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME_NOTIFICATIONS;
			$name = 'push_notifications';
		}else{ //Exit in case export products or coupons button has not been pressed
			return;
		}
		
		$rows = $wpdb->get_results( "SELECT * FROM $table" );
		if($rows){ //If we have rows in the table
			$csv_rows = array();

			//Building CSV file header
			foreach($rows as $row => $values){
			    $csv_header_row = array();
				foreach($values as $key => $value){ //Looping through object values to build CSV header
					$csv_header_row[] = $key;
				}
				break; //Break foreach loop after first row is ready as this is our header
			}

			//Looping through the row contents necessary for CSV body
			foreach($rows as $row => $values){
				$csv_output = array();
				foreach($values as $key => $value){ //Looping through object values to build CSV body
					$csv_output[] = $value;
				}
				$csv_rows[] = $csv_output;
			}

			$this->generate_csv_file( $csv_header_row, $csv_rows, $name );
		}
	}

	/**
	 * Method creates CSV file from given information
	 *
	 * $csv_header_row	= Table header column values, array
	 * $csv_rows		= Table rows that hold table contents, array
	 * $cart_table		= Name of the table being exported, string
	 *
	 * @since    3.2
	 * @param    $csv_header_row    Table header row
	 * @param    $csv_rows          Table rows
	 * @param    $cart_table        Name of the table
	 */
	function generate_csv_file( $csv_header_row, $csv_rows, $cart_table ){

		//Creating the CSV file output
		$filename = CARTBOUNTY_PRO."_". $cart_table ."_".date("Y-m-d_H-i",time());

		//Define CSV file header compatible with MS Excel
		header('Pragma: public');
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Content-Description: File Transfer');
		header('Content-Type: text/csv');
		header('Content-Disposition: attachment; filename='.$filename.'.csv');
		header('Content-Transfer-Encoding: binary');
		
		$output = fopen('php://output', 'w'); //Open file pointer to standard output
		fputs($output, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) )); //Add BOM to fix UTF-8 in Excel
		
		fputcsv( $output, $csv_header_row, ';'); //Outputting header row
		foreach($csv_rows as $csv_row){ //Looping through array to output each array in a sepparate row
			fputcsv( $output, $csv_row, ';'); //Outputting the content rows
		}
		fclose( $output );
		exit;
	}

	/**
	 * Check if provided string includes specific fields
	 *
	 * @since    9.7.4.3
	 * @return 	 Boolean
	 * @param    string        $columns            String of comma sepparated fields
	 * @param    array         $fields             Array of fields that we are looking to find
	 */
	function check_columns( $columns, $fields ){
		$result = true;

		if( $columns != '*' ){
			$columns = str_replace( ' ', '', $columns ); //Remove whitespaces from string
			$columns = explode( ',', $columns ); //Convert string to array
			$found_values = array_intersect( $columns, $fields );

			if( count( $found_values ) != count( $fields ) ){ //In case did not find all values in search array
				$result = false;
			}
		}

		return $result;

	}

	/**
	 * Method removes empty abandoned carts
	 * First removing carts that are anonymous and do not have cart contents
	 * Then deleting recoverable carts without cart contents
	 * Next looking for ordered carts and updating them to ordered-deducted carts and decreasing recoverable cart count
	 * Finally deleting ordered deducted carts from database since they have never really been abandoned (customer placed items, CartBounty saved them and user went through with purchase)
	 *
	 * @since    4.0
	 */
	function delete_empty_carts(){
		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
		$time = $this->get_time_intervals();
		$public = $this->public();
		$where_sentence = $this->get_where_sentence( 'anonymous' );

		//Deleting anonymous rows with empty cart contents from database first
		$anonymous_cart_count = $wpdb->query(
			$wpdb->prepare(
				"DELETE FROM $cart_table
				WHERE cart_contents = ''
				$where_sentence AND
				time < %s",
				$time['cart_abandoned']
			)
		);

		$public->decrease_anonymous_cart_count( $anonymous_cart_count );

		//Deleting recoverable abandoned carts without products
		$recoverable_empty_cart_count = $wpdb->query(
			$wpdb->prepare(
				"DELETE FROM $cart_table
				WHERE cart_contents = '' AND
				time < %s",
				$time['cart_abandoned']
			)
		);

		//Updating ordered carts as ordered-deducted carts
		//This way we can immediately decrease recoverable cart count and leave them with other abandoned carts
		//This can be useful if we would like to search cart history to look if a specific coupon code has been used by a specific email address before
		$ordered_cart_count = $wpdb->query(
			$wpdb->prepare(
				"UPDATE {$cart_table}
				SET type = %d
				WHERE type = %d AND
				time < %s",
				$this->get_cart_type( 'ordered_deducted' ),
				$this->get_cart_type( 'ordered' ),
				$time['cart_abandoned']
			)
		);

		$public->decrease_recoverable_cart_count( $recoverable_empty_cart_count + $ordered_cart_count ); //Decreasing recoverable cart count by a number that consists of both ordered cart and recoverable empty cart counts

		//Deleting ordered-deducted carts from database since they have never really been abandoned (user has added an item to cart and placed an order without abandoneding the cart)
		$ordered_deducted_cart_count = $wpdb->query(
			$wpdb->prepare(
				"DELETE FROM $cart_table
				WHERE type = %d AND
				time < %s",
				$this->get_cart_type( 'ordered_deducted' ),
				$time['anonymization_period']
			)
		);
	}

	/**
	 * Method to clear cart data from row
	 *
	 * @since    1.3
	 */
	function clear_cart_data(){
		//If a new Order is added from the WooCommerce admin panel, we must check if WooCommerce session is set. Otherwise we would get a Fatal error.
		if( !isset( WC()->session ) ){
			$this->log('info', esc_html( CARTBOUNTY_PRO_SHORT ) . ': ' . 'Unable to clear cart data: WooCommerce session not found' );
			return;
		}

		if( WC()->session->get( 'cartbounty_pro_order_placed' ) ){ //If user created a new order - do not clear the cart for the first time in case of a quick checkout form submission or else the cart is cleared
			WC()->session->__unset( 'cartbounty_pro_order_placed' );
			return;
		}

		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
		$public = $this->public();
		$cart = $public->read_cart();

		if( !isset( $cart['session_id'] ) ){
			$this->log('info', esc_html( CARTBOUNTY_PRO_SHORT ) . ': ' . 'Unable to clear cart data: cart session_id not set' );
			return;
		}
		
		//Cleaning Cart data
		$update_result = $wpdb->query(
			$wpdb->prepare(
				"UPDATE $cart_table
				SET cart_contents = '',
				cart_total = %d,
				currency = %s,
				time = %s
				WHERE session_id = %s AND
				(type = %d OR type = %d)",
				0,
				sanitize_text_field( $cart['cart_currency'] ),
				sanitize_text_field( $cart['current_time'] ),
				$cart['session_id'],
				$this->get_cart_type('abandoned'),
				$this->get_cart_type('recovered_pending')
			)
		);

		if (false === $update_result) { //If there has been an error updating the database
			$this->log('info', esc_html( CARTBOUNTY_PRO_SHORT ) . ': ' . sprintf( 'Unable to clear cart data: Row update failed. Cart session_id = %s', esc_html( $cart['session_id'] ) ) );

		}elseif($update_result > 0){
			$this->log('info', esc_html( CARTBOUNTY_PRO_SHORT ) . ': ' . sprintf( 'Clearing cart data: Success. Cart session_id = %s', esc_html( $cart['session_id'] ) ) );

		}else{ //In case if no rows were updated
			$this->log('info', esc_html( CARTBOUNTY_PRO_SHORT ) . ': ' . sprintf( 'Unable to clear cart data: No rows were updated. Cart session_id = %s', esc_html( $cart['session_id'] ) ) );
		}
	}

	/**
	 * Resetting abandoned cart data in case if a registered user has an existing abandoned cart and updates his data on his Account page
	 *
	 * @since    8.2.2
	 */
	public function reset_abandoned_cart(){
		
		if( !is_user_logged_in() ) return; //Exit in case the user is not logged in

		global $wpdb;
		$user_id = 0;

		if( !empty( $_POST['user_id'] ) && is_numeric( $_POST['user_id'] ) ){ //In case the user's data is updated from WordPress admin dashboard "Edit profile page"
			$user_id = $_POST['user_id'];

		}elseif( !empty( $_POST['action'] ) ){ //This check is to prevent profile update to be fired after a new Order is created since no "action" is provided and the user's ID remains 0 and we exit resetting of the abandoned cart
			$user_id = get_current_user_id();
		}

		if( !$user_id ) return; //Exit in case we do not have user's ID value

		$public = $this->public();
		$cart = array(
			'session_id' 	=> $user_id,
			'cart_contents' => '',
		);

		if( $public->cart_saved( $cart, $ip_address = '', $ignore_cooldown = true ) ){ //If we have saved an abandoned cart for the user - go ahead and reset in case it has been abandoned or payment is still pending
			$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
			$updated_rows = $wpdb->query(
				$wpdb->prepare(
					"UPDATE $cart_table
					SET name = '',
					surname = '',
					email = '',
					phone = '',
					location = '',
					cart_contents = '',
					cart_total = '',
					currency = '',
					time = '',
					other_fields = ''
					WHERE session_id = %s AND
					type != %d",
					$user_id,
					$this->get_cart_type( 'recovered' )
				)
			);
		}
	}

	/**
	 * Method returns different expressions depending on the amount of captured carts
	 *
	 * @since    4.1.2
	 * @return 	 String
	 */
	function get_expressions(){
		if($this->total_cartbounty_recoverable_cart_count() <= 10){
			$expressions = array(
				'exclamation' => esc_html__('Congrats!', 'woo-save-abandoned-carts')
			);
		}elseif($this->total_cartbounty_recoverable_cart_count() <= 30){
			$expressions = array(
				'exclamation' => esc_html__('Awesome!', 'woo-save-abandoned-carts')
			);
		}elseif($this->total_cartbounty_recoverable_cart_count() <= 100){
			$expressions = array(
				'exclamation' => esc_html__('Amazing!', 'woo-save-abandoned-carts')
			);
		}elseif($this->total_cartbounty_recoverable_cart_count() <= 300){
			$expressions = array(
				'exclamation' => esc_html__('Incredible!', 'woo-save-abandoned-carts')
			);
		}elseif($this->total_cartbounty_recoverable_cart_count() <= 500){
			$expressions = array(
				'exclamation' => esc_html__('Wow!', 'woo-save-abandoned-carts')
			);
		}elseif($this->total_cartbounty_recoverable_cart_count() <= 1000){
			$expressions = array(
				'exclamation' => esc_html__('Fantastic!', 'woo-save-abandoned-carts')
			);
		}else{
			$expressions = array(
				'exclamation' => esc_html__('Insane!', 'woo-save-abandoned-carts')
			);
		}
		return $expressions;
	}

    /**
	 * Handle reCAPTCHA saved values
	 *
	 * @since    4.2
	 * @return   Array
	 */
	function get_recaptcha(){
		$recaptcha_array = array();
		$recaptcha = $this->get_settings( 'settings', 'recaptcha' );

		if(isset($recaptcha['status'])){
			$recaptcha_array['status'] = $recaptcha['status'];
		}else{
			$recaptcha_array['status'] = 0;
		}

		if(isset($recaptcha['site_key'])){
			$recaptcha_array['site_key'] = $recaptcha['site_key'];
		}else{
			$recaptcha_array['site_key'] = false;
		}

		if(isset($recaptcha['secret_key'])){
			$recaptcha_array['secret_key'] = $recaptcha['secret_key'];
		}else{
			$recaptcha_array['secret_key'] = false;
		}

		if(!$recaptcha_array['status'] || !$recaptcha_array['site_key'] || !$recaptcha_array['secret_key']){
			$recaptcha_array['enabled'] = false;
		}else{
			$recaptcha_array['enabled'] = true;
		}

		return $recaptcha_array;
	}

	/**
	 * Outputs debugging information to WooCommerce log
	 *
	 * @since    4.2
	 * @param    $level    Log level - string
	 * @param    $message  Message to output
	 */
	function log( $level, $message ){
		if( !class_exists( 'WooCommerce' ) ) return; //If WooCommerce does not exist

		if( $this->get_settings( 'settings', 'logging_status' ) ){
			$logger = wc_get_logger();
			$woocommerce_log_name = array( 'source' => CARTBOUNTY_PRO_PLUGIN_NAME_SLUG );
			$logger->log( $level, $message, $woocommerce_log_name );
		}
	}

	/**
	 * Method reads GET parameter from the link to restore the cart
	 * At first all products from the cart are removed and then populated with those that were previously saved
	 *
	 * @since    2.0
	 */
	function restore_cart(){

		if( !class_exists( 'WooCommerce' ) ) return;

		global $wpdb;
		$automation = $this->automation();
		$recovery = '';
		$shortlink = false;
		$unsubscribe_request = false;
		$shortlink_recovery = false;
		$shortlink_coupon = false;
		$step_nr = false;
		$mc_cid = false;
		$gr_m = false;

		//Determine where the recovery type request origintated from
		if( isset( $_GET['recovery'] ) ){
			$recovery = $_GET['recovery'];
		}
		
		//Checking if CartBounty argument is present in the link. If not - exit
		if ( !empty( $_GET['cartbounty-pro'] ) ){ //In the case of a default link
			$link = trim( $_GET['cartbounty-pro'], '.,;:!?' ); //Remove special characters from the beginning and end of the string
			$encryption = 'sha256';
			$field = 'email';
			$hash_id = sanitize_text_field( $link ); //Getting and sanitizing value from the link
			$parts = explode( '-', $hash_id ); //Splitting GET value into hash and ID
			$hash = $parts[0];
			$id = $parts[1];

			//Determine recovery step
			if( isset( $_GET['step'] ) ){
				$step_nr = (int)$_GET['step'];
			}

		}elseif( !empty( $_GET['cb'] ) ){ //If this is shortlink
			$link = trim( $_GET['cb'], '.,;:!?' ); //Remove special characters from the beginning and end of the string
			$shortlink = true;
			$encryption = 'sha1';
			$field = 'phone';
			$first_char = substr( sanitize_text_field( $link ), 0, 1 ); //The first character identifies recovery which has generated the link
			$hash = substr( $link, 1, 5 ); //Hash is 5 characters long and starts after first character
			$link_end = substr( $link, 6 ); //Get the end of the link which includes cart ID and step number data
			$id = substr( $link_end, 0, -1 ); //Cart ID
			$step_nr = (int)substr( $link_end, -1 ); //automation step number is in the last position
			$recovery = 'bulkgate';

			if( $first_char == 'U' ){ //If this is unsubscribe request
				$unsubscribe_request = true;

			}elseif( $first_char == 'B' ){ //In case we are dealing with a shortlink originating from BulkGate
				$shortlink_recovery = true;
			}

		}else{
			return;
		}

		//Check if there is tracking data
		if (!empty( $_GET['mc_cid'] )){
			$mc_cid = sanitize_text_field($_GET['mc_cid']); //Getting and sanitizing MailChimp Campaign ID for tracking purposes
		}

		if (!empty( $_GET['gr_m'] )){
			$gr_m = sanitize_text_field($_GET['gr_m']); //Getting and sanitizing GetResponse Campaign ID for tracking purposes
		}

		//Retrieve row from the abandoned cart table in order to check if hashes match
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
		$row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT id, email, phone, session_id, refferals, coupons, language, cart_contents, cart_meta
				FROM $cart_table
				WHERE id = %d AND
				type != %d",
				$id,
				$this->get_cart_type('recovered')
			)
		);

		if( empty( $row ) ) return; //Exit function if no row found

		//Checking if hashes match
		$row_hash = hash_hmac( $encryption, $row->$field . $row->session_id, CARTBOUNTY_PRO_ENCRYPTION_KEY ); //Building encrypted hash from the row
		if( $shortlink ){ //If dealing with a shortlink - leave just only first 5 symbols for comparison
			$row_hash = substr( $row_hash , 0, 5 );
		}

		if( !hash_equals( $hash, $row_hash ) ) return; //If hashes do not match, exit function

		//If we have received an Unsubscribe request - stop restoring cart and unsubscribe user instead
		if( isset( $_GET['cartbounty-pro-unsubscribe'] ) || $unsubscribe_request ){

			if( $recovery || $unsubscribe_request ){
				$this->unsubscribe_user( $id, $step_nr, $recovery );
				$message_type = esc_html__( 'emails', 'woo-save-abandoned-carts' );
				
				if ( $recovery == 'sms' ){
					$message_type = esc_html__( 'text messages', 'woo-save-abandoned-carts' );
				}

				wp_die( 
					sprintf(
						/* translators: %s - Message type e.g. email */
						esc_html__( 'You have successfully unsubscribed from further %s about your shopping cart.', 'woo-save-abandoned-carts' ), esc_html( $message_type )
					), esc_html__( 'Successfully unsubscribed', 'woo-save-abandoned-carts'), $args = array( 'link_url' => get_site_url(), 'link_text' => esc_html__( 'Return to store', 'woo-save-abandoned-carts') ) );
			}
		}

		$this->maybe_auto_login_user( $row, $step_nr, $recovery );

		//Update email stats in case link contains recovery click tracking information (in the case of WordPress and Bulkgate)
		if ( isset( $_GET['step'] ) || $shortlink_recovery ){
			if( $recovery ){
				$automation->handle_message_stats( 'click', $row->id, $step_nr, $recovery );
			}
		}

		$this->build_cart( $row, $ignore = false, $mc_cid, $gr_m, $step_nr, $recovery ); //Restore cart with previous products
		$this->restore_custom_product_fields( $row->cart_meta );
		$this->auto_apply_coupon( $row->coupons, $recovery, $step_nr );

		//Redirecting user to Checkout page
		$checkout_url = $this->get_landing_url( $row->language );
		wp_redirect( $checkout_url, '303' );
		exit();
	}

	/**
	 * Method restores previously saved custom product fields
	 *
	 * @since    10.1.1
	 * @param    array     $cart_contents   	Cart contents
	 */
	function restore_custom_product_fields( $cart_meta ){

		if( $cart_meta ){
			$cart_meta = $this->get_saved_cart_contents( $cart_meta );

			if( $cart_meta ){
				//Handling WooCommerce Product Bundle products
				//Excluding incomplete object classes (in case WooCommerce Product Bundle plugin disabled)
				foreach( $cart_meta as $key => $item ){

					if( is_object( $item['data'] ) ){

						if( get_class( $item['data'] ) == '__PHP_Incomplete_Class' ){
							unset( $cart_meta[$key] );
						}
					}
				}

				WC()->cart->set_cart_contents( $cart_meta ); //Used in oder to restore Custom product fields (Product addons)
			}
		}
	}

	/**
	 * Method automatically logs-in a registered user if the following conditions are passed:
	 *   - Magic sign in is enabled
	 *   - user has an active account
	 *   - user role is correct (by default non-admin roles are allowed e.g. customer, subscriber)
	 *   - reminder link has not been previously clicked (can be disabled via settings)
	 *   - a specific time period has not passed between when the message was sent and when it got opened (by default 2 days)
	 *
	 * @since    10.9
	 * @param    object     $cart   		    Cart data
	 * @param    integer    $step_nr            Automation step number
	 * @param    string     $recovery			Recovery type e.g. ActiveCampaign, WordPress etc.
	 */
	function maybe_auto_login_user( $cart, $step_nr, $recovery ){
		$settings = $this->get_settings( 'settings' );
		$magic_login_enabled = $settings['magic_login'];
		$magic_login_first_click_enabled = $settings['magic_login_first_click'];
		$allowed_roles = $settings['magic_login_roles'];

		if( $magic_login_enabled ){
			$user = get_userdata( (int) $cart->session_id );

			if( empty( $user->roles ) ) return; //If no roles are present

			$roles = $user->roles;

			if( !array_intersect( $roles, $allowed_roles ) ){ //Auto login only allowed roles
				$this->log(
					'notice', sprintf(
						esc_html( 'Magic login canceled: Current user role not allowed. User ID: %d, Recovery: %s, Step Nr: %d', 'woo-save-abandoned-carts' ),
						esc_html( (int)$cart->session_id ),
						esc_html( $recovery ),
						esc_html( $step_nr ),
					)
				);
				return;
			}

			$automation = $this->automation();

			if( $magic_login_first_click_enabled ){

				if( $automation->message_recovery_link_clicked( $recovery, $cart->id, $step_nr ) ){ //Auto login only if link was not opened before
					$this->log(
						'notice', sprintf(
							esc_html( 'Magic login canceled: Link has already been clicked before. User ID: %d, Recovery: %s, Step Nr: %d', 'woo-save-abandoned-carts' ),
							esc_html( (int)$cart->session_id ),
							esc_html( $recovery ),
							esc_html( $step_nr ),
						)
					);
					return;
				}
			}

			if( !$automation->message_sent_recently( $recovery, $cart->id, $step_nr ) ){ //Stop if message has not been sent recently
				$this->log(
					'notice', sprintf(
						esc_html( 'Magic login canceled: Link has passed expiration period. User ID: %d, Recovery: %s, Step Nr: %d', 'woo-save-abandoned-carts' ),
						esc_html( (int)$cart->session_id ),
						esc_html( $recovery ),
						esc_html( $step_nr ),
					)
				);
				return;
			}

			$user_login = $user->data->user_login;
			wp_set_auth_cookie( $cart->session_id );
			do_action( 'wp_login', $user_login, $user );
		}
	}

	/**
	 * Get landing page URL where the user is taken after returning from a reminder email
	 *
	 * @since    9.6
	 * @return   string
	 * @param    string     $language   	User's language code, e.g. 'de_DE'
	 */
	public function get_landing_url( $language = '' ){
		
		if( !class_exists( 'WooCommerce' ) ) return; //Exit if WooCommerce not active

		$url = apply_filters( 'cartbounty_pro_landing_url', 'checkout' );

		if( $url == 'checkout' ){ //Checkout URL
			$url = wc_get_checkout_url();
		
		}elseif( $url == 'cart' ){ //Cart URL
			$url = wc_get_cart_url();

		}else{ //Custom URL
			$url = $url;
		}

		$url = $this->retrieve_language_specific_url( $url, $language );

		return $url;
	}

	/**
	 * Preparing URL according to customer's previous language preference
	 * Currently Supporting WPML and TranslatePress.
	 * Loco translate does not provide a language switcher therefore this function is not relevant at the moment for it.
	 *
	 * @since    10.1.2
	 * @return   string
	 * @param    string     $url   		    URL
	 * @param    string     $language   	User's language code, e.g. 'de_DE'
	 */
	public function retrieve_language_specific_url( $url, $language = '' ){
		//If WPML is active
		$url = apply_filters( 'wpml_permalink', $url, $this->get_language_code( $language ) );

		//If TranslatePress is active
		$translatepress = new CartBounty_Pro_TranslatePress();

		if( $translatepress->is_trp_active() ){
			$url = $translatepress->get_trp_language_specific_url( $url, $language );
		}

		return $url;
	}

	/**
	 * Build cart
	 *
	 * @since    9.4
	 * @return   boolean
	 * @param    object     $cart   		    Cart data
	 * @param    boolean    $ignore       		Should the cart be ignored or not. Ignored cart is required to build a temporary cart for coupon validation.
	 * @param    string     $mc_cid   		    MailChimp tracking ID
	 * @param    string     $gr_m   		    GetResponse tracking ID
	 * @param    integer    $step_nr            Automation step number
	 * @param    string     $recovery			Recovery type e.g. ActiveCampaign, WordPress etc.
	 */
	public function build_cart( $cart, $ignore = false, $mc_cid = false, $gr_m = false, $step_nr = false, $recovery = '' ){
		
		if( WC()->cart ){ //Checking if WooCommerce has loaded
			WC()->cart->empty_cart();//Removing any products that might have be added in the cart

			$cart_contents = array();
			$cart_meta = array();

			if( isset( $cart->cart_contents ) ){
				$cart_contents = $this->get_saved_cart_contents( $cart->cart_contents );
			}

			if( isset( $cart->cart_meta ) ){
				$cart_meta = $this->get_saved_cart_contents( $cart->cart_meta );
			}

			if( !$cart_contents ) return; //If missing products

			if( $ignore ){ //In case we are building a temporary cart for coupon validation and do not want to save it
				WC()->session->set( 'cartbounty_pro_ignore_cart', true ); //Setting a marker that current cart is only used to validate Coupon code
			}

			foreach( $cart_contents as $product ){ //Looping through cart products
				$custom_meta = array();
				$product_exists = wc_get_product( $product['product_id'] ); //Checking if the product exists
				
				if( !$product_exists ){
					$this->log( 'notice', sprintf(
						/* translators: %d - Product ID */
						esc_html__( 'Unable to restore product in the shopping cart since the product no longer exists. ID: %d', 'woo-save-abandoned-carts' ), esc_html( $product['product_id'] ) ) );
				}else{

					$variation_attributes = '';

					if( isset( $product['product_variation_attributes'] ) ){
						$variation_attributes = $product['product_variation_attributes'];

					}elseif( $product['product_variation_id'] ){ //Deprecated since version 10.1.1. Will be removed in future
						$single_variation = new WC_Product_Variation( $product['product_variation_id'] );
						$single_variation_data = $single_variation->get_data();
						$variation_attributes = $single_variation->get_variation_attributes();
					}
					
					foreach( $cart_meta as $key => $meta ){
						if( $meta['product_id'] == $product['product_id'] ){
							$custom_meta = $meta;
						}
					}

					WC()->cart->add_to_cart( $product['product_id'], $product['quantity'], $product['product_variation_id'], $variation_attributes, $custom_meta ); //Adding previous products back to cart
				}
			}

			if( !$ignore ){ //In case we are not building a temporary cart for coupon validation
				//Restore previous session id because we want the user abandoned cart data to be in sync
				//Starting session in order to check if we have to insert or update database row with the data from input boxes
				WC()->session->set( 'cartbounty_pro_session_id', $cart->session_id ); //Putting previous customer ID back to WooCommerce session
				WC()->session->set( 'cartbounty_pro_from_link', true ); //Setting a marker that current user arrived from email
				WC()->session->set( 'cartbounty_pro_step_nr', $step_nr ); //Setting step number from which the user arrived
				WC()->session->set( 'cartbounty_pro_recovery', $recovery ); //Setting recovery type from which the user arrived
				
				if( $mc_cid ){ //If we have MailChimp Campaign ID, save it in database to use it in case of a new order
					$this->update_refferal( $mc_cid, $cart->refferals, $cart->session_id, 'mailchimp' );					
				}

				if( $gr_m ){ //If we have GetResponse Campaign ID, save it in database to use it in case of a new order
					$this->update_refferal( $gr_m, $cart->refferals, $cart->session_id, 'getresponse' );					
				}
			}
		}
	}

	/**
	 * Automatically apply coupon to the cart in case coupon code exists
	 * First apply generated coupon codes by CartBounty.
	 * If generated coupons do not exust - see if manual coupon codes have been applied before and restore them
	 * If coupon is limited and can be used by Abandoned cart email - coupon code will not auto apply and must be added manually
	 *
	 * @since    9.7
	 * @param    array | string     $coupons			Unserialized array of coupons or a single coupon code in case coming from CartBounty tools
	 * @param    string     		$recovery			Recovery type e.g. ActiveCampaign, WordPress etc.
	 * @param    integer    		$step_nr            Automation step number
	 * @param    boolean    		$coming_from_tool   If method called from a CartBounty tool or not
	 */
	public function auto_apply_coupon( $coupons, $recovery, $step_nr = false, $coming_from_tool = false ){

		if( !apply_filters( 'cartbounty_pro_coupon_auto_apply', true ) && !$coming_from_tool ) return; //Exit if automatic coupon application disabled and if coupon is not supposed to be applied because it was just generated by Exit Intent or Early capture tools

		$coupon_code = false;
		$manual_coupon = false;
		$coupons_array = maybe_unserialize( $coupons );

		if( $coupons_array ){ //If coupons exist
			
			if( isset( $coupons_array[$recovery] ) ){
				$coupon_code = $coupons_array[$recovery];
			}
		}

		if( is_array( $coupon_code ) ){ //If generated coupon code found
			
			if( isset( $coupon_code[$step_nr] ) ){
				$coupon_code = $coupon_code[$step_nr];

			}else{
				$coupon_code = false;
			}

		}else{ //In case generated coupon code has not been found - check if coupons have been added via CartBounty tools or adding coupon code manually

			if( $coupons_array ){ //If coupons exist

				if( isset( $coupons_array['manual'] ) ){ //If we have a manual coupon added by customer
					$coupon_code = $coupons_array['manual'];
					$manual_coupon = true;

				}elseif( isset( $coupons_array['early_capture'] ) ){ //If we have a coupon added via Early capture
					$coupon_code = $coupons_array['early_capture'];
					$manual_coupon = false;

				}elseif( isset( $coupons_array['exit_intent'] ) ){ //If we have a coupon added via Exit Intent
					$coupon_code = $coupons_array['exit_intent'];
					$manual_coupon = false;
				}
			}
		}

		if( $coming_from_tool ){ //In case we are trying to auto apply a coupon after user has added an item to the cart via CartBounty tools
			$coupon_code = $coupons;
			$manual_coupon = false;
		}

		if ( !empty( $coupon_code ) ){ //If there is a coupon for the appropriate recovery option - try to auto apply it
			
			if( WC()->cart ){

				$discounts = new WC_Discounts( WC()->cart );

				if( $manual_coupon ){ //In case of manual coupon code, add all applied coupons
					
					foreach ( $coupon_code as $key => $coupon ) {
						$coupon_object = new WC_Coupon( $coupon );
						$response = $discounts->is_coupon_valid( $coupon_object );
						
						if( !is_wp_error( $response ) ) { //If the coupon is valid
							WC()->cart->add_discount( sanitize_text_field( $coupon ) );
						}
					}

				}else{ //In case of generated coupon code - add single coupon code
					$coupon_object = new WC_Coupon( $coupon_code );
					$response = $discounts->is_coupon_valid( $coupon_object );

					if( !is_wp_error( $response ) ) { //If the coupon is valid
						$result = WC()->cart->add_discount( sanitize_text_field( $coupon_code ) );
					}
				}
			}
		}
	}

	/**
	 * Unserialize and return all refferals or a specified refferal ID in case recovery value has been provided 
	 *
	 * @since    9.5
	 * @return   array or string
	 * @param    array     $refferals   		 Cart refferals
	 * @param    array     $recovery   		     Recovery type e.g. ActiveCampaign, WordPress etc.
	 */ 
	public function get_refferals( $refferals = array(), $recovery = false ) {
		$refferals = maybe_unserialize( $refferals );

		if( $refferals ){

			if( $recovery ){ //If refferal for a specific recovery type have been requested

				if( isset( $refferals[$recovery] ) ){
					$refferals = $refferals[$recovery];
				}
			}
		}

		return $refferals;
	}

	/**
	 * Update refferal of abandoned cart in case the user has arrived from a specific campaign
	 *
	 * @since    9.5
	 * @param    string    $refferal_code        Refferal ID
	 * @param    array     $refferals   		 Cart refferals
	 * @param    string    $session_id   		 Session ID
	 * @param    string    $recovery   	    	 Recovery type e.g. ActiveCampaign, WordPress etc.
	 */ 
	public function update_refferal( $refferal_id, $refferals, $session_id, $recovery ) {
		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
		$refferals = $this->get_refferals( $refferals );
		$refferals[$recovery] = $refferal_id;

		$wpdb->update( //Update abandoned cart and save refferal
			$cart_table,
			array(
				'refferals'	=>	sanitize_text_field( maybe_serialize( $refferals ) )
			),
			array(
				'session_id' => $session_id
			),
			array('%s'),
			array('%s')
		);
	}

	/**
	 * Method edits checkout fields
	 * Tries to move email and/or phone fields higher in the checkout form and insert additional checkout field
	 * Adding consent checkbox field
	 *
	 * @since    6.7
	 * @return 	 Array
	 * @param 	 $fields    Checkout form fields
	 */
	public function edit_checkout_fields( $fields ) {
		$settings = $this->get_settings( 'settings' );
		$lift_email = esc_attr( $settings['lift_email'] );
		$lift_phone = esc_attr( $settings['lift_phone'] );
		$checkout_consent = $this->get_checkout_consent();
		$checkout_consent = apply_filters( 'wpml_translate_single_string', $checkout_consent['value'], 'woo-save-abandoned-carts', $checkout_consent['name'] );

		if( $lift_email ){ //Changing the priority and moving the email higher
			if( isset( $fields['billing_email'] ) ){
				$fields['billing_email']['priority'] = 4;
			}
		}

		if( $lift_phone ){ //Changing the priority and moving the phone higher
			if( isset( $fields['billing_phone'] ) ){
				$fields['billing_phone']['priority'] = 6;
			}
		}

		$consent_data = $this->get_consent_field_data( $value = false, $fields );
		$consent_enabled = $consent_data['consent_enabled'];
		$field_name = $consent_data['field_name'];
		$consent_position = $consent_data['consent_position'];

		if( $consent_enabled ){ //If consent enabled

			$fields[$field_name] = apply_filters(
				'cartbounty_pro_consent_checkbox_args',
				array(
					'label' 		=> $checkout_consent,
					'type' 			=> 'checkbox',
					'priority' 		=> $consent_position,
					'required' 		=> false,
					'default' 		=> false,
					'clear' 		=> true,
					'class' 		=> array( 'cartbounty-pro-consent' )
				)
			);
		}

		if( $this->international_phone_enabled() ){ //Add additional class to phone field so that it could be used for easy international phone input
			$fields['billing_phone']['class'][] = 'cartbounty-pro-international';
		}

		return $fields;
	}

	/**
	 * Retrieve consent field name
	 *
	 * @since    10.4
	 * @return 	 array
	 * @param 	 $value     Value to return
	 */
	public function get_consent_field_name( $value = false ) {
		$name = '';

		if( $value == 'email' ){
			$name = apply_filters( 'cartbounty_pro_consent_email_name', 'billing_email_consent' );

		}elseif( $value == 'phone' ){
			$name = apply_filters( 'cartbounty_pro_consent_phone_name', 'billing_phone_consent' );

		}elseif( $value == 'phone-and-email' ){
			$name = apply_filters( 'cartbounty_pro_consent_email_phone_name', 'billing_email_phone_consent' );
		}

		return $name;
	}

	/**
	 * Retrieve consent field data
	 *
	 * @since    10.4
	 * @return 	 array
	 * @param 	 $value     Value to return
	 * @param 	 $fields    Checkout form fields
	 */
	public function get_consent_field_data( $value = false, $fields = array() ) {
		$consent_settings = $this->get_consent_settings();
		$email_consent_enabled = $consent_settings['email'];
		$phone_consent_enabled = $consent_settings['phone'];
		$field_name = '';
		$consent_enabled = false;
		$consent_position = '';

		if( $email_consent_enabled && $phone_consent_enabled ){
			$field_name = $this->get_consent_field_name( 'phone-and-email' );
			$consent_enabled = true;

			if( isset( $fields['billing_email'] ) ){
				$consent_position = $fields['billing_email']['priority'] + 1;
			}

		}elseif( $email_consent_enabled ){
			$field_name = $this->get_consent_field_name( 'email' );
			$consent_enabled = true;

			if( isset( $fields['billing_email'] ) ){
				$consent_position = $fields['billing_email']['priority'] + 1;
			}

		}elseif( $phone_consent_enabled ){
			$field_name = $this->get_consent_field_name( 'phone' );
			$consent_enabled = true;

			if( isset( $fields['billing_phone'] ) ){
				$consent_position = $fields['billing_phone']['priority'] + 1;
			}
		}

		$result = array(
			'field_name' 		=>	$field_name,
			'consent_enabled' 	=>	$consent_enabled,
			'consent_position' 	=>	$consent_position,
		);

		if( $value ){ //If a single value should be returned
			
			if( isset( $result[$value] ) ){ //Checking if value exists
				$result = $result[$value];
			}
		}

		return $result;
	}

	/**
	 * Retrieve customer's saved consent field value
	 *
	 * @since    10.4
	 * @return 	 boolean
	 * @param    boolean     $saved_cart    		  Customer's abandoned cart data
	 */
	public function get_customers_consent( $saved_cart = false ){
		$consent = false;

		if( !$saved_cart ){
			$public = $this->public();
			$saved_cart = $public->get_saved_cart();
		}
		
		$get_consent_field_data = $this->get_consent_field_data( 'field_name' );
		$email_consent_field_name = $this->get_consent_field_name( 'email' );
		$phone_consent_field_name = $this->get_consent_field_name( 'phone' );
		$phone_email_consent_field_name = $this->get_consent_field_name( 'phone-and-email' );

		if( ( $get_consent_field_data == $phone_email_consent_field_name && $saved_cart->email_consent && $saved_cart->phone_consent ) ||
			( $get_consent_field_data == $email_consent_field_name && $saved_cart->email_consent ) ||
			( $get_consent_field_data == $phone_consent_field_name && $saved_cart->phone_consent ) 
		){
			$consent = true;
		}

		return $consent;
	}

	/**
	 * Method prepares and returns an array of different time intervals used for calculating time subtractions
	 *
	 * @since    6.8
	 * @return 	 Array
	 * @param    integer     $interval    		  	  Time interval that has to be waited for in milliseconds
	 * @param    boolean     $first_step    		  Whether function requested during the first step of WordPress automation. Default false
	 */
	public function get_time_intervals( $interval = false, $first_step = false ){
		$waiting_time = $this->get_waiting_time();
		$mc_cart_sync_period = 3; //In minutes. Defines the time period after which an abandoned cart will be synced over to MailChimp
		$default_waiting_time = 60;

		if($waiting_time > $default_waiting_time){ //In case if waiting time is set to be longer than 60 minutes, adjust the sync time over to MailChimp
			$mc_cart_sync_period = $waiting_time - ( $default_waiting_time - $mc_cart_sync_period ); // 60 minutes is the minimum time MailChimp allows to set for sending out abandoned cart reminder emails
		}

		$ac_cart_sync_period = $waiting_time - 5; //In minutes. Defines the time period after which an abandoned cart will be synced over to ActiveCampaign
		
		$gr_cart_sync_period = $waiting_time - 5; //In minutes. Defines the time period after which an abandoned cart will be synced over to GetResponse
		
		$gr_contact_sync_period = 5; //In minutes. Defines the time period after which an abandoned cart contact will be synced over to GetResponse
		
		$wh_sync_period = $waiting_time - 5; //In minutes. Defines the time period after which an abandoned cart will be synced over to Webhook

		if($first_step){ //In case if we need to get WordPress first automation step time interval, we must add additional time the cart was waiting to be recognized as abandoned
			$interval = $interval + $waiting_time;
		}

		$interval = $this->convert_milliseconds_to_minutes( $interval );

		//Calculating time intervals
		$datetime = current_time( 'mysql', true );
		$date_format = 'Y-m-d H:i:s';

		return array(
			'cart_abandoned' 			=> date( $date_format, strtotime( '-' . $waiting_time . ' minutes', strtotime( $datetime ) ) ),
			'cart_recovered' 			=> date( $date_format, strtotime( '-30 seconds', strtotime( $datetime ) ) ),
			'old_cart' 					=> date( $date_format, strtotime( '-' . CARTBOUNTY_PRO_NEW_NOTICE . ' minutes', strtotime( $datetime ) ) ),
			'anonymous_cart_age' 		=> date( $date_format, strtotime( '-' . $interval . ' minutes', strtotime( $datetime ) ) ),
			'ten_minutes' 				=> date( $date_format, strtotime( '-10 minutes', strtotime( $datetime ) ) ),
			'two_hours' 				=> date( $date_format, strtotime( '-2 hours', strtotime( $datetime ) ) ),
			'day' 						=> date( $date_format, strtotime( '-1 day', strtotime( $datetime ) ) ),
			'week' 						=> date( $date_format, strtotime( '-7 days', strtotime( $datetime ) ) ),
			'month' 					=> date( $date_format, strtotime( '-1 month', strtotime( $datetime ) ) ),
			'mc_cart_sync_period' 		=> date( $date_format, strtotime( '-' . $mc_cart_sync_period . ' minutes', strtotime( $datetime ) ) ),
			'ac_cart_sync_period' 		=> date( $date_format, strtotime( '-' . $ac_cart_sync_period . ' minutes', strtotime( $datetime ) ) ),
			'gr_cart_sync_period' 		=> date( $date_format, strtotime( '-' . $gr_cart_sync_period . ' minutes', strtotime( $datetime ) ) ),
			'gr_contact_sync_period' 	=> date( $date_format, strtotime( '-' . $gr_contact_sync_period . ' minutes', strtotime( $datetime ) ) ),
			'wh_sync_period' 			=> date( $date_format, strtotime( '-' . $wh_sync_period . ' minutes', strtotime( $datetime ) ) ),
			'wp_step_send_period' 		=> date( $date_format, strtotime( '-' . $interval . ' minutes', strtotime( $datetime ) ) ),
			'sms_step_send_period' 		=> date( $date_format, strtotime( '-' . $interval . ' minutes', strtotime( $datetime ) ) ),
			'pn_step_send_period' 		=> date( $date_format, strtotime( '-' . $interval . ' minutes', strtotime( $datetime ) ) ),
			'maximum_sync_period'		=> date( $date_format, strtotime( '-' . CARTBOUNTY_PRO_MAX_SYNC_PERIOD . ' days', strtotime( $datetime ) ) ),
			'anonymization_period'		=> date( $date_format, strtotime( '-' . apply_filters( 'cartbounty_pro_anonymization_interval', CARTBOUNTY_PRO_ANONYMIZATION_PERIOD ) . ' days', strtotime( $datetime ) ) ),
			'magic_login_period' 		=> date( $date_format, strtotime( '-' . $interval . ' minutes', strtotime( $datetime ) ) ),
		);
	}

	/**
	 * Getting time period during which the cart is not considered abandoned - the customer is presumed to be shopping
	 *
	 * @since    9.2.3
	 * @return 	 Number
	 */
	public function get_waiting_time(){
		$default_waiting_time = 60; //In minutes. Defines the time period after which an email notice will be sent to admin and the cart is presumed abandoned
		$waiting_time = apply_filters( 'cartbounty_pro_waiting_time', $default_waiting_time );
		
		if($waiting_time < 20){ //Making sure minimum waiting period is not less than 20 minutes
			$waiting_time = 20;
		}

		return $waiting_time;
	}

	/**
	* Method counts carts in the selected category
	*
	* @since    8.1
	* @return   number
	* @param    string   	$cart_status		Cart status
	* @param    boolean   	$search				True only where we would like to display the total number of results found also using search. Default false
	*/
	function get_cart_count( $cart_status, $search = false ){
		global $wpdb;
		$total_items = 0;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
		$where_sentence = $this->get_where_sentence( $cart_status );
		$search_query = '';
		$variables = array( '' );

		if( $search ){
			$search_handle_data = $this->handle_search( $variables, 'back' );

			if( isset( $search_handle_data['query'] ) && isset( $search_handle_data['variables'] ) ){
				$search_query = $search_handle_data['query'];
				$variables = $search_handle_data['variables'];
			}
		}

		$total_items = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(id)
				FROM $cart_table
				WHERE cart_contents != %s
				$search_query
				$where_sentence",
				$variables
			)
		);

		return $total_items;
	}

    /**
     * Method displays available cart type filters
     *
     * @since    8.2
     * @return   Array
     * @param 	 Array   	$variables		Variables that must be added to the list of mysql query
     * @param 	 string   	$position		Position of where the new variables should be attached to (beginning or end of the existing array)
     */
    function handle_search( $variables, $position ){
    	if(isset($_GET['cartbounty-pro-search'])){ //In case have a search request
            $nonce = $_REQUEST['search-nonce'];
            if ( ! wp_verify_nonce( $nonce, 'search_carts' )){ //Exit in case security check is not passed
                die(); 
            }

            $needle = "%" . sanitize_text_field($_GET['cartbounty-pro-search']) . "%"; //Broad search by adding % to start and end of the term
            $search_query ='AND (
                name LIKE %s OR
                surname LIKE %s OR
                email LIKE %s OR
                phone LIKE %s OR
                location LIKE %s OR
                cart_contents LIKE %s
            )';

            if($position == 'front'){ //Attaching variables to the front of array
            	array_unshift( $variables, $needle, $needle, $needle, $needle, $needle, $needle );
            }else{ //Attaching variables to the end of array
            	array_push( $variables, $needle, $needle, $needle, $needle, $needle, $needle ); 
            }

            $data = array(
            	'query'			=> $search_query,
            	'variables'		=> $variables
            );

            return $data;
        }
    }

	/**
	 * Method returns if anonymous carts are excluded
	 *
	 * @since    9.10
	 * @return   boolean
	 */
	function anonymous_carts_excluded(){
		$exclude = false;
		$settings = $this->get_settings( 'settings' );

		if( $settings['exclude_anonymous_carts'] && empty( $settings['allowed_countries'] ) ){
			$exclude = true;
		}

		return $exclude;
	}

    /**
     * Method displays available cart type filters
     *
     * @since    8.1
     * @return   string
     * @param 	 $cart_status    Currently filtered cart status
     * @param 	 $tab    		 Currently open tab
     */
	function display_cart_statuses( $cart_status, $tab ){
		$exclude = $this->anonymous_carts_excluded();
		$cart_types = array(
			'all' 					=> esc_html__('All', 'woo-save-abandoned-carts'),
			'recoverable' 			=> esc_html__('Recoverable', 'woo-save-abandoned-carts'),
			'anonymous' 			=> esc_html__('Anonymous', 'woo-save-abandoned-carts'),
			'recovered' 			=> esc_html__('Recovered', 'woo-save-abandoned-carts')
		);

		$output = '<ul id="cartbounty-pro-cart-statuses" class="subsubsub">';
		$search_phrase = '';
		$counter = 0;
		
		if( isset( $_GET['cartbounty-pro-search'] ) ){
			$nonce = '&search-nonce='. $_REQUEST['search-nonce'];
			$search_phrase = '&cartbounty-pro-search=' . $_GET['cartbounty-pro-search'] . $nonce;
		}

		foreach( $cart_types as $key => $type ){
			$counter++;
			$divider = '<em>|</em>';
			$count = $this->get_cart_count( $key, $search = true );

			if( $counter == 1 ){ //Do not output vertical line before the first item
				$divider = '';
			}

			$class = ( $key == $cart_status ) ? 'current' : '';

			if( $count != 0 ){//Do not display empty categories

				if( !( $key == 'anonymous' && $exclude ) ){ //If we are not processing Anonymous carts and they have not been excluded
					$url = '?page="'. esc_attr( CARTBOUNTY_PRO ) .'"&tab='. esc_attr( $tab ) .'&cart-status='. esc_attr( $key ) . esc_attr( $search_phrase );
					$output .= "<li>". wp_kses( $divider, 'data' ) ."<a href='". esc_url( $url ) ."' title='". esc_attr( $type ) ."' class='". esc_attr( $class ) ."'>". esc_html( $type ) ." <span class='count'>(". esc_html( $count ) .")</span></a></li>";
				}
			}
		}

		$output .= '</ul>';
		echo $output;
	}

	/**
     * Method for creating SQL query depending on different post types 
     * If cart object provided - validate its status e.g. if it is recovered, anonymous etc. (developed for use by reports)
     *
     * @since    8.1
     * @return   string / boolean
     * @param    integer    $cart_status    		 Currently filtered cart status
     * @param    boolean    $starting_and    		 If the query should start with AND or not
     * @param    object     $cart					 Abandoned cart object
     */
	function get_where_sentence( $cart_status, $starting_and = true, $cart = null ){
		$where_sentence = '';
		$cart_validation_result = false;

		if( $cart_status == 'recoverable' ){

			if( $cart ){
				//If all of these conditions are true - $cart_validation_result will be true
				$cart_validation_result = ( !empty( $cart->email ) || !empty( $cart->phone ) || !empty( $cart->pn_subscription ))
				&& $cart->type != $this->get_cart_type( 'recovered' )
				&& $cart->type != $this->get_cart_type( 'ordered' )
				&& $cart->type != $this->get_cart_type( 'ordered_deducted' )
				&& $cart->type != $this->get_cart_type( 'excluded' );

			}else{
				$where_sentence = "AND (email != '' OR phone != '' OR pn_subscription != '') AND type != ". $this->get_cart_type( 'recovered' ) ." AND type != " . $this->get_cart_type( 'ordered' ) ." AND type != " . $this->get_cart_type( 'ordered_deducted' ) ." AND type != " . $this->get_cart_type( 'excluded' );
			}

		}elseif( $cart_status == 'push_notification' ){

			if( $cart ){
				//If all of these conditions are true - $cart_validation_result will be true
				$cart_validation_result = !empty( $cart->pn_subscription )
				&& $cart->type != $this->get_cart_type( 'recovered' )
				&& $cart->type != $this->get_cart_type( 'ordered' )
				&& $cart->type != $this->get_cart_type( 'ordered_deducted' )
				&& $cart->type != $this->get_cart_type( 'excluded' );

			}else{
				$where_sentence = "AND pn_subscription != '' AND type != ". $this->get_cart_type( 'recovered' ) ." AND type != " . $this->get_cart_type( 'ordered' ) ." AND type != " . $this->get_cart_type( 'ordered_deducted' ) ." AND type != " . $this->get_cart_type( 'excluded' );
			}

		}elseif( $cart_status == 'anonymous' ){

			if( $cart ){
				//If all of these conditions are true - $cart_validation_result will be true
				$cart_validation_result = empty( $cart->email )
				&& empty( $cart->phone )
				&& empty( $cart->pn_subscription )
				&& $cart->type != $this->get_cart_type( 'recovered' )
				&& $cart->type != $this->get_cart_type( 'ordered' )
				&& $cart->type != $this->get_cart_type( 'ordered_deducted' )
				&& $cart->type != $this->get_cart_type( 'excluded' );

			}else{
				$where_sentence = "AND ((email IS NULL OR email = '') AND (phone IS NULL OR phone = '') AND (pn_subscription IS NULL OR pn_subscription = '')) AND type != ". $this->get_cart_type( 'recovered' ) ." AND type != " . $this->get_cart_type( 'ordered' ) ." AND type != " . $this->get_cart_type( 'ordered_deducted' ) ." AND type != " . $this->get_cart_type( 'excluded' );
			}

		}elseif( $cart_status == 'recovered' ){

			if( $cart ){
				$cart_validation_result = $cart->type == $this->get_cart_type( 'recovered' );

			}else{
				$where_sentence = "AND type = ". $this->get_cart_type( 'recovered' );
			}

		}elseif( $cart_status == 'ordered' ){

			if( $cart ){
				$cart_validation_result = (
					$cart->type == $this->get_cart_type( 'recovered' )
					|| $cart->type == $this->get_cart_type( 'ordered' )
					|| $cart->type == $this->get_cart_type( 'ordered_deducted' )
				);

			}else{
				$where_sentence = "AND (type = ". $this->get_cart_type( 'recovered' ) ." OR type = ". $this->get_cart_type( 'ordered' ) ." OR type = ". $this->get_cart_type( 'ordered_deducted' ) .")";
			}

		}elseif( $cart_status == 'abandoned' ){

			if( $cart ){
				$cart_validation_result = $cart->type != $this->get_cart_type( 'recovered' )
				&& $cart->type != $this->get_cart_type( 'ordered' )
				&& $cart->type != $this->get_cart_type( 'ordered_deducted' )
				&& $cart->type != $this->get_cart_type( 'excluded' );

			}else{
				$where_sentence = "AND ( type != ". $this->get_cart_type( 'recovered' ) ." AND type != " . $this->get_cart_type( 'ordered' ) ." AND type != " . $this->get_cart_type( 'ordered_deducted' ) ." AND type != " . $this->get_cart_type( 'excluded' );
			}

		}elseif( $cart_status == 'all' ){ //Used to count the total number of all abandoned carts in the abandoned cart table
			$additional_anonymous_cart_validation = false;

			if( $cart ){

				if( $this->anonymous_carts_excluded() ){ //In case anonymous shopping carts are excluded - do not include them
					$additional_anonymous_cart_validation = ( !empty( $cart->email )
					|| !empty( $cart->phone )
					|| !empty( $cart->pn_subscription ) );
				}

				$cart_validation_result = $cart->type != $this->get_cart_type( 'ordered' )
				&& $cart->type != $this->get_cart_type( 'ordered_deducted' )
				&& $cart->type != $this->get_cart_type( 'excluded' )
				&& $additional_anonymous_cart_validation;

			}else{

				if( $this->anonymous_carts_excluded() ){ //In case anonymous shopping carts are excluded - do not include them
					$additional_anonymous_cart_validation = " AND (email != '' OR phone != '' OR pn_subscription != '')";
				}

				$where_sentence = "AND type != " . $this->get_cart_type( 'ordered' ) ." AND type != " . $this->get_cart_type( 'ordered_deducted' ) ." AND type != " . $this->get_cart_type( 'excluded' ) . $additional_anonymous_cart_validation;
			}
		}

		if( !empty( $where_sentence ) ){ //Looking if "AND" needs to be removed from the query

			if( $starting_and == false ){

				if( substr( $where_sentence, 0, 4 ) === 'AND ' ){ //If "AND" is at the beginning of the query
					$where_sentence = substr( $where_sentence, 4 ); //Removing "AND" from the start of the query
				}
			}
		}

		//In case we must validate returned carts in a PHP operation (e.g. in reports)
		if( $cart ){
			$where_sentence = $cart_validation_result;
		}

		return $where_sentence;
    }

	/**
	 * Method detects if we have abandoned carts that have been captured by the Free plugin version
	 *
	 * @since    7.0
	 * @return 	 Boolean
	 */
	public function get_free_version_carts(){
		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_TABLE_NAME;
		$carts_exist = false;
		$value = 'checked';
		$free_version_table_exists = $this->get_cartbounty_transient( 'free_version_table_exists' );

		if( $free_version_table_exists && $free_version_table_exists !== 'checked' ){ //If we have checked the carts previously and the value is true
			$carts_exist = true;
			$value = true;

		}elseif( $free_version_table_exists !== 'checked' ){ //If we have not cached the value - check if the table exists
			$table_exists = $wpdb->query(
				"SHOW TABLES LIKE '{$cart_table}'"
			);

			if( $table_exists ){ //In case table exists, check if it has at least one abandoned cart
				$rows = $wpdb->get_var(
					"SELECT COUNT(id)
					FROM $cart_table"
				);

				if( $rows ){ //If have abandoned carts
					$carts_exist = true;
					$value = true;
				}
			}
		}

		$this->set_cartbounty_transient( 'free_version_table_exists', $value, 60*60*24 ); //Checking if table exists once a day
		return $carts_exist;
	}

	/**
	 * Method handles import of abandoned carts that have been captured by the Free plugin version
	 * Carts are imported automatically as soon as the plugin is activated however it can also be triggered by user manually in case of an automated issue
	 * Carts will be imported only once
	 *
	 * @since    7.0
	 * @return 	 Boolean
	 */
	public function import_carts(){
		$activated_by_user = false;

		if( isset( $_POST['action'] ) ){

			if( $_POST['action'] == 'import_carts' ){
				$activated_by_user = true;
			}
		}

		if( !$this->import_complete() ){ //If carts have not been imported
			
			if( $this->get_free_version_carts() ){ //If there are carts in the Free version
				global $wpdb;
				$cart_table = $wpdb->prefix . CARTBOUNTY_TABLE_NAME;
				$cart_table_pro = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
				$time = $this->get_time_intervals();
				$abandoned_carts = $wpdb->get_results( //Selecting all rows that are not empty and are not older than the Maximums sync period
					$wpdb->prepare(
						"SELECT * FROM $cart_table
						WHERE cart_contents != '' AND
						type != %d AND
						type != %d AND
						type != %d AND
						time > %s",
						$this->get_cart_type( 'ordered' ),
						$this->get_cart_type( 'ordered_deducted' ),
						$this->get_cart_type( 'excluded' ),
						$time['maximum_sync_period']
					)
				);

				if( $abandoned_carts ){ //Ready to start the import
					$imported_cart_count = 0;
					$batch_count = 0; //Keeps count of current batch of data to insert
					$batches = array(); //Array containing the batches of import since SQL is having troubles importing too many columns at once
					$abandoned_cart_data = array();
					$placeholders = array();

					foreach( $abandoned_carts as $key => $cart ){ // Looping through abandoned carts to create the arrays
						$batch_count++;
						array_push(
							$abandoned_cart_data,
							sanitize_text_field( $cart->name ),
							sanitize_text_field( $cart->surname ),
							sanitize_email( $cart->email ),
							sanitize_text_field( $cart->phone ),
							sanitize_text_field( $cart->location ),
							sanitize_text_field( $cart->cart_contents ),
							sanitize_text_field( $cart->cart_total ),
							sanitize_text_field( $cart->currency ),
							sanitize_text_field( $cart->time ),
							sanitize_text_field( $cart->session_id ),
							sanitize_text_field( $cart->mail_sent ),
							sanitize_text_field( $cart->other_fields ),
							sanitize_text_field( $cart->wp_unsubscribed ),
							sanitize_text_field( $cart->wp_steps_completed ),
							sanitize_text_field( $cart->wp_complete ),
							sanitize_text_field( $cart->type )
						);
						$placeholders[] = "( %s, %s, %s, %s, %s, %s, %0.2f, %s, %s, %s, %d, %s, %d, %d, %d, %s )";

						if($batch_count >= 100){ //If we get a full batch, add it to the array and start preparing a new one
							$batches[] = array(
								'data'			=>	$abandoned_cart_data,
								'placeholders'	=>	$placeholders
							);
							$batch_count = 0;
							$abandoned_cart_data = array();
							$placeholders = array();
						}
					}

					//In case something is left at the end of the loop, we add it to the batches so we do not loose any abandoned carts during the import process
					if($abandoned_cart_data){
						$batches[] = array(
							'data'			=>	$abandoned_cart_data,
							'placeholders'	=>	$placeholders
						);
					}
					
					foreach( $batches as $key => $batch ){ //Looping through the batches and importing the carts
						$query = "INSERT INTO ". $cart_table_pro ." (name, surname, email, phone, location, cart_contents, cart_total, currency, time, session_id, mail_sent, other_fields, wp_unsubscribed, wp_steps_completed, wp_complete, type) VALUES ";
						$query .= implode( ', ', $batch['placeholders'] );
						$count = $wpdb->query( $wpdb->prepare( "$query ", $batch['data'] ) );
						$imported_cart_count = $imported_cart_count + $count;
					}

					if( $imported_cart_count ){ //If at least one abandoned cart was imported
						$misc_settings = $this->get_settings( 'misc_settings' );
						$misc_settings['carts_imported'] = true;
						update_option( 'cartbounty_pro_misc_settings', $misc_settings ); //Making sure the user is not allowed to import the abandoned carts more than once

						if( $activated_by_user ){
							wp_send_json_success( sprintf(
								/* translators: %s - Imported cart count */
								esc_html( _n( 'Successfully imported %s abandoned cart.', 'Successfully imported %s abandoned carts.', $imported_cart_count, 'woo-save-abandoned-carts' ) ), esc_html( $imported_cart_count ) ) );
						}

					}else{

						if( $activated_by_user ){
							wp_send_json_error( esc_html__( 'Unfortunately, no abandoned carts were imported.', 'woo-save-abandoned-carts' ) );
						}
					}

				}else{

					if( $activated_by_user ){
						wp_send_json_error( sprintf(
							/* translators: %s - Number */
							esc_html__( 'Sorry, but there is nothing to import. Seems like all your abandoned carts are older than %d days.', 'woo-save-abandoned-carts' ), esc_html( CARTBOUNTY_PRO_MAX_SYNC_PERIOD )
						) );
					}
				}
	    	}
		}
	}

	/**
	 * Method checks if abandoned cart import from the Free version has been finished
	 *
	 * @since    10.0
	 * @return 	 Boolean
	 */
	public function import_complete(){
		$complete = false;

		if( $this->get_settings( 'misc_settings', 'carts_imported' ) ){
			$complete = true;
		}

		return $complete;
	}

	/**
	 * Method handles "Force sync" button functionality
	 *
	 * @since    9.0
	 * @return 	 Boolean
	 */
	public function force_sync(){
		$data = $_POST;
		if ( check_ajax_referer( 'force_sync', 'nonce', false ) == false ) { //If the request does not include our nonce security check, stop executing the function
	        wp_send_json_error(esc_html__( 'Sync failed. Looks like you are not allowed to do this.', 'woo-save-abandoned-carts' ));
	    }

	    switch ( $data['integration'] ) {

			case 'activecampaign':
				$activecampaign = $this->activecampaign();
				$activecampaign->auto_sync();
				break;

			case 'getresponse':
				$getresponse = $this->getresponse();
				$getresponse->auto_sync();
				break;

			case 'mailchimp':
				$mailchimp = $this->mailchimp();
				$mailchimp->auto_sync();
				break;

			case 'wordpress':
				$wordpress = $this->wordpress();
				$wordpress->auto_send();
				break;

			case 'bulkgate':
				$bulkgate = $this->bulkgate();
				$bulkgate->auto_send();
				break;

			case 'push_notification':
				$push_notification = $this->push_notification();
				$push_notification->auto_send();
				break;

			case 'webhook':
				$webhook = $this->webhook();
				$webhook->auto_send();
				break;
		}
		wp_send_json_success( esc_html__("Sync finished", 'woo-save-abandoned-carts' ));
	}

	/**
	 * Method displays the Force sync button
	 *
	 * @since    9.0
	 * @return 	 String
	 */
	public function display_force_sync_button( $integration ){
		if( !$integration ){
			return;
		}

		$button_name = esc_html__( 'Force sync', 'woo-save-abandoned-carts' );
		if( $integration == 'wordpress' || $integration == 'bulkgate' || $integration == 'push_notification' || $integration == 'webhook' ){
			$button_name = esc_html__( 'Force send', 'woo-save-abandoned-carts' );
		}

		$nonce = wp_create_nonce( 'force_sync' );
		$button = "<a id='force_sync' class='cartbounty-pro-button button button-secondary' href='#' data-integration='". esc_attr( $integration ) ."' data-nonce='". esc_attr( $nonce ) ."'>". esc_html( $button_name ) ."</a>";
		return $button;
	}

	/**
	 * Method creates database table to save products for synchronizing with MailChimp or GetResponse
	 *
	 * @since    2.0
	 */
	public static function create_product_table(){
		global $wpdb;
		$admin = new CartBounty_Pro_Admin( CARTBOUNTY_PRO_PLUGIN_NAME_SLUG, CARTBOUNTY_PRO_VERSION_NUMBER );
		$getresponse = new CartBounty_Pro_GetResponse();
		$product_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME_PRODUCTS;
		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE $product_table (
			product_id INT NOT NULL,
			variations LONGTEXT,
			first_created DATETIME DEFAULT '0000-00-00 00:00:00',
			last_updated DATETIME DEFAULT '0000-00-00 00:00:00',
			last_synced DATETIME DEFAULT '0000-00-00 00:00:00',
			gr_last_synced DATETIME DEFAULT '0000-00-00 00:00:00',
			gr_product_ids LONGTEXT,
			PRIMARY KEY (product_id)
		) $charset_collate;";

		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta( $sql );
		
		//Resets table Auto increment index to 1
		$sql = "ALTER TABLE $product_table AUTO_INCREMENT = 1";
		dbDelta( $sql );
		
		$misc_settings = $admin->get_settings( 'misc_settings' );
		$misc_settings['product_table_exists'] = true;
		update_option( 'cartbounty_pro_misc_settings', $misc_settings ); //Updating status and telling that table has been created
		
		$gr_settings = $getresponse->get_settings();
		$gr_settings['product_table_support'] = true;
		update_option( 'cartbounty_pro_getresponse_settings', $gr_settings ); //Updating status and telling that table supports GetResponse
		return;
	}

	/**
	 * Method checks if a specific database table has been created
	 *
	 * @since    9.10
	 * @return   boolean
	 * @param    string     $option    		 Database option field name
	 */
	public function table_exists( $option ){
		$exists = true;
		$table_exists = $this->get_settings( 'misc_settings', $option );
		$table_supports_getresponse = true;

		if( $option == 'product_table_exists' ){ //In case we are looking for existence of product table - must also check if table supports GetResponse
			$getresponse = $this->getresponse();
			$table_supports_getresponse = $getresponse->get_settings( 'product_table_support' );
		}
		
		if( empty( $table_exists ) || empty( $table_supports_getresponse ) ){
			$exists = false;
		}

		return $exists;
	}

	/**
	 * Method creates abandoned cart URL that is used to restore the shopping cart
	 *
	 * @since    8.0
	 * @return   string
	 * @param    string   	$email			Cart email
	 * @param    string   	$session_id		Cart session ID
	 * @param    integer   	$cart_id		Cart ID
	 * @param    string   	$recovery		Recovery type
	 */
	public function create_cart_url( $email, $session_id, $cart_id, $recovery = false ){
		$cart_url = wc_get_cart_url();
		$hash = hash_hmac('sha256', $email . $session_id, CARTBOUNTY_PRO_ENCRYPTION_KEY) . '-' . $cart_id; //Creating encrypted hash with abandoned cart row ID in the end
		$recovery = '&recovery=' . $recovery;
		$checkout_url = $cart_url . '?cartbounty-pro=' . $hash . $recovery;

		$utm_tracking = apply_filters( 'cartbounty_pro_cart_url_utm_tracking', '' );
		
		if( !empty( $utm_tracking ) ){ //Add additional tracking tags to URL if provided
			$checkout_url = $checkout_url . '&' . $utm_tracking;
		}

		return $checkout_url;
	}

	/**
	 * Method creates short abandoned cart URL that is used to restore the shopping cart inside text messages
	 * Shortlink construction:
	 * ?cb=[ Recovery type - One letter long ][ Hash consisting of 5 symbols ][ Cart ID ][ Automation step number - One digit long ]
	 * e.g. ?cb=BFbj2918370
	 *
	 * @since    9.7
	 * @return   string
	 * @param    string   	$phone			Cart phone
	 * @param    string   	$session_id		Cart session ID
	 * @param    integer   	$cart_id		Cart ID
	 * @param    string   	$recovery		Recovery type
	 * @param    string   	$coupon			Coupon code
	 */
	public function create_short_cart_url( $phone, $session_id, $cart_id, $recovery ){
		$cart_url = wc_get_cart_url();
		$hash = substr( hash_hmac( 'sha1', $phone . $session_id, CARTBOUNTY_PRO_ENCRYPTION_KEY ) , 0, 5 ); //Leaving only first 5 characters of the hash

		if( $recovery == 'bulkgate' ){
			$recovery = 'B';
		}

		$checkout_url = $cart_url . '?cb=' . $recovery . $hash . $cart_id;
		return $checkout_url;
	}

	/**
     * Generate Unsubscribe URL
     *
     * @since    9.3
     * @return   string
     * @param    string     $email   		    Cart email
     * @param    string     $session_id   		Cart Session ID
     * @param    integer    $cart_id   			Cart ID
     * @param    string     $recovery   		Recovery type, e.g. wordpress
     */
	public function get_unsubscribe_url( $email, $session_id, $cart_id, $recovery ){
		$store_url = get_site_url();
		$hash = hash_hmac('sha256', $email . $session_id, CARTBOUNTY_PRO_ENCRYPTION_KEY) . '-' . $cart_id; //Creating encrypted hash with abandoned cart row ID in the end
		return $unsubscribe_url = $store_url . '?cartbounty-pro=' . $hash .'&recovery='. $recovery .'&cartbounty-pro-unsubscribe=1';
	}

	/**
     * Generate short Unsubscribe URL used inside text messages
     * Shortlink construction:
	 * ?cb=[ U - Direction to unsubscribe ][ Hash consisting of 5 symbols ][ Cart ID ]
	 * e.g. ?cb=UFbj291837
     *
     * @since    9.7
     * @return   string
     * @param    string     $phone   		    Cart phone
     * @param    string     $session_id   		Cart Session ID
     * @param    integer    $cart_id   			Cart ID
     */
	public function get_short_unsubscribe_url( $phone, $session_id, $cart_id ){
		$unsubscribe_code = 'U';
		$store_url = get_site_url();
		$hash = substr( hash_hmac( 'sha1', $phone . $session_id, CARTBOUNTY_PRO_ENCRYPTION_KEY ) , 0, 5 ); //Leaving only first 5 characters of the hash
		return $unsubscribe_url = $store_url . '?cb=' . $unsubscribe_code . $hash . $cart_id;
	}

	/**
     * Unsubscribe user from further messages about abandoned cart
     *
     * @since    9.3
     * @param    integer    $cart_id   			Cart ID
     * @param    integer    $step_nr            Automation step number
     * @param    string     $recovery   		Recovery type, e.g. wordpress
     */
	public function unsubscribe_user( $cart_id, $step_nr, $recovery ){
		global $wpdb;
		$automation = $this->automation();
		$field = false;
		
		if( $recovery == 'wordpress' ){
			$field = 'wp_unsubscribed';

		}elseif( $recovery == 'bulkgate' ){
			$field = 'sms_unsubscribed';
		}

		if( $field ){
			$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
			$wpdb->query(
				$wpdb->prepare(
					"UPDATE {$cart_table}
					SET $field = %d
					WHERE id = %d",
					1,
					$cart_id
				)
			);

			$automation->handle_message_stats( $action = 'unsubscribed', $cart_id, $step_nr, $recovery );
		}
	}

	/**
	 * Return cart type from cart name
	 *
	 * @since    9.5
	 * @return   integer
	 * @param    string    	$status		    Cart status. 
	 * 										0 = abandoned (default),
	 *										1 = recovered,
	 *										2 = order created,
	 *										3 = recovered, but payment pending
	 *										4 = order created and cart deducted from recoverable cart count stats (this type added just to make sure we keep longer ordered abandoned carts in our database to check if a user has used a coupon code in previous orders). Cart has never really been abandoned (user has added an item to cart and placed an order without abandoning the cart)
	 *										9 = excluded, user's cart has been excluded from abandoend carts
	 */
	function get_cart_type( $status ){
		if( empty($status) ){
			return;
		}

		$type = 0;

		switch ( $status ) {
			case 'abandoned':

				$type = 0;
				break;

			case 'recovered':

				$type = 1;
				break;

			case 'ordered':

				$type = 2;
				break;

			case 'recovered_pending':

				$type = 3;
				break;

			case 'ordered_deducted':

				$type = 4;
				break;

			case 'excluded':

				$type = 9;
				break;
		}
		return $type;
	}

	/**
	 * Method updates cart type along with WooCommerce order id if one exists and returns updated row count
	 *
	 * @since    9.5
	 * @return   boolean / integer
	 * @param    string    	$session_id		Session ID
	 * @param    integer   	$type			Cart status type
	 * @param    integer    $order_id		Order ID
	 * @param    string     $field			Field type that must used for update. Default session_id
	 * @param    boolean    $cart_found		Whether the cart was found by searching for it in the carts or not - it means we must update wc_order_id
	 * @param    object     $cart			Abandoned cart data
	 */
	function update_cart_type( $session_id = false, $type = false, $order_id = false, $field = false, $cart_found = false, $cart = false ){
		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
		$field = 'session_id';
		$where_value = $session_id;
		$order_status_changed = false;
		$updated_rows = 0;

		if( $cart_found ){ //Update both cart type and order_id if we had to use search to locate cart 
			if( empty( $cart ) ){
				return;
			}
			$where_value = $cart->session_id;
			$data = array(
				'type = ' . sanitize_text_field($type),
				'wc_order_id = ' . (int)$order_id
			);

		}elseif( $session_id ){ //If session_id present (in cases if the function is triggered by a customer)
			$data = array(
				'type = ' . sanitize_text_field($type),
				'wc_order_id = ' . (int)$order_id
			);

		}else{ //Update cart type using order_id (in case if the order status has changed)
			$field = 'wc_order_id';
			$where_value = $order_id;
			$data = array(
				'type = ' . sanitize_text_field($type)
			);
			$order_status_changed = true;
		}

		if( $type == $this->get_cart_type('recovered') ){ //If the cart has been recovered, clear mail_sent data as we want to send a newly recovered cart admin notification and increase total recovered carts
			$data[] = 'mail_sent = 0';
			$public = $this->public();
			$public->increase_recovered_cart_count( $order_status_changed );
		}

		$data = implode(', ', $data);

		$updated_rows = $wpdb->query(
			$wpdb->prepare(
				"UPDATE $cart_table
				SET $data
				WHERE $field = %s AND
				type != %d",
				$where_value,
				$this->get_cart_type('recovered')
			)
		);

		return $updated_rows;
	}

	/**
	 * Handling abandoned carts in case of a new order is placed.
	 * If order has status completed or processing - abandoned cart is removed alongside duplicate carts with the same email or phone and cart contents.
	 * If order has other status except completed, processing - the cart remains in the list and emails are sent out.
	 * In case order status is changed from completed or processing to a different one (except refunded) - we try to restore abandoned cart so that the reminder emails continue to be sent out.
	 *
	 * @since    8.2.1
	 * @param    integer    $order_id            ID of the order created by WooCommerce
	 * @param    string     $old_status          Previous order status. Default false
	 * @param    string     $new_status          New order status. Default false
	 */
	function handle_order( $order_id, $old_status = false, $new_status = false ){

		if( !isset( $order_id ) ){ //Exit if Order ID is not present
			return;
		}

		global $wpdb;
		$public = $this->public();
		$mailchimp = $this->mailchimp();
		$activecampaign = $this->activecampaign();
		$getresponse = $this->getresponse();
		$webhook = $this->webhook();
		$automation = $this->automation();

		$abandoned = $this->get_cart_type( 'abandoned' );
		$recovered = $this->get_cart_type( 'recovered' );
		$ordered = $this->get_cart_type( 'ordered' );
		$recovered_pending = $this->get_cart_type( 'recovered_pending' );

		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
		$time_intervals = $this->get_time_intervals();
		$order_status = $new_status;
		$field = 'wc_order_id';
		$value_type = '%d';
		$value = $order_id;
		$from_link = false;
		$session_id = false;
		$cart_found = false;
		$step_nr = false;
		$recovery = '';

		if( !$new_status ){ //If a new ordrer is placed (neither new nor old statuses exist)
			$public->update_logged_customer_id(); //In case user creates an account during checkout process, the session_id changes to a new one so we must update it
			$order = wc_get_order( $order_id );
			$order_status = $order->get_status();
			$field = 'session_id';
			$value_type = '%s';
			$value = '';

			if( WC()->session ){ //If WooCommerce session is started
				$cart = $public->read_cart();
				$value = $cart['session_id'];
				$session_id = $value;

				if( WC()->session->get( 'cartbounty_pro_from_link' ) ){ //If user has arrived from CartBounty recovery link
					$from_link = true;
				}

				if( WC()->session->get( 'cartbounty_pro_step_nr' ) ){ //Check which was the step number the user arrived from
					$step_nr = WC()->session->get( 'cartbounty_pro_step_nr' );
				}

				if( WC()->session->get( 'cartbounty_pro_recovery' ) ){ //Check which was the recovery type the user arrived from
					$recovery = WC()->session->get( 'cartbounty_pro_recovery' );
				}
			}
		}

		$cart = $wpdb->get_row( //Retrieve latest abandoned cart
			$wpdb->prepare(
				"SELECT *
				FROM $cart_table
				WHERE $field = $value_type AND
				cart_contents != '' AND
				time > %s
				ORDER BY time DESC",
				$value,
				$time_intervals['maximum_sync_period']
			)
		);

		if( !$cart ){ //If abandoned cart has not been found

			if( !$new_status ){
				return;
			}

			//Try one additonal search to locate cart by email and cart_contents. This is required in the case if there are multiple orders created by one cart and the status has not been changed by the latest order placed
			$order = wc_get_order( $order_id );
			$items = $order->get_items();
			$data = $order->get_data();
			$email = '';
			$phone = '';

			if( isset( $data['billing']['email'] ) ){
				$email = $data['billing']['email'];
			}

			if( isset( $data['billing']['phone'] ) ){
				$phone = $data['billing']['phone'];
			}

			$cart_contents = array();

			foreach( $items as $item_id => $item ){
				$product_id = $item->get_product_id(); // the Product id
				$cart_contents[] = array( 'product_id' => $product_id );
			}

			$recent_unpaid_user_carts = $this->get_recent_unpaid_user_carts( $email, $phone );
			$matching_carts = $this->get_matching_cart_contents( $recent_unpaid_user_carts, maybe_serialize( $cart_contents ) );
			
			if( empty( $matching_carts ) ){ //Exit in case we have not been able to find the cart
				return;
			}

			$matching_carts = reset( $matching_carts );
			$cart = $wpdb->get_row( //Retrieve latest abandoned cart
				$wpdb->prepare(
					"SELECT *
					FROM $cart_table
					WHERE id = %d AND
					cart_contents != '' AND
					time > %s
					ORDER BY time DESC",
					$matching_carts->id,
					$time_intervals['maximum_sync_period']
				)
			);

			$cart_found = true;

			if( !$cart ){ //If abandoned cart has not been found
				return;
			}
		}

		$unfinished_statuses = $this->unfinished_order_statuses();

		if ( in_array( $order_status, $unfinished_statuses ) ) { //If order has unfinished order status - must leave or restore abandoned cart in the list and continue with abandoned cart recovery

			if( $old_status ){ //If previous status exists
				if ( in_array( $old_status, $unfinished_statuses ) ) { //If previous status was already unfinished - do not run this again as there will be nothing to update
					return;
				}
			}

			if( $cart->type == $recovered || $new_status == 'refunded' ){ //Exit and do not do anything since cart already was recovered or order has been refunded
				return;
			}

			if( $from_link ){ //If user has arrived from CartBounty recovery link
				$type = $recovered_pending;
				$this->update_cart_type( $session_id, $type, $order_id, $field, $cart_found, $cart ); //Update cart type to recovered order with pending payment

			}else{
				$type = $abandoned;
				
				if( $cart->type == $recovered_pending ){ //In case the cart previously was marked as recovered with pending order, do not change it so we would later know if the order gets paid for that it was recovered with the help of abandoned cart recovery
					$type = $recovered_pending;
				}

				$this->update_cart_type( $session_id, $type, $order_id, $field, $cart_found, $cart ); //Update cart type to recovered order with pending payment
			}

		}else{ //If order has finished order status (e.g., Completed or Processing) - exclude the cart from abandoned cart reminders

			if( $old_status ){ //If previous status exists
				if ( ! in_array( $old_status, $unfinished_statuses ) ) { //If previous order status was not already unfinished - do not run this again as there will be nothing to update
					return;
				}
			}

			if( $cart->type == $recovered ){ //If cart has been marked recovered - exit and do not do anything since cart already was recovered and there is nothing else to be done
				return;
			}

			$activecampaign->sync_order( $cart );
			$getresponse->sync_order( $cart );
			$mailchimp->sync_order( $cart );
			$webhook->sync_order( $cart );

			if( $from_link ){ //If user has arrived from CartBounty recovery link
				$type = $recovered;
				
			}else{
				$type = $ordered;

				if( $cart->type == $recovered_pending ){ //In case the cart previously was marked as recovered with pending order, do not change it so we would later know if the order gets paid for that it was recovered with the help of abandoned cart recovery
					$type = $recovered;
				}
			}

			$this->update_cart_type( $session_id, $type, $order_id, $field, $cart_found, $cart );

			//Calculate recovered message stats for WordPress, BulkGate and Push notifications
			if( $type == $recovered ){
				$active_automations = array();
				
				
				//If no recovery options are passed (case when order Processing or Completed status gets updated later)
				//List all active automations that should count recovered cart count
				if( !$recovery ){
					
					if( $automation->automation_enabled( 'wordpress' ) ){
						$active_automations[] = 'wordpress';
					}

					if( $automation->automation_enabled( 'bulkgate' ) ){
						$active_automations[] = 'bulkgate';
					}

					if( $automation->automation_enabled( 'push_notification' ) ){
						$active_automations[] = 'push_notification';
					}

				}else{
					$active_automations[] = $recovery;
				}

				foreach( $active_automations as $key => $recovery_name) {
					$automation->handle_message_stats( 'recovered', $cart->id, $step_nr, $recovery_name );
				}
			}

			$this->handle_duplicate_carts( $cart->email, $cart->phone, $cart->cart_contents );
		}

		if( !$new_status ){ //If a new order is placed

			$automation->update_message_stats( $action = 'recovered', $cart->id, $step_nr, $recovery );
			
			if( WC()->session ){ //If WooCommerce session is started
				WC()->session->set( 'cartbounty_pro_order_placed', true ); //Add marker to session since we do not want to clear the abandoned cart saved via CartBounty after it has been ordered. This happened when the order was placed quickly on the Checkout page and the cart update function fired after the order was already placed.
			}
		}
	}

	/**
	 * Handling duplicate abandoned carts in case of a new order is placed.
	 * If duplicates are found, do not delete them, but remove them from integrations and set type to "ordered" (2).
	 *
	 * @since    9.5
	 * @param    string     $email                  Cart email
	 * @param    string     $phone                  Cart phone
	 * @param    array      $cart_contents          Cart contents
	 */
	function handle_duplicate_carts( $email, $phone, $cart_contents ){
		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;

		$recent_unpaid_user_carts = $this->get_recent_unpaid_user_carts( $email, $phone );
		$matching_carts = $this->get_matching_cart_contents( $recent_unpaid_user_carts, $cart_contents );

		if( empty( $matching_carts ) ) return;

		$mailchimp = $this->mailchimp();
		$activecampaign = $this->activecampaign();
		$getresponse = $this->getresponse();
		$webhook = $this->webhook();

		$mailchimp->delete_duplicate_carts( $matching_carts );
		$activecampaign->delete_duplicate_carts( $matching_carts );
		$getresponse->delete_duplicate_carts( $matching_carts );
		$webhook->delete_duplicate_carts( $matching_carts );

		$ordered = $this->get_cart_type( 'ordered' );
		$duplicate_cart_ids = array();

		foreach ( $matching_carts as $key => $cart ) {
			$duplicate_cart_ids[] = $key;
		}

		if( empty( $duplicate_cart_ids ) ) return;

		$ids = implode( ', ', $duplicate_cart_ids );
		$placeholders = implode( ', ', array_fill( 0, count( $duplicate_cart_ids ), '%d' ) );

		$result = $wpdb->query( //Update all duplicate carts to type = ordered (2)
			$wpdb->prepare(
				"UPDATE $cart_table
				SET type = %d
				WHERE id IN ($placeholders)",
				array_merge( array( $ordered ), $duplicate_cart_ids )
			)
		);
	}

	/**
	 * Returning recoverable abandoned carts with the same email address or phone number which have not been paid for during the last 7 days
	 *
	 * @since    9.5
	 * @return   array 
	 * @param    string     $email                  Email we are searching for 
	 * @param    string     $phone                  Phone we are searching for 
	 */
	function get_recent_unpaid_user_carts( $email, $phone ){
		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
		$where_sentence = $this->get_where_sentence( 'recoverable' );
		$time_intervals = $this->get_time_intervals();

		if( !$this->validate_phone_number( $phone ) ){ //If phone number is not valid, considering it empty
			$phone = '';
		}
		
		$carts = $wpdb->get_results( //Get carts with the same email in the last 7 days
			$wpdb->prepare(
				"SELECT *
				FROM $cart_table
				WHERE ((email = %s AND email != '') OR (phone = %s AND phone != ''))
				$where_sentence AND
				time > %s
				ORDER BY time DESC",
				$email,
				$phone,
				$time_intervals['week']
			)
		);

		return $carts;
	}

	/**
	 * Retrieve abandoned carts that have the same contents that are passed for comparing.
	 * Not looking at product variations, quantities or prices - if the product ID values match, we consider it as a duplicate cart which should no longer be reminded about
	 *
	 * @since    9.5
	 * @return   array 
	 * @param    array      $carts                  Abandoned carts
	 * @param    array      $cart_contents          Cart contents that must be compared
	 */
	function get_matching_cart_contents( $carts, $cart_contents ){
		
		if( empty( $carts ) ) return; //Exit if we have no carts

		$cart_contents = $this->get_saved_cart_contents( $cart_contents );
		
		if( !is_array( $cart_contents ) ){ //In case cart contents are not an array - exit
			return;
		}
		
		$ordered_products = array();
		$duplicate_carts = array();

		foreach( $cart_contents as $key => $product ){ //Build ordered product array
			$ordered_products[] = $product['product_id'];
		}

		foreach( $carts as $key => $cart ){ //Build product comparison array for each cart look for duplicates
			$cart_contents_to_compare = $this->get_saved_cart_contents( $cart->cart_contents );
			
			if( is_array( $cart_contents_to_compare ) ){
				$products = array();
				foreach( $cart_contents_to_compare as $key => $product ){ //Build product array we are comparing against

					if( isset( $product['product_id'] )){
						$products[] = $product['product_id'];
					}
				}

				sort( $ordered_products );
			    sort( $products );

				if( $ordered_products == $products ){ //Comparing arrays
					$duplicate_carts[$cart->id] = $cart; //Cart is a duplicate, must add to duplicates array
				}
			}
		}

		return $duplicate_carts;
	}

	/**
	 * Adds one or more classes to the body tag in the dashboard
	 *
	 * @since    9.0
	 * @return   String    Altered body classes
	 * @param    String    $classes    Current body classes
	 */
	function add_cartbounty_body_class( $classes ) {
		global $cartbounty_pro_admin_menu_page;
		$screen = get_current_screen();
		if(is_object($screen) && $screen->id == $cartbounty_pro_admin_menu_page){ //If we are on CartBounty page
			$classes = $classes .' '.  CARTBOUNTY_PRO_PLUGIN_NAME_SLUG .' ';
		}
	    return $classes;
	}

	/**
	 * Returns a link with tracking information
	 *
	 * @since    9.2.1
	 * @return   String
	 * @param    String    $url        URL
	 * @param    String    $medium     Determines where the button was clicked from. Default none
	 * @param    String    $tag        Hashtag to a specific section in the document. Default none
	 */
	function get_trackable_link( $url, $medium = '', $tag = '' ) {
		$medium = 'pro_' . $medium;
		return $url .'?utm_source='. urlencode(get_bloginfo("url")) .'&utm_medium='. esc_attr( $medium ) .'&utm_campaign='. esc_attr( CARTBOUNTY_PRO ) . esc_attr( $tag );
	}

	/**
	* Temporary function since version 9.3.2. Will be removed in future releases
	* Making sure that the Type column default value is changed from NULL into 0
	*
	* @since    9.3.2
	*/
	function update_type_column(){
		$misc_settings = $this->get_settings( 'misc_settings' );

		if( !$misc_settings['type_column_updated'] ){ //If we have not yet updated the column
			global $wpdb;
			$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
			//Update cart row according to what the cart has been synced to before
			$wpdb->query(
				$wpdb->prepare(
					"UPDATE $cart_table
					SET type = %d
					WHERE type IS NULL OR type = %s",
					$this->get_cart_type('abandoned'),
					''
				)
			);
			
			$misc_settings['type_column_updated'] = true;
			update_option( 'cartbounty_pro_misc_settings', $misc_settings ); //Making sure this function is fired once
		}
	}

	/**
	 * Returns abandoned cart product price with or without VAT
	 *
	 * @since    9.3.3
	 * @return   Number
	 * @param    Array or Object    $product          		Cart line item (array) or WooCommerce Product (object)
	 * @param    Boolean  			$force_tax     			Should we bypass all filters and display price with VAT. Default false
	 * @param    Boolean  			$force_exclude_tax     	Weather we should bypass all filters and exclude taxes in the price. Default false
	 */
	function get_product_price( $product, $force_tax = false, $force_exclude_tax = false ) {
		if ( !class_exists( 'WooCommerce' ) ){ //If WooCommerce is not active
			return;
		}

		$tax = 0;
		$price = 0;
		$decimals = 0;

		if( wc_get_price_decimals() ){
			$decimals = wc_get_price_decimals();
		}

		if( is_array( $product ) ){ //In case we are working with CartBounty line item
			$price = $product['product_variation_price'];
			
			if( empty( $price ) ){
				$price = 0;
			}

			if( isset( $product['product_tax'] ) ){ //If tax data exists
				$tax = $product['product_tax'];
			}

		}elseif( is_object( $product ) ){ //In case we are working with WooCommerce product
			$price_with_tax = wc_get_price_including_tax( $product );
			$price = $product->get_price();
			
			if( empty( $price_with_tax ) ){
				$price_with_tax = 0;
			}

			if( empty( $price ) ){
				$price = 0;
			}
			
			$product_data = $product->get_data();

			//Calculate WooCommerce Product Bundles plugin pricing
			if( isset( $product_data['min_raw_price'] ) ){ //Using minimum price of WooCommerce Product Bundle item
				$price_with_tax = $product_data['min_raw_price'];
			}

			$tax = $price_with_tax - $price;
		}

		if( $force_exclude_tax ){ //If we do not wat to include taxes. E.g., in GetResponse sync
			$tax = 0;
		}

		if( !empty( $tax ) && ( apply_filters( 'cartbounty_pro_include_tax', true ) || $force_tax == true ) ){ //If the tax value is set, the filter is set to true or the taxes are forced to display
			$price = $price + $tax;
		}

		if( empty( $price ) ){ //In case the price is empty
			$price = 0;
		}

		return round( $price, $decimals );
	}

	/**
	* Method sanitizes field allowing only safe output
	*
	* @since    9.3.3
	* @return   string
	* @param    string    $field    		  Field that should be sanitized
	*/
	public function sanitize_field( $field ){
		$allowed_html = wp_kses_allowed_html( 'post' );
		$allowed_html = apply_filters( 'cartbounty_pro_allowed_html', $allowed_html );
		$content = wp_kses( $field, $allowed_html );
		return $content;
	}

	/**
     * Returning Tools defaults
     *
     * @since    9.4.1
     * @return   array or string
     * @param    string     $value    		  	  Value to return
     * @param    integer    $tool    		      Tool name
     */
	public function get_tools_defaults( $value = false, $tool = false ){
		switch ( $tool ) {
			case 'exit_intent':

				$defaults = array(
					'heading'		=> esc_html__( 'You were not leaving your cart just like that, right?', 'woo-save-abandoned-carts' ),
					'heading_name'	=> 'Exit Intent title',
					'content'		=> esc_html__( 'Enter your details below to save your shopping cart for later. And, who knows, maybe we will even send you a sweet discount code :)', 'woo-save-abandoned-carts' ),
					'content_name'	=> 'Exit Intent content'
				);

				break;

			case 'early_capture':

				$defaults = array(
					'heading'		=> esc_html__( 'Please enter your details to add this item to your cart', 'woo-save-abandoned-carts' ),
					'heading_name'	=> 'Early capture title'
				);
			
				break;

			case 'tab_notification':

				$defaults = array(
					'content'		=> esc_html__( 'I miss you 💔', 'woo-save-abandoned-carts' ),
					'content_name'	=> 'Tab notification message',
					'interval'		=> 2000
				);
			
				break;

			case 'push_notification':

				$defaults = array(
					'permission_heading' 		=> esc_html__( 'Want to receive personalized offers?', 'woo-save-abandoned-carts' ),
					'permission_heading_name'	=> 'Notification permission title',
					'permission_content'		=> esc_html__( 'Allow notifications to get real-time updates about your shopping cart and who knows, you may even receive a sweet discount code 😊', 'woo-save-abandoned-carts' ),
					'permission_content_name'	=> 'Notification permission content',
					'permission_style' 			=> 1,
					'main_color' 				=> '',
					'inverse_color' 			=> '',
					'permission_image' 			=> ''
				);
			
				break;
		}

		if($value){ //If a single value should be returned
			if(isset($defaults[$value])){ //Checking if value exists
				$defaults = $defaults[$value];
			}
		}

		return $defaults;
	}

	/**
	* Method for outputting price accordingly to the user's selected WooCommerce currency position
	*
	* @since    9.4.1
	* @return   string
	* @param    float      $price    		  	  Price value
	* @param    string     $currency_code   	  Currency code, e.g. EUR, USD
	*/
	public function format_price( $price, $currency_code = false ){
		
		if( !class_exists( 'WooCommerce' ) ) return;

		$decimals = 0;
		
		if( wc_get_price_decimals() ){
			$decimals = wc_get_price_decimals();
		}

		$price = number_format( ( float )$price, $decimals, '.', '' ); //Format price so there would always be correct number of decimals after comma, e.g. 2.30 instead of 2.3
		$woocommerce_price_format = get_woocommerce_price_format(); //Retrieve the pricing format the user has set
		$currency = $this->get_currency( $currency_code );
		$price = sprintf( apply_filters( 'cartbounty_pro_price_format', $woocommerce_price_format ), $currency, $price );
		return $price;
	}

	/**
	* Return currency from provided currency code
	*
	* @since    9.6
	* @return   string
	* @param    string     $currency_code   	  Currency code, e.g. EUR, USD
	*/
	public function get_currency( $currency_code = false ){
		
		if( !class_exists( 'WooCommerce' ) ) return;

		$currency = get_woocommerce_currency_symbol( $currency_code );

		if( apply_filters( 'cartbounty_pro_display_currency_code', false ) ){ //If currency code display is enabled, display currency code instead of symbol. By default we display currency symbol
			$currency = $currency_code;
		}

		if( empty( $currency ) ){ //If the currency is empty, retrieve default WooCommerce currency ignoring the one saved in the abandoned cart
			$currency = get_woocommerce_currency_symbol();
		}

		return $currency;
	}

	/**
	* Method scans all files inside CartBounty templates folder. 
	* Returns an array of all found files.
	*
	* @since    9.4.2
	* @return   array
	* @param    string    $default_path			Default path to template files.
	*/
	function scan_files( $default_path ){
		$files  = scandir($default_path);
		$result = array();

		if(!empty($files)){
			foreach($files as $key => $value){
				if(!in_array($value, array( '.', '..' ), true)){
					if(is_dir($default_path . '/' . $value)){
						$sub_files = $this->scan_files( $default_path . '/' . $value );
						foreach($sub_files as $sub_file){
							$result[] = $sub_file;
						}
						foreach ($sub_files as $sub_file){
							$result[] = $value . '/' . $sub_file;
						}

					}else{
						$result[] = $value;
					}
				}
			}
		}
		return $result;
	}

	/**
	* Get an array of templates that have been overridden
	*
	* @since    9.4.2
	* @return   array
	*/
	function get_template_overrides(){
		$template_path = 'templates/';
		$default_path = plugin_dir_path( __FILE__ ) . '../templates/';
		$override_files = array();
		$scan_files = $this->scan_files( $default_path );

		foreach($scan_files as $file){
			if(file_exists(get_stylesheet_directory() . '/' . $file)){
				$theme_file = get_stylesheet_directory() . '/' . $file;

			}elseif(file_exists(get_stylesheet_directory() . '/' . $template_path . $file)){
				$theme_file = get_stylesheet_directory() . '/' . $template_path . $file;

			}elseif(file_exists(get_template_directory() . '/' . $file)){
				$theme_file = get_template_directory() . '/' . $file;

			}elseif(file_exists(get_template_directory() . '/' . $template_path . $file)){
				$theme_file = get_template_directory() . '/' . $template_path . $file;

			}else{
				$theme_file = false;
			}

			if(!empty($theme_file)){
				$override_files[] = str_replace(WP_CONTENT_DIR . '/themes/', '', $theme_file);
			}
		}
		return $override_files;
	}

	/**
	* Prepare abandoned cart rows for output.
	* Personal data is anonymized.
	*
	* @since    9.4.2
	* @return   array
	* @param    array    $carts			Abandoned carts
	*/
	public function prepare_cart_rows( $carts ){
		$anonymized_carts = array();
		$max_products = 10; //Maximum products that will be displayed in the notification email

		if( !empty( $carts ) ){
			foreach( $carts as $key => $cart ){
				$products = array();
				$email = '';
				$phone = '';
				$pn_subscription = '';

				if( !empty( $cart->email ) ){
					$email = $this->anonymize_email( $cart->email );

					//If anonymization is disabled via filter, then output full data
					$anonymize_admin_notification_email = apply_filters( 'cartbounty_pro_admin_anonymize_notification_email', true );
					
					if( !$anonymize_admin_notification_email ){
						$email = $cart->email;
					}
				}

				if( !empty( $cart->phone ) ){
					$phone = $this->anonymize_phone( $cart->phone );

					//If anonymization is disabled via filter, then output full data
					$anonymize_admin_notification_phone = apply_filters( 'cartbounty_pro_admin_anonymize_notification_phone', true );
					
					if( !$anonymize_admin_notification_phone ){
						$phone = $cart->phone;
					}
				}

				if( !empty( $cart->pn_subscription ) ){
		            $pn_subscription = esc_html__( 'Push notification' );
		        }

		        if( isset( $cart->cart_contents ) ){ //If we have a cart

					if( !empty( $cart->cart_contents ) ){

						$cart_contents = $this->get_saved_cart_contents( $cart->cart_contents );
						
						if( is_array( $cart_contents ) ){
							$limit = 1;

							foreach( $cart_contents as $key => $item ){ //Building product array
								
								if( $limit > apply_filters( 'cartbounty_pro_notification_max_products', $max_products ) ){ //Once we have reached the maximum product count that can be displayed, stop adding new ones
									break;
								}
								
								$image_url = $this->get_product_thumbnail_url( $item, 'thumbnail' );
								$product_price = $this->get_product_price( $item );

								$products[] = array(
									'title' => $item['product_title'],
									'price' => $this->format_price( $product_price, esc_html( $cart->currency ) ),
									'quantity' => $item['quantity'],
									'image' => $image_url,
									'id' => $item['product_id']
								);
								$limit++;
							}
						}
					}
				}

				$anonymized_carts[] = array(
					'email' 			=> $email,
					'phone' 			=> $phone,
					'pn_subscription' 	=> $pn_subscription,
					'products' 			=> $products,
					'cart_total' 		=> $this->format_price( $cart->cart_total, esc_html( $cart->currency ) ),
				);
			}
		}

		return $anonymized_carts;
	}

	/**
	* Anonymize email
	*
	* @since    9.4.2
	* @return   string
	* @param    string    $email			Email address
	*/
	public function anonymize_email( $email ){
		$em = explode( '@', $email );
		$name = implode( '@', array_slice($em, 0, count($em) - 1) );
		$length = floor( strlen($name)/2 );
		if( $length > 3 ){
			$length = 3;
		}
		return substr($name, 0, $length) . '***' . '@' . end($em);
	}

	/**
	* Anonymize phone number
	*
	* @since    9.4.2
	* @return   string
	* @param    string    $phone			Phone number
	*/
	public function anonymize_phone( $phone ){
		return substr($phone, 0, 5) . '***';
	}

	/**
	* Anonymize string
	*
	* @since    10.1
	* @return   string
	* @param    string    $string			Any string that reuqires to be anonymized
	*/
	public function anonymize_string( $string ){
		$length = mb_strlen( $string, 'UTF-8' );
		
		if( $length > 3 ) {
			$length = 3;
		}

		return mb_substr( $string, 0, $length, 'UTF-8' ) . '***';
	}

	/**
	* Add email badge
	*
	* @since    9.4.2
	* @return   html
	*/
	function add_email_badge(){
		$public = $this->public();
		$image = $public->get_plugin_url() . '/public/assets/sent-via-cartbounty.png';
		$output = '';
		$output .= '<table cellpadding="0" cellspacing="0" border="0" align="center" style="border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt;">
			<tr>
				<td valign="top">
					<table cellpadding="0" cellspacing="0" border="0" align="center" style="border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt;">
						<tr>
							<td valign="top" width="650"  align="center" style="text-align: center;">
								<a href="'. esc_url( $this->get_trackable_link('', 'admin_notification_email') ) .'" style="display: block;">
									<img src="'. esc_url( $image ) .'" alt="'. esc_attr( CARTBOUNTY_PRO_SHORT ) .'" title="'. esc_attr( CARTBOUNTY_PRO_SHORT ) .'" width="130" height="auto" style="display:inline; text-align: center; margin: 0; -ms-interpolation-mode: bicubic; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; border: none 0;" />
								</a>
							</td>
						</tr>
					</table>
				</td>
			</tr>
		</table>';
		echo $output;
	}

	/**
	 * Fire functions on WordPress load
	 *
	 * @since    9.4.3
	 */
	function trigger_on_load(){
		$wordpress = $this->wordpress();
		$this->restore_cart(); //Restoring abandoned cart if a user returns back from an abandoned cart email link
		$wordpress->track_email_open_rate(); //Tracking email open rate for WordPress recovery emails
		$this->validate_cart_deletion(); //Make sure abandoned cart deletion passes nonce security
	}

	/**
     * Setting message language according to the user's language the cart was left
     * Loco translate is able to use switch_to_locale() function and default get_locale language like "es_ES"
     * WPML does not support switch_to_locale function so we use WPML sitepress global variable
     *
     * @since    9.3
     * @param    object     $locale   		Current language locale
     */
	public function set_message_language( $language = false ){
		//For additional WPML support
		$wpml = new CartBounty_Pro_WPML();

		if( $wpml->wpml_enabled() ){
			global $sitepress;

			if( method_exists( $sitepress, 'switch_lang' ) ){
				do_action( 'wpml_switch_language', $this->get_language_code( $language ) );
			}

		}else{
			switch_to_locale( $this->adjust_locale( $language ) );
			$this->cartbounty_pro_text_domain(); //Loading text domain or else no translations are visible
		}
	}

	/**
	 * Adjusting WordPress language locale in case the translation locale is different
	 * E.g. WordPress returns Latvian locale as 'lv_LV', but the translation locale is set as 'lv'
	 *
	 * @since    9.3
	 * @return   String
	 * @param    String   $locale     WordPress language locale
	 */
	function adjust_locale( $locale = false ){
		$locales = array(
			'lv_LV'	=> 'lv',
		);

		if( isset( $locales[$locale] ) ){
			$locale = $locales[$locale];
		}

		return $locale;
	}

	/**
	 * Return language code. Taking WordPress locale like 'es_ES' and turning it into 'es'
	 *
	 * @since    9.6
	 * @return   String
	 * @param    String   $locale     WordPress language
	 */
	function get_language_code( $locale ){
		
		if ( !empty( $locale ) ){
			$language = explode( '_', $locale );
			
			if ( ! empty( $language ) && is_array( $language ) ) {
				$locale = strtolower( $language[0] );
			}
		}

		return $locale;
	}

	/**
	 * Return locale with hyphen instead of default underscore. Taking WordPress locale like 'es_ES' and turning it into 'es-ES'
	 *
	 * @since    10.0
	 * @return   String
	 * @param    String   $locale     WordPress language
	 */
	function get_locale_with_hyphen( $locale ){
		
		if ( !empty( $locale ) ){
			$locale = str_replace('_', '-', $locale);
		}

		return $locale;
	}

	/**
	 * Detect current language
	 *
	 * @since    10.7
	 * @return   String
	 */
	function detect_languege(){
		$language = get_locale();
		return $language;
	}

	/**
	 * Output emoji button
	 *
	 * @since    9.6
	 * @return   HTML
	 */
	function add_emojis(){
		$icon = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 67 67"><path d="M33.5,0A33.5,33.5,0,1,0,67,33.5,33.5,33.5,0,0,0,33.5,0Zm0,61.88A28.37,28.37,0,1,1,61.86,33.51,28.37,28.37,0,0,1,33.49,61.88Z"/><path d="M24.23,32a2.55,2.55,0,0,1-2.55-2.55c0-2,0-3.1,0-5.21a2.46,2.46,0,0,1,2.55-2.54,2.51,2.51,0,0,1,2.54,2.57c0,.72,0,5.2,0,5.2A2.56,2.56,0,0,1,24.25,32Z"/><path d="M42.78,32a2.55,2.55,0,0,1-2.54-2.58c0-2.17,0-3.2,0-5.21a2.55,2.55,0,0,1,5.09,0c0,.71,0,5.2,0,5.2A2.55,2.55,0,0,1,42.78,32Z"/><path d="M18.64,43.33a27.92,27.92,0,0,0,5.52,4.35,19.35,19.35,0,0,0,18.52.08,27,27,0,0,0,5.67-4.43c2.54-2.38-1.28-6.2-3.82-3.82a22.36,22.36,0,0,1-4.11,3.33,14,14,0,0,1-6.92,1.84,13.83,13.83,0,0,1-6.77-1.75,22.73,22.73,0,0,1-4.27-3.42c-2.53-2.38-6.36,1.44-3.82,3.82Z"/></svg>';
		$output = "<div class='cartbounty-pro-icon-button-container'><div class='cartbounty-pro-button button-secondary cartbounty-pro-emoji cartbounty-pro-icon-button button'>". $icon ."</div></div>";
		echo $output;
	}

	/**
	 * Output persnalization tags button
	 *
	 * @since    9.6
	 * @return   HTML
	 */
	function add_tags( $exclude = array() ){
		$icon = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 82.56 67.4"><path d="M3.55,67.4c-1.93,0-3.28-.49-3.49-2a18.69,18.69,0,0,1,.22-4.31c.16-1.13.31-2.19.55-3.23,2.55-11,9.08-19,19.39-23.74L22.56,33l-1.68-1.92c-5.08-5.42-6.58-11.6-4.46-18.34S23.34,1.73,30.56.32A17.8,17.8,0,0,1,33.89,0,18.22,18.22,0,0,1,35.5,36.35c-.82.09-1.65.13-2.53.17a28.77,28.77,0,0,0-4.19.39C17.7,39.05,10.2,45.6,6.51,56.37,6.19,57.32,5,62.25,5,62.25H33.45a2.69,2.69,0,0,1,2.28,1.16A2.46,2.46,0,0,1,36,65.74a2.38,2.38,0,0,1-2.14,1.6C33.56,67.37,3.55,67.4,3.55,67.4Zm30-61.91a12.91,12.91,0,0,0-9.14,22,12.74,12.74,0,0,0,9.1,3.79,12.91,12.91,0,0,0,.08-25.82Z"/><path d="M80,46.72H67.12V33.89a2.61,2.61,0,0,0-5.21,0V46.72H49.08a2.61,2.61,0,1,0,0,5.21H61.91V64.76a2.61,2.61,0,1,0,5.21,0V51.93H80a2.61,2.61,0,1,0,0-5.21Z"/></svg>';
		$output = "<div class='cartbounty-pro-icon-button-container'><div class='cartbounty-pro-button button-secondary cartbounty-pro-tags cartbounty-pro-icon-button button'>". $icon ."</div><div class='cartbounty-pro-tags-container'>". $this->output_tags( $exclude ) ."</div></div>";
		echo $output;
	}

	/**
	 * Output personalization tags
	 *
	 * @since    9.6
	 * @return   HTML
	 * @param    array    $exclude				Tags that should be excluded
	 */
	function output_tags( $exclude = array() ){
		$tags = array(
			'name'				=> __( 'Name', 'woo-save-abandoned-carts' ),
			'surname'			=> __( 'Surname', 'woo-save-abandoned-carts' ),
			'email'				=> __( 'Email', 'woo-save-abandoned-carts' ),
			'phone'				=> __( 'Phone', 'woo-save-abandoned-carts' ),
			'country'			=> __( 'Country', 'woo-save-abandoned-carts' ),
			'city'				=> __( 'City', 'woo-save-abandoned-carts' ),
			'postcode'			=> __( 'Postcode', 'woo-save-abandoned-carts' ),
			'language'			=> __( 'Language', 'woo-save-abandoned-carts' ),
			'cart_total'		=> __( 'Cart total', 'woo-save-abandoned-carts' ),
			'currency'			=> __( 'Currency', 'woo-save-abandoned-carts' ),
			'item_count'		=> __( 'Item count', 'woo-save-abandoned-carts' ),
			'product_id'		=> __( 'Product ID', 'woo-save-abandoned-carts' ),
			'coupon'			=> __( 'Coupon code', 'woo-save-abandoned-carts' ),
			'coupon_expiry'		=> __( 'Coupon expiration date', 'woo-save-abandoned-carts' ),
			'recovery_link'		=> __( 'Recovery link', 'woo-save-abandoned-carts' ),
			'unsubscribe_link'	=> __( 'Unsubscribe link', 'woo-save-abandoned-carts' ),
			'store_name'		=> __( 'Store name', 'woo-save-abandoned-carts' )
		);

		if( !empty( $exclude ) ){ //In case there are tags that should be removed
			foreach($exclude as $key){
				unset( $tags[$key] );
			}
		}

		$output = '<div class="cartbounty-pro-tags-list-container cartbounty-pro-options-tooltip">';
		$output .= '<h3 class="cartbounty-pro-tags-title">'. esc_html__( 'Add personalization', 'woo-save-abandoned-carts' ) .'</h3>';
		$output .= '<div class="cartbounty-pro-tags-list">';
		$output .= '<ul>';
		foreach ($tags as $key => $tag) {
			$output .= '<li><a href="#" title="'. esc_attr( $tag ) .'" data-tag="'. esc_attr( $key ) .'">'. esc_html( $tag ) .'</a></li>';
		}
		$output .= '</ul>';
		$output .= '</div>';
		$output .= '</div>';
		return $output;
	}

	/**
	 * Prepare personalization tags
	 * First we exctract and handle all [if] .. [else] .. [endif] or [if] .. [endif] conditionals.
	 * After that we populate the remaining tags with data or use fallbacks if data missing.
	 * Nested conditional statements are not supported.
	 *
	 * @since    9.6
	 * @return   string
	 * @param    string    $content				Content that has to be prepared
	 * @param    object    $cart    			Cart data
	 * @param    string    $coupon_code    		Coupon code
	 * @param    string    $coupon_expiry    	Coupon code expiration
	 * @param    string    $recovery_link    	Recovery link
	 * @param    string    $unsubscribe_link    Unsubscribe link
	 * @param    boolean   $in_tags    			Weather recovery and unsubscribe links should be wrapped in <a></a> tags
	 */
	function prepare_tags( $content, $cart, $coupon_code = false, $coupon_expiry = false, $recovery_link = false, $unsubscribe_link = false, $in_tags = false ){
		$content = $this->extract_conditionals( htmlspecialchars_decode( $content ), $cart, $coupon_code, $coupon_expiry, $recovery_link, $unsubscribe_link, $in_tags ); //Using character decoding function since '>' value is saved in the database as &gt;
		$content = $this->replace_tags( $content, $cart, $coupon_code, $coupon_expiry, $recovery_link, $unsubscribe_link, $in_tags ); //Handle tag replacements and fallbacks
		return $content;
	}

	/**
	 * Extract conditional statements
	 *
	 * @since    9.6
	 * @return   string
	 * @param    string    $content				Content that has to be extracted
	 * @param    object    $cart    			Cart data
	 * @param    string    $coupon_code    		Coupon code
	 * @param    string    $coupon_expiry    	Coupon code expiration
	 * @param    string    $recovery_link    	Recovery link
	 * @param    string    $unsubscribe_link    Unsubscribe link
	 * @param    boolean   $in_tags    			Weather recovery and unsubscribe links should be wrapped in <a></a> tags
	 */
	function extract_conditionals( $content, $cart, $coupon_code = false, $coupon_expiry = false, $recovery_link = false, $unsubscribe_link = false, $in_tags = false ){
		$extracted_content = '';
		if( preg_match( '/\[if[^\]]*\]/s', $content ) ){ //If content has conditional statement [if:...] block inside
			preg_match( '/(^$|.*?)\[if(.+?)\](.+?)\[endif\](^$|.*)/s', $content, $matches ); //Extract conditional block

			if( isset( $matches[1] ) ){ //Add first match to the extracted string as this should always be string
				$extracted_content .= $matches[1];
			}

			if( isset( $matches[2] ) ){ //Handle if / else condition
				if( isset( $matches[3] ) ){
					$extracted_content .= $this->handle_condition( $matches[2], $matches[3], $cart, $coupon_code, $coupon_expiry, $recovery_link, $unsubscribe_link, $in_tags );
				}
			}

			if( isset( $matches[4] ) ){ //Continue checking if there are any conditional statements left and extract them
				$extracted_content .= $this->extract_conditionals( $matches[4], $cart, $coupon_code, $coupon_expiry, $recovery_link, $unsubscribe_link, $in_tags );
			}

		}else{ //In case there are no longer any conditional statements
			$extracted_content = $content;
		}

		return $extracted_content;
	}

	/**
	 * Replace tags with content
	 *
	 * @since    9.6
	 * @return   string
	 * @param    string    $content				Content that has to be extracted
	 * @param    object    $cart    			Cart data
	 * @param    string    $coupon_code    		Coupon code
	 * @param    string    $coupon_expiry    	Coupon code expiration
	 * @param    string    $recovery_link    	Recovery link
	 * @param    string    $unsubscribe_link    Unsubscribe link
	 * @param    boolean   $in_tags    			Weather recovery and unsubscribe links should be wrapped in <a></a> tags
	 */
	function replace_tags( $content, $cart, $coupon_code = false, $coupon_expiry = false, $recovery_link = false, $unsubscribe_link = false, $in_tags = false ){
		$replaced_content = '';
		if( preg_match( '/\[[^\]]*\]/s', $content ) ){ //If content has [...] tag block inside
			preg_match( '/(^$|.*?)\[(.+?)\](^$|.*)/s', $content, $matches ); //Extract tag

			if( isset( $matches[1] ) ){ //Add first match to the extracted string as this should always be string
				$replaced_content .= $matches[1];
			}

			if( isset( $matches[2] ) ){ //Handle condition
				$replaced_content .= $this->handle_replacement( $matches[2], $cart, $coupon_code, $coupon_expiry, $recovery_link, $unsubscribe_link, $in_tags );
			}

			if( isset( $matches[3] ) ){ //Continue checking if there are any tags remaining that must be replaced with data
				$replaced_content .= $this->replace_tags( $matches[3], $cart, $coupon_code, $coupon_expiry, $recovery_link, $unsubscribe_link, $in_tags );
			}

		}else{ //In case there are no longer any tags remaining
			$replaced_content = $content;
		}

		return $replaced_content;
	}

	/**
	 * Handle conditional statement values
	 * Allowed operators are =, !=, >, <, >=, <=
	 *
	 * @since    9.6
	 * @return   string
	 * @param    string    $condition			Condition that is set
	 * @param    string    $outcome				Outcome for condition
	 * @param    object    $cart    			Cart data
	 * @param    string    $coupon_code    		Coupon code
	 * @param    string    $coupon_expiry    	Coupon code expiration
	 * @param    string    $recovery_link    	Recovery link
	 * @param    string    $unsubscribe_link    Unsubscribe link
	 * @param    boolean   $in_tags    			Weather recovery and unsubscribe links should be wrapped in <a></a> tags
	 */
	function handle_condition( $condition, $outcome, $cart, $coupon_code = false, $coupon_expiry = false, $recovery_link = false, $unsubscribe_link = false, $in_tags = false ){
		$variable = false;
		$operator = false;
		$comparison = false;

		if( preg_match( '/>=|<=|!=|=|>|</s', $condition ) ){ //If allowed operator is present in the condition
			preg_match( '/:(.*?)(>=|<=|!=|=|>|<)(.*)/s', $condition, $parts ); //Extract variable, operator and comparison value

			//Handle condition
			if( isset( $parts[1] ) ){ //If variable is set
				$variable = $this->get_tag_value( $parts[1], $cart, $coupon_code, $coupon_expiry, $recovery_link, $unsubscribe_link, $in_tags );
			}

			if( isset( $parts[2] ) ){ //If any operator provided >, <, =, != etc.
				$operator = str_replace( ' ', '', $parts[2] );
			}

			if( isset( $parts[3] ) ){ //If comparison
				$comparison = trim( $parts[3], ' ' );
				if( str_replace( ' ', '', strtolower( $parts[1] ) ) == 'phone'){ //In case we are comparing phone - trim all whitespaces in the number
					$comparison = str_replace( ' ', '', $parts[3] );
				}
			}

			if( empty( $operator ) ){ //If operator is missing
				return;
			}

			$conditional_outcome = $this->get_condition_outcome( $outcome );
			$result_map = array(
				"=" 	=> $variable == $comparison,
				"!=" 	=> $variable != $comparison,
				">" 	=> $variable > $comparison,
				"<" 	=> $variable < $comparison,
				">=" 	=> $variable >= $comparison,
				"<=" 	=> $variable <= $comparison
			);

			if( isset( $result_map[ $operator ] ) ){ //If such operator exists in our array
				if( $result_map[ $operator ] ) { //If comparison result is true
					if( isset( $conditional_outcome[ 'true' ] ) ){
						$outcome = $conditional_outcome[ 'true' ];

					}else{
						$outcome = '';
					}

				}else{ //If comparison result is false
					if( isset( $conditional_outcome[ 'false' ] ) ){
						$outcome = $conditional_outcome[ 'false' ];

					}else{
						$outcome = '';
					}
				}
			}
			
		}else{ //Handle boolean condition e.g. [if:name]
			preg_match( '/:(.*)/s', $condition, $parts ); //Extract variable

			if( isset( $parts[1] ) ){ //If variable is set
				$variable = $this->get_tag_value( $parts[1], $cart, $coupon_code, $coupon_expiry, $recovery_link, $unsubscribe_link, $in_tags );
			}

			$conditional_outcome = $this->get_condition_outcome( $outcome );

			if( $variable ){ //If value is true
				if( isset( $conditional_outcome[ 'true' ] ) ){
					$outcome = $conditional_outcome[ 'true' ];

				}else{
					$outcome = '';
				}

			}else{ //If value is false
				if( isset( $conditional_outcome[ 'false' ] ) ){
					$outcome = $conditional_outcome[ 'false' ];

				}else{
					$outcome = '';
				}
			}
		}

		return $outcome;
	}

	/**
	 * Handle tag replacement.
	 * Using regex to determine if we have fallback | divider not.
	 *
	 * @since    9.6
	 * @return   string
	 * @param    string    $tag					Tag or tag with fallback e.g. "name | John"
	 * @param    object    $cart    			Cart data
	 * @param    string    $coupon_code    		Coupon code
	 * @param    string    $coupon_expiry    	Coupon code expiration
	 * @param    string    $recovery_link    	Recovery link
	 * @param    string    $unsubscribe_link    Unsubscribe link
	 * @param    boolean   $in_tags    			Weather recovery and unsubscribe links should be wrapped in <a></a> tags
	 */
	function handle_replacement( $tag, $cart, $coupon_code = false, $coupon_expiry = false, $recovery_link = false, $unsubscribe_link = false, $in_tags = false ){
		if( preg_match( '/\|/s', $tag ) ){ //If fallback | is set
			preg_match( '/(.*)\|(.*)/s', $tag, $parts ); //Extract value, operator and comparison value

			if( isset( $parts[1] ) ){ //Default variable
				$link_name = false;
				if( str_replace( ' ', '', strtolower( $parts[1] ) ) == 'recovery_link' || str_replace( ' ', '', strtolower( $parts[1] ) ) == 'unsubscribe_link' ){ //In case we have a link [recovery_link | Link name] - the fallback is used as the name of the link
					$link_name = $parts[2];
				}

				$value = $this->get_tag_value( $parts[1], $cart, $coupon_code, $coupon_expiry, $recovery_link, $unsubscribe_link, $in_tags, $link_name );

				if( empty( $value ) ){
					if( isset( $parts[2] ) ){ //Fallback value
						$value = trim( $parts[2], ' ' ); //Removing whitespaces from the start and end of the value
					}
				}
			}

		}else{
			$value = $this->get_tag_value( $tag, $cart, $coupon_code, $coupon_expiry, $recovery_link, $unsubscribe_link, $in_tags );
		}

		return $value;
	}

	/**
	 * Get value according to the received conditional variable
	 *
	 * @since    9.6
	 * @return   string
	 * @param    string    			$value						Variable that has been received
	 * @param    object    			$cart    					Cart data
	 * @param    string    			$coupon_code    			Coupon code
	 * @param    string    			$coupon_expiry    			Coupon code expiration
	 * @param    string    			$recovery_link    			Recovery link
	 * @param    string    			$unsubscribe_link   		Unsubscribe link
	 * @param    boolean   			$in_tags    				Weather recovery and unsubscribe links should be wrapped in <a></a> tags
	 * @param    string or false    $link_name    				Used to change the default link name to a custom one
	 */
	function get_tag_value( $value, $cart, $coupon_code = false, $coupon_expiry = false, $recovery_link = false, $unsubscribe_link = false, $in_tags = false, $link_name = false ){
		$new_value = str_replace( ' ', '', strtolower( $value ) ); //Removing whitespaces and convert variable to lowercase

		switch ( $new_value ) {
			case 'name':

				$new_value = '';
				if( isset( $cart->name ) ){ //If name is set
					$new_value = $cart->name;
				}

				break;

			case 'surname':

				$new_value = '';
				if( isset( $cart->surname ) ){ //If surname is set
					$new_value = $cart->surname;
				}

				break;

			case 'email':

				$new_value = '';
				if( isset( $cart->email ) ){ //If email is set
					$new_value = $cart->email;
				}

				break;

			case 'phone':

				$new_value = '';
				if( isset( $cart->phone ) ){ //If phone is set
					$new_value = $cart->phone;
				}

				break;

			case 'cart_total':

				$new_value = 0;
				if( isset( $cart->cart_total ) ){ //If cart total is set
					$new_value = $cart->cart_total;
				}

				break;

			case 'currency':

				$new_value = $this->get_currency();
				if( isset( $cart->currency ) ){ //If currency is set
					$new_value = $this->get_currency( $cart->currency );
				}

				break;

			case 'item_count':

				$new_value = 0;
				if( isset( $cart->cart_contents ) ){ //If cart contents are set
					if( !empty( $cart->cart_contents ) ){
						$cart_contents = $this->get_saved_cart_contents( $cart->cart_contents );
						if( is_array( $cart_contents ) ){
							$new_value = count( $cart_contents );
						}
					}
				}

				break;

			case 'product_id':

				$new_value = 0;
				if( isset( $cart->cart_contents ) ){ //If cart contents are set
					if( !empty( $cart->cart_contents ) ){
						$cart_contents = $this->get_saved_cart_contents( $cart->cart_contents );
						if( is_array( $cart_contents ) ){
							if (count( $cart_contents ) == 1){ //If just one product is in the cart
								$new_value = $cart_contents[0]['product_id'];
							}
						}
					}
				}

				break;

			case 'coupon':

				$new_value = '';
				if( $coupon_code ){ //If coupon code is set
					$new_value = $coupon_code;
				}

				break;

			case 'coupon_expiry':

				$new_value = '';
				if( $coupon_expiry ){ //If coupon expiration date is set
					$new_value = $coupon_expiry;
				}

				break;

			case 'country':

				$new_value = '';
				if( isset( $cart->location ) ){ //If cart location is set
					if( !empty( $cart->location ) ){
						$new_value = $this->get_cart_location( $cart->location, 'country' );
					}
				}

				break;

			case 'city':

				$new_value = '';
				if( isset( $cart->location ) ){ //If cart location is set
					if( !empty( $cart->location ) ){
						$new_value = $this->get_cart_location( $cart->location, 'city' );
					}
				}

				break;

			case 'postcode':

				$new_value = '';
				if( isset( $cart->location ) ){ //If cart location is set
					if( !empty( $cart->location ) ){
						$new_value = $this->get_cart_location( $cart->location, 'postcode' );
					}
				}

				break;

			case 'language':

				$new_value = $this->get_language_code( get_locale() );
				if( isset( $cart->language ) ){ //If language is set
					$new_value = $this->get_language_code( $cart->language );
				}

				break;

			case 'recovery_link':

				$new_value = '';
				if( $recovery_link && $in_tags ){ //If recovery link is present and we want to output link with HTML tags (inside WordPress email)
					$name = esc_html__( 'Complete checkout', 'woo-save-abandoned-carts' );
					
					if( $link_name ){ //Check if custom link name provided [recovery_link | Link name]
						$name = trim( $link_name, ' ' );
					}

					$new_value = '<a href="' . $recovery_link . '">'. $name .'</a>';

				}else{
					$new_value = $recovery_link;
				}

				break;

			case 'unsubscribe_link':

				$new_value = '';
				if( $unsubscribe_link && $in_tags ){ //If unsubscribe link is present and we want to output link with HTML tags (inside WordPress email)
					$name = esc_html__( 'Unsubscribe', 'woo-save-abandoned-carts' );
					
					if( $link_name ){ //Check if custom link name provided [unsubscribe_link | Link name]
						$name = trim( $link_name, ' ' );
					}

					$new_value = '<a href="' . $unsubscribe_link . '">'. $name .'</a>';

				}else{
					$new_value = $unsubscribe_link;
				}

				break;

			case 'store_name':

				$new_value = get_bloginfo( 'name' );

				break;
		}

		return $new_value;
	}

	/**
	 * Get value according to the entered conditional variable
	 *
	 * @since    9.6
	 * @return   string
	 * @param    string    $outcome				Variable that has been received
	 */
	function get_condition_outcome( $outcome ){
		$outcome_aray = array();
		$outcome_aray['true'] = $outcome;

		if( preg_match( '/\[else\]/s', $outcome ) ){ //Check if the outcome has [else] statement inside with two parts of outcome
			preg_match( '/(^$|.*?)\[else\](^$|.*)/s', $outcome, $parts );
			
			if( isset( $parts[1] ) ){
				$outcome_aray['true'] = $parts[1];
			}

			if( isset( $parts[2] ) ){
				$outcome_aray['false'] = $parts[2];
			}
		}

		return $outcome_aray;
	}

	/**
	 * Check consent collection settings status
	 *
	 * @since    10.4
	 * @return   boolean
	 * @param    string     $value                Value to return
	 */
	function get_consent_settings( $value = false ){
		$settings = $this->get_settings( 'settings' );
		$consent_settings = array(
			'email' => false,
			'phone' => false
		);

		if( isset( $settings['email_consent'] ) ){
			$consent_settings['email'] = $settings['email_consent'];
		}

		if( isset( $settings['phone_consent'] ) ){
			$consent_settings['phone'] = $settings['phone_consent'];
		}

		if( $value ){ //If a single value should be returned
			
			if( isset( $consent_settings[$value] ) ){ //Checking if value exists
				$consent_settings = $consent_settings[$value];
			}
		}

		return $consent_settings;
	}

	/**
	 * Retrieve default consent placeholders
	 *
	 * @since    10.4
	 * @return   array
	 * @param    array     	$types    			Consent types, e.g. email, phone
	 */
	function get_consent_default_placeholders( $types = array() ){
		$email_consent_enabled = false;
		$phone_consent_enabled = false;
		$privacy_policy_url = '';
		$checkout_consent = esc_attr__( 'Get news and offers via text messages', 'woo-save-abandoned-carts' );
		$tools_consent = esc_attr__( 'By entering your phone number, you agree to get news and offers via text messages. You can unsubscribe using a link inside the message.', 'woo-save-abandoned-carts' );

		if( !empty( $types ) ){ //If request coming from Ajax

			foreach( $types as $key => $type ) {

				if( $type == 'email' ){
					$email_consent_enabled = true;
				}

				if( $type == 'phone' ){
					$phone_consent_enabled = true;
				}
			}

		}else{ //Default PHP request handling
			$consent_settings = $this->get_consent_settings();
			$email_consent_enabled = $consent_settings['email'];
			$phone_consent_enabled = $consent_settings['phone'];
		}

		if( $email_consent_enabled && $phone_consent_enabled ){
			$checkout_consent = esc_attr__( 'Get news and offers via email or text messages', 'woo-save-abandoned-carts' );
			$tools_consent = esc_attr__( 'By entering your email or phone number, you agree to get news and offers via email and text messages. You can unsubscribe using a link inside the message.', 'woo-save-abandoned-carts' );

		}elseif( $email_consent_enabled ){
			$checkout_consent = esc_attr__( 'Get news and offers via email', 'woo-save-abandoned-carts' );
			$tools_consent = esc_attr__( 'By entering your email, you agree to get news and offers via email. You can unsubscribe using a link inside the message.', 'woo-save-abandoned-carts' );
		}
		
		if ( function_exists( 'get_privacy_policy_url' ) ) { //This function is available starting from WP 4.9.6
			$privacy_policy_url = get_privacy_policy_url();
		}
		
		if( !empty( $privacy_policy_url ) ){ //If privacy policy url is available, add it to the default text
			$tools_consent = $tools_consent . ' ' . sprintf(
				/* translators: %s - URL link */
				esc_attr__( 'View %sPrivacy policy%s.', 'woo-save-abandoned-carts' ), '<a href="' . esc_attr( esc_url( $privacy_policy_url ) ) . '" target="_blank">', '</a>'
			);
		}

		return array(
			'checkout_consent' => $checkout_consent,
			'tools_consent' => $tools_consent,
		);
	}

	/**
	 * Retrieve consent input contents for ajax request
	 *
	 * @since    10.4
	 * @return   boolean
	 */
	function get_consent_placeholders(){

		if ( check_ajax_referer( 'consent_nonce', 'nonce', false ) == false ) { //If the request does not include our nonce security check, stop executing function
			wp_send_json_error( esc_html__( 'Looks like you are not allowed to do this.', 'woo-save-abandoned-carts' ) );
		}

		$placeholders = array();
		$consent_placeholders = array();

		if( isset( $_POST['checkboxes'] ) ){
			$checkboxes = $_POST['checkboxes'];

			if( is_array( $checkboxes ) ){
				
				foreach( $checkboxes as $key => $checkbox ){
					$consent_placeholders[] = $checkbox;
				}

				$placeholders = $this->get_consent_default_placeholders( $consent_placeholders );
			}
		}

		wp_send_json_success( $placeholders );
	}

	/**
	 * Check if international phone validation enabled
	 *
	 * @since    9.7
	 * @return   boolean
	 */
	function international_phone_enabled(){
		$enabled = false;
		$international_phone = $this->get_settings( 'settings', 'international_phone' );
		if( $international_phone ){ //If international phone validation enabled
			$enabled = true;
		}
		return $enabled;
	}

	/**
	 * Method displays quiet hour settings
	 *
	 * @since    9.7
	 * @return   string
	 * @param    string     $recovery			Recovery option
	 */
	function display_quiet_hours( $recovery ){
		if( !class_exists( 'WooCommerce' ) ){ //Check if WooCommerce plugin is active
			return;
		}?>
		<div class="cartbounty-pro-flex-container">
			<div class="cartbounty-pro-time-select">
				<?php echo $this->display_hours( $recovery, 'hours_from' ); ?>
			</div>
			<div class="cartbounty-pro-time-select">
				<?php echo $this->display_hours( $recovery, 'hours_to' ); ?>
			</div>
		</div>
		<?php
	}

    /**
     * Method displays hour dropdowns
     *
     * @since    9.7
     * @return   string
     * @param    string     $recovery			Recovery option
     * @param    string     $option				Option identifier
	 */
	function display_hours( $recovery, $option ){
		$hours = array(
			'0' 	=> '00:00',
			'1' 	=> '01:00',
			'2' 	=> '02:00',
			'3' 	=> '03:00',
			'4' 	=> '04:00',
			'5' 	=> '05:00',
			'6' 	=> '06:00',
			'7' 	=> '07:00',
			'8' 	=> '08:00',
			'9' 	=> '09:00',
			'10' 	=> '10:00',
			'11' 	=> '11:00',
			'12' 	=> '12:00',
			'13' 	=> '13:00',
			'14' 	=> '14:00',
			'15' 	=> '15:00',
			'16' 	=> '16:00',
			'17' 	=> '17:00',
			'18' 	=> '18:00',
			'19' 	=> '19:00',
			'20' 	=> '20:00',
			'21' 	=> '21:00',
			'22' 	=> '22:00',
			'23' 	=> '23:00'
		);

		if( $option == 'hours_from' ){
			$label_name = esc_html__( 'From', 'woo-save-abandoned-carts' );
			$selected_time = $this->get_defaults( 'hours_from' ); //Default from time

		}else if( $option == 'hours_to' ){
			$label_name = esc_html__( 'To', 'woo-save-abandoned-carts' );
			$selected_time = $this->get_defaults( 'hours_to' ); //Default from time
		}

		if( $recovery == 'bulkgate' ){
			$option_name = 'cartbounty_pro_bulkgate_settings';
			$bulkgate_settings = get_option( $option_name );

			if( isset( $bulkgate_settings[$option] ) ){
				$selected_time = $bulkgate_settings[$option];
			}
		}?>
		<label for="cartbounty-pro-automation-<?php esc_attr_e( $option ); ?>"><?php echo $label_name; ?>: </label>
			<select id="cartbounty-pro-automation-<?php esc_attr_e( $option ); ?>" class="cartbounty-pro-select" name="<?php echo esc_attr( $option_name ) . '['. esc_attr( $option ) .']'; ?>" autocomplete="off" <?php echo $this->disable_field(); ?>>
			<?php foreach( $hours as $key => $hour ){
				echo "<option value='". esc_attr( $key ) ."' ". selected( $selected_time, $key, false ) .">". esc_html( $hour ) ."</option>";
			}?>
		</select>
		<?php
    }

    /**
	 * Check if TCPA/GDPR guidlines have been confirmed
	 *
	 * @since    9.7
	 * @return   boolean
	 * @param    string    $recovery				Recovery option
	 */
	function tcpa_gdpr_confirmed( $recovery ){
		$confirmed = false;
		
		if( $recovery == 'bulkgate' ){
			$bulkgate_settings = get_option( 'cartbounty_pro_bulkgate_tcpa_gdpr' );
			if( $bulkgate_settings ){
				$confirmed = true;
			}
		}

		return $confirmed;
	}

	/**
	* Save TCPA/GDPR option so that it no longer is presented to the user
	*
	* @since    9.7
	*/
	public function save_tcpa_gdpr(){
		if ( check_ajax_referer( 'save_tcpa_gdpr', 'nonce', false ) == false ) { //If the request does not include our nonce security check, stop executing function
			wp_send_json_error( esc_html__( 'Looks like you are not allowed to do this.', 'woo-save-abandoned-carts' ) );
		}

		$recovery = '';
		if( isset( $_POST['recovery'] ) ){
			$recovery = $_POST['recovery'];
		}

		if( $recovery == 'bulkgate' ){
			$option_name = 'cartbounty_pro_bulkgate_tcpa_gdpr';
		}

		update_option( $option_name, true );
		wp_send_json_success();
	}

	/**
	* Get default country
	* First trying to detect if we have user's country from which he has arrived
	* If that fails - falling back to using set WooCommerce store country
	*
	* @since    9.7
	* @return 	string
	* @param    string     $country    		  	Country code e.g. 'UK', 'US'
	*/
	public function get_default_country( $country = false ) {
		
		if(!class_exists('WooCommerce')){ //Check if WooCommerce plugin is active
    		return;
    	}

    	if( empty( $country ) ){  //If we know country - use it, else fallback to WooCommerce base country
    		$store_location = new WC_Countries();
    		$country = apply_filters( 'cartbounty_pro_default_country', $store_location->get_base_country() );
    	}

		return $country;
	}

	/**
	* Get prefered countries for easy international phone input
	* By default default WooCommerce store country is used as preffered
	*
	* @since    9.7
	*/
	public function get_international_phone_preferred_countries() {
		return apply_filters( 'cartbounty_pro_international_phone_preferred_countries', array( $this->get_default_country() ) );
	}

	/**
	 * Check weather text message is allowed for the given country 
	 *
	 * @since    9.7
	 * @return 	 Boolean
	 * @param    string     $recovery			Recovery option
	 * @param    object     $cart    		  	Cart data
	 */
	function is_country_allowed_text_message( $recovery, $cart ){
		$allowed = true;

		if( $recovery == 'bulkgate' ){
			$option_name = 'cartbounty_pro_bulkgate_settings';
			$bulkgate_settings = get_option( $option_name );

			if( isset( $bulkgate_settings[ 'enable_countries' ] ) ){ //If country limitation has been enabled
				if( isset( $bulkgate_settings[ 'countries' ] ) ){
					$allowed_countries = $bulkgate_settings[ 'countries' ];
					
					if( !empty( $allowed_countries ) ){
						$allowed = false; //If at least one country added - by default no text message allowed
						$phone_country = $this->get_phone_country( $cart->phone, $cart->location );

						if( !empty( $phone_country ) ){
							if( in_array( $phone_country, $allowed_countries ) ){ //If country is in the list of allowed countries
								$allowed = true;
							}
						}
					}
				}
			}
		}

		return $allowed;
	}

	/**
	 * Check weather quiet hours are over for the given country and its time zone
	 * In case if dealing with US phone number and quiet hours are not set - force quiet hours for US phone numbers from 23:00 to 08:00
	 *
	 * @since    9.7
	 * @return 	 Boolean
	 * @param    string     $recovery			Recovery option
	 * @param    object     $cart    		  	Cart data
	 */
	function quiet_hours_over( $recovery, $cart ){
		$allowed = true;
		$option_name = '';

		if( $recovery == 'bulkgate' ){
			$option_name = 'cartbounty_pro_bulkgate_settings';
		}

		$bulkgate_settings = get_option( $option_name );
		$phone_country = $this->get_phone_country( $cart->phone, $cart->location );
		$quiet_hours_enabled = false;

		//Defining default hours for US phones in case quiet hours not defined
		$hours_from = $this->get_defaults( 'hours_from' ); 
		$hours_to = $this->get_defaults( 'hours_to' );

		if( isset( $bulkgate_settings[ 'enable_quiet_hours' ] ) ){
			$quiet_hours_enabled = true;
		}

		if( $quiet_hours_enabled || $phone_country == 'US' ){ //If quiet hours enabled or phone country is US
			$allowed = false; //If at quiet hours enabled - by default no text message allowed
			$phone_timezones = $this->get_phone_timezones( $cart->phone, $cart->location );

			//Using From and To times set in the settings in case quiet hours enabled and we have data
			if( $quiet_hours_enabled && isset( $bulkgate_settings[ 'hours_from' ] ) && isset( $bulkgate_settings[ 'hours_to' ] ) ){ 
				$hours_from = $bulkgate_settings[ 'hours_from' ];
				$hours_to = $bulkgate_settings[ 'hours_to' ];
			}

			if( !empty( $phone_timezones ) ){
				if( isset( $phone_timezones[0] ) ){
					//Checking if phone number in time zone is not in the range of quiet hours
					$phone_timezone = $phone_timezones[0]; //Pick the first timezone in case there are multiple ones
					$current_timezone = new DateTimeZone( $phone_timezone );
					$current_time = new DateTime( 'now', $current_timezone ); //Current time in the timezone
					$current_time_hours = $current_time->format( 'H' ); //If it is 21:30:58, output will be 21

					//Prepare time objects that can be used for comparisons
					$from_time_object = DateTime::createFromFormat( 'H', $hours_from );
					$to_time_object = DateTime::createFromFormat( 'H', $hours_to );
					$current_time_object = DateTime::createFromFormat( 'H', $current_time_hours );

					if ( $from_time_object > $to_time_object ){ //Add extra day in case the From hours are greater than To hours
						$to_time_object->modify( '+1 day' );
					}

					if ( !( ( $from_time_object <= $current_time_object && $current_time_object < $to_time_object ) || ( $from_time_object <= $current_time_object->modify( '+1 day' ) && $current_time_object < $to_time_object ) ) ){ //In case phone time according to its local time zone is out of quiet hours - can send message
						$allowed = true;
					}
				}
			}
		}

		return $allowed;
	}

	/**
	 * Check if phone number is valid or not
	 * Source and documentation: https://github.com/giggsey/libphonenumber-for-php
	 *
	 * @since    9.7
	 * @return 	 Boolean
	 * @param    string     $phone			      Phone number
	 * @param    array      $location			  Location array
	 */
	function is_valid_phone( $phone, $location = array() ){
		$valid = false;
		$cart_country = $this->get_cart_location( $location, 'country');
		$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
		
		try {
			$phone_data = $phoneUtil->parse( $phone, $this->get_default_country( $cart_country ) );
			
			if( $phoneUtil->isValidNumber( $phone_data ) ){
				$valid = true;
			}

		}catch (\libphonenumber\NumberParseException $error) { //If phone number validation generates error - log it
			$this->log( 'notice', sprintf(
				/* translators: %s - Error message, %s - Phone number */
				esc_html__( 'Phone validation: %s Phone number: %s', 'woo-save-abandoned-carts' ), esc_html( $error->getMessage() ), esc_html( $phone ) ) );
		}

		return $valid;
	}

	/**
	 * Retrieve country from phone number
	 * Source and documentation: https://github.com/giggsey/libphonenumber-for-php
	 *
	 * @since    9.7
	 * @return 	 string
	 * @param    string     $phone			      Phone number
	 * @param    array      $location			  Location array
	 */
	function get_phone_country( $phone, $location = array() ){
		$country = '';
		$cart_country = $this->get_cart_location( $location, 'country');
		$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();

		try {
			$phone_data = $phoneUtil->parse( $phone, $this->get_default_country( $cart_country ) );
			$country = $phoneUtil->getRegionCodeForNumber( $phone_data );

		}catch (\libphonenumber\NumberParseException $error) { //If phone number validation generates error - log it
			$this->log( 'notice', sprintf(
				/* translators: %s - Error message, %s - Phone number */
				esc_html__( 'Phone validation: %s Phone number: %s', 'woo-save-abandoned-carts' ), esc_html( $error->getMessage() ), esc_html( $phone ) ) );
		}

		return $country;
	}

	/**
	 * Retrieve timezone from phone number
	 * Source and documentation: https://github.com/giggsey/libphonenumber-for-php
	 *
	 * @since    9.7
	 * @return 	 array
	 * @param    string     $phone			      Phone number
	 * @param    array      $location			  Location array
	 */
	function get_phone_timezones( $phone, $location = array() ){
		$time_zones = array();
		$cart_country = $this->get_cart_location( $location, 'country');
		$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
		$timezoneMapper = \libphonenumber\PhoneNumberToTimeZonesMapper::getInstance();

		try {
			$phone_data = $phoneUtil->parse( $phone, $this->get_default_country( $cart_country ) );
			$time_zones = $timezoneMapper->getTimeZonesForNumber( $phone_data );

		}catch (\libphonenumber\NumberParseException $error) { //If phone number validation generates error - log it
			$this->log( 'notice', sprintf(
				/* translators: %s - Error message, %s - Phone number */
				esc_html__( 'Phone validation: %s Phone number: %s', 'woo-save-abandoned-carts' ), esc_html( $error->getMessage() ), esc_html( $phone ) ) );
		}

		return $time_zones;
	}

	/**
	 * Return phone country code from country
	 * If country parameter is not provided, return country code for default store location
	 * Source and documentation: https://github.com/giggsey/libphonenumber-for-php
	 *
	 * @since    9.7
	 * @return 	 array
	 * @param    string     $country			  Country code
	 */
	function get_phone_area_code_from_country( $country = false ){
		$area_code = array();
		$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();

		if( !$country ){
			$country = $this->get_default_country();
		}

		$area_code = '+' . $phoneUtil->getCountryCodeForRegion( $country );
		return $area_code;
	}

	/**
	 * Return phone number prepared for sending a message
	 * If number provided withput country code, default country code is used
	 * International phone number is returned
	 * Source and documentation: https://github.com/giggsey/libphonenumber-for-php
	 *
	 * @since    9.7
	 * @return 	 string
	 * @param    string     $phone				Phone number
	 * @param    array      $location			Location array
	 */
	function prepare_phone_number( $phone, $location = array() ){
		$cart_country = $this->get_cart_location( $location, 'country');
		$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();

		try {
			$phone = $phoneUtil->parse( $phone, $this->get_default_country( $cart_country ) );
			$phone = $phoneUtil->format( $phone, \libphonenumber\PhoneNumberFormat::E164 ); //Formatting phone number

		}catch (\libphonenumber\NumberParseException $error) { //If phone number validation generates error - log it
			$this->log( 'notice', sprintf(
				/* translators: %s - Error message, %s - Phone number */
				esc_html__( 'Phone validation: %s Phone number: %s', 'woo-save-abandoned-carts' ), esc_html( $error->getMessage() ), esc_html( $phone ) ) );
		}
		
		return $phone;
	}

	/**
	 * Check if unfinished order recovery enabled
	 *
	 * @since    9.7.2
	 * @return   boolean
	 */
	function recover_orders_enabled(){
		$enabled = false;
		$order_recovery = $this->get_settings( 'settings', 'order_recovery' );
		if( $order_recovery ){ //If order recovery enabled
			$enabled = true;
		}
		return $enabled;
	}

	/**
	* Method displays available WooCommerce orders
	*
	* @since    9.4
	* @return   HTML
	*/
	public function display_order_statuses(){
		if( !class_exists( 'WooCommerce' ) ){ //Check if WooCommerce plugin is active
			return;
		}

		if ( !function_exists( 'wc_get_order_statuses' ) ) { //In case this WooCommerce function is not defined
			return;
		}

		$original_statuses = wc_get_order_statuses();
		$status_slugs = str_replace( 'wc-', '', array_keys( $original_statuses ) ); //Remove "wc-" from beginning of the status
		$statuses = array_combine( $status_slugs, $original_statuses );
		unset( $statuses[ 'refunded' ] ); //Remove Refunded status from the list of available statuses
		$settings = $this->get_settings( 'settings' );

		$option_name = 'cartbounty_pro_main_settings[order_statuses]';
		$selected_statuses = $settings['order_statuses'];

		if( !$selected_statuses ){ //In case no status is added, restore default statuses
			$settings['order_statuses'] = array( 'pending', 'failed' );
			update_option( 'cartbounty_pro_main_settings', $settings ); 
			$selected_statuses = $this->get_settings( 'settings', 'order_statuses' );
		}

		echo '<select id="cartbounty-pro-order-statuses" class="cartbounty-pro-select cartbounty-pro-multiple cartbounty-pro-select-multiple-items" multiple name="' . $option_name . '[]" placeholder="' . esc_attr__( 'Select order status', 'woo-save-abandoned-carts' ) . '" autocomplete="off" '. $this->disable_field() .'>';
		foreach( $statuses as $key => $status ){
			$selected = '';
			if( in_array( $key, $selected_statuses ) ){
				$selected = 'selected';
			}
			echo "<option value='". esc_attr( $key ) ."' $selected>". esc_html( $status ) ."</option>";
		}
		echo '</select>';
	}

	/**
	 * Retrieve unfinished order statuses that are used as indicators for recovery
	 *
	 * @since    9.7.2
	 * @return   array
	 */
	function unfinished_order_statuses(){
		$statuses = array();
		if ( $this->recover_orders_enabled() ){ //If unfinished order recovery enabled
			$selected_statuses = $this->get_settings( 'settings', 'order_statuses' );
			if( !empty( $selected_statuses ) ){
				$statuses = $selected_statuses;
			}
		}
		return apply_filters( 'cartbounty_pro_unfinished_order_statuses', $statuses );
	}

	/**
	 * Get checkout consent value
	 *
	 * @since    9.7.3
	 * @return   array
	 */
	function get_checkout_consent(){
		$field = array();
		$field['name'] = $this->get_defaults( 'checkout_consent_name' ); //This is necessary for WPML
		$field['value'] = $this->get_defaults( 'checkout_consent' );
		$checkout_consent = $this->get_settings( 'settings', 'checkout_consent' );
		
		if( trim( $checkout_consent ) != '' ){ //If the value is not empty and does not contain only whitespaces
			$field['value'] = $this->sanitize_field( $checkout_consent );
		}
		return $field;
	}

	/**
	 * Get tools consent value
	 *
	 * @since    9.7.3
	 * @return   array
	 */
	function get_tools_consent(){
		$field = array();
		$field['name'] = $this->get_defaults( 'tools_consent_name' ); //This is necessary for WPML
		$field['value'] = $this->get_defaults( 'tools_consent' );
		$tools_consent = $this->get_settings( 'settings', 'tools_consent' );

		if( trim( $tools_consent ) != '' ){ //If the value is not empty and does not contain only whitespaces
			$field['value'] = $this->sanitize_field( $tools_consent );
		}
		return $field;
	}

	/**
	 * Get Exit Intent heading value
	 *
	 * @since    9.7.3
	 * @return   array
	 */
	function get_exit_intent_heading(){
		$field = array();
		$field['name'] = $this->get_tools_defaults( 'heading_name', 'exit_intent' ); //This is necessary for WPML
		$field['value'] = $this->get_tools_defaults( 'heading', 'exit_intent' );
		$heading = $this->get_settings( 'exit_intent', 'heading' );

		if( trim( $heading ) != '' ){ //If the value is not empty and does not contain only whitespaces
			$field['value'] = $this->sanitize_field( $heading );
		}
		return $field;
	}

	/**
	 * Get Exit Intent content value
	 *
	 * @since    9.7.3
	 * @return   array
	 */
	function get_exit_intent_content(){
		$field = array();
		$field['name'] = $this->get_tools_defaults( 'content_name', 'exit_intent' ); //This is necessary for WPML
		$field['value'] = $this->get_tools_defaults( 'content', 'exit_intent' );
		$content = $this->get_settings( 'exit_intent', 'content' );

		if( trim( $content ) != '' ){ //If the value is not empty and does not contain only whitespaces
			$field['value'] = $this->sanitize_field( $content );
		}
		return $field;
	}

	/**
	 * Get Early capture heading value
	 *
	 * @since    9.7.3
	 * @return   array
	 */
	function get_early_capture_heading(){
		$field = array();
		$field['name'] = $this->get_tools_defaults( 'heading_name', 'early_capture' ); //This is necessary for WPML
		$field['value'] = $this->get_tools_defaults( 'heading', 'early_capture' );
		$heading = $this->get_settings( 'early_capture', 'heading' );

		if( trim( $heading ) != '' ){ //If the value is not empty and does not contain only whitespaces
			$field['value'] = $this->sanitize_field( $heading );
		}
		return $field;
	}

	/**
	 * Get Tab notification message value
	 *
	 * @since    9.7.3
	 * @return   array
	 */
	function get_tab_notification_message(){
		$field = array();
		$field['name'] = $this->get_tools_defaults( 'content_name', 'tab_notification' ); //This is necessary for WPML
		$field['value'] = $this->get_tools_defaults( 'content', 'tab_notification' );
		$content = $this->get_settings( 'tab_notification', 'content' );

		if( trim( $content ) != '' ){ //If the value is not empty and does not contain only whitespaces
			$field['value'] = $this->sanitize_field( $content );
		}
		return $field;
	}

	/**
	 * Get Push notification request heading value
	 *
	 * @since    9.10
	 * @return   array
	 */
	function get_notification_permission_request_heading(){
		$push_notification = $this->push_notification();
		$field = array();
		$field['name'] = $this->get_tools_defaults( 'permission_heading_name', 'push_notification' ); //This is necessary for WPML
		$field['value'] = $this->get_tools_defaults( 'permission_heading', 'push_notification' );

		if( trim( $push_notification->get_settings( 'permission_heading' ) ) != '' ){ //If the value is not empty and does not contain only whitespaces
			$field['value'] = $this->sanitize_field( $push_notification->get_settings( 'permission_heading' ) );
		}
		return $field;
	}

	/**
	 * Get Push notification request content value
	 *
	 * @since    9.10
	 * @return   array
	 */
	function get_notification_permission_request_content(){
		$push_notification = $this->push_notification();
		$field = array();
		$field['name'] = $this->get_tools_defaults( 'permission_content_name', 'push_notification' ); //This is necessary for WPML
		$field['value'] = $this->get_tools_defaults( 'permission_content', 'push_notification' );

		if( trim( $push_notification->get_settings( 'permission_content' ) ) != '' ){ //If the value is not empty and does not contain only whitespaces
			$field['value'] = $this->sanitize_field( $push_notification->get_settings( 'permission_content' ) );
		}
		return $field;
	}

	/**
	 * Get product thumbnail
	 *
	 * @since    9.7.4.2
	 * @return   string
	 * @param    object     $product			Abandoned cart product data
	 * @param    string     $size				Image size, default 'woocommerce_thumbnail' 300x300 (with hard crop)
	 */
	function get_product_thumbnail_url( $product, $size = 'woocommerce_thumbnail' ){
		$image = '';

		if( function_exists( 'has_image_size' ) && !has_image_size( 'woocommerce_thumbnail' ) && $size == 'woocommerce_thumbnail' ){ //If 'woocommerce_thumbnail' image requested but it does not exist, fallback to default WordPress image size 'medium'
			$size = 'medium';
		}

		if( !empty( $product['product_variation_id'] ) ){ //In case of a variable product
			$image = get_the_post_thumbnail_url( $product['product_variation_id'], $size );
		}

		if( empty( $image ) ){ //In case of a simple product or if variation did not have an image set
			$image = get_the_post_thumbnail_url( $product['product_id'], $size );
		}

		if( empty( $image ) && class_exists( 'WooCommerce' ) ){ //In case WooCommerce is active and product has no image, output default WooCommerce image
			$image = wc_placeholder_img_src( $size );
		}

		return $image;
	}

	/**
     * Exclude cart from further recovery
     *
     * @since    9.7.5
     * @param    string     $recovery           Recovery type e.g. ActiveCampaign, WordPress, MailChimp
     * @param    object     $cart   		    Cart data
     */
	public function exclude_cart( $recovery, $cart ){

		if( empty( $cart ) ) return;

		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;

		switch ( $recovery ) {

			case 'activecampaign':
				$field_name = 'ac_excluded';
				break;

			case 'getresponse':
				$field_name = 'gr_excluded';
				break;

			case 'mailchimp':
				$field_name = 'mc_excluded';
				break;

			case 'wordpress':
				$field_name = 'wp_excluded';
				break;

			case 'bulkgate':
				$field_name = 'sms_excluded';
				break;

			case 'push_notification':
				$field_name = 'pn_excluded';
				break;

			case 'webhook':
				$field_name = 'wh_excluded';
				break;
		}

		$wpdb->query(
			$wpdb->prepare(
				"UPDATE {$cart_table}
				SET $field_name = 1
				WHERE id = %d",
				$cart->id
			)
		);
	}

	/**
     * Delete cart
     *
     * @since    10.6
     * @return   integer
     * @param    integer     $cart_id   		    Abandoned cart ID
     */
	public function delete_cart( $cart_id ){

		if( !$this->user_is_admin() ){
			wp_die( esc_html__( 'You do not have sufficient permissions to perform this action.', 'woo-save-abandoned-carts' ) );
		}

		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;

		if( empty( $cart_id ) ) return;

		$rows = $wpdb->query(
			$wpdb->prepare(
				"DELETE FROM $cart_table
				WHERE id = %d",
				intval( $cart_id )
			)
		);

		if( !$rows ){
			$rows = 0;
		}

		return $rows;
	}

	/**
     * Pause cart from recovery
     * Anonymous carts and recovered carts can't be paused since they are not recoverable
     *
     * @since    9.7.5
     * @return   integer
     * @param    integer     $cart_id   		    Abandoned cart ID
     */
	public function pause_cart( $cart_id ){
		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;

		if( empty( $cart_id ) ) return;

		$rows = $wpdb->query(
			$wpdb->prepare(
				"UPDATE {$cart_table}
				SET paused = 1
				WHERE id = %d AND
				( ( email != '' OR
				phone != '' OR
				pn_subscription != '' ) AND
				anonymized = 0 AND
				type != %d )",
				$cart_id,
				$this->get_cart_type( 'recovered' )
			)
		);

		if( !$rows ){
			$rows = 0;
		}

		return $rows;
	}

	/**
     * Resume abandoned cart recovery
     *
     * @since    9.7.5
     * @return   integer
     * @param    integer     $cart_id   		    Abandoned cart ID
     */
	public function resume_cart( $cart_id ){
		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;

		if( empty( $cart_id ) ) return;

		$rows = $wpdb->query(
			$wpdb->prepare(
				"UPDATE {$cart_table}
				SET paused = 0
				WHERE anonymized = 0 AND 
				id = %d",
				$cart_id
			)
		);

		if( !$rows ){
			$rows = 0;
		}

		return $rows;
	}

	/**
     * Restart abandoned cart recovery process
     *
     * @since    10.6
     * @return   integer
     * @param    integer     $cart_id   		    Abandoned cart ID
     */
	public function restart_cart( $cart_id ){
		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;

		if( empty( $cart_id ) ) return;

		$rows = $wpdb->query(
			$wpdb->prepare(
				"UPDATE {$cart_table}
				SET restarts = restarts + 1,
				wp_steps_completed = 0,
				wp_complete = 0,
				sms_steps_completed = 0,
				sms_complete = 0,
				pn_steps_completed = 0,
				pn_complete = 0
				WHERE id = %d AND
				( ( email != '' OR
				phone != '' OR
				pn_subscription != '' ) AND 
				anonymized = 0 AND
				type != %d )",
				$cart_id,
				$this->get_cart_type( 'recovered' )
			)
		);

		if( !$rows ){
			$rows = 0;
		}

		return $rows;
	}

	/**
	* Search for WooCommerce items (coupons, products etc.) and return a list of matches
	*
	* @since    9.4
	* @return   array
	*/
	public function find_items(){
		if ( check_ajax_referer( 'find_items', 'nonce', false ) == false ) { //If the request does not include our nonce security check, stop executing the function
			wp_send_json_error(esc_html__( 'Looks like you are not allowed to do this.', 'woo-save-abandoned-carts' ));
		}

		global $wpdb;
		$search_phrase = ( isset( $_GET['search'] ) ) ? $_GET['search'] : '';
		$search_type = ( isset( $_GET['search_type'] ) ) ? $_GET['search_type'] : '';
		$table = $wpdb->prefix . 'posts';
		$order = 'ORDER BY post_title ASC';

		if( $search_type == 'shop_coupon' ){ //Change result order to date in case if searching for coupons
			$order = 'ORDER BY post_date DESC';
		}

		$items = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT post_title, id FROM {$table}
				WHERE post_type = %s AND
				(post_status = 'publish' OR 
				post_status = 'future') AND
				post_title LIKE '%s'
				$order",
				$search_type,
				'%'. $wpdb->esc_like( $search_phrase ) .'%'
			)
		);

		wp_send_json_success( $items );
	}

	/**
	* Get item name from item id inside the wp_posts table
	*
	* @since    9.4
	* @return   string
	* @param    string     $id             Post ID
	* @param    string     $post_type      Post type we are searching for
	*/
	public function get_item_name_by_id( $id, $post_type ){
		global $wpdb;
		$table = $wpdb->prefix . 'posts';
		$post_title = '';

		$item_name = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT post_title, id FROM {$table}
				WHERE id = %d AND
				post_type = %s",
				$id,
				$post_type
			)
		);
		if(isset($item_name->post_title)){
			$post_title = $item_name->post_title;
		}
		return $post_title;
	}

	/**
	* Method displays available product categories
	*
	* @since    9.4
	* @return   HTML
	* @param    string     $recovery             Recovery type e.g. ActiveCampaign, WordPress, MailChimp
	* @param    string     $option               Option data field name for storing values
	* @param    string     $step_nr              Automation step number
	* @param    string     $automation           Name for labeling
	* @param    string     $field_id             Field ID for distinguishing input fields
	* @param    string     $operation            Include or exclude coupons
	* @param    string     $placement            Placement where product categories are displayed e.g. Coupon block or Exclusions
	*/
	public function display_product_categories( $recovery, $option, $step_nr, $automation, $field_id, $operation, $placement ){
		$coupons = $this->coupons();
		$placeholder = esc_html__( 'Any category', 'woo-save-abandoned-carts' );

		if( $placement == 'coupons' ){ //If displaying data inside Coupon settings block
			$block = '-coupon-';
			$selected_categories = $coupons->get_coupon_settings( $recovery, $option, $step_nr, 'coupon_'. $operation .'_categories' );
			$full_option = '[coupon_'. esc_attr( $operation ) .'_categories]';

		}else{
			$block = '-';
			$selected_categories = $this->get_exclusion_settings( $recovery, $option, $operation .'_product_categories' );
			$full_option = '[' . esc_attr( $operation ) .'_product_categories]';
		}

		if( $operation == 'exclude' ){
			$placeholder = esc_html__( 'No categories', 'woo-save-abandoned-carts' );
		}

		$args = array(
			'taxonomy'		=> 'product_cat',
			'orderby'		=> 'name',
			'hide_empty'	=> false
		);
		$categories = get_categories( $args );

		echo '<select id="cartbounty-pro-'. esc_attr( $automation ) . $block . esc_attr( $operation ) .'-product-categories'. esc_attr( $field_id ) .'" class="cartbounty-pro-select cartbounty-pro-multiple cartbounty-pro-select-multiple-items" multiple name="'. esc_attr( $option ) . esc_attr( $step_nr ) . $full_option . '[]" placeholder="'. esc_attr( $placeholder ) .'" autocomplete="off" '. $this->disable_field() .'>';
		foreach( $categories as $key => $category ){
			$selected = '';

			if(in_array($category->term_id, $selected_categories)){
				$selected = 'selected';
			}

			echo "<option value='". esc_attr( $category->term_id ) ."' $selected>". esc_html( $category->name ) ."</option>";
		}
		echo '</select>';
	}

	/**
	* Check if cart contains any excluded items
	*
	* @since    9.7.5
	* @return   string
	* @param    string     $recovery             Recovery type e.g. ActiveCampaign, WordPress etc.
	*/
	public function get_exclusion_option_name( $recovery ){
		$option = '';

		switch ( $recovery ) {

			case 'activecampaign':
				$option = 'cartbounty_pro_activecampaign_exclusions';
				break;

			case 'getresponse':
				$option = 'cartbounty_pro_getresponse_exclusions';
				break;

			case 'mailchimp':
				$option = 'cartbounty_pro_mailchimp_exclusions';
				break;

			case 'wordpress':
				$option = 'cartbounty_pro_automation_exclusions';
				break;

			case 'bulkgate':
				$option = 'cartbounty_pro_bulkgate_exclusions';
				break;

			case 'push_notification':
				$option = 'cartbounty_pro_push_notification_exclusions';
				break;

			case 'webhook':
				$option = 'cartbounty_pro_webhook_exclusions';
				break;
		}

		return $option;
	}

	/**
	* Returning HTML of product settings
	*
	* @since    9.7.5
	* @return   HTML
	* @param    string     $recovery             Recovery type e.g. ActiveCampaign, WordPress, MailChimp
	*/
	public function display_exclusion_settings( $recovery ){

		$option = $this->get_exclusion_option_name( $recovery );

		$automation = $recovery;
		$enable_exclusions = $this->get_exclusion_settings( $recovery, $option, 'enable_exclusions' );
		$excluded_products = $this->get_exclusion_settings( $recovery, $option, 'excluded_products' );
		$excluded_emails_phones = $this->get_exclusion_settings( $recovery, $option, 'excluded_emails_phones' );
		$find_items_nonce = wp_create_nonce( 'find_items' ); ?>

		<div class="cartbounty-pro-titles-column cartbounty-col-sm-12 cartbounty-col-md-4 cartbounty-col-lg-3">
			<h4><?php esc_html_e('Exclusions', 'woo-save-abandoned-carts'); ?></h4>
			<p class="cartbounty-pro-titles-column-description">
				<?php esc_html_e( 'Exclude from abandoned cart recovery carts containing specific products or categories.', 'woo-save-abandoned-carts' ); ?> <?php echo sprintf(
					/* translators: %1$s - Link start, %2$s - Link end */
					esc_html__( 'Use %1$svarious filters%2$s to exclude carts by language, country etc.', 'woo-save-abandoned-carts' ), '<a href="'. esc_url( $this->get_trackable_link( '' . 'actions-and-filters', 'custom_exclusion_filters', '#exclude-specific-countries-from-abandoned-cart-recovery' ) ) .'" target="_blank">', '</a>' ); ?>
			</p>
		</div>
		<div class="cartbounty-pro-settings-column cartbounty-col-sm-12 cartbounty-col-md-8 cartbounty-col-lg-9<?php if( $enable_exclusions ){ echo ' cartbounty-pro-checked-parent'; }?>">
			<div class="cartbounty-pro-settings-group cartbounty-pro-toggle">
				<label for="cartbounty-pro-<?php echo esc_attr( $automation ); ?>-enable-exclusions" class="cartbounty-pro-switch cartbounty-pro-control-visibility">
					<input id="cartbounty-pro-<?php echo esc_attr( $automation ); ?>-enable-exclusions" class="cartbounty-pro-checkbox" type="checkbox" name="<?php echo esc_attr( $option ); ?>[enable_exclusions]" value="1" <?php echo $this->disable_field(); ?> <?php echo checked( 1, $enable_exclusions, false ); ?> autocomplete="off" />
					<span class="cartbounty-pro-slider round"></span>
				</label>
				<label for="cartbounty-pro-<?php echo esc_attr( $automation ); ?>-enable-exclusions" class="cartbounty-pro-control-visibility"><?php esc_html_e( 'Enable', 'woo-save-abandoned-carts' ); ?></label>
			</div>
			<div class="cartbounty-pro-settings-group cartbounty-pro-hidden">
				<div class="cartbounty-pro-settings-group">
					<label for="cartbounty-pro-<?php echo esc_attr( $automation ); ?>-excluded-products"><?php esc_html_e( 'Exclude carts containing any of these products', 'woo-save-abandoned-carts' ); ?></label>
					<select id="cartbounty-pro-<?php echo esc_attr( $automation ); ?>-excluded-products" class="cartbounty-pro-select cartbounty-pro-multiple cartbounty-pro-ajax-search" multiple name="<?php echo esc_attr( $option ); ?>[excluded_products][]" placeholder="<?php esc_html_e( 'Search products...', 'woo-save-abandoned-carts' ); ?>" autocomplete="off" data-search-type="product" data-action="find_items" data-nonce="<?php echo esc_attr( $find_items_nonce ); ?>">
						<?php foreach( $excluded_products as $product ){
							echo "<option value='". esc_attr( $product ) ."' selected>". esc_html( $this->get_item_name_by_id( $product, 'product' ) ) ."</option>";
						}?>
					</select>
				</div>
				<div class="cartbounty-pro-settings-group">
					<label for="cartbounty-pro-<?php echo esc_attr( $automation ); ?>-exclude-product-categories"><?php esc_html_e( 'Exclude carts containing any of these categories', 'woo-save-abandoned-carts' ); ?></label>
					<?php esc_html( $this->display_product_categories( $recovery, $option, $step_nr = false, $automation, $field_id = false, 'exclude' , $placement = 'exclusions' ) ); ?>
				</div>
				<div class="cartbounty-pro-settings-group">
					<label for="cartbounty-pro-<?php echo esc_attr( $automation ); ?>-excluded-emails-phones"><?php esc_html_e( 'Exclude carts containing any of these emails and phone numbers', 'woo-save-abandoned-carts' ); ?></label>
					<input id="cartbounty-pro-<?php echo esc_attr( $automation ); ?>-excluded-emails-phones" class="cartbounty-pro-text cartbounty-pro-display-emails" type="text" name="<?php echo esc_attr( $option ); ?>[excluded_emails_phones]" value="<?php echo esc_attr( $excluded_emails_phones ); ?>" <?php echo $this->disable_field(); ?> />
					<p class='cartbounty-pro-additional-information'>
						<?php esc_html_e( 'You can add multiple emails and phone numbers separated by a comma.', 'woo-save-abandoned-carts' ); ?> <?php esc_html_e( 'You can also use an asterisk (*) to match parts of an email. For example, "*@gmail.com" would match all Gmail addresses.', 'woo-save-abandoned-carts' ); ?>
					</p>
				</div>
			</div>
		</div>
	<?php }

	/**
	* Return exclusion settings depending on recovery type
	*
	* @since    9.7.5
	* @return   array
	* @param    string     $recovery             Recovery type e.g. ActiveCampaign, WordPress etc.
	* @param    string     $option               Option data field name for storing values
	* @param    string     $value                Value to return
	*/
	public function get_exclusion_settings( $recovery, $option, $value = false ){
		$settings = array();
		$saved_options = get_option($option);
		$exclusions = (object)$saved_options;

		if( isset($exclusions->enable_exclusions) ){ //If coupon generation enabled
			$settings['enable_exclusions'] = $exclusions->enable_exclusions;
		}else{
			$settings['enable_exclusions'] = false;
		}

		if( !empty($exclusions->excluded_products) ){ //If the selected products array is not empty
			$settings['excluded_products'] = $exclusions->excluded_products;
		}else{
			$settings['excluded_products'] = array();
		}

		if( !empty($exclusions->exclude_product_categories) ){ //If the selected categories array is not empty
			$settings['exclude_product_categories'] = $exclusions->exclude_product_categories;
		}else{
			$settings['exclude_product_categories'] = array();
		}

		if( !empty($exclusions->excluded_emails_phones) ){ //If the selected emails / phones array is not empty
			$settings['excluded_emails_phones'] = $exclusions->excluded_emails_phones;
		}else{
			$settings['excluded_emails_phones'] = '';
		}

		if($value){ //If a single value should be returned
			if( isset( $settings[$value] ) ){ //Checking if value exists
				$settings = $settings[$value];
			}
		}

		return $settings;
	}

	/**
	* Check if cart contains any excluded items
	* Products or product categories
	* Minimum cart total
	* Country
	* Languages
	*
	* @since    9.7.5
	* @return   array
	* @param    object     $cart    		  	 Cart data
	* @param    string     $recovery             Recovery type e.g. ActiveCampaign, WordPress etc.
	*/
	public function has_excluded_items( $cart, $recovery ){
		
		if( empty( $cart ) ) return;

		$option = $this->get_exclusion_option_name( $recovery );
		$exclusions_enabled = $this->get_exclusion_settings( $recovery, $option, 'enable_exclusions' );

		if( !$exclusions_enabled ) return; //Exit if exclusions are disabled

		$exclude = false;
		$excluded_products = $this->get_exclusion_settings( $recovery, $option, 'excluded_products' );
		$excluded_product_categories = $this->get_exclusion_settings( $recovery, $option, 'exclude_product_categories' );
		$product_categories = array();
		$excluded_countries = apply_filters( 'cartbounty_pro_excluded_countries', array() );
		$excluded_languages = apply_filters( 'cartbounty_pro_excluded_languages', array() );
		$minimum_cart_total = esc_html( apply_filters( 'cartbounty_pro_minimum_cart_total', false ) );

		//Check cart content exclusions
		if( isset( $cart->cart_contents ) ){ //If we have cart contents
			
			if( !empty( $cart->cart_contents ) ){
				$cart_contents = $this->get_saved_cart_contents( $cart->cart_contents );
				
				if( is_array( $cart_contents ) ){
					foreach( $cart_contents as $key => $item ){ //Building product array
						$terms = get_the_terms( $item['product_id'], 'product_cat' );
						
						if( is_array( $terms ) ){
							foreach ( $terms as $term ) {
								$product_categories[] = $term->term_id;
							}
						}

						if( in_array( $item['product_id'], $excluded_products ) || $this->item_in_array( $product_categories, $excluded_product_categories ) ){ //If product in the list of exluded products or categories
							$exclude = true;
							break;
						}
					}
				}
			}
		}

		//Check Minimum cart total
		if( !empty( $minimum_cart_total ) ){

			if( isset( $cart->cart_total ) ){ //If the cart has language

				if( !empty( $cart->cart_total ) ){

					if( $cart->cart_total <= $minimum_cart_total ){ //If cart total does not exceed the minimum allowed value
						$exclude = true;
					}
				}
			}
		}

		//Check country exclusions
		if( !empty( $excluded_countries ) ){

			if( isset( $cart->location ) ){ //If cart location is set
				
				if( !empty( $cart->location ) ){

					if( in_array( $this->get_cart_location( $cart->location, 'country' ), $excluded_countries ) ){ //If country is in the list of excluded countries
						$exclude = true;
					}
				}
			}
		}

		//Check language exclusions
		if( !empty( $excluded_languages ) ){

			if( isset( $cart->language ) ){ //If the cart has language

				if( !empty( $cart->language ) ){

					if( is_array( $excluded_languages ) ){

						if( in_array( $cart->language, $excluded_languages ) ){ //If language is in the excluded language array
							$exclude = true;
						}
					}
				}
			}
		}

		//Check if email or phone number excluded
		if( $this->email_phone_excluded( $cart, $recovery, $option ) ){
			$exclude = true;
		}

		return $exclude;
	}

	/**
	* Checking if user email or phone number is excluded or not
	* First checking exact match of email or phone
	* Then checking if we have wildcard match using * symbol and regex expression
	*
	* @since    9.11
	* @return   boolean
	* @param    object    $cart              Cart data
	* @param    string    $recovery          Recovery type e.g. ActiveCampaign, WordPress, MailChimp
	* @param    string    $option            Option data field name for storing values
	* @param    integer   $step_nr           Automation step number
	* @param    boolean   $coupon            Determines if method check related to coupon exclusion
	* @param    boolean   $settings          Determines if method check related to global CartBounty exclusion settings
	*/
	function email_phone_excluded( $cart, $recovery, $option, $step_nr = '', $coupon = false, $settings = false ){
		$result = false;

		if( $coupon ){
			$coupons = $this->coupons();
			$settings = (object)$coupons->get_coupon_settings( $recovery, $option, $step_nr );
			$excluded_emails_phones = $settings->excluded_emails_phones;

		}elseif( $settings ){
			$excluded_emails_phones = $this->get_settings( 'settings', 'excluded_emails_phones' );

		}else{
			$excluded_emails_phones = $this->get_exclusion_settings( $recovery, $option, 'excluded_emails_phones' );
		}

		if( !empty( $excluded_emails_phones ) ){ //If emails or phones have been entered
			$excluded_emails_phones = esc_html( $excluded_emails_phones );
			$excluded_emails_phones = str_replace( ' ', '', $excluded_emails_phones );
			$excluded_emails_phones = explode(',', $excluded_emails_phones);

			if( is_array( $excluded_emails_phones ) ){

				if( in_array( $cart->email, $excluded_emails_phones ) || in_array( $cart->phone, $excluded_emails_phones ) ) { //If we find a direct match inside excluded emails or phone numbers - exit and do not continue this function
					$result = true;

				}else{
					// Go through allowed emails and phone numbers and return true if they match a given wildcard
					foreach( $excluded_emails_phones as $key => $email_phone ) {
						$regex = '/^' . str_replace( array( '+', '*' ), '(.+)?', $email_phone ) . '$/'; //Replacing wildcard asterisk * and + sign (in phone numbers) with a regex that searches for any characters
						preg_match( $regex, $cart->email, $match_email );
						preg_match( $regex, str_replace( '+', '', $cart->phone ), $match_phone ); //Using string replace to remove + sign from phone number when trying to find a match since it is also being removed from $regex line before
						
						if ( ! empty( $match_email ) || ! empty( $match_phone ) ) { //If email or phone match found - return true
							$result = true;
							break;
						}
					}
				}
			}
		}

		return $result;
	}

	/**
	* Check if one array item is inside another array
	*
	* @since    9.7.5
	* @return   boolean
	* @param    array      $needle    		  	 Search value
	* @param    array      $haystack             Search region
	*/
	function item_in_array( $needle, $haystack ){
		$found = false;
		
		if( is_array( $needle ) ){
			foreach( $needle as $stack ) {
				
				if ( in_array( $stack, $haystack ) ) {
					$found = true;
				}

			}
		}

		return $found;
	}

	/**
	* Convert milliseconds to minutes
	*
	* @since    9.9.3
	* @return   integer
	* @param    integer    $milliseconds    		 A numeric value of milliseconds
	*/
	function convert_milliseconds_to_minutes( $milliseconds ){
		$minutes = 0;

		if( !empty( $milliseconds ) ){
			$minutes = intval( $milliseconds / 60000 );
		}
		
		return $minutes;
	}

	/**
	* Convert minutes to milliseconds
	*
	* @since    9.9.3
	* @return   integer
	* @param    integer    $minutes    		 A numeric value of minutes
	*/
	function convert_minutes_to_milliseconds( $minutes ){
		$milliseconds = 0;

		if( !empty( $minutes ) ){
			$milliseconds = intval( $minutes * 60000 );
		}
		
		return $milliseconds;
	}

	/**
	* Deleting anonymous carts
	*
	* @since    9.9.3
	*/
	function delete_anonymous_carts(){
		$interval_data = $this->get_interval_data( 'cartbounty_pro_main_settings[delete_anonymous_carts]' );

		if( $interval_data['selected'] == 0 ) return; //Exit deletion in case Anonymous cart deletion disabled

		global $wpdb;
		$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
		$time = $this->get_time_intervals( $interval_data['selected'] );
		$where_sentence = $this->get_where_sentence( 'anonymous', $starting_and = false );

		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM $cart_table
				WHERE $where_sentence AND
				time < %s",
				$time['anonymous_cart_age']
			)
		);
	}

	/**
	* Retrieve current domain name
	*
	* @since    9.9.3
	* @return   string
	*/
	function get_current_domain_name(){
		$domain = strtolower( parse_url( get_site_url(), PHP_URL_HOST ) );
		return $domain;
	}

	/**
	* Retrieve expired license key renewal information message
	*
	* @since    9.10
	* @return   HTML
	* @param    String    $medium     				Determines where the button was clicked from. Default none
	*/
	function get_expired_license_message( $medium = '' ){
		$notice_contents = $this->get_notice_contents( 'license_expired', $medium  );
		$message = $notice_contents['description'];
		return $message;
	}

	/**
	* Retrieve license about to expire information message
	*
	* @since    10.9
	* @return   HTML
	* @param    String    $medium     				Determines where the button was clicked from. Default none
	*/
	function get_license_about_to_expire_message( $medium = '' ){
		$notice_contents = $this->get_notice_contents( 'license_about_to_expire', $medium  );
		$message = $notice_contents['description'];
		return $message;
	}

	/**
	* Method for encoding emoji symbols in content input fields
	*
	* @since    9.10
	* @param    string   $item    		 Array value
	* @param    string   $key    		 Array key
	*/
	function encode_emojis( &$item, $key ) {
		$content_fields = array( //Content fields that may include emoji symbols
			'subject',
			'heading',
			'content',
			'permission_heading',
			'permission_content',
			'coupon_description',
			'checkout_consent',
			'tools_consent',
		);

		if( in_array( $key, $content_fields ) ){ //Encoding only content input fields
			$item = wp_encode_emoji( $item );
		}
	}

	/**
	* Filtering CartBounty options before their values are serialized and saved inside database
	*
	* @since    9.10
	* @return   mixed
	* @param    mixed    $value    		 	 The new, unserialized option value
	* @param    string   $option    		 Name of the option
	* @param    mixed    $old_value    		 The old option value
	*/
	function validate_cartbounty_fields( $value, $option, $old_value ) {
		
		if ( strpos( $option, 'cartbounty_pro_' ) === 0 ) { //Check if the option being updated belongs to CartBounty

			if( is_array( $value ) ){ //If option value is an array
				array_walk_recursive( $value, array( $this, 'encode_emojis' ) );

			}else{
				$this->encode_emojis( $value, $option );
			}
		}

		return $value;
	}

	/**
	* Returning cart location data. A single value or if no $value is specified - returning all location data as an array
	*
	* @since    9.11
	* @return   string or array
	* @param    string   $value    		 	 Location value to return, e.g. "country", "city"
	*/
	function get_cart_location( $location_data, $value = false ) {
		$location_array = '';
		$location_value = array( //Setting defaults
			'country' 	=> '',
			'city' 		=> '',
			'postcode' 	=> '',
		);

		if( is_string( $location_data ) ){
			$location_array = maybe_unserialize( $location_data );
		}

		if( is_array( $location_array ) ){ //If unserialization succeeded and we have an array
			
			if( isset( $location_array['country'] ) ){
				$location_value['country'] = $location_array['country'];
			}

			if( isset( $location_array['city'] ) ){
				$location_value['city'] = $location_array['city'];
			}

			if( isset( $location_array['postcode'] ) ){
				$location_value['postcode'] = $location_array['postcode'];
			}

		}

		if( $value ){ //If a single value should be returned
			
			if( isset( $location_value[$value] ) ){ //Checking if value exists
				$location_value = $location_value[$value];
			}

		}

		return $location_value;
	}

	/**
	* Try to create a coupon code if a specific tool coupon code has been enabled
	*
	* @since    9.12
	* @return   array
	* @param    string    $session_id        Session ID
	* @param    array     $_post             Submitted $_POST data array
	*/
	function try_provide_coupon_code_for_tool( $session_id, $_post ){
		$result = array(
			'success' => false,
			'coupon' => '',
			'coupon_html' => '',
			'message' => '',
		);
		$source = '';
		$option = '';

		if( !empty( $_post['source'] ) ){
			
			if( $_post['source'] == 'cartbounty_pro_early_capture' ){
				$source = 'early_capture';
				$option = 'cartbounty_pro_early_capture_coupon';

			}elseif( $_post['source'] == 'cartbounty_pro_exit_intent' ){
				$source = 'exit_intent';
				$option = 'cartbounty_pro_exit_intent_coupon';
			}

			$test_mode = $this->get_settings( $source, 'test_mode' );
			$coupons = $this->coupons();
			$coupon_enabled = $coupons->coupon_enabled( $source, $option, false );

			if( $coupon_enabled ){

				if( $session_id !== NULL && !empty( $option ) ){
					global $wpdb;
					$cart_table = $wpdb->prefix . CARTBOUNTY_PRO_TABLE_NAME;
					$cart = $wpdb->get_row(
						$wpdb->prepare(
							"SELECT id, email, phone, name, surname, session_id, location, cart_contents, cart_total, currency, time, language, coupons
							FROM $cart_table
							WHERE session_id = %s AND
							(type = %d OR type = %d)",
							$session_id,
							$this->get_cart_type('abandoned'),
							$this->get_cart_type('recovered_pending')
						)
					);

					if( !empty( $cart ) ){
						$existing_coupons = maybe_unserialize( $cart->coupons );

						if( $existing_coupons && !$test_mode ){ //If coupons exist and Test mode is disabled - check if one has already been created before for this specific tool or not
							
							if( isset( $existing_coupons[$source] ) ){ //Stop creating a new coupon if coupon has already been created for this particular tool
								return $result;
							}
						}

						$coupon = $coupons->get_coupon( $source, $option, $step_nr = false, $cart ); //Coupon code creation

						if( isset( $coupon['coupon_code'] ) ){ //If coupon code created successfully
							$result['success'] = true;
							$result['coupon'] = $coupon['coupon_code'];
							$result['coupon_html'] = '<div id="cartbounty-pro-tool-coupon"><span id="cartbounty-pro-tool-coupon-message"></span><span id="cartbounty-pro-tool-close-coupon-message"></span></div>';
							$result['message'] = $message = __( 'Coupon code applied successfully.', 'woo-save-abandoned-carts' );
							$this->auto_apply_coupon( $coupon['coupon_code'], $source, $step_nr = false, $coming_from_tool = true );

						}else{
							$message = __( 'The coupon code could not be applied.', 'woo-save-abandoned-carts' ); //Default error message

							if( !empty( $coupon['error_message'] ) ){
								$message = $coupon['error_message'];
							}

							$result['success'] = false;
							$result['coupon_html'] = '<div id="cartbounty-pro-tool-coupon" class="cartbounty-pro-coupon-error"><span id="cartbounty-pro-tool-coupon-message"></span><span id="cartbounty-pro-tool-close-coupon-message"></span></div>';
							$result['message'] = $message;
						}

						wc_clear_notices(); //Making sure that another PHP coupon application message is not displayed after page reload (using Ajax to display notice)
					}
				}
			}
		}

		return $result;
	}

	/**
	 * Display active features
	 *
	 * @since    10.0
	 * @return   HTML
	 */
	public function display_active_features(){
		$content = '';
		$features = array();
		$features['recovery'] = $this->get_sections( 'recovery' );
		$features['tools'] = $this->get_sections( 'tools' );
		ob_start(); ?>
		<?php foreach( $features as $section => $feature ): ?>
			<?php foreach( $feature as $key => $item ): ?>
				<?php if( $item['connected'] ): ?>
					<?php $link = '?page='. CARTBOUNTY_PRO .'&tab='. $section .'&section='. $key; ?>
					<div class="cartbounty-col-xs-6 cartbounty-pro-section-item-container">
						<a class="cartbounty-pro-section-item cartbounty-pro-connected" href="<?php echo esc_url( $link ); ?>" title="<?php echo esc_attr( $item['name'] ); ?>">
							<span class="cartbounty-pro-section-image"><?php echo $this->get_icon( $key, false, false, true ); ?></span>
							<span class="cartbounty-pro-section-content">
								<em class="cartbounty-pro-section-title"><?php echo esc_html( $item['name'] ); ?></em>
								<?php echo $this->get_connection( $item['connected'], true, $section ); ?>
							</span>
						</a>
					</div>
				<?php endif; ?>
			<?php endforeach; ?>
		<?php endforeach; ?>
		<?php $content = ob_get_contents();
		ob_end_clean();
		return $content;
	}

	/**
	 * Retrieve notice contents
	 *
	 * @since    10.0
	 * @return   array
	 * @param    string    $notice_type        		Notice type
	 * @param    String    $medium     				Determines where the button was clicked from. Default none
	 * @param    String    $tag        				Hashtag to a specific section in the document. Default none
	 */
	public function get_notice_contents( $notice_type, $medium = '', $tag = '' ){
		$contents = array();
		$expression = $this->get_expressions();
		$saved_cart_count = $this->total_cartbounty_recoverable_cart_count();
		$closest_lowest_cart_count_decimal = $this->get_closest_lowest_integer( $saved_cart_count );
		$name = esc_html__( 'captain', 'woo-save-abandoned-carts');
		$current_user = wp_get_current_user();
		$settings_tab = $this->get_settings_tab_url();
		
		if( !empty( $current_user->display_name ) ){
			$name = $current_user->display_name;

		}elseif( !empty( $current_user->first_name ) ){
			$name = $current_user->first_name;
		}

		$name = ucfirst( $name ); //Capitalize name

		switch( $notice_type ){

			case 'missing_license':
				$contents = array(
					'title' 		=> sprintf(
									/* translators: %1$s - User's name */
									esc_html__( 'Adventures await, %1$s!', 'woo-save-abandoned-carts' ), esc_html( $name ) ),
					'description' 	=> sprintf(
									/* translators: %1$s - Name of the plugin, %2$s - Link start, %3$s - Link end */
									esc_html__( 'Thank you for activating %1$s. Please navigate to %2$sSettings%3$s, input your license key, and prepare for a treasure trove of bounties and wild cart-saving adventures ahead! :)', 'woo-save-abandoned-carts' ), esc_html( CARTBOUNTY_PRO_ABBREVIATION ), '<a href="'. esc_url( $settings_tab ) .'">', '</a>'),
					'image'			=> plugins_url( 'assets/treasure-awaits.gif', __FILE__ ),
					'color_class'	=> ' cartbounty-pro-teal',
					'main_url'		=> $settings_tab,
					'local_url'		=> true,
					'using_buttons'	=> true,
					'url_label'		=> esc_html__( 'Add license', 'woo-save-abandoned-carts' ),
					'done_label'	=> '',
					'close_label'	=> ''
				);
				break;

			case 'license_expired':
				$contents = array(
					'title' 		=> esc_html__( 'Your CartBounty license has expired!', 'woo-save-abandoned-carts' ),
					'description' 	=> sprintf(
									/* translators: %1$s - Exclamation, gets replaced by an expression of excitement e.g. Awesome, %2$s - Name of the user, %3$d - Abandoned cart count, %4$s - URL link start, %5$s - URL link end */
									wp_kses_post(
										_n(
											'%1$s, %2$s! You have saved over <b>%3$d abandoned cart</b> with CartBounty! However, your premium support and access to updates have expired. %4$sRenew your license%5$s to stay connected with our latest updates, premium support, and receive the latest features. Embark on new adventures and bounties ahead with us!',
											'%1$s, %2$s! You have saved over <b>%3$d abandoned carts</b> with CartBounty! However, your premium support and access to updates have expired. %4$sRenew your license%5$s to stay connected with our latest updates, premium support, and receive the latest features. Embark on new adventures and bounties ahead with us!',
											esc_html( $closest_lowest_cart_count_decimal ), 'woo-save-abandoned-carts'
										)
									),
									esc_html( rtrim( $expression['exclamation'], '!' ) ),
									esc_html( ucfirst( $name ) ),
									esc_html( $closest_lowest_cart_count_decimal ),
									'<a href="' . esc_url( $this->get_trackable_link( '', $medium ) ) . '" target="_blank">',
									'</a>'),
					'image'			=> plugins_url( 'assets/lonely-island.gif', __FILE__ ),
					'color_class'	=> '',
					'main_url'		=> $this->get_trackable_link( '', $medium, $tag ),
					'local_url'		=> false,
					'using_buttons'	=> true,
					'url_label'		=> esc_html__( 'Renew license', 'woo-save-abandoned-carts' ),
					'done_label'	=> '',
					'close_label'	=> esc_html__( 'Close', 'woo-save-abandoned-carts' )
				);
				break;

			case 'license_about_to_expire':
				$expiration_date = $this->get_settings( 'misc_settings', 'expiration_date' );
				$now       = current_time( 'timestamp', true );
				$utc_time  = strtotime( $expiration_date );
				$days_left = ceil( ( $utc_time - $now ) / DAY_IN_SECONDS );

				$contents = array(
					'title'        => sprintf(
						/* translators: %s - Number of days */
						esc_html__( 'Your CartBounty license is about to expire in %s days!', 'woo-save-abandoned-carts' ),
						esc_html( $days_left )
					),
					'description'  => sprintf(
					/* translators: %1$s - Exclamation (e.g., Awesome), %2$s - User's name, %3$d - Abandoned cart count, %4$s - URL link start, %5$s - URL link end */
						wp_kses_post(
							_n(
								'%1$s, %2$s! You have saved over <b>%3$d abandoned cart</b> with CartBounty! Your premium support and access to updates will end in <b>%6$s days</b>. %4$sRenew your license %5$s now to keep uninterrupted updates, premium support and get the latest features. New features and treasure just over the horizon!',
								'%1$s, %2$s! You have saved over <b>%3$d abandoned carts</b> with CartBounty! Your premium support and updates will end in <b>%6$s days</b>. %4$sRenew your license %5$s now to keep uninterrupted updates, premium support and get the latest features. New features and treasure just over the horizon!',
								esc_html( $closest_lowest_cart_count_decimal ), 'woo-save-abandoned-carts'
							)
						),
						esc_html( rtrim( $expression['exclamation'], '!' ) ),
						esc_html( ucfirst( $name ) ),
						esc_html( $closest_lowest_cart_count_decimal ),
						'<a href="' . esc_url( $this->get_trackable_link( '', $medium ) ) . '" target="_blank">',
						'</a>',
						esc_html( $days_left )
					),

					'image'			=> plugins_url( 'assets/lonely-island.gif', __FILE__ ),
					'color_class'	=> '',
					'main_url'		=> $this->get_trackable_link( '', $medium, $tag ),
					'local_url'		=> false,
					'using_buttons'	=> true,
					'url_label'		=> esc_html__( 'Renew license', 'woo-save-abandoned-carts' ),
					'done_label'	=> '',
					'close_label'	=> esc_html__( 'Close', 'woo-save-abandoned-carts' )
				);
				break;

			case 'review':
				$contents = array(
					'title' 		=> sprintf(
										/* translators: %s - Gets replaced by an excitement word e.g. Awesome!, %d - Abandoned cart count */
										esc_html( _n( '%s You have already captured %d abandoned cart!', '%s You have already captured %d abandoned carts!', $closest_lowest_cart_count_decimal , 'woo-save-abandoned-carts' ) ), esc_html( $expression['exclamation'] ), esc_html( $closest_lowest_cart_count_decimal ) ),
					'description' 	=> esc_html__( 'If you like our plugin, please leave us a 5-star rating. It is the easiest way to help us grow and keep evolving further.', 'woo-save-abandoned-carts' ),
					'image'			=> plugins_url( 'assets/review-notification.gif', __FILE__ ),
					'color_class'	=> '',
					'main_url'		=> CARTBOUNTY_PRO_REVIEW_LINK,
					'local_url'		=> false,
					'using_buttons'	=> true,
					'url_label'		=> esc_html__( 'Leave a 5-star rating', 'woo-save-abandoned-carts' ),
					'done_label'	=> esc_html__( 'Done', 'woo-save-abandoned-carts' ),
					'close_label'	=> esc_html__( 'Close', 'woo-save-abandoned-carts' )
				);
				break;
		}

		return $contents;
	}

	/**
	 * Display dashboard notices
	 * Priority in which notices will be displayed:
	 *		1) Information notice
	 *		2) Sales notice
	 *		3) Expired license notice
	 *		4) Review request
	 *
	 * @since    10.0
	 * @return   HTML
	 */
	public function display_dashboard_notices(){
		$content = '';
		$dashboard = true;

		if( $this->should_display_notice( 'missing_license', $dashboard ) ){
			$content = $this->prepare_notice( 'missing_license', $dashboard );

		}elseif( $this->should_display_notice( 'license_expired', $dashboard ) ){
			$content = $this->prepare_notice( 'license_expired', $dashboard, 'expired_dashboard' );

		}elseif( $this->should_display_notice( 'license_about_to_expire', $dashboard ) ){
			$content = $this->prepare_notice( 'license_about_to_expire', $dashboard, 'license_about_to_expire_dashboard' );

		}elseif( $this->should_display_notice( 'review', $dashboard ) ){ //Checking if we should display the Review notice
			$content = $this->prepare_notice( 'review', $dashboard );
		}

		return $content;
	}

	/**
	 * Check if notice should be displayed or not
	 *
	 * @since    10.0
	 * @return   boolean
	 * @param    string    		$notice_type        Notice type
	 * @param    boolean    	$dashboard        	If notice is a Dashboard notice
	 */
	function should_display_notice( $notice_type, $dashboard = false ){
		$display = false;
		$recoverable_cart_count = $this->total_cartbounty_recoverable_cart_count();

		switch( $notice_type ){
			
			case 'missing_license':

				if( !$this->check_license() && !$recoverable_cart_count ){ //Display welcome message in case license is inactive and no cart has been saved so far
					$display = true; //Show the notice
				}

				break;

			case 'license_expired':

				if( $this->is_license_expired() ){
					
					if( $dashboard ){ //If looking at Dashboard notices
						if( !$this->is_notice_submitted( $notice_type ) ){
							$display = true;
						}

					}else{ //If looking at global notice warning in the top of the page

						if( empty( get_user_meta( get_current_user_id(), 'cartbounty_pro_expired_notice', true ) ) ){
							$display = true;
						}
					}
				}

				break;

			case 'license_about_to_expire':

				//Display notice 1 month before expiration
				//If time has passed - do not display it
				$expiration_date = $this->get_settings( 'misc_settings', 'expiration_date' );
				
				if( !empty( $expiration_date ) ){
					$now = current_time( 'timestamp', true );
					$time = new DateTime( $expiration_date );
					$utc_time = $time->format( 'U' );
					$month = strtotime( '-1 month', $utc_time );

					if( $now >= $month && $now < $utc_time ){
						
						if( $dashboard ){ //If looking at Dashboard notices
							
							if( !$this->is_notice_submitted( $notice_type ) ){
								$display = true;
							}

						}else{ //If looking at global notice warning in the top of the page

							if( empty( get_user_meta( get_current_user_id(), 'cartbounty_pro_license_about_to_expire_notice', true ) ) ){
								$display = true;
							}
						}
					}
				}

				break;

			case 'review':

				if( !$this->is_notice_submitted( $notice_type ) ){
					$level = $this->get_achieved_review_level();
					
					if( $level ){
						$display = true;
					}
				}

				break;
		}

		return $display;
	}

	/**
	 * Prepare notice contents
	 *
	 * @since    10.0
	 * @return   HTML
	 * @param    string    	$notice_type        Notice type
	 * @param    boolean    $dashboard        	If the notice should be displayed on dashboard or not
	 * @param    String    $medium     			Determines where the button was clicked from. Default none
	 * @param    String    $tag        			Hashtag to a specific section in the document. Default none
	 */
	public function prepare_notice( $notice_type, $dashboard = false, $medium = '', $tag = '' ){
		$notice_contents = $this->get_notice_contents( $notice_type, $medium, $tag );
		$title = $notice_contents['title'];
		$description = $notice_contents['description'];
		$image_url = $notice_contents['image'];
		$color_class = $notice_contents['color_class'];
		$main_url = $notice_contents['main_url'];
		$local_url = $notice_contents['local_url'];
		$using_buttons = $notice_contents['using_buttons'];
		$url_label = $notice_contents['url_label'];
		$done_label = $notice_contents['done_label'];
		$close_label = $notice_contents['close_label'];
		$nonce = wp_create_nonce( 'notice_nonce' );
		$class = '';
		$target = '_blank';

		if( $dashboard ){ //If not displaying notice inside dashboard
			$class = ' cartbounty-pro-report-widget';
		}else{
			$class = ' cartbounty-pro-bubble';
		}

		if( $local_url ){ //In case this is a local URL, open link in a the same tab
			$target = '_self';
		}

		ob_start(); ?>
		<div id="cartbounty-pro-notice-<?php echo $notice_type; ?>" class="cartbounty-pro-notice-block<?php echo $class; ?>">
			<?php if( $image_url ): ?>
			<a class="cartbounty-pro-notice-image<?php echo $color_class; ?>" href="<?php echo esc_url( $main_url ); ?>" title="<?php echo esc_attr( $title); ?>" target="<?php echo $target; ?>">
				<img src="<?php echo esc_url( $image_url ); ?>"/>
			</a>
			<?php endif; ?>
			<div class="cartbounty-pro-notice-content">
				<h2><?php echo $title; ?></h2>
				<p><?php echo $description; ?></p>
				<?php if( $using_buttons ): ?>
				<div class="cartbounty-pro-button-row">
					<?php if( $url_label ): ?>
					<a href="<?php echo esc_url( $main_url ); ?>" class="button cartbounty-pro-button" target="<?php echo $target; ?>"><?php echo $url_label; ?></a>
					<?php endif; ?>
					<?php if( $done_label ): ?>
					<button type="button" class='button cartbounty-pro-button cartbounty-pro-notice-done cartbounty-pro-close-notice' data-operation='submitted' data-type='<?php echo $notice_type; ?>' data-nonce='<?php echo esc_attr( $nonce ); ?>'><?php echo $done_label; ?></button>
					<?php endif; ?>
					<?php if( $close_label ): ?>
					<button type="button" class='button cartbounty-pro-button cartbounty-pro-close cartbounty-pro-close-notice' data-operation='declined' data-type='<?php echo $notice_type; ?>' data-nonce='<?php echo esc_attr( $nonce ); ?>'><?php echo $close_label; ?></button>
					<?php endif; ?>
				</div>
				<?php endif; ?>
			</div>
		</div>
		<?php $content = ob_get_contents();
		ob_end_clean();

		return $content;
	}

	/**
	 * Return currently achieved review level
	 * Used to define various levels at which the review should be displayed
	 *
	 * @since    10.0.3
	 * @return   integer
	 */
	public function get_achieved_review_level(){
		$level = 0;
		$levels = array(
			'1' => 20,
			'2' => 40,
			'3' => 80,
			'4' => 120,
			'5' => 250,
			'6' => 500,
			'7' => 1000,
		);
		$times_review_declined = $this->get_settings( 'misc_settings', 'times_review_declined' );
		$maximum_value = max( array_keys( $levels ) );
		
		if( $times_review_declined >= $maximum_value ) return; //Stop in case we have reached maximum level at which we ask reviews

		$recoverable_cart_count = $this->total_cartbounty_recoverable_cart_count();

		foreach( $levels as $key => $value ) {
			if( $recoverable_cart_count >= $value && $times_review_declined < $key ){
				$level = $key;
			}
		}

		return $level;
	}

	/**
	* Return saved abandoned cart data
	*
	* @since    10.1.1
	* @return   array
	* @param    array     $cart_data         Cart data that needs to be returned
	*/
	public function get_saved_cart_contents( $cart_data ){
		$saved_cart_data = maybe_unserialize( $cart_data );

		if( isset( $saved_cart_data['products'] ) ){ //Temporary block since version 10.8. Will be removed in future versions. Supports previous version of saving cart contents and cart mete information in the same column
			$saved_cart_data = $saved_cart_data['products'];
		}

		return $saved_cart_data;
	}

	/**
	* Validate abandoned cart deletion security nonce
	*
	* @since    10.3
	*/
	public function validate_cart_deletion(){
		
		if( isset( $_GET['page'] ) && $_GET['page'] == CARTBOUNTY_PRO ){ //If delete action coming from CartBounty

			if( isset( $_GET['action'] ) && $_GET['action'] == 'delete' ){ //Check if any delete action fired including bottom Bulk delete action

				$nonce = false;

				if( isset( $_GET['nonce'] ) ){
					$nonce = $_GET['nonce'];
				}

				if( !wp_verify_nonce( $nonce, 'delete_cart_nonce' ) && !wp_verify_nonce( $nonce, 'bulk_action_nonce' ) ){
					wp_die( esc_html__( 'Security check failed. The link is not valid.', 'woo-save-abandoned-carts' ) ); 
				}
			}
		}
	}

	/**
	* Validate phone number
	*
	* @return   boolean
	* @param    string     $phone     Phone number
	* @since    10.7
	*/
	public function validate_phone_number( $phone ){
		$valid = false;
		$pattern = '^[+0-9\s]\s?\d[0-9\s.\-]{6,30}$';
		$regex = '/'. $pattern .'/';

		if( !empty( $phone ) ){
			
			if( preg_match( $regex, $phone ) === 1 ){
				$valid = true;
			}
		}
		
		return $valid;
	}

	/**
	* Return modal container used for example on WordPress recovery email preview
	*
	* @since    9.3
	* @return   HTML
	* @param    string    $modal_id              Identifier to distinguish modal windows from one another
	*/
	public function output_modal_container( $modal_id = false ){
		$output = '';
		$output .= '<div class="cartbounty-pro-modal" id="cartbounty-pro-modal-'. esc_attr( $modal_id ) .'" aria-hidden="true">';
			$output .= '<div class="cartbounty-pro-modal-overlay" tabindex="-1" data-micromodal-close>';
				$output .= '<div class="cartbounty-pro-modal-content-container" role="dialog" aria-modal="true">';
					$output .= '<button type="button" class="cartbounty-pro-close-modal" aria-label="'. esc_html__("Close", 'woo-save-abandoned-carts') .'" data-micromodal-close></button>';
					$output .= '<div class="cartbounty-pro-modal-content" id="cartbounty-pro-modal-content-'. esc_attr( $modal_id ) .'"></div>';
				$output .= '</div>';
			$output .= '</div>';
		$output .= '</div>';
		return $output;
	}

	/**
	* Retrieve current license server URL
	*
	* @since    10.8
	* @return   string
	*/
	public function get_license_server_url(){
		$server = '';
		
		if( apply_filters( 'cartbounty_pro_enable_secondary_license_server', false ) ){
			$server = '';
		}

		return $server;
	}

	/**
	 * Replacing WordPress default transients with custom function for storing temporary data
	 * Transients do not seem to be working reliably for all users
	 * Using WooCommerce session value as a unique identifier
	 *
	 * @since    10.8
	 * @param    string    $key                Temporary data field identifier
	 * @param    string    $value              Value to be stored
	 * @param    string    $expiration         Data expiration time
	 * @param    boolean   $unique         	   If the transient should be unique for each customer or not
	 */
	function set_cartbounty_transient( $key, $value, $expiration = 60, $unique = false ){
		$customer_id = '';
		
		if( $unique ){ //If storing unique option for each visitor

			if( WC()->session ){
				$customer_id = '_' . WC()->session->get_customer_id();
			}
		}

		$data = array(
			'value'      => $value,
			'expiration' => time() + absint( $expiration ),
		);

		$id = 'cartbounty_pro_temp_' . $key . $customer_id;
		update_option( $id, $data, false );
	}

	/**
	 * Retrieving custom transient data from database
	 *
	 * @since    10.8
	 * @return   false / string
	 * @param    string    $key                Temporary data field identifier
	 * @param    boolean   $unique         	   If the transient should be unique for each customer or not
	 */
	function get_cartbounty_transient( $key, $unique = false ){
		$result = false;
		$customer_id = '';

		if( $unique ){ //If retrieving a unique option for each visitor

			if( WC()->session ){
				$customer_id = '_' . WC()->session->get_customer_id();
			}
		}

		$id = 'cartbounty_pro_temp_' . $key . $customer_id;
		$data = get_option( $id );

		if( empty( $data ) || !is_array( $data ) || !isset( $data['expiration'] ) ){ //If data is missing
			//Do nothing
		
		}elseif( time() > $data['expiration'] ){ //Clean up expired data
			delete_option( $id );

		}else{
			$result = $data['value'];
		}

		return $result;
	}

	/**
	 * Delete a single transient with the given id
	 *
	 * @since    10.8
	 * @param    string    $key                Temporary data field identifier
	 */
	function delete_cartbounty_transient( $key ){
		$id = 'cartbounty_pro_temp_' . $key;
		delete_option( $id );
	}

	/**
	* Deleting transients
	* Function does not check if transient has expired or not
	*
	* @since    10.8
	*/
	function delete_expired_cartbounty_transients(){
		global $wpdb;
		$options_table = $wpdb->options;
		$prefix = 'cartbounty_pro_temp_';
		$now = time();

		$wpdb->get_results(
			$wpdb->prepare(
				"DELETE FROM $options_table
				 WHERE option_name
				 LIKE %s",
				$wpdb->esc_like( $prefix ) . '%'
			)
		);
	}

	/**
	* Checks if current user has Admin privileges
	*
	* @since    10.8
	* @return   boolean
	*/
	function user_is_admin(){
		return current_user_can( 'manage_options' );
	}

	/**
	* Checks if current user has Shop manager privileges
	*
	* @since    10.8
	* @return   boolean
	*/
	function user_is_shop_manager(){
		return current_user_can( 'list_users' );
	}

	/**
	 * Retrieving key fingerprint for indentifying if the contents inside input field or fields have changed or not
	 * This generates a unique value that can be used for storing information in the database instead of caching each field and then comparing
	 * them if they have changed since last time or not
	 *
	 * @since    10.8
	 * @return   string
	 * @param    string    $a						First data field
	 * @param    string    $b						Second data field
	 */
	public function get_key_fingerprint( $a, $b = '' ){
		return substr( hash( 'sha256', $a . '|' . $b . '|' . get_home_url() ), 0, 16 );
	}

	/**
	* Method displays allowed user roles for Magic login
	*
	* @since    10.9
	* @return   HTML
	*/
	public function display_magic_login_roles(){
		$available_roles = array();
		$roles = get_editable_roles();
		
		if( is_array( $roles ) ){
			foreach( $roles as $key => $role ){
				
				if( isset( $role['name'] ) ){
					$available_roles[ $key ] = $role['name'];
				}
			}
		}

		$settings = $this->get_settings( 'settings' );
		$option_name = 'cartbounty_pro_main_settings[magic_login_roles]';
		$selected_roles = $settings['magic_login_roles'];

		if( !$selected_roles ){ //In case no status is added, restore default statuses
			$settings['magic_login_roles'] = array( 'customer', 'subscriber' );
			update_option( 'cartbounty_pro_main_settings', $settings ); 
			$selected_roles = $this->get_settings( 'settings', 'magic_login_roles' );
		}

		echo '<select id="cartbounty-pro-magic-login-roles" class="cartbounty-pro-select cartbounty-pro-multiple cartbounty-pro-select-multiple-items" multiple name="' . $option_name . '[]" placeholder="' . esc_attr__( 'Select user roles ', 'woo-save-abandoned-carts' ) . '" autocomplete="off" '. $this->disable_field() .'>';
		foreach( $available_roles as $key => $status ){
			$selected = '';
			if( in_array( $key, $selected_roles ) ){
				$selected = 'selected';
			}
			echo "<option value='". esc_attr( $key ) ."' $selected>". esc_html( $status ) ."</option>";
		}
		echo '</select>';
	}

	/**
	 * Converts the WooCommerce country codes to 3-letter ISO codes
	 *
	 * @since    8.0
	 * @return   string    ISO 3-letter country code
	 * @param    string    $country               WooCommerce's 2 letter country code
	 */
	public function convert_country_code( $country ) {
		$countries = array(
			'AF' => 'AFG', //Afghanistan
			'AX' => 'ALA', //&#197;land Islands
			'AL' => 'ALB', //Albania
			'DZ' => 'DZA', //Algeria
			'AS' => 'ASM', //American Samoa
			'AD' => 'AND', //Andorra
			'AO' => 'AGO', //Angola
			'AI' => 'AIA', //Anguilla
			'AQ' => 'ATA', //Antarctica
			'AG' => 'ATG', //Antigua and Barbuda
			'AR' => 'ARG', //Argentina
			'AM' => 'ARM', //Armenia
			'AW' => 'ABW', //Aruba
			'AU' => 'AUS', //Australia
			'AT' => 'AUT', //Austria
			'AZ' => 'AZE', //Azerbaijan
			'BS' => 'BHS', //Bahamas
			'BH' => 'BHR', //Bahrain
			'BD' => 'BGD', //Bangladesh
			'BB' => 'BRB', //Barbados
			'BY' => 'BLR', //Belarus
			'BE' => 'BEL', //Belgium
			'BZ' => 'BLZ', //Belize
			'BJ' => 'BEN', //Benin
			'BM' => 'BMU', //Bermuda
			'BT' => 'BTN', //Bhutan
			'BO' => 'BOL', //Bolivia
			'BQ' => 'BES', //Bonaire, Saint Estatius and Saba
			'BA' => 'BIH', //Bosnia and Herzegovina
			'BW' => 'BWA', //Botswana
			'BV' => 'BVT', //Bouvet Islands
			'BR' => 'BRA', //Brazil
			'IO' => 'IOT', //British Indian Ocean Territory
			'BN' => 'BRN', //Brunei
			'BG' => 'BGR', //Bulgaria
			'BF' => 'BFA', //Burkina Faso
			'BI' => 'BDI', //Burundi
			'KH' => 'KHM', //Cambodia
			'CM' => 'CMR', //Cameroon
			'CA' => 'CAN', //Canada
			'CV' => 'CPV', //Cape Verde
			'KY' => 'CYM', //Cayman Islands
			'CF' => 'CAF', //Central African Republic
			'TD' => 'TCD', //Chad
			'CL' => 'CHL', //Chile
			'CN' => 'CHN', //China
			'CX' => 'CXR', //Christmas Island
			'CC' => 'CCK', //Cocos (Keeling) Islands
			'CO' => 'COL', //Colombia
			'KM' => 'COM', //Comoros
			'CG' => 'COG', //Congo
			'CD' => 'COD', //Congo, Democratic Republic of the
			'CK' => 'COK', //Cook Islands
			'CR' => 'CRI', //Costa Rica
			'CI' => 'CIV', //Côte d\'Ivoire
			'HR' => 'HRV', //Croatia
			'CU' => 'CUB', //Cuba
			'CW' => 'CUW', //Curaçao
			'CY' => 'CYP', //Cyprus
			'CZ' => 'CZE', //Czech Republic
			'DK' => 'DNK', //Denmark
			'DJ' => 'DJI', //Djibouti
			'DM' => 'DMA', //Dominica
			'DO' => 'DOM', //Dominican Republic
			'EC' => 'ECU', //Ecuador
			'EG' => 'EGY', //Egypt
			'SV' => 'SLV', //El Salvador
			'GQ' => 'GNQ', //Equatorial Guinea
			'ER' => 'ERI', //Eritrea
			'EE' => 'EST', //Estonia
			'ET' => 'ETH', //Ethiopia
			'FK' => 'FLK', //Falkland Islands
			'FO' => 'FRO', //Faroe Islands
			'FJ' => 'FIJ', //Fiji
			'FI' => 'FIN', //Finland
			'FR' => 'FRA', //France
			'GF' => 'GUF', //French Guiana
			'PF' => 'PYF', //French Polynesia
			'TF' => 'ATF', //French Southern Territories
			'GA' => 'GAB', //Gabon
			'GM' => 'GMB', //Gambia
			'GE' => 'GEO', //Georgia
			'DE' => 'DEU', //Germany
			'GH' => 'GHA', //Ghana
			'GI' => 'GIB', //Gibraltar
			'GR' => 'GRC', //Greece
			'GL' => 'GRL', //Greenland
			'GD' => 'GRD', //Grenada
			'GP' => 'GLP', //Guadeloupe
			'GU' => 'GUM', //Guam
			'GT' => 'GTM', //Guatemala
			'GG' => 'GGY', //Guernsey
			'GN' => 'GIN', //Guinea
			'GW' => 'GNB', //Guinea-Bissau
			'GY' => 'GUY', //Guyana
			'HT' => 'HTI', //Haiti
			'HM' => 'HMD', //Heard Island and McDonald Islands
			'VA' => 'VAT', //Holy See (Vatican City State)
			'HN' => 'HND', //Honduras
			'HK' => 'HKG', //Hong Kong
			'HU' => 'HUN', //Hungary
			'IS' => 'ISL', //Iceland
			'IN' => 'IND', //India
			'ID' => 'IDN', //Indonesia
			'IR' => 'IRN', //Iran
			'IQ' => 'IRQ', //Iraq
			'IE' => 'IRL', //Republic of Ireland
			'IM' => 'IMN', //Isle of Man
			'IL' => 'ISR', //Israel
			'IT' => 'ITA', //Italy
			'JM' => 'JAM', //Jamaica
			'JP' => 'JPN', //Japan
			'JE' => 'JEY', //Jersey
			'JO' => 'JOR', //Jordan
			'KZ' => 'KAZ', //Kazakhstan
			'KE' => 'KEN', //Kenya
			'KI' => 'KIR', //Kiribati
			'KP' => 'PRK', //Korea, Democratic People\'s Republic of
			'KR' => 'KOR', //Korea, Republic of (South)
			'KW' => 'KWT', //Kuwait
			'KG' => 'KGZ', //Kyrgyzstan
			'LA' => 'LAO', //Laos
			'LV' => 'LVA', //Latvia
			'LB' => 'LBN', //Lebanon
			'LS' => 'LSO', //Lesotho
			'LR' => 'LBR', //Liberia
			'LY' => 'LBY', //Libya
			'LI' => 'LIE', //Liechtenstein
			'LT' => 'LTU', //Lithuania
			'LU' => 'LUX', //Luxembourg
			'MO' => 'MAC', //Macao S.A.R., China
			'MK' => 'MKD', //Macedonia
			'MG' => 'MDG', //Madagascar
			'MW' => 'MWI', //Malawi
			'MY' => 'MYS', //Malaysia
			'MV' => 'MDV', //Maldives
			'ML' => 'MLI', //Mali
			'MT' => 'MLT', //Malta
			'MH' => 'MHL', //Marshall Islands
			'MQ' => 'MTQ', //Martinique
			'MR' => 'MRT', //Mauritania
			'MU' => 'MUS', //Mauritius
			'YT' => 'MYT', //Mayotte
			'MX' => 'MEX', //Mexico
			'FM' => 'FSM', //Micronesia
			'MD' => 'MDA', //Moldova
			'MC' => 'MCO', //Monaco
			'MN' => 'MNG', //Mongolia
			'ME' => 'MNE', //Montenegro
			'MS' => 'MSR', //Montserrat
			'MA' => 'MAR', //Morocco
			'MZ' => 'MOZ', //Mozambique
			'MM' => 'MMR', //Myanmar
			'NA' => 'NAM', //Namibia
			'NR' => 'NRU', //Nauru
			'NP' => 'NPL', //Nepal
			'NL' => 'NLD', //Netherlands
			'AN' => 'ANT', //Netherlands Antilles
			'NC' => 'NCL', //New Caledonia
			'NZ' => 'NZL', //New Zealand
			'NI' => 'NIC', //Nicaragua
			'NE' => 'NER', //Niger
			'NG' => 'NGA', //Nigeria
			'NU' => 'NIU', //Niue
			'NF' => 'NFK', //Norfolk Island
			'MP' => 'MNP', //Northern Mariana Islands
			'NO' => 'NOR', //Norway
			'OM' => 'OMN', //Oman
			'PK' => 'PAK', //Pakistan
			'PW' => 'PLW', //Palau
			'PS' => 'PSE', //Palestinian Territory
			'PA' => 'PAN', //Panama
			'PG' => 'PNG', //Papua New Guinea
			'PY' => 'PRY', //Paraguay
			'PE' => 'PER', //Peru
			'PH' => 'PHL', //Philippines
			'PN' => 'PCN', //Pitcairn
			'PL' => 'POL', //Poland
			'PT' => 'PRT', //Portugal
			'PR' => 'PRI', //Puerto Rico
			'QA' => 'QAT', //Qatar
			'RE' => 'REU', //Reunion
			'RO' => 'ROU', //Romania
			'RU' => 'RUS', //Russia
			'RW' => 'RWA', //Rwanda
			'BL' => 'BLM', //Saint Barth&eacute;lemy
			'SH' => 'SHN', //Saint Helena
			'KN' => 'KNA', //Saint Kitts and Nevis
			'LC' => 'LCA', //Saint Lucia
			'MF' => 'MAF', //Saint Martin (French part)
			'SX' => 'SXM', //Sint Maarten / Saint Matin (Dutch part)
			'PM' => 'SPM', //Saint Pierre and Miquelon
			'VC' => 'VCT', //Saint Vincent and the Grenadines
			'WS' => 'WSM', //Samoa
			'SM' => 'SMR', //San Marino
			'ST' => 'STP', //S&atilde;o Tom&eacute; and Pr&iacute;ncipe
			'SA' => 'SAU', //Saudi Arabia
			'SN' => 'SEN', //Senegal
			'RS' => 'SRB', //Serbia
			'SC' => 'SYC', //Seychelles
			'SL' => 'SLE', //Sierra Leone
			'SG' => 'SGP', //Singapore
			'SK' => 'SVK', //Slovakia
			'SI' => 'SVN', //Slovenia
			'SB' => 'SLB', //Solomon Islands
			'SO' => 'SOM', //Somalia
			'ZA' => 'ZAF', //South Africa
			'GS' => 'SGS', //South Georgia/Sandwich Islands
			'SS' => 'SSD', //South Sudan
			'ES' => 'ESP', //Spain
			'LK' => 'LKA', //Sri Lanka
			'SD' => 'SDN', //Sudan
			'SR' => 'SUR', //Suriname
			'SJ' => 'SJM', //Svalbard and Jan Mayen
			'SZ' => 'SWZ', //Swaziland
			'SE' => 'SWE', //Sweden
			'CH' => 'CHE', //Switzerland
			'SY' => 'SYR', //Syria
			'TW' => 'TWN', //Taiwan
			'TJ' => 'TJK', //Tajikistan
			'TZ' => 'TZA', //Tanzania
			'TH' => 'THA', //Thailand    
			'TL' => 'TLS', //Timor-Leste
			'TG' => 'TGO', //Togo
			'TK' => 'TKL', //Tokelau
			'TO' => 'TON', //Tonga
			'TT' => 'TTO', //Trinidad and Tobago
			'TN' => 'TUN', //Tunisia
			'TR' => 'TUR', //Turkey
			'TM' => 'TKM', //Turkmenistan
			'TC' => 'TCA', //Turks and Caicos Islands
			'TV' => 'TUV', //Tuvalu     
			'UG' => 'UGA', //Uganda
			'UA' => 'UKR', //Ukraine
			'AE' => 'ARE', //United Arab Emirates
			'GB' => 'GBR', //United Kingdom
			'US' => 'USA', //United States
			'UM' => 'UMI', //United States Minor Outlying Islands
			'UY' => 'URY', //Uruguay
			'UZ' => 'UZB', //Uzbekistan
			'VU' => 'VUT', //Vanuatu
			'VE' => 'VEN', //Venezuela
			'VN' => 'VNM', //Vietnam
			'VG' => 'VGB', //Virgin Islands, British
			'VI' => 'VIR', //Virgin Island, U.S.
			'WF' => 'WLF', //Wallis and Futuna
			'EH' => 'ESH', //Western Sahara
			'YE' => 'YEM', //Yemen
			'ZM' => 'ZMB', //Zambia
			'ZW' => 'ZWE', //Zimbabwe
		);

		$iso_code = isset( $countries[$country] ) ? $countries[$country] : $country;
		return $iso_code;
	}
}