<?php

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



class DateBook_Subscription_Plan {

    /**
     * Subscription plan id
     *
     * @access public
     * @var int
     */
    public $id;

    /**
     * Subscription plan name
     *
     * @access public
     * @var string
     */
    public $name;

    /**
     * Subscription plan description
     *
     * @access public
     * @var string
     */
    public $description;

    /**
     * Subscription plan price
     *
     * @access public
     * @var int
     */
    public $price;

    /**
     * Subscription plan status
     *
     * @access public
     * @var string
     */
    public $status;

    /**
     * Subscription plan duration
     *
     * @access public
     * @var int
     */
    public $duration;

    /**
     * Subscription plan duration unit
     *
     * @access public
     * @var string
     */
    public $duration_unit;

    /**
     * Parent subscription plan
     *
     * @access public
     * @var string
     */
    public $top_parent;


    public function __construct( $id_or_post ) {

        if( !is_object( $id_or_post ) )
            $id_or_post = (int)$id_or_post;

        // Abort if id is not an integer
        if( !is_object( $id_or_post ) && !is_int( $id_or_post ) )
            return;

        $this->init( $id_or_post );

    }


    public function init( $id_or_post ) {

        /*
         * Set subscription plan data from the post itself
         *
         */
        if( is_object( $id_or_post ) ) {

            $id = $id_or_post->ID;
            $post_subscription = $id_or_post;

        } else {

            $id = $id_or_post;
            $post_subscription = get_post( $id );

        }


        if( !$post_subscription )
            return null;

        $this->id   = (int)$post_subscription->ID;
        $this->name = $post_subscription->post_title;


        /*
         * Set subscription plan data from the post meta data
         *
         */
        $post_meta_subscription = get_post_meta( $id );

        // Subscription plan description
        $this->description =  isset( $post_meta_subscription['datebook_subscription_plan_description'] ) ? $post_meta_subscription['datebook_subscription_plan_description'][0] : '';

        // Subscription plan price
        $this->price =  isset( $post_meta_subscription['datebook_subscription_plan_price'] ) ? $post_meta_subscription['datebook_subscription_plan_price'][0] : 0;

        // Subscription plan status
        $this->status =  isset( $post_meta_subscription['datebook_subscription_plan_status'] ) ? $post_meta_subscription['datebook_subscription_plan_status'][0] : '';

        // Subscription plan duration and duration unit
        $this->duration = ( isset( $post_meta_subscription['datebook_subscription_plan_duration'] ) && !empty( $post_meta_subscription['datebook_subscription_plan_duration'][0] ) ) ? $post_meta_subscription['datebook_subscription_plan_duration'][0] : 0;
        $this->duration_unit = isset( $post_meta_subscription['datebook_subscription_plan_duration_unit'] ) ? $post_meta_subscription['datebook_subscription_plan_duration_unit'][0] : '';

        // Set top parent of the group
        $this->top_parent = isset( $post_meta_subscription['datebook_subscription_plan_top_parent'] ) ? $post_meta_subscription['datebook_subscription_plan_top_parent'][0] : '';

    }


    /*
     * Method that checks if the subscription plan is active
     *
     */
    public function is_active() {

        if( $this->status == 'active' )
            return true;
        elseif( $this->status == 'inactive' )
            return false;

    }


    /**
     * Returns the expiration date of the subscription plan
     *
     * @param bool $timestamp
     * 
     * @return string
     *
     */
    public function get_expiration_date( $timestamp = false ) {

        if( $this->duration != 0 ) {
            $duration = $this->duration;
            $duration_unit = $this->duration_unit;
        } else {
            $duration = 100;
            $duration_unit = 'year';
        }

        if( $timestamp )
            return strtotime( "+" . $duration . ' ' . $duration_unit );
        else
            return date( 'Y-m-d H:i:s', strtotime( "+" . $duration . ' ' . $duration_unit ) );

    }


}

/**
 * Class DateBook_Profile_Subscription
 *
 * @class DateBook_Profile_Subscription
 * @package DateBook/Classes
 * @author Pagick Themes
 */
class DateBook_Profile_Subscription {

	private static $datebook_options = null;

	public $prefix;

	public function __construct($datebook_options_array) {

		self::$datebook_options = $datebook_options_array;

		// The prefix of the plugin
		$this->prefix = 'datebook_';

        // Install needed components on plugin activation
        register_activation_hook( __FILE__, array( $this, 'install' ) );

        register_deactivation_hook(__FILE__, array($this, 'uninstall') );

        // Include dependencies
        $this->include_dependencies();

        // Initialize the components
        $this->init();

    }




    /*
     * Method that gets executed on plugin activation
     *
     */
    public function install( $network_activate = false ) {

        // Add a cron job to be executed daily
        $this->cron_job();

    }

    /*
     * Method that gets executed on plugin deactivation
     *
     */
    public function uninstall() {

        // Clear cron job
        $this->clear_cron_job();

    }


    /*
     * Function that schedules a hook to be executed daily (cron job)
     *
     */
    public function cron_job() {

        // Process payments for custom member subscriptions
        wp_schedule_event( time(), 'daily', 'datebook_cron_process_member_subscriptions_payments' );

        // Schedule event for checking subscription status
        wp_schedule_event(time(), 'daily', 'datebook_check_subscription_status');

        //Schedule event for deleting expired activation keys used for password reset
        wp_schedule_event(time(), 'daily', 'datebook_remove_activation_key');


    }

    /*
     * Function that cleans the scheduler on plugin deactivation:
     *
     */
    public function clear_cron_job() {

        wp_clear_scheduled_hook( 'datebook_cron_process_member_subscriptions_payments' );

        wp_clear_scheduled_hook('datebook_check_subscription_status');

        wp_clear_scheduled_hook('datebook_remove_activation_key');

    }



    /*
     * Function to include the files needed
     *
     */
    public function include_dependencies() {

		// Gateway base class and extends
		if( file_exists( DATEBOOK_DIR . 'includes/payment/class-datebook-gateway.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/class-datebook-gateway.php';
		}
		
		// Notices
		if( file_exists( DATEBOOK_DIR . 'includes/payment/includes/class-notices.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/includes/class-notices.php';
		}
		
		// Core files
		if( file_exists( DATEBOOK_DIR . 'includes/payment/includes/functions-core.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/includes/functions-core.php';
		}
		
		if( file_exists( DATEBOOK_DIR . 'includes/payment/includes/class-success.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/includes/class-success.php';
		}
		
		// Admin Submenu Page Class
		if( file_exists( DATEBOOK_DIR . 'includes/payment/includes/class-submenu-page.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/includes/class-submenu-page.php';
		}
		
		// Member object class
		if( file_exists( DATEBOOK_DIR . 'includes/payment/includes/class-member.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/includes/class-member.php';
		}
		
		// Payment object class
		if( file_exists( DATEBOOK_DIR . 'includes/payment/includes/class-payment.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/includes/class-payment.php';
		}
		
		// PayPal Gateway
		if( file_exists( DATEBOOK_DIR . 'includes/payment/gateways/paypal/class-datebook-paypal.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/gateways/paypal/class-datebook-paypal.php';
		}

		// Bank Gateway
		if( file_exists( DATEBOOK_DIR . 'includes/payment/gateways/class-datebook-bank.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/gateways/class-datebook-bank.php';
		}
		// No Gateway (When subscription plan is free)
		if( file_exists( DATEBOOK_DIR . 'includes/payment/gateways/class-datebook-free-no-gateway.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/gateways/class-datebook-free-no-gateway.php';
		}
		// WooCommerce extension
		if( file_exists( DATEBOOK_DIR . 'includes/payment/woocommerce/class-datebook-woocommerce.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/woocommerce/class-datebook-woocommerce.php';
		}
		// Paystack gateway
		if( file_exists( DATEBOOK_DIR . 'includes/payment/gateways/paystack/class-datebook-paystack.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/gateways/paystack/class-datebook-paystack.php';
		}


		// 2checkout gateway
		/*if( file_exists( DATEBOOK_DIR . 'includes/payment/gateways/2checkout/Twocheckout.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/gateways/2checkout/Twocheckout.php';
		}
		// Stripe gateway
		if( file_exists( DATEBOOK_DIR . 'includes/payment/gateways/Stripe/vendor/autoload.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/gateways/Stripe/vendor/autoload.php';
		}
		// Authorized.Net gateway
		if( file_exists( DATEBOOK_DIR . 'includes/payment/gateways/authorized/autoload.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/gateways/authorized/autoload.php';
		}
		// Braintree gateway
		if( file_exists( DATEBOOK_DIR . 'includes/payment/gateways/braintree/Braintree.php' ) ){
			include_once DATEBOOK_DIR . 'includes/payment/gateways/braintree/Braintree.php';
		}
		// Bluepay gateway
		if( file_exists( DATEBOOK_DIR . 'includes/payment/gateways/bluepay/Bluepay.php' ) ){
			//include_once DATEBOOK_DIR . 'includes/payment/gateways/bluepay/Bluepay.php';
		}

		if ( isset( $_POST[ 'recurring_pp_submit' ] ) ) {
			require_once( DATEBOOK_DIR . 'includes/payment/gateways/paypal/expresscheckout.php' );
		}


		// Many other gateways
        define('PLUGIN_PREFIX', 'WPD_');
        define('WPD_URI', plugin_dir_url(__FILE__));

        $files__[] = __DIR__ . "/application/classes/ajax.php";
        $files__[] = __DIR__ . "/application/classes/common.php";
        $files__[] = __DIR__ . "/application/classes/currencies.php";
        $files__[] = __DIR__ . "/application/classes/view.php";
        foreach ($files__ as $file) {
            if (!is_dir($file)) {
                require_once($file);
            }
        }

        WPD_View::get_instance()->library('Donations', FALSE);

        WPD_View::get_instance()->library('Stripe_', FALSE);

		//if (is_admin()) {
			//WPD_Admin::WPD_Init();
			//return;
		//}
    
		function datebook_database_table_structure(){
			global $wpdb, $charset_collate;

			$table_name = $wpdb->prefix . "datebook_gateway_payments";
			if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
				$sql_create_table = "CREATE TABLE IF NOT EXISTS $table_name (
					`id` int(11) NOT NULL AUTO_INCREMENT,
					`amount` varchar(50) NOT NULL,
					`cycle` varchar(50) NOT NULL,
					`cycle_time` varchar(50) NOT NULL,
					`f_name` varchar(50) NOT NULL,
					`l_name` varchar(50) NOT NULL,
					`email` varchar(50) NOT NULL,
					`contact` varchar(50) NOT NULL,
					`address` varchar(200) NOT NULL,
					`type` varchar(50) NOT NULL,
					`source` varchar(50) NOT NULL,
					`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
					`transaction_id` varchar(100) NOT NULL,
					`currency` varchar(10) NOT NULL,
					`donation_for` varchar(50) NOT NULL,
					`post_id` varchar(50) NOT NULL,
					PRIMARY KEY (`id`)
				) $charset_collate; ";

				require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

				dbDelta($sql_create_table);

			}
		}

		//register_activation_hook(__FILE__, 'datebook_database_table');
		function datebook_database_table($networkwide){
			datebook_database_table_structure();
		}
		add_action('plugins_loaded', 'datebook_database_table');*/


		// Hook to include needed files
		do_action( 'datebook_include_files' );

	}


	/**
	 * Hook actions and filters.
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function init() {

		// Load this function after WordPress Mail function loaded
		add_action( 'wp_loaded', array( __CLASS__, 'datebook_time_check_expired' ) );
		add_action( 'datebook_ajax_activate_top', array( __CLASS__, 'datebook_process_ajax_activate_top' ) );
		add_action( 'datebook_activate_subscription_after_payment', array( __CLASS__, 'process_subscription_after_payment'), 10, 1);
		add_action( 'datebook_redirect_subscription_to_gateway', array( __CLASS__, 'datebook_process_payment_subscription' ) );
		
		add_action( 'datebook_display_subsciption_plans', array( __CLASS__, 'datebook_get_subsciption_plans' ) );
		add_action( 'datebook_profile_subscription_page', array( __CLASS__, 'display_profile_subscription_page' ) );
		add_action( 'datebook_profile_cart_page', array( __CLASS__, 'datebook_display_profile_cart_page' ) );
		add_action( 'datebook_profile_checkout_page', array( __CLASS__, 'datebook_display_profile_checkout_page' ) );

		add_action( 'datebook_profile_subscription_navigation', array( __CLASS__, 'datebook_display_profile_subscription_navigation' ) );
		
        // Hook to be executed on a specific interval, by the cron job (wp_schedule_event); used to check if a subscription has expired
        add_action('datebook_check_subscription_status','datebook_member_check_expired_subscriptions');

		add_action( 'datebook_insert_member_payments_data', array( __CLASS__, 'insert_member_payments_data'), 10, 1);

        // Hook to be executed on a daily interval, by the cron job (wp_schedule_event); used to remove the user activation key from the db (make it expire) every 24 hours
        add_action('datebook_remove_activation_key','datebook_remove_expired_activation_key');

		add_action( 'init', array( __CLASS__, 'datebook_payment_gateways_webhook_catcher'), 1 );

    }
	
	



	/**
	 * Function that returns an array with all payment gateways
	 *
	 * @param $only_slugs - returns an array with the payment gateways slugs
	 *
	 * @return array
	 *
	 */
	public static function datebook_get_payment_gateways( $only_slugs = false ) {

		global $datebook_payment_gateways;

		$payment_gateways = array();

		$item = get_option('datebook_gateways');

		if($item){

			foreach($item as $key => $value){
				if (isset($datebook_payment_gateways[$key]) && isset($value['enabled']) && $value['enabled'] == 1) {
					$payment_gateways[$key] = array(
						'display_name_user'  => $datebook_payment_gateways[$key],
						'display_name_admin' => $datebook_payment_gateways[$key],
						'class_name'         => "DateBook_Payment_Gateway_$key"
					);
				}
			}

			$payment_gateways['free'] = array(
				'display_name_user'  => esc_html__( 'Free Activation', 'datebook' ),
				'display_name_admin' => esc_html__( 'Free Activation', 'datebook' ),
				'class_name'         => 'DateBook_Payment_Gateway_Free'
			);

	    	if( $only_slugs ){
				$payment_gateways = array_keys( $payment_gateways );
			}
		}

	    return $payment_gateways;

	}


	/**
	 * Returns the payment gateway object
	 *
	 * @param string $gateway_slug
	 * @param array $payment_data
	 *
	 * @return object
	 *
	 */
	public static function datebook_get_payment_gateway( $gateway_slug = '', $payment_data = array() ) {

		if( empty( $gateway_slug ) ){
			return null;
		}

		$payment_gateways = self::datebook_get_payment_gateways();

		if( !isset( $payment_gateways[$gateway_slug] ) || !isset( $payment_gateways[$gateway_slug]['class_name'] ) ){
			return null;
		}
		
		return new $payment_gateways[$gateway_slug]['class_name']( $payment_data );

	}


	/*
	 * Processes the webhooks for all active payment gateways
	 *
	 * @return void
	 *
	 */
	public static function datebook_payment_gateways_webhook_catcher() {

		$gateways = self::datebook_get_payment_gateways();

	    foreach( $gateways as $gateway_slug => $gateway_details ) {
    	    $gateway = self::datebook_get_payment_gateway( $gateway_slug );
			

        	if( $gateway !== null ){
				$gateway->datebook_process_payment_response();
			}
	    }

	}


	/**
	 * Verifies if a feature is supported by any of the given payment gateways
	 *
	 * @param array $payment_gateways
	 * @param string $feature
	 *
	 * @return bool
	 *
	 */
	public static function datebook_payment_gateways_support( $payment_gateways = array(), $feature = '' ) {

    	if( empty( $feature ) )
        	return false;

	    if( empty( $payment_gateways ) )
    	    return false;

	    foreach( $payment_gateways as $gateway_slug ) {

    	    $payment_gateway = self::datebook_get_payment_gateway( $gateway_slug );

        	if( is_null( $payment_gateway ) )
            	continue;

	        if( $payment_gateway->supports( $feature ) )
    	        return true;

	    }

    	return false;

	}


	/**
	 * Returns the active pay gates selected by the admin in the Payments tab in DateBook Settings
	 *
	 * @return array
	 *
	 */
	public static function datebook_get_active_payment_gateways() {

    	$settings = get_option('datebook_settings');

	    if( empty( $settings['payments']['active_pay_gates'] ) ){
			return array();
		} else {
			return $settings['payments']['active_pay_gates'];
		}

	}


    /**
     * Returns the URL where the user should be redirected back to
     * after registering or completing a purchase
     *
     * @return string
     *
     */
    public static function get_redirect_url() {

        $url      = '';
        $location = 'new_subscription';

        switch( $location ) {

            case 'upgrade_subscription':
            case 'renew_subscription':
            case 'new_subscription':
            case 'retry_payment':
                $url = datebook_get_current_page_url( true );

                // Add success message
                $url = add_query_arg( array( 'datebook_gateway_payment_action' => $location ), $url );
                break;

        }

        return apply_filters( 'datebook_get_redirect_url', $url, $location );

    }



	/**
	 * Display Currency title tooltip for price
	 * 
	 * @access public
	 */
	public static function datebook_tooltip_currency_title() {

		$allowedposttags = array( 'span' => array( 'class' => array(), 'data-toggle' => array(), 'data-placement' => array(), 'data-original-title' => array() ));

		$datebook_field_titles = get_query_var( 'datebook_field_titles' );
		if ( is_array( $datebook_field_titles ) ) { extract($datebook_field_titles); }

		$default_currency = isset(self::$datebook_options['default_currency']) ? self::$datebook_options['default_currency'] : '';

		$currency_name = $datebook_currency_titles[$default_currency][0];
		
		$tooltip_currency_title = isset(self::$datebook_options['tooltip_currency_title']) ? ' <span class="badge" data-toggle="tooltip" data-placement="top" data-original-title="' . $currency_name . '">?</span>' : '';

		echo wp_kses( $tooltip_currency_title, $allowedposttags );

	}


	/**
	 * Format price, currency symbol, currency title
	 * 
	 * @access public
	 */
	public static function datebook_format_money($price) {
		
		global $datebook_currency_titles;

		$datebook_field_titles = get_query_var( 'datebook_field_titles' );
		if ( is_array( $datebook_field_titles ) ) { extract($datebook_field_titles); }

		$default_currency = isset(self::$datebook_options['default_currency']) ? self::$datebook_options['default_currency'] : '';

		$currency_name = $datebook_currency_titles[$default_currency][0];
		$currency_code = $datebook_currency_titles[$default_currency][1];
		$currency_symbol = $datebook_currency_titles[$default_currency][2];
		$currency_single_name = $datebook_currency_titles[$default_currency][3];
		$currency_plural_name = $datebook_currency_titles[$default_currency][4];

		$price_format = isset(self::$datebook_options['price_format']) ? self::$datebook_options['price_format'] : 0;

		switch($price_format) {

			case 0 : 
				$formatted_price = ($price < 0 ? '-' : '') . number_format($price, 0, '.', ' ');
				break;
			case 1 : 
				$formatted_price = ($price < 0 ? '-' : '') . number_format($price, 1, '.', ' ');
				break;
			case 2 : 
				$formatted_price = ($price < 0 ? '-' : '') . number_format($price, 2, '.', ' ');
				break;
			case 3 : 
				$formatted_price = ($price < 0 ? '-' : '') . number_format($price, 3, '.', ' ');
				break;
			case 4 : 
				$formatted_price = ($price < 0 ? '-' : '') . number_format($price, 0, '.', ',');
				break;
			case 5 : 
				$formatted_price = ($price < 0 ? '-' : '') . number_format($price, 1, '.', ',');
				break;
			case 6 : 
				$formatted_price = ($price < 0 ? '-' : '') . number_format($price, 2, '.', ',');
				break;
			case 7 : 
				$formatted_price = ($price < 0 ? '-' : '') . number_format($price, 3, '.', ',');
				break;
			case 8 : 
				$formatted_price = ($price < 0 ? '-' : '') . number_format($price, 0, '.', '.');
				break;
			case 9 : 
				$formatted_price = ($price < 0 ? '-' : '') . number_format($price, 1, '.', '.');
				break;
			case 10 : 
				$formatted_price = ($price < 0 ? '-' : '') . number_format($price, 2, '.', '.');
				break;
			case 11 : 
				$formatted_price = ($price < 0 ? '-' : '') . number_format($price, 3, '.', '.');
				break;

			default : $formatted_price = ($price < 0 ? '-' : '') . number_format($price, 2, '.', ','); break;

		}

		$round_price = number_format(abs($price), 0, '.', ',');
		
		$currency_spell = DateBook_Utilities::datebook_spellplural($round_price, $currency_single_name, $currency_plural_name);

		$currency_sign_places = isset(self::$datebook_options['currency_sign_places']) ? self::$datebook_options['currency_sign_places'] : '';

		switch($currency_sign_places) {

			case 0 : 
				$currency_text = $currency_symbol . $formatted_price; 
				break;
			case 1 : 
				$currency_text = $currency_symbol . $formatted_price . ' ' . $currency_code; 
				break;
			case 2 : 
				$currency_text = $currency_symbol . $formatted_price . ' ' . $currency_spell; 
				break;
			case 3 : 
				$currency_text = $currency_symbol . ' ' . $formatted_price; 
				break;
			case 4 : 
				$currency_text = $currency_symbol . ' ' . $formatted_price . ' ' . $currency_code; 
				break;
			case 5 : 
				$currency_text = $currency_symbol . ' ' . $formatted_price . ' ' . $currency_spell; 
				break;
			case 6 : 
				$currency_text = $formatted_price . $currency_symbol; 
				break;
			case 7 : 
				$currency_text = $formatted_price . $currency_symbol . ' ' . $currency_code; 
				break;
			case 8 : 
				$currency_text = $formatted_price . $currency_symbol . ' ' . $currency_spell; 
				break;
			case 9 : 
				$currency_text = $formatted_price . ' ' . $currency_symbol; 
				break;
			case 10 : 
				$currency_text = $formatted_price . ' ' . $currency_symbol . ' ' . $currency_code; 
				break;
			case 11 : 
				$currency_text = $formatted_price . ' ' . $currency_symbol . ' ' . $currency_spell; 
				break;
			case 12 : 
				$currency_text = $formatted_price . ' ' . $currency_code; 
				break;
			case 13 : 
				$currency_text = $formatted_price . ' ' . $currency_spell; 
				break;
			case 14 : 
				$currency_text = $currency_code . ' ' . $formatted_price; 
				break;
			case 15 : 
				$currency_text = $currency_code . ' ' . $currency_symbol . $formatted_price; 
				break;
			case 16 : 
				$currency_text = $currency_code . ' ' . $currency_symbol . ' ' . $formatted_price; 
				break;
			case 17 : 
				$currency_text = $currency_code . ' ' . $formatted_price . $currency_symbol; 
				break;
			case 18 : 
				$currency_text = $currency_code . ' ' . $formatted_price . $currency_symbol; 
				break;
			case 19 : 
				$currency_text = ucfirst($currency_spell) . ' ' . $formatted_price; 
				break;
			case 20 : 
				$currency_text = ucfirst($currency_spell) . ' ' . $currency_symbol . $formatted_price; 
				break;
			case 21 : 
				$currency_text = ucfirst($currency_spell) . ' ' . $currency_symbol . ' ' . $formatted_price; 
				break;
			case 22 : 
				$currency_text = ucfirst($currency_spell) . ' ' . $formatted_price . $currency_symbol; 
				break;
			case 23 : 
				$currency_text = ucfirst($currency_spell) . ' ' . $formatted_price . ' ' . $currency_symbol; 
				break;

			default : $currency_text = $currency_symbol . $formatted_price; break;

		}

		return $currency_text;

	}


	/**
	 * Create custom payment button
	 * 
	 * @access private
	 */
	private static function datebook_show_button_otherpayment($current_user_id, $profile_id, $subscription_arg) {

		global $allowedposttags;

		$datebook_field_titles = get_query_var( 'datebook_field_titles' );
		if ( is_array( $datebook_field_titles ) ) { extract($datebook_field_titles); }


		$bankpaymentoption = isset(self::$datebook_options['bankpaymentoption']) ? self::$datebook_options['bankpaymentoption'] : '';
		$bankpaymentoption = strtr($bankpaymentoption, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />'));


		// Profile data
		$profile = get_post($profile_id);
		$profile_post_name = $profile->post_name;

		// Tooltip
		$info_tooltip = esc_html__( 'You should transfer', 'datebook' ) . ' ';
		$info_tooltip .= self::datebook_format_money($subscription_arg['subscriptionplan_price']) . ' ';
		$info_tooltip .= esc_html__( 'to the bank shown below. After payment is made, tell us', 'datebook' ).' ';
		$info_tooltip .= esc_html__( 'your Profile ID', 'datebook' ) . '. ';
		$info_tooltip .= esc_html__( 'We\'ll activate your Subscription plan for you', 'datebook' ) . '.';

		// Description how to make payment on Bank transfer
		$info = esc_html__( 'Profile ID', 'datebook' ).': '.esc_attr($profile_post_name);
		$info .= '<div class="datebook-clear10"></div>';
		$info .= esc_html__( 'How to make payment', 'datebook' ) . ' ';
		$info .= '<span class="badge" data-toggle="tooltip" data-placement="top" data-original-title="' . esc_attr($info_tooltip) . '">?</span>';
		$info .= '<div class="datebook-clear10"></div>';
		
		$info .= wp_kses( $bankpaymentoption, $allowedposttags );
		
		return $info;

	}


	/**
	 * Get subscription data of user
	 *
	 * @access public
	 */
	public static function get_member_subsciption_data($current_user_id) {
		
		$datebook_get_member = array('status' => 'pending');

		// Get user subscription data
		$member = datebook_get_member($current_user_id);
		
		if(isset($member->subscriptions) && is_array($member->subscriptions) && !empty($member->subscriptions)){

			$datebook_get_member = array('user_id' => $member->user_id, 'id' => $member->subscriptions[0]['id'], 'subscription_plan_id' => $member->subscriptions[0]['subscription_plan_id'], 'plan_price_period' => $member->subscriptions[0]['plan_price_period'], 'start_date' => $member->subscriptions[0]['start_date'], 'expiration_date' => $member->subscriptions[0]['expiration_date'], 'status' => $member->subscriptions[0]['status'], 'payment_profile_id' => $member->subscriptions[0]['payment_profile_id']);
			
		}

		return $datebook_get_member;

	}


	/**
	 * Check and get subscription status of user
	 *
	 * @access public
	 */
	public static function get_subsciption_status($current_user_id) {

		$member_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $current_user_id ) );

		$member_subscription_status = isset($member_subscriptions[0]->status) ? $member_subscriptions[0]->status : NULL;

		return $member_subscription_status;

	}


	/**
	 * Create and show the list of subscription plans with Select buttons
	 *
	 * @access public
	 */
	public static function datebook_get_subsciption_plans() {

		if (DateBook_Utilities::check_if_gateway_activated()) {

			if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
				$current_user_id = DATEBOOK_CURRENT_USER_ID;
			} else {
				global $current_user;
				wp_get_current_user();
				$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
			}

			$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );

			$subscription_array = array('active' => 0);

			$member_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $current_user_id ) );

			$member_splan_id = isset($member_subscriptions[0]->subscription_plan_id) ? $member_subscriptions[0]->subscription_plan_id : NULL;
			$member_splan_price_period = isset($member_subscriptions[0]->plan_price_period) ? $member_subscriptions[0]->plan_price_period : NULL;

			$member_subscription_status = isset($member_subscriptions[0]->status) ? $member_subscriptions[0]->status : NULL;
			
			$member_subscription_start_date = isset($member_subscriptions[0]->start_date) ? $member_subscriptions[0]->start_date : NULL;
			$member_subscription_expiration_date = isset($member_subscriptions[0]->expiration_date) ? $member_subscriptions[0]->expiration_date : NULL;

			$member_payment_gateway = isset($member_subscriptions[0]->payment_gateway) ? $member_subscriptions[0]->payment_gateway : NULL;

			$days_notification_of_unpaid_order = isset(self::$datebook_options['days_notification_of_unpaid_order']) ? self::$datebook_options['days_notification_of_unpaid_order'] : 3;
			$current_date = strtotime(date('Y-m-d H:i:s'));

			// Get last payment
			if (isset(self::$datebook_options['activate_woocommerce_subscription']) && self::$datebook_options['activate_woocommerce_subscription'] == '2' && function_exists( 'WC' ) ) {

				$args = array(
					'post_type' => 'product',
					'post_status' => 'publish',
					'posts_per_page' => 100,
					'meta_key' => '_datebook_subscribe',
					'meta_value' => 'yes',
					'meta_compare' => '='
				);
				
				$i = 0;

				$wc_query = new WP_Query($args);

				if ($wc_query->have_posts()) :

					while ($wc_query->have_posts()) : $wc_query->the_post();
				
						$i++;

						$get_the_ID = get_the_ID();

						$product = wc_get_product( $get_the_ID );

						$subscription_array[$get_the_ID] = array('get_the_ID' => $get_the_ID, 'subscription_id' => $member_splan_id, 'status' => $member_subscription_status, 'get_price_html' => $product->get_price_html(), 'is_taxable' => $product->is_taxable(), 'get_regular_price' => $product->get_regular_price(), 'get_sale_price' => $product->get_sale_price(), 'get_price' => $product->get_price(), 'on_sale' => $product->is_on_sale(), 'price_is_per' => datebook_get_prop( $product, '_wcaddon_price_is_per' ));

					endwhile;
	
					wp_reset_postdata();
	
				endif;
			
				if($i > 0){
					$subscription_array['active'] = 1;
				}

				$customer_last_order = wc_get_customer_last_order($current_user_id);

				if (isset($customer_last_order) && !empty($customer_last_order) && $customer_last_order !== NULL){

					$subscription_array['last_order'] = $customer_last_order;

					$date_order_placed = strtotime("+" . $days_notification_of_unpaid_order . " days", strtotime($customer_last_order->get_date_created()->format('Y-m-d H:i:s'))); //date_modified

				} else {

					$subscription_array['last_order'] = '';

					$date_order_placed = '';

				}

			} else {

				$args = array(
					'user_id'	=> $current_user_id,
					'number'	=> 1
				);
				$subscription_array['last_order'] = datebook_get_payments( $args );

				$date_order_placed = isset($subscription_array['last_order'][0]->date) ? strtotime("+" . $days_notification_of_unpaid_order . " days", strtotime($subscription_array['last_order'][0]->date)) : 0;

			}

			$subscription_plans_args = array('current_user_id' => $current_user_id, 'profile_id' => $profile_id, 'subscription_plan_id' => $member_splan_id, 'plan_price_period' => $member_splan_price_period, 'status' => $member_subscription_status, 'start_date' => $member_subscription_start_date, 'expiration_date' => $member_subscription_expiration_date, 'payment_gateway' => $member_payment_gateway, 'date_order_placed' => $date_order_placed, 'current_date' => $current_date, 'all_subscription_plans' => $subscription_array);

			// display the list of Payment gateways
			echo DateBook_Template_Loader::load( 'payment/profile-subscription-plans-list', $subscription_plans_args );

		}

	}


	/**
	 * Function that outputs the payment gateway options
	 *
	 */
	private static function datebook_get_output_payment_gateways($subscriptionplan_price_count, $subscription_arg) {

		// Generate output string for the payment gateways
		$active_gateways = $active_gateways_array = self::datebook_get_payment_gateways();

		unset($active_gateways_array['free']);

       	// Output content for the payment gateways
		$output = $output_title = $output_form = $output_form_out = '';

   		if( !empty( $active_gateways ) ) {

			// Set default payment gateway
			$default_gateway = isset(self::$datebook_options['default_gateway']) ? self::$datebook_options['default_gateway'] : 'paypal_standard';

			if(count($active_gateways_array) > 1){
				$output_title .= '<div id="accordion" class="accordion">';
			}

           	foreach( $active_gateways as $key => $value ) {

				$pay_gate = $key;

				$item = get_option('datebook_gateways');
				$item = isset($item[$key]) ? $item[$key] : '';
				
				if($subscriptionplan_price_count > 0 && $key != 'free' && isset($item['slug']) && $item['slug'] == $key && $item['enabled'] == 1 && $subscription_arg['subscriptionplan_free_for_genders'] == 0){
					
					if($default_gateway == $key) {$selectedkey = ' show';} else {$selectedkey = '';}
					
					$logo_url = isset($item['logo_url']) ? $item['logo_url'] : '';

					$logo_description = isset($item['logo_description']) ? $item['logo_description'] : '';

					$output_title .= '<div class="card border-0 mb-1 grey lighten-5 datebook-payment-gateway-panel">';
					$output_title .= '<div class="card-header" id="heading' . $key . '">';
					$output_title .= '<h6 class="mb-0">';
					$output_title .= '<label class="mb-0" data-toggle="collapse" data-parent="#accordion" data-target="#collapse' . $key . '" aria-expanded="true" aria-controls="collapse' . $key . '">';
					
					if(count($active_gateways_array) > 1){
					$output_title .= '<input type="radio" name="pay_gate" value="' . esc_attr( $key ) . '" ' . checked( $default_gateway, $key, false ) . ' />';
					}

					$output_title .= '<span class="pl-2">' . $value['display_name_user'] . '</span></label>';
					$output_title .= '</h6>';
					$output_title .= '</div>';

					if(count($active_gateways_array) > 1){
					$output_title .= '<div id="collapse' . $key . '" class="collapse' . $selectedkey . ' grey lighten-4" aria-labelledby="heading' . $key . '" data-parent="#accordion">';
					}
					$output_title .= '<div class="card-body">';
					$output_title .= '<p class="card-text">' . $logo_description . '</p>';

					if($logo_url){
						$output_title .= '<img src="' . $logo_url . '" class="card-img-top" alt="' . $value['display_name_user'] . '">';
					}

					$output_title .= '</div>';

					if(count($active_gateways_array) > 1){
					$output_title .= '</div>';
					}
					$output_title .= '</div>';

					// Insert form
					if(count($active_gateways_array) > 1){
					$output_form_out .= '<div id="collapse' . $key . '" class="collapse' . $selectedkey . ' mt-4" aria-labelledby="heading' . $key . '" data-parent="#accordion">';
					}

					if($key == 'paystack') {

						$output_form_out .= datebook_paystack_display_form($subscriptionplan_price_count, $subscription_arg, $pay_gate);

					} else if($key == 'paypal_standard') {

						$output_form_out .= self::datebook_display_standard_form($subscriptionplan_price_count, $subscription_arg, $pay_gate);

					} else if($key == 'bank') {

						$output_form_out .= self::datebook_display_standard_form($subscriptionplan_price_count, $subscription_arg, $pay_gate);

					}

					if(count($active_gateways_array) > 1){
						$output_form_out .= '</div>';
					}

				} else if(($subscription_arg['subscriptionplan_free_for_genders'] == 1 && $key == 'free') || ($subscriptionplan_price_count == 0 && $key == 'free')){
					
					$output_form_out .= self::datebook_display_standard_form($subscriptionplan_price_count, $subscription_arg, $pay_gate);

				}

			}

			$output_title .= $output_form_out;
			
			if(count($active_gateways_array) > 1){
				$output_title .= '</div>';
			}

			$output .= $output_title;
			
			

		}

	    return $output;

	}


	/**
	 * Show Checkout form on Checkout page
	 *
	 * @access public
	 */
	private static function datebook_display_standard_form($subscriptionplan_price_count, $subscription_arg, $pay_gate) {

		$paybutton_out = '';
		$paybutton = '';
		
		$random_ocurring = rand(20,10000);
		
		$my_upgrade_page = isset(self::$datebook_options['my_upgrade_page']) ? self::$datebook_options['my_upgrade_page'] : '';

		$paybutton .= '<form id="datebook-new-subscription-form" class="datebook-payment-form" enctype="multipart/form-data" method="post" action="' . esc_url(get_permalink($my_upgrade_page)) . '">';

		$paybutton .= wp_nonce_field( 'datebook_new_subscription_form_nonce', 'datebooktkn', true, false );
		$paybutton .= datebook_display_success_messages( datebook_success()->get_messages('subscription_plans'), true );

		$field_errors = datebook_errors()->get_error_messages( 'subscription_plans' );
		$paybutton .= !empty( $field_errors ) ? 'datebook-field-error' : '';

		$paybutton .= '<input type="hidden" name="action" value="payment_page">';
		$paybutton .= '<input type="hidden" name="payment_page" value="3">';

		$paybutton .= '<input name="subscriptionplan" type="hidden" value="' . $subscription_arg['subscription_id'] . '" />';
		$paybutton .= '<input name="subscriptionplan_period_key" type="hidden" value="' . $subscription_arg['subscriptionplan_period_key'] . '" />';

		$paybutton .= '<input type="hidden" name="pay_gate" value="' . esc_attr( $pay_gate ) . '" />';

		// Add error message if no plans have been selected
		$paybutton .= datebook_display_field_errors( datebook_errors()->get_error_messages('subscription_plans'), true );
		
		// Show the ocurring checkbox option
		if (isset($subscription_arg['subscriptionplan_recurring']) && ($subscription_arg['subscriptionplan_recurring'] == 1 || $subscription_arg['subscriptionplan_recurring'] == 2) && isset($subscription_arg['subscriptionplan_price']) && $subscription_arg['subscriptionplan_price'] > 0) {

			$paybutton .= '<hr/>';

			$paybutton .= '<div class="custom-control custom-checkbox mb-3">';

			if ($subscription_arg['subscriptionplan_recurring'] == 2) {
				$paybutton .= '<input type="checkbox" name="recurring" value="1" class="custom-control-input" id="datebookOcurring' . $pay_gate . $random_ocurring . '" checked disabled>';
			} else {
				$paybutton .= '<input type="checkbox" name="recurring" value="1" class="custom-control-input" id="datebookOcurring' . $pay_gate . $random_ocurring . '" ' . checked( '1', $subscription_arg['subscriptionplan_recurring'], false ) . ' />';
			}
			$paybutton .= '<label class="custom-control-label" for="datebookOcurring' . $pay_gate. $random_ocurring . '">' . esc_html__('Auto-renew', 'datebook') . '</label>';
			$paybutton .= '</div>';

		}


		// If profile has some subscription plan then show Active sign
		if($subscription_arg['subscriptionplan_free_for_genders'] == 1){

			// Check if genders selected who must pay for a subscription plan
			$paybutton .= '<input type="hidden" name="free_for_gender" value="1">';

			$paybutton .= '<p>' . esc_html__( 'You may activate this plan for free. Just click on the button to activate it.', 'datebook' ) . '</p>';
			$paybutton .= '<div class="datebook-clear15"></div>';
			$paybutton .= '<button class="btn btn-primary" type="submit" name="submit">' . esc_html__( 'Activate', 'datebook' ) . '</button>';

		} else if ($subscriptionplan_price_count > 0 && ($pay_gate != 'free')){

			$paybutton .= '<div class="datebook-clear15"></div>';
			$paybutton .= '<button class="btn btn-primary" name="submit" type="submit">' . esc_html__( 'Subscribe', 'datebook' ) . '</button>';
			if (is_super_admin()) {
				$paybutton .= '<button class="btn btn-success btn-sm" name="admin_activated" value="1" type="submit">' . esc_html__( 'Activate for free', 'datebook' ) . '<br>(' . esc_html__( 'You are logged in as Administrator', 'datebook' ) . ')</button>';
			}

		} else if($subscriptionplan_price_count == 0 && ($pay_gate == 'free' || $pay_gate == 'bacs' || $pay_gate == 'cod' || $pay_gate == 'cheque')){

			$paybutton .= '<p>' . esc_html__( 'This is a free plan. Just click on the button to activate it.', 'datebook' ) . '</p>';
			$paybutton .= '<div class="datebook-clear15"></div>';
			$paybutton .= '<button class="btn btn-primary" type="submit" name="submit">' . esc_html__( 'Activate', 'datebook' ) . '</button>';

		}


		$paybutton .= '</form>';

		if ($paybutton != '') {

			$paybutton_out .= $paybutton;

		}

		return $paybutton_out;

	}


	/**
	 * Get Subscription plans
	 *
	 * @access public
	 */
	public static function user_selected_subscription_plan($current_user_id, $profile_id = 0, $get_profile_data = array()){

		$user_selected_plan = 0;

		$get_subscription_plans = get_option('datebook_subscription_plans');

		if (is_array($get_subscription_plans)){

			/*if($profile_id > 0){
				$profile_id = $profile_id;
			} else {
				$profile_id = get_user_meta($current_user_id, 'profile_postid', true );
			}
			
			if (is_array($get_subscription_plans) && !empty($get_subscription_plans) && is_array($get_profile_data) && !empty($get_profile_data)){
				$get_profile_data = $get_profile_data;
			} else {
				$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
			}
			$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

			$profile_subscription_plan = isset($datebook_get_data['profile_subscription']['plan']) ? $datebook_get_data['profile_subscription']['plan'] : '';*/

			$member_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $current_user_id ) );

			$profile_subscription_plan = isset($member_subscriptions[0]->subscription_plan_id) ? $member_subscriptions[0]->subscription_plan_id : NULL;

			
			foreach($get_subscription_plans as $key => $value){

				if (isset($value['active']) && $value['active'] == 1) {

					if ($profile_subscription_plan == $key){

						$user_selected_plan++;

					}
				}
			}
		}

		return $user_selected_plan;

	}


	/**
	 * Show Checkout form on Checkout page
	 *
	 * @access public
	 */
	public static function profile_payment_checkout_form($item_type, $current_user_id, $profile_id, $subscription_arg) {

		$paybutton_out = '';
		$paybutton = '';

		$subscriptionplan_price_count = 0;

		// Get Subscription plans
		$all_splans = get_option('datebook_subscription_plans');

		if (is_array($all_splans)){

			foreach($all_splans as $key => $value){

				if (isset($value['active']) && $value['active'] == 1) {

					$value['subscription_id'] = isset($value['subscription_id']) ? $value['subscription_id'] : '';
					
					if ($subscription_arg['subscriptionplan'] == $value['subscription_id'] && $subscription_arg['subscriptionplan_price'] > 0 ) {
						
						$subscriptionplan_price_count++;

					}
				} 
			}
		}


		$paybutton .= self::datebook_get_output_payment_gateways($subscriptionplan_price_count, $subscription_arg);


		// Show the ocurring checkbox option
		//if (isset($subscription_arg['subscriptionplan_recurring']) && $subscription_arg['subscriptionplan_recurring'] == 1) {
			
			//$paybutton .= '<hr/>';

			//$paybutton .= '<div class="custom-control custom-checkbox">';
			//$paybutton .= '<input class="custom-control-input" id="datebookOcurring" type="checkbox" name="recurring" value="1" ' . checked( '1', $subscription_arg['subscriptionplan_recurring'], false ) . ' />';
			//$paybutton .= '<label class="custom-control-label" for="datebookOcurring">' . esc_html__('Auto-renew', 'datebook') . '</label>';
			//$paybutton .= '</div>';

		//} else if (isset($subscription_arg['subscriptionplan_recurring']) && $subscription_arg['subscriptionplan_recurring'] == 2) {

			//$paybutton .= '<input type="hidden" name="recurring" value="1">';

		//}
		
		if ($paybutton != '') {

			$paybutton_out .= $paybutton;

		}

		return $paybutton_out;

	}


	/**
	 * Activate Top status
	 * 
	 * @since 2.1
	 * @access public
	 */
	public static function datebook_ajax_activate_topfeatured() {

		if( isset($_GET['action']) && is_user_logged_in()) {

			//Catch the whatisit - cities, logincheck, defaultimage, realphotodelete, activateprofile, logodelete, favoriteset, tourdelete, touredit, activate Top or Featured status
			$whatisit = isset( $_GET['whatisit'] ) ? esc_attr($_GET['whatisit']) : '';

			// Add to Favorites
			if ($whatisit == 'activate-topfeatured') {

				if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
					$current_user_id = DATEBOOK_CURRENT_USER_ID;
				} else {
					global $current_user;
					wp_get_current_user();
					$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
				}

				if(preg_match("/top/i", $_GET['id'])) {
					$profile_qid = str_replace('datebook-top-', '', $_GET['id']);
					$status_section = 'top';
				} else if(preg_match("/featured/i", $_GET['id'])) {
					$profile_qid = str_replace('datebook-featured-', '', $_GET['id']);
					$status_section = 'featured';
				}

				if (!$profile_qid || $profile_qid == 0) { die(); }

				$all_splans = get_option('datebook_subscription_plans');

				if (is_array($all_splans)){

					// Get profile data and check if it has subscription plan
					$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );

					if($profile_id == $profile_qid){

						// Period variables
						global $period_list_array;

						$status_expiration = '';

						$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
						$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

						// Calculate the Subscription plan period time
						$datebook_get_subscriptionplan = isset($datebook_get_data['profile_subscription']['plan']) && strlen($datebook_get_data['profile_subscription']['plan']) > 1 ? $datebook_get_data['profile_subscription']['plan'] : '';
						$datebook_get_subscriptionplan_price = isset($datebook_get_data['profile_subscription']['price']) ? $datebook_get_data['profile_subscription']['price'] : '';

						// Top position
						$top_times_total = isset($datebook_get_data['profile_subscription']['top_times_total']) && $datebook_get_data['profile_subscription']['top_times_total'] > 0 ? $datebook_get_data['profile_subscription']['top_times_total'] : 0;
						$top_times_left = isset($datebook_get_data['profile_subscription']['top_times_left']) && $datebook_get_data['profile_subscription']['top_times_left'] > 0 ? $datebook_get_data['profile_subscription']['top_times_left'] : 0;

						if($top_times_total > 0 && $top_times_left > 0 && $top_times_left <= $top_times_total && $status_section == 'top'){

							$period_long_number_top_position = isset($all_splans[$datebook_get_subscriptionplan]['period_long_number_top_position']) ? $all_splans[$datebook_get_subscriptionplan]['period_long_number_top_position'] : 0;
							$period_long_top_position = isset($all_splans[$datebook_get_subscriptionplan]['period_long_top_position']) ? $all_splans[$datebook_get_subscriptionplan]['period_long_top_position'] : 0;

							$topad_expiration = $status_expiration = strtotime("+" . $period_long_number_top_position . " " . $period_list_array[$period_long_top_position]);

							$available_days = get_post_meta($profile_id, 'topad_ends', true);
							if ($available_days && $available_days > time()) {
								$topad_expiration = $topad_expiration + ($available_days - time());
							}

							update_post_meta($profile_id, 'topad', '1');
							update_post_meta($profile_id, 'topad_ends', esc_attr($topad_expiration));

							$post = array(
								'ID' => $profile_id,
								'post_modified' => date( 'Y:m:d H:i:s' ),
								'post_modified_gmt' => date( 'Y:m:d H:i:s' ),
							);
							wp_update_post($post);

							// Deduct points for Top position by myCred
							if (isset(self::$datebook_options['points_system']) && self::$datebook_options['points_system'] == 1 && class_exists('myCRED_Core')) {

								$points_for_top_position = isset($all_splans[$datebook_get_subscriptionplan]['points_for_top_position']) ? $all_splans[$datebook_get_subscriptionplan]['points_for_top_position'] : 0;

								if($points_for_top_position > 0){
									mycred_add( 'subscription', $current_user_id, -$points_for_top_position, 'Points deducted for Top position' );
								}
							}

							$datebook_get_data['profile_subscription']['topad'] = '1';
							$datebook_get_data['profile_subscription']['topad_starts'] = time();
							$datebook_get_data['profile_subscription']['topad_ends'] = $topad_expiration;

							$top_times_left_updated = $times_left_updated = $top_times_left - 1;
							$datebook_get_data['profile_subscription']['top_times_left'] = $top_times_left_updated;

						}


						// Featured position
						$featured_times_total = isset($datebook_get_data['profile_subscription']['featured_times_total']) && $datebook_get_data['profile_subscription']['featured_times_total'] > 0 ? $datebook_get_data['profile_subscription']['featured_times_total'] : 0;
						$featured_times_left = isset($datebook_get_data['profile_subscription']['featured_times_left']) && $datebook_get_data['profile_subscription']['featured_times_left'] > 0 ? $datebook_get_data['profile_subscription']['featured_times_left'] : 0;

						if($featured_times_left > 0 && $featured_times_total > 0 && $featured_times_left <= $featured_times_total && $status_section == 'featured'){

							$period_long_number_featured_position = isset($all_splans[$datebook_get_subscriptionplan]['period_long_number_featured_position']) ? $all_splans[$datebook_get_subscriptionplan]['period_long_number_featured_position'] : 0;
							$period_long_featured_position = isset($all_splans[$datebook_get_subscriptionplan]['period_long_featured_position']) ? $all_splans[$datebook_get_subscriptionplan]['period_long_featured_position'] : 0;

							$featured_expiration = $status_expiration = strtotime("+" . $period_long_number_featured_position . " " . $period_list_array[$period_long_featured_position]);

							$available_days = get_post_meta($profile_id, 'featured_ends', true);
							if ($available_days && $available_days > time()) {
								$featured_expiration = $featured_expiration + ($available_days - time());
							}

							update_post_meta($profile_id, 'featured', '1');
							update_post_meta($profile_id, 'featured_ends', esc_attr($featured_expiration));

							// Deduct points for Featured position by myCred
							if (isset(self::$datebook_options['points_system']) && self::$datebook_options['points_system'] == 1 && class_exists('myCRED_Core')) {

								$points_for_featured_position = isset($all_splans[$datebook_get_subscriptionplan]['points_for_featured_position']) ? $all_splans[$datebook_get_subscriptionplan]['points_for_featured_position'] : 0;

								if($points_for_featured_position > 0){
									mycred_add( 'subscription', $current_user_id, -$points_for_featured_position, 'Points deducted for Featured status' );
								}
							}

							$datebook_get_data['profile_subscription']['featured'] = '1';
							$datebook_get_data['profile_subscription']['featured_starts'] = time();
							$datebook_get_data['profile_subscription']['featured_ends'] = $featured_expiration;

							$featured_times_left_updated = $times_left_updated = $featured_times_left - 1;
							$datebook_get_data['profile_subscription']['featured_times_left'] = $featured_times_left_updated;

						}

						// Update the post meta
						update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);

						$status_expiration_out = esc_html__( 'till', 'datebook' ) . ': ' . DateBook_Utilities::datebook_date_i18n(2, $status_expiration, false);

						$times_left_updated = isset($times_left_updated) ? $times_left_updated : 0;

						// display the confirmation of activation
						$response = array('success' => 1, 'text' => esc_html__('Activated', 'datebook' ), 'period' => $status_expiration_out, 'timesleft' => $times_left_updated);

						wp_send_json($response);

					}
				}
			}

			if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )) {

					die();

			}
		}
	}
	
	
	/**
	 * Proccess Top and Featured statuses via ajax
	 * 
	 * @since 2.1
	 * @access public
	 */
	public static function datebook_process_ajax_activate_top() {

		if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

			// update all the input data
			add_action( 'wp_loaded', self::datebook_ajax_activate_topfeatured() );

		}

	}


	/**
	 * Add Top and Featured plans to Subscription plan
	 *
	 * @access public
	 * @return void
	 */
	public static function add_new_subscription_plan_to_profile($payment_args) {
		
		global $datebook_field_titles;

		// Get current user ID
		if(isset($payment_args['user_id']) && $payment_args['user_id'] > 0){

			$current_user_id = $payment_args['user_id'];

		} else {

			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);

		}

		set_query_var( 'datebook_field_titles', $datebook_field_titles );

		$datebook_field_titles = get_query_var( 'datebook_field_titles' );
		if ( is_array( $datebook_field_titles ) ) { extract($datebook_field_titles); }

		$subscriptionplan_id = !empty($payment_args['subscription_plan_id']) && $payment_args['subscription_plan_id'] > 1 ? $payment_args['subscription_plan_id'] : (!empty($payment_args['subscription_id']) && $payment_args['subscription_id'] > 1 ? $payment_args['subscription_id'] : '');

		$all_splans = get_option('datebook_subscription_plans');

		if(isset($all_splans[$subscriptionplan_id]['subscription_id']) && $all_splans[$subscriptionplan_id]['subscription_id'] == $subscriptionplan_id) {

			// Period variables
			global $period_list_array;

			// Get profile data and check if it has subscription plan
			$profile_id = isset($payment_args['profile_id']) && $payment_args['profile_id'] > 1 ? $payment_args['profile_id'] : get_user_meta( $current_user_id, 'profile_postid', true );
			
			$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
			$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

			// Get user id
			$member = datebook_get_member($current_user_id);
			
			// Remember a default plan
			$activate_plan_by_default = isset($all_splans[$subscriptionplan_id]['activate_by_default']) && $all_splans[$subscriptionplan_id]['activate_by_default'] == 1 ? $subscriptionplan_id : 0;
			// Remember a plan to hide in the subscription panel
			$hide_plan_by_default = isset($all_splans[$subscriptionplan_id]['hide_by_default']) && $all_splans[$subscriptionplan_id]['hide_by_default'] == 1 ? $subscriptionplan_id : 0;
			// Remember a plan to hide after expiration
			$hide_plan_after_expire = isset($all_splans[$subscriptionplan_id]['hide_after_expire']) && $all_splans[$subscriptionplan_id]['hide_after_expire'] == 1 ? $subscriptionplan_id : 0;

			// Prepare the Subscription data for post meta
			$datebook_get_data['profile_subscription'] = isset($all_splans[$subscriptionplan_id]['subscription_id']) ? array(
				'subscription_id' => $subscriptionplan_id,
				'plan' => $all_splans[$subscriptionplan_id]['subscription_id'],
				'price' => $payment_args['price'], 
				'recurring' => 0,
				'starts' => $payment_args['starts'], 
				'ends' => $payment_args['ends'],
				'status' => $payment_args['status'],
				'activate_plan_by_default' => $activate_plan_by_default,
				'hide_plan_by_default' => $hide_plan_by_default,
				'hide_plan_after_expire' => $hide_plan_after_expire,
				'profile_id' => $profile_id) : array();


			$get_subscription_status = isset($payment_args['status']) && $payment_args['status'] == 'active' ? 1 : 0;
			
			if ($get_subscription_status == 1) {

				// Top position
				$keep_top_featured_periods = isset(self::$datebook_options['keep_top_featured_periods']) ? self::$datebook_options['keep_top_featured_periods'] : '';

				$keep_top_period = ($keep_top_featured_periods['1'] == 1) ? 1 : 0;

				if ($keep_top_period == 0) {

					delete_post_meta($profile_id, 'topad');
					delete_post_meta($profile_id, 'topad_ends');

				}

				if(isset($all_splans[$subscriptionplan_id]['top_position']) && $all_splans[$subscriptionplan_id]['top_position'] == 1){

					$period_long_number_top_position = isset($all_splans[$subscriptionplan_id]['period_long_number_top_position']) ? $all_splans[$subscriptionplan_id]['period_long_number_top_position'] : 0;
					$period_long_top_position = isset($all_splans[$subscriptionplan_id]['period_long_top_position']) ? $all_splans[$subscriptionplan_id]['period_long_top_position'] : 0;

					$topad_expiration = strtotime("+" . $period_long_number_top_position . " " . $period_list_array[$period_long_top_position]);

					$available_days = get_post_meta($profile_id, 'topad_ends', true);
					if ($available_days && $available_days > time()) {
						$topad_expiration = $topad_expiration + ($available_days - time());
					}

					$top_times_total = isset($all_splans[$subscriptionplan_id]['times_top_position']) && $all_splans[$subscriptionplan_id]['times_top_position'] > 0 ? $all_splans[$subscriptionplan_id]['times_top_position'] : 0;

					$datebook_get_data['profile_subscription']['top_times_total'] = $top_times_total;

					$datebook_get_data['profile_subscription']['topad'] = '1';
					$datebook_get_data['profile_subscription']['topad_starts'] = time();
					$datebook_get_data['profile_subscription']['topad_ends'] = $topad_expiration;
					
					if(isset($all_splans[$subscriptionplan_id]['firstactivate_top_position']) && $all_splans[$subscriptionplan_id]['firstactivate_top_position'] > 0){

						$datebook_get_data['profile_subscription']['top_times_left'] = $top_times_total - 1;
						update_post_meta($profile_id, 'topad', '1');
						update_post_meta($profile_id, 'topad_ends', $topad_expiration);

						$post = array(
							'ID' => $profile_id,
							'post_modified' => date("Y:m:d H:i:s"),
							'post_modified_gmt' => date("Y:m:d H:i:s"),
						);
						wp_update_post($post);

						// Deduct points for Top position by myCred
						if (isset(self::$datebook_options['points_system']) && self::$datebook_options['points_system'] == 1 && class_exists('myCRED_Core')) {

							$points_for_top_position = isset($all_splans[$subscriptionplan_id]['points_for_top_position']) ? $all_splans[$subscriptionplan_id]['points_for_top_position'] : 0;

							if($points_for_top_position > 0){
								mycred_add( 'subscription', $current_user_id, -$points_for_top_position, 'Points deducted for Top position' );
							}
						}

					} else {

						$datebook_get_data['profile_subscription']['top_times_left'] = $top_times_total;

					}
				}


				// Featured position
				$keep_featured_period = $keep_top_featured_periods['2'] == 1 ? 1 : 0;

				if ($keep_featured_period == 0) {

					delete_post_meta($profile_id, 'featured');
					delete_post_meta($profile_id, 'featured_ends');

				}

				if(isset($all_splans[$subscriptionplan_id]['featured_position']) && $all_splans[$subscriptionplan_id]['featured_position'] == 1){

					$period_long_number_featured_position = isset($all_splans[$subscriptionplan_id]['period_long_number_featured_position']) ? $all_splans[$subscriptionplan_id]['period_long_number_featured_position'] : 0;
					$period_long_featured_position = isset($all_splans[$subscriptionplan_id]['period_long_featured_position']) ? $all_splans[$subscriptionplan_id]['period_long_featured_position'] : 0;

					if ($period_long_number_featured_position > 0) {

						$featured_expiration = strtotime("+" . $period_long_number_featured_position . " " . $period_list_array[$period_long_featured_position]);

						$available_days = get_post_meta($profile_id, 'featured_ends', true);
						if ($available_days && $available_days > time()) {
							$featured_expiration = $featured_expiration + ($available_days - time());
						}

						$featured_times_total = isset($all_splans[$subscriptionplan_id]['times_featured_position']) && $all_splans[$subscriptionplan_id]['times_featured_position'] > 0 ? $all_splans[$subscriptionplan_id]['times_featured_position'] : 0;

						$datebook_get_data['profile_subscription']['featured_times_total'] = $featured_times_total;
						$datebook_get_data['profile_subscription']['featured'] = '1';
						$datebook_get_data['profile_subscription']['featured_starts'] = time();
						$datebook_get_data['profile_subscription']['featured_ends'] = $featured_expiration;

						if(isset($all_splans[$subscriptionplan_id]['firstactivate_featured_position']) && $all_splans[$subscriptionplan_id]['firstactivate_featured_position'] > 0){

							$datebook_get_data['profile_subscription']['featured_times_left'] = $featured_times_total - 1;
							update_post_meta($profile_id, 'featured', '1');
							update_post_meta($profile_id, 'featured_ends', $featured_expiration);

							$post = array(
								'ID' => $profile_id,
								'post_modified' => date("Y:m:d H:i:s"),
								'post_modified_gmt' => date("Y:m:d H:i:s"),
							);
							wp_update_post($post);

							// Deduct points for Featured position by myCred
							if (isset(self::$datebook_options['points_system']) && self::$datebook_options['points_system'] == 1 && class_exists('myCRED_Core')) {

								$points_for_featured_position = isset($all_splans[$subscriptionplan_id]['points_for_featured_position']) ? $all_splans[$subscriptionplan_id]['points_for_featured_position'] : 0;

								if($points_for_featured_position > 0){
									mycred_add( 'subscription', $current_user_id, -$points_for_featured_position, 'Points deducted for Featured status' );
								}
							}

						} else {

							$datebook_get_data['profile_subscription']['featured_times_left'] = $featured_times_total;

						}
					}
				}
			}

			// Update the post meta
			update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);

		}
	}


	/**
	 * Redirect to Confirmation page after Subscription plan is paid and activated
	 *
	 * Sixth step of processing Subscription data. Last!
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_process_redirect_to_confirmation( $payment_args ) {

		if(isset($payment_args['subscription_plan_id']) && $payment_args['subscription_plan_id'] > 1 && isset($payment_args['payment_id']) && $payment_args['payment_id'] > 0 && isset($payment_args['profile_id']) && $payment_args['profile_id'] > 0){
			
			$my_upgrade_page = isset(self::$datebook_options['my_upgrade_page']) ? self::$datebook_options['my_upgrade_page'] : '';

			$payment_page = isset($payment_args['payment_page']) && $payment_args['payment_page'] > 0 ? $payment_args['payment_page'] : 0;

			$redirect_url = add_query_arg(
				array(
					'action' => 'payment_page', 
					'payment_page' => $payment_page
				), 
				get_permalink($my_upgrade_page)
			);

			wp_redirect($redirect_url);
			exit;

		}
	}


	/**
	 * Process Activation of profile after payment is made
	 * 
	 * @access public
	 * @return void
	 */
	public static function activate_profile_after_payment($payment_args){

		if(isset($payment_args['subscription_plan_id']) && $payment_args['subscription_plan_id'] > 0){

			// Get profile data and check if it has subscription plan
			$current_user_id = isset($payment_args['user_id']) && $payment_args['user_id'] > 0 ? $payment_args['user_id'] : 0;

			$profile_id = isset($payment_args['profile_id']) && $payment_args['profile_id'] > 0 ? $payment_args['profile_id'] : get_user_meta( $current_user_id, 'profile_postid', true );

			// Activate profile
			if (isset(self::$datebook_options['activate_manual_new_profile']) && self::$datebook_options['activate_manual_new_profile'] == '1') {

				$temp_post = get_post($profile_id);
				$post_status = $temp_post->post_status;

				if ($post_status == 'publish') {
					$post_status = 'publish';
				} else {
					$post_status = 'private';
				}

			} else {

				$post_status = 'publish';

				// 1. Check an email verified
				$emailhash = get_user_meta( $current_user_id, 'emailhash', true );
				if ($emailhash != '') {
					$post_status = 'private';
				}

				$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
				$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

				// 2. Check a profile has a photo
				if(isset(self::$datebook_options['user_must_upload_photo']) && self::$datebook_options['user_must_upload_photo'] == '1'){
					$profile_photo_id = isset($datebook_get_data['profile_photo_id']) ? $datebook_get_data['profile_photo_id'] : '';
					$profile_photo_id_parse = explode('/', $profile_photo_id);
					$profile_photo_id = count($profile_photo_id_parse) > 1 ? $profile_photo_id_parse[1] : $profile_photo_id_parse[0];
					if($profile_photo_id == ''){
						$post_status = 'private';
					}
				}


				// 3. Check a profile completed
				if(isset(self::$datebook_options['user_must_complete_profile']) && self::$datebook_options['user_must_complete_profile'] == '1'){
					$profile_must_complete = isset($datebook_get_data['profile_must_complete']) && $datebook_get_data['profile_must_complete'] == 1 ? 1 : 0;
					if($profile_must_complete == 0){
						$post_status = 'private';
					}
				}

			}

			// Insert location counter after user paid for a subscription plan
			if($post_status == 'publish'){

				global $wpdb;

				$table_countries = strtolower($wpdb->prefix) . 'datebook_countries';

				// Get all member subscriptions
				$member_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $current_user_id ) );

				foreach( $member_subscriptions as $member_subscription ) {

					//if( $member_subscription->subscription_plan_id != $payment_data['subscription_id'] ) continue;

					// Update subscription
					$member_subscription->update( array(
						'subscription_plan_id' => $payment_args['subscription_plan_id'],
						'plan_price_period' => $payment_args['plan_price_period'],
						'start_date' => $payment_args['start_date'],
						'expiration_date' => $payment_args['expiration_date'],
						'status' => 'active',
						'payment_gateway' => $payment_args['payment_gateway']
					));

				}

				// Get the payment
				$payment = datebook_get_payment( $payment_args['payment_id'] );
				// Complete payment
				$payment->update( array( 'status' => 'completed', 'transaction_id' => $payment_args['transaction_id'] ) );

				// Update profile subscription data
				self::add_new_subscription_plan_to_profile($payment_args);

				$post_profile = array( 'ID' => $profile_id, 'post_status' => $post_status );
				wp_update_post( $post_profile );

				$get_profile_city = get_post_meta($profile_id, 'city', true);

				if(isset($get_profile_city) && $get_profile_city > 0){

					// increment counts in counter in city
					$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $get_profile_city) );

				}

				$get_profile_region = get_post_meta($profile_id, 'region', true);

				if(isset($get_profile_region) && $get_profile_region > 0){

					// increment counts in counter in region
					$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $get_profile_region) );

				}

				$get_profile_country = get_post_meta($profile_id, 'country', true);

				if(isset($get_profile_country) && $get_profile_country > 0){

					// increment counts in counter in country
					$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $get_profile_country) );

				}

				$profile_get_permalink = get_permalink($profile_id);

				// Send an email notification to user that his profile is activated
				add_action('plugins_loaded', function() {

					//$datebook_user_info = get_userdata($current_user_id);
					$datebook_user_info = get_user_by('ID', $current_user_id);

					$to_email = $datebook_user_info->user_email;

					// Put all data to an array
					$datebook_email_var = array(
						'profile_name' => $datebook_user_info->display_name,
						'user_login' => $datebook_user_info->user_login,
						'emailaddress' => $datebook_user_info->user_email,
						'profile_get_permalink' => $profile_get_permalink
					);

					set_query_var( 'datebook_email_var', $datebook_email_var );

					// Send email to profile
					$select_email_template = 'profile_activated_to_profile';

					include DateBook_Template_Loader::locate( 'misc/email-templates' );

					$datebook_email_sitename = isset(self::$datebook_options['email_sitename']) ? self::$datebook_options['email_sitename'] : '';

					$subject_in_email = esc_html__( 'Welcome to', 'datebook' ) . ' ' . $datebook_email_sitename;

					DateBook_Utilities::datebook_email_send(NULL, NULL, $to_email, $subject_in_email, $body);

				});

				// Send email about payment made to admin
				if (isset(self::$datebook_options['email_when_payment']) && self::$datebook_options['email_when_payment'] == '1') {

					// Email
					$to_email = isset(self::$datebook_options['email_website']) ? self::$datebook_options['email_website'] : get_bloginfo('admin_email');

					// Subject
					$subject_in_email = esc_html__('New payment', 'datebook');

					// Message
					$body = esc_html__( 'Hello', 'datebook' ) . ', ' . esc_html__( 'Admin', 'datebook' ) . '!<br /><br />';
					$body .= esc_html__( 'Subscription plan has been selected', 'datebook' ) . '.<br /><br />';
					$body .= esc_html__( 'Profile has been activated', 'datebook' ) . '.<br /><br />';
					$body .= esc_html__( 'Profile', 'datebook' ).': <a href="' . $profile_get_permalink . '">' . $profile_get_permalink . '</a>';

					// Send email to admin
					$datebook_mail = DateBook_Utilities::datebook_email_send(NULL, NULL, $to_email, $subject_in_email, $body);

				}

				// Delete all subsciption temporary data that a user selected before
				delete_post_meta($profile_id, 'subscriptionplan_temp');

				// Add point by myCred
				if (isset(self::$datebook_options['points_system']) && self::$datebook_options['points_system'] == 1 && class_exists('myCRED_Core')) {

					$all_splans = get_option('datebook_subscription_plans');

					$pointsquantity = isset($all_splans[$payment_args['subscription_plan_id']]['pointsquantity']) ? $all_splans[$payment_args['subscription_plan_id']]['pointsquantity'] : 0;

					if($pointsquantity > 0){

						mycred_add( 'subscription', $current_user_id, $pointsquantity, 'Points added for subscription' );

					}
				}
			}
		}
	}


	/**
	 * Process Subscription data after payment is made
	 * 
	 * Fifth step of processing Subscription data
	 * Second execution of subscription after registration
	 *
	 * @access public
	 * @return void
	 */
	public static function process_subscription_after_payment($payment_args){

		if(isset($payment_args['subscription_plan_id']) && $payment_args['subscription_plan_id'] > 0){

			// Get profile data and check if it has subscription plan
			$current_user_id = isset($payment_args['user_id']) && $payment_args['user_id'] > 0 ? $payment_args['user_id'] : 0;

			$profile_id = isset($payment_args['profile_id']) && $payment_args['profile_id'] > 1 ? $payment_args['profile_id'] : get_user_meta( $current_user_id, 'profile_postid', true );

			if(isset($payment_args['payment_gateway']) && $payment_args['payment_gateway'] == 'bank' && !is_super_admin()){

				$payment_args['payment_page'] = '6';

			} else {

				$payment_args['payment_page'] = '5';

				// Activate profile
				self::activate_profile_after_payment($payment_args);
			}
		}


		/*
		// Tour activation
		$body .= esc_html__( 'Your tour has been activated', 'datebook' );
		$post_tour = array( 'ID' => $profile_id, 'post_status' => 'publish' );

		// Activate the tour
		wp_update_post( $post_tour );
		update_post_meta($profile_id, "tour_txn_id", sanitize_text_field($txn_id));
		*/

		$notredirect_to_subscription_page = isset($payment_args['notredirect_to_subscription_page']) && $payment_args['notredirect_to_subscription_page'] == 1 ? 1 : 0;

		if($payment_args['payment_gateway'] == 'paystack'){
			return;
		}

		if($payment_args['payment_gateway'] != 'paystack' && $notredirect_to_subscription_page == 0){

			// Redirect to Payment Confirmation page after subscription is paid
			self::datebook_process_redirect_to_confirmation($payment_args);

		}

		// Redirect to custom page after email verified
		$profile_id = isset($payment_args['profile_id']) && $payment_args['profile_id'] > 1 ? $payment_args['profile_id'] : get_user_meta( $current_user_id, 'profile_postid', true );

		$redirect_to_after_email_confirmation = isset(self::$datebook_options['redirect_to_after_email_confirmation']) && self::$datebook_options['redirect_to_after_email_confirmation'] > 0 ? self::$datebook_options['redirect_to_after_email_confirmation'] : $profile_id;

		$redirect_url = add_query_arg( array(
			'message' => 'emailverified'
		), get_permalink($redirect_to_after_email_confirmation));

		wp_redirect($redirect_url);
		exit;

	}


    /**
     * Pre Checkout process. Process insert or update Member and Payments records
     * First execution of subscription after registration
	 *
     */
	public static function insert_member_payments_data($subscription_plan) {

		// Get current user ID
		if(isset($subscription_plan['user_id']) && $subscription_plan['user_id'] > 0){

			$current_user_id = $subscription_plan['user_id'];

		} else {

			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);

		}
		
		$datebook_user_info = get_user_by('ID', $current_user_id);
		$user_email = $datebook_user_info->user_email;

        // Stop if there are errors
        if ( count( datebook_errors()->get_error_codes() ) > 0 )
            return;

		$datebook_field_titles = get_query_var( 'datebook_field_titles' );
		if ( is_array( $datebook_field_titles ) ) { extract($datebook_field_titles); }

		// Base data
		$subscription_data = array(
            'user_id'				=> $current_user_id,
			'subscription_plan_id'	=> $subscription_plan['subscription_id'],
			'plan_price_period'		=> $subscription_plan['plan_price_period'],
			'start_date'			=> $subscription_plan['start_date'],
			'expiration_date'		=> $subscription_plan['expiration_date'],
			'status'				=> $subscription_plan['status'],
			'payment_gateway'		=> $subscription_plan['payment_gateway'],
			'payment_profile_id'	=> $subscription_plan['profile_id'],
			'billing_amount'		=> $subscription_plan['price'],
			'billing_duration'		=> '',
			'billing_duration_unit'	=> ''
		);

        // Insert the subscription into the db

        /**
         * We can't assume that this won't get executed multiple times. ( on PB registration if we had the field multiple times this executed as many times as the number of fields
         * and resulted in the user having the same subscription multiple times )
         * After a discussion we decided to make sure that the user can't have the same subscription multiple times amd we should prevent this
         * There is a possible feature request to allow the same subscription multiple times but for now we leave it like this
         */
		$subscription_already_exist = false;
		$current_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $current_user_id ) );

		if( !empty( $current_subscriptions ) ){
			foreach( $current_subscriptions as $current_subscription ) {
				$subscription = $current_subscription;
				$subscription_already_exist = true;
					break;
			}
		}
		
		// If user subscription is not exists then insert a new subscription
		if(!$subscription_already_exist){

			$member_subscription = new DateBook_Member_Subscription();
			$member_subscription->insert($subscription_data);

			//if (isset(self::$datebook_options['activate_woocommerce_subscription']) && self::$datebook_options['activate_woocommerce_subscription'] == '2' && function_exists( 'WC' ) ) {
				//self::add_new_subscription_plan_to_profile( $subscription_plan );
			//}

		} else {

			// Get user id
			$member = datebook_get_member($current_user_id);

			// Chech if subscription plan is already selected and redirect to payment gateway
			if($member->get_subscriptions_count() >= 1) {

				// Check if user already has active subscription and do not change to another subsciption plan
				if(!empty($subscription->status) && $subscription->status != 'active'){

					if(isset($subscription_data['referrer']) && $subscription_data['referrer'] == 'woocommerce') {
						$subscription_status = $subscription_data['status'];
					} else if($subscription_data['payment_gateway'] == 'free') {
						$subscription_status = 'active';
					} else {
						$subscription_status = 'pending';
					}

					$subscription_array = array(
						'subscription_plan_id' => $subscription_data['subscription_plan_id'],
						'plan_price_period' => $subscription_data['plan_price_period'],
						'start_date' => $subscription_data['start_date'],
						'expiration_date' => $subscription_data['expiration_date'],
						'status' => $subscription_status,
						'payment_gateway' => $subscription_data['payment_gateway']
					);

					foreach( $current_subscriptions as $member_subscription ) {

						// Update subscription
						$member_subscription->update($subscription_array);

					}

					self::add_new_subscription_plan_to_profile( $subscription_plan );

				} else {

					// Save temporary data to database
					update_post_meta($subscription_plan['profile_id'], 'subscriptionplan_temp', $subscription_plan);

				}
			}
		}


		// Payment data
		$payment_data = array(
			'plan'						=> $subscription_plan['subscription_id'],
			'user_id'					=> $current_user_id,
			'user_email'				=> $user_email,
			'subscription_plan_id'		=> $subscription_plan['subscription_id'],
			'plan_price_period'			=> $subscription_plan['plan_price_period'],
			'subscription_plan_name'	=> $subscription_plan['plan_title'],

			'date'						=> $subscription_plan['starts'],
			'start_date'				=> $subscription_plan['start_date'],
			'expiration_date'			=> $subscription_plan['expiration_date'],

			'amount'					=> $subscription_plan['price'],
			'period_number_key'			=> $subscription_plan['period_number_key'],
			'period_key'				=> $subscription_plan['period_key'],
			'recurring'					=> $subscription_plan['recurring'],
			'payment_gateway'			=> $subscription_plan['payment_gateway'],
			'type'						=> $subscription_plan['type'],
			'currency'					=> $subscription_plan['currency'],
			'status'					=> (isset($subscription_plan['status']) ? $subscription_plan['status'] : 'pending'),//'pending', //(isset($subscription_plan['price']) && $subscription_plan['price'] > 0 ? 'pending' : 'completed'),
			'profile_id'				=> $subscription_plan['profile_id'],
			'payment_page'				=> $subscription_plan['payment_page'],
			'datebooktkn'				=> $subscription_plan['datebooktkn']
		);


		$form_location = 'new_subscription';


		// Prepare payment gateway data, this is actually the "old" payment_data
		$payment_gateway_data = array(
			'subscription_data' => $subscription_data,
			'sign_up_amount'    => NULL,
			'redirect_url'      => self::get_redirect_url(),
			'form_location'     => $form_location,
		);

		// Insert the payment into the database
		if( isset( $subscription_plan['price'] ) && $subscription_plan['price'] >= 0 ) {

			$payment = new DateBook_Payment_Class();
			$payment->insert( $payment_data );
			$payment_gateway_data['payment_id'] = $payment->id;
			
			// Insert payment id for WooCommerce
			$subscription_profile_id = $subscription_plan['profile_id'];
			$payment_id = $payment->id;

			update_post_meta($subscription_profile_id, 'payment_id', $payment_id);

		}

		$payment_gateway_data = array_merge( $payment_gateway_data, $payment_data );
		
		return $payment_gateway_data;

	}


    /**
     * Checkout process
	 *
	 * Second step of processing Subscription data
	 *
     * - validates the data from the forms
     * - registers the user if the request is coming from the register form
     * - prepares the subscription and payment data
     * - sends the payment to be processed by the payment gateway and activates the subscription
     *   if everything is okay
     *
     */
    private static function process_checkout($subscription_plan) {

		$payment_gateway_data = self::insert_member_payments_data($subscription_plan);

		if($subscription_plan['admin_activated'] == 1){

			$payment_data = array(
				'subscription_plan_id'		=> $subscription_plan['subscription_id'],
				'payment_id'				=> $payment_gateway_data['payment_id'],
				'plan_price_period'			=> $payment_gateway_data['plan_price_period'],
				'profile_id'				=> $subscription_plan['profile_id'],
				'user_id'					=> $subscription_plan['user_id'],
				'payment_gateway'			=> $subscription_plan['payment_gateway'],
				'transaction_id'			=> '',

				'start_date'				=> $subscription_plan['start_date'],
				'expiration_date'			=> $subscription_plan['expiration_date'],

				'status'					=> $subscription_plan['status'], 
				'price'						=> $subscription_plan['price'], 
				'starts'					=> $subscription_plan['starts'], 
				'ends'						=> $subscription_plan['ends'],

				'notredirect_to_subscription_page' => $subscription_plan['notredirect_to_subscription_page'],

				'admin_activated'			=> $subscription_plan['admin_activated']
			);

			// Let's activate Subscription for member after payment is made
			self::process_subscription_after_payment($payment_data);

		} else {

			// Direct the data flow to the payment gateway
			$payment_gateway = self::datebook_get_payment_gateway( $subscription_plan['payment_gateway'], $payment_gateway_data );
			$payment_gateway->process_redirect_to_payment_gateway($payment_gateway_data);

		}
	}


	/**
	 * Process Subscription data before payment is made
	 *
	 * First step of processing Subscription data
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_process_payment_subscription() {

		$get_payment_page = !empty($_POST['payment_page']) ? $_POST['payment_page'] : 0;

		if (isset($_POST['action']) && $_POST['action'] == 'payment_page' && $get_payment_page == '3') {

			$get_splan = isset($_POST['subscriptionplan']) && strlen($_POST['subscriptionplan']) > 1 ? $_POST['subscriptionplan'] : 0;
			$get_splan_period_key = !empty($_POST['subscriptionplan_period_key']) ? $_POST['subscriptionplan_period_key'] : 0;
			$wp_verify_nonce = !empty($_REQUEST['datebooktkn']) ? $_REQUEST['datebooktkn'] : '';

			$subscribe_invisible = isset($_POST['subscribe_invisible']) && $_POST['subscribe_invisible'] == 1 ? 1 : 0;

			if ($get_splan > 0 && (isset($wp_verify_nonce) || wp_verify_nonce($wp_verify_nonce, 'datebook_new_subscription_form_nonce') || $subscribe_invisible == 1)) {

				global $datebook_field_titles;

				if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
					$current_user_id = DATEBOOK_CURRENT_USER_ID;
				} else {
					global $current_user;
					wp_get_current_user();
					$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
				}

				// Get profile data and check if it has subscription plan
				$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );

				// Check and notify the user to click the validation link
				$user_verified_email_array = DateBook_Utilities::check_if_email_verified($current_user_id);

				$user_must_upload_photo = 1;

				if(isset(self::$datebook_options['user_must_upload_photo']) && self::$datebook_options['user_must_upload_photo'] == '1'){
					// Get Profile personal data
					$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
					$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();
					// Check a profile has a photo
					$profile_photo_id = isset($datebook_get_data['profile_photo_id']) ? $datebook_get_data['profile_photo_id'] : '';
					$profile_photo_id_parse = explode('/', $profile_photo_id);
					$profile_photo_id = count($profile_photo_id_parse) > 1 ? $profile_photo_id_parse[1] : $profile_photo_id_parse[0];

					$user_must_upload_photo = $profile_photo_id > 0 ? 1 : 0;

				}
				
				$profile_must_complete = 1;

				if (isset(self::$datebook_options['user_must_complete_profile']) && self::$datebook_options['user_must_complete_profile'] == '1') {

					$profile_must_complete = isset($datebook_get_data['profile_must_complete']) && $datebook_get_data['profile_must_complete'] == 1 ? 1 : 0;

				}

				if (($user_verified_email_array['emailhash'] == '' && $user_must_upload_photo == 1 && $profile_must_complete == 1) || $subscribe_invisible == 1) {

					set_query_var( 'datebook_field_titles', $datebook_field_titles );

					$datebook_field_titles = get_query_var( 'datebook_field_titles' );
					if ( is_array( $datebook_field_titles ) ) { extract($datebook_field_titles); }

					$all_splans = get_option('datebook_subscription_plans');

					if($all_splans[$get_splan]['subscription_id'] == $get_splan) {

						$get_splan_price = $all_splans[$get_splan]['price'][$get_splan_period_key];

						$current_user_id = $subscribe_invisible == 1 && isset($_POST['current_user_id']) && $_POST['current_user_id'] > 0 ? $_POST['current_user_id'] : $current_user_id;

						// Get user id
						$member_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $current_user_id ) );

						$member_splan_id = isset($member_subscriptions[0]->subscription_plan_id) ? $member_subscriptions[0]->subscription_plan_id : NULL;
						$member_subscription_status = isset($member_subscriptions[0]->status) && ($member_subscriptions[0]->status == 'active' || $member_subscriptions[0]->status == 'completed') ? 1 : 0;

						$member = datebook_get_member($current_user_id);

						// Chech if subscription plan is already selected and redirect to payment gateway
						if($member_splan_id == $get_splan && $member_subscription_status == 1 && $member->get_subscriptions_count() >= 1 && $member->subscriptions[0]['status'] == 'active') {
							
							$my_upgrade_page = isset(self::$datebook_options['my_upgrade_page']) ? self::$datebook_options['my_upgrade_page'] : '';

							$redirect_url = add_query_arg(
								array(
									'action' => 'payment_page', 
									'payment_page' => '4'
								), get_permalink($my_upgrade_page));

							wp_redirect($redirect_url);
							exit;

						} else {
							
							// Period variables
							global $period_list_array, $datebook_paymentperiod_titles, $datebook_currency_titles;

							// Get payment gateway
							$pay_gate = ( ! empty( $_POST['pay_gate'] ) ? $_POST['pay_gate'] : '' );

							$item = get_option('datebook_gateways');
						
							// Payment type
							if($pay_gate == 'bank' && isset($item['bank']['enabled']) && $item['bank']['enabled'] == 1) {

							$subscription_type = 'bank_payment';	        

						} else if($pay_gate == 'paypal_standard' && isset($item['paypal_standard']['enabled']) && $item['paypal_standard']['enabled'] == 1) {

							if (isset($item['paypal_standard']['method']) && $item['paypal_standard']['method'] == 'subscription') {
								$subscription_type = 'subscription_initial_payment';
							} else {
								$subscription_type = 'web_accept_paypal_standard';
							}

						} else {

							$subscription_type = 'subscription_initial_payment';

						}
						
						// Calculate the Subscription plan period time
						$subscription_period_number_key = $all_splans[$get_splan]['register_period_number'][$get_splan_period_key];
						
						$subscription_period_key = $all_splans[$get_splan]['register_period'][$get_splan_period_key];

						if ($subscription_period_number_key > 0) {

							$subscription_period_expiration = date('Y-m-d H:i:s', strtotime("+" . $subscription_period_number_key . " " . $period_list_array[$subscription_period_key]));

						} else {

							$subscription_period_expiration = '0000-00-00 00:00:00';

						}

						$subscription_status = 'pending';

						$default_currency = isset(self::$datebook_options['default_currency']) ? self::$datebook_options['default_currency'] : '';
						$currency_code = $datebook_currency_titles[$default_currency][1];
						
						// Detect if a subscription plan is free for selected genders
						$admin_activated = 0;
						if(isset($_POST['free_for_gender']) && $_POST['free_for_gender'] == 1) {
							$gender = get_post_meta($profile_id, 'gender', true);
							if(isset($all_splans[$get_splan]['free_for_gender'][$gender])){
								$subscription_status = 'active';
								$admin_activated = 1;
							}
						} else if (isset($_POST['admin_activated']) && $_POST['admin_activated'] == 1 && is_super_admin()) {
							$admin_activated = 1;
						}
						
						if (isset($_POST['notredirect_to_subscription_page']) && $_POST['notredirect_to_subscription_page'] == 1) {
							$notredirect_to_subscription_page = 1;
							$admin_activated = 1;
							$subscription_status = 'active';
						} else {
							$notredirect_to_subscription_page = 0;
						}


						// Prepare the Subscription data for post meta
						$new_submitted_subscription = isset($all_splans[$get_splan]['subscription_id']) && isset($all_splans[$get_splan]['price'][$get_splan_period_key]) ? array(
							'subscription_id'	=> $all_splans[$get_splan]['subscription_id'],
							'plan_price_period'	=> $get_splan_period_key,
							'plan'				=> $all_splans[$get_splan]['subscription_id'],
							'plan_title'		=> $all_splans[$get_splan]['name_' . DATEBOOK_WPLANG],
							'price'				=> $all_splans[$get_splan]['price'][$get_splan_period_key],
							'currency'			=> $currency_code,
							'recurring'			=> isset($all_splans[$get_splan]['recurring']) && $all_splans[$get_splan]['recurring'] == 1 ? '1' : '0',
							'status'			=> $subscription_status,
							'type'				=> $subscription_type,

							'start_date'		=> date('Y-m-d H:i:s', time()),
							'expiration_date'	=> $subscription_period_expiration,

							'starts'			=> date('Y-m-d H:i:s', time()), 
							'ends'				=> $subscription_period_expiration,

							'profile_id'		=> $profile_id,
							'user_id'			=> $current_user_id,
							'payment_gateway'	=> $pay_gate,
							'period_number_key'	=> $subscription_period_number_key,
							'period_key'		=> $subscription_period_key,
							'payment_page'		=> $get_payment_page,
							'notredirect_to_subscription_page' => $notredirect_to_subscription_page,
							'datebooktkn'		=> $wp_verify_nonce,
							'admin_activated'	=> $admin_activated,
						) : array();

						// Stop if there are errors
						if ( count( datebook_errors()->get_error_codes() ) > 0 )
							return;

						// Proceed to checkout
						self::process_checkout($new_submitted_subscription);
					
						}
					}
				}
			}
		}
	}


	/**
	 * Return Subsciption page with plans
	 *
	 * @access public
	 * @return void
	 */
	public static function return_display_profile_subscription_page() {

		global $datebook_field_titles;
		set_query_var( 'datebook_field_titles', $datebook_field_titles );

		if (isset(self::$datebook_options['activate_woocommerce_subscription']) && self::$datebook_options['activate_woocommerce_subscription'] == '2' && function_exists( 'WC' ) ) {

			echo do_shortcode('[woocommerce_my_account]');

		} else {
			
			$item = get_option('datebook_gateways');
			
			if (isset($_GET['action']) && $_GET['action'] == 'payment_page' && $_GET['payment_page'] == '6' && isset($item['bank']['enabled']) && $item['bank']['enabled'] == 1) {

				// Bank. display the confirmation of payment is pending
				return DateBook_Template_Loader::load( 'payment/profile-payment-pending' );

			} else if (isset($_GET['action']) && $_GET['action'] == 'payment_page' && $_GET['payment_page'] == '5') {

				// Gateway. display the confirmation of payment
				return DateBook_Template_Loader::load( 'payment/profile-payment-confirmed' );

			} else if (isset($_GET['action']) && $_GET['action'] == 'payment_page' && $_GET['payment_page'] == '4') {

				// display the notification that this subscription plan has been selected
				return DateBook_Template_Loader::load( 'payment/profile-subscriptionplan-already-selected' );

			} else if (isset($_POST['action']) && $_POST['action'] == 'payment_page' && $_POST['payment_page'] == '2' && isset($_POST['subscriptionplan']) && isset($_POST['subscriptionplan_price']) && $_POST['subscriptionplan_price'] != '') {

				// display the list of Payment gateways
				return DateBook_Template_Loader::load( 'payment/profile-payment-checkout' );

			} else {

				if(isset($_POST['action']) && $_POST['action'] == 'payment_page' && $_POST['payment_page'] == '2' && isset($_POST['subscriptionplan'])){
					$subscriptionplan_selected = (isset($_POST['subscriptionplan_price']) && $_POST['subscriptionplan_price'] != '') ? 1 : 0;
					if($subscriptionplan_selected == 0){
						include DateBook_Template_Loader::locate( 'payment/profile-subscription-not-selected' );
					}
				}

				// display the list of Subsciption plans
				return DateBook_Template_Loader::load( 'payment/profile-payment-start' );

			}

		}
	}


	/**
	 * Show Subsciption page with plans
	 *
	 * @access public
	 * @return void
	 */
	public static function display_profile_subscription_page() {

		echo self::return_display_profile_subscription_page();

	}


	/**
	 * Show Cart page
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_display_profile_cart_page() {

		global $datebook_field_titles;
		set_query_var( 'datebook_field_titles', $datebook_field_titles );

		if (isset(self::$datebook_options['activate_woocommerce_subscription']) && self::$datebook_options['activate_woocommerce_subscription'] == '2' && function_exists( 'WC' ) ) {

			echo do_shortcode('[woocommerce_cart]');

		} else {


			if (DateBook_Utilities::check_if_gateway_activated()) {

				if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
					$current_user_id = DATEBOOK_CURRENT_USER_ID;
				} else {
					global $current_user;
					wp_get_current_user();
					$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
				}

				$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );

				$subscription_temp_args = array();
				
				// Get temporary payment data from database
				$subscription_temp_array = get_post_meta($profile_id, 'subscriptionplan_temp');

				if(is_array($subscription_temp_array) && !empty($subscription_temp_array)){

					$subscription_temp_args['subscription_id'] = isset($subscription_temp_array[0]['subscription_id']) ? $subscription_temp_array[0]['subscription_id'] : 0;
					$subscription_temp_args['subscription_type'] = isset($subscription_temp_array[0]['subscription_type']) ? $subscription_temp_array[0]['subscription_type'] : '';
					$subscription_temp_args['subscriptionplan'] = isset($subscription_temp_array[0]['subscriptionplan']) ? $subscription_temp_array[0]['subscriptionplan'] : '';
					$subscription_temp_args['subscriptionplan_title'] = isset($subscription_temp_array[0]['subscriptionplan_title']) ? $subscription_temp_array[0]['subscriptionplan_title'] : '';
					$subscription_temp_args['subscription_price_title'] = isset($subscription_temp_array[0]['subscription_price_title']) ? $subscription_temp_array[0]['subscription_price_title'] : '';
					$subscription_temp_args['subscriptionplan_price'] = isset($subscription_temp_array[0]['subscriptionplan_price']) ? $subscription_temp_array[0]['subscriptionplan_price'] : '';
					$subscription_temp_args['subscription_period_ends'] = isset($subscription_temp_array[0]['subscriptionplan_period_number']) ? $subscription_temp_array[0]['subscriptionplan_period_number'] : '';
					$subscription_temp_args['subscription_period_ends_title'] = isset($subscription_temp_array[0]['subscriptionplan_period']) ? $subscription_temp_array[0]['subscriptionplan_period'] : '';
					$subscription_temp_args['subscriptionplan_period_title'] = isset($subscription_temp_array[0]['subscriptionplan_period_title']) ? $subscription_temp_array[0]['subscriptionplan_period_title'] : '';
					$subscription_temp_args['subscriptionplan_recurring'] = isset($subscription_temp_array[0]['subscriptionplan_recurring']) ? $subscription_temp_array[0]['subscriptionplan_recurring'] : '';
					$subscription_temp_args['subscriptionplan_period_key'] = isset($subscription_temp_array[0]['subscriptionplan_period_key']) ? $subscription_temp_array[0]['subscriptionplan_period_key'] : '';

				}

				$subscription_plans_args = array('current_user_id' => $current_user_id, 'profile_id' => $profile_id, 'subscription_temp_cart' => $subscription_temp_args);

				// display the Payment Cart
				echo DateBook_Template_Loader::load( 'payment/profile-payment-cart', $subscription_plans_args );
			
			}
		}
	}


	/**
	 * Show Checkout page
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_display_profile_checkout_page() {

		global $datebook_field_titles;
		set_query_var( 'datebook_field_titles', $datebook_field_titles );

		if (isset(self::$datebook_options['activate_woocommerce_subscription']) && self::$datebook_options['activate_woocommerce_subscription'] == '2' && function_exists( 'WC' ) ) {

			echo do_shortcode('[woocommerce_checkout]');

		} else {
			
			if(isset($_POST['subscriptionplan']) && isset($_POST['subscriptionplan_price'])) {

				// display the Payment Checkout page
				echo DateBook_Template_Loader::load( 'payment/profile-payment-checkout' );
				
			} else {
				
				// display the Payment Cart
				echo DateBook_Template_Loader::load( 'payment/profile-payment-checkout-empty' );
				
			}

		}
	}


	/**
	 * Show Navigation menu on Subscription, Cart, Checkout pages
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_display_profile_subscription_navigation() {

		$tab_my_upgrade_page_active = '';
		$tab_my_orders_page_active = '';
		$tab_my_address_page_active = '';
		$tab_my_cart_page_active = '';
		$tab_my_checkout_page_active = '';

		/*
		 * WooCommerce endpoint links. Can be useful for adding to menu
		 *
		 * is_account_page(); // Returns true on the customer’s account pages
		 * is_wc_endpoint_url(); // Returns true when viewing any WooCommerce endpoint
		 * is_wc_endpoint_url( 'orders' ); // When the endpoint page for view order is being displayed
		 * is_wc_endpoint_url( 'order-pay' ); // When the endpoint page for order pay is being displayed
		 * is_wc_endpoint_url( 'order-received' ); // When the endpoint page for order received is being displayed
		 * is_wc_endpoint_url( 'view-order' ); // When the endpoint page for view order is being displayed
		 * is_wc_endpoint_url( 'edit-account' ); // When the endpoint page for edit account is being displayed
		 * is_wc_endpoint_url( 'edit-address' ); // When the endpoint page for edit address is being displayed
		 * is_wc_endpoint_url( 'lost-password' ); // When the endpoint page for lost password is being displayed
		 * is_wc_endpoint_url( 'customer-logout' ); // When the endpoint page for customer logout is being displayed
		 * is_wc_endpoint_url( 'add-payment-method' ); // When the endpoint page for add payment method is being displayed
		 */
		
		if((function_exists( 'WC' ) && (is_wc_endpoint_url( 'orders' ) == 1 || is_wc_endpoint_url( 'view-order' ) == 1)) || isset($_GET['pagetab']) && $_GET['pagetab'] == 'orders'){
			$tab_my_orders_page_active = ' active';
		} else if((function_exists( 'WC' ) && is_wc_endpoint_url( 'edit-address' ) == 1) || isset($_GET['pagetab']) && $_GET['pagetab'] == 'address'){
			$tab_my_address_page_active = ' active';
		} else if((isset(self::$datebook_options['my_cart_page']) && get_the_ID() == self::$datebook_options['my_cart_page']) || (function_exists( 'WC' ) && is_cart())){
			$tab_my_cart_page_active = ' active';
		} else if(
		((isset(self::$datebook_options['my_checkout_page']) && get_the_ID() == self::$datebook_options['my_checkout_page']) || (function_exists( 'WC' ) && is_checkout())) || 
		(isset($_POST['subscriptionplan']) && isset($_POST['subscriptionplan_price']) && $_POST['subscriptionplan_price'] != '' && isset($_POST['action']) && $_POST['action'] == 'payment_page' && ($_POST['payment_page'] == '2' || $_POST['payment_page'] == '4')) || 
		(isset($_GET['action']) && $_GET['action'] == 'payment_page' && ($_GET['payment_page'] == '4' || $_GET['payment_page'] == '5' || $_GET['payment_page'] == '6'))){
			$tab_my_checkout_page_active = ' active';
		} else {
			$tab_my_upgrade_page_active = ' active';
		}
		
		$my_upgrade_page = isset(self::$datebook_options['my_upgrade_page']) ? self::$datebook_options['my_upgrade_page'] : '';

		if (isset(self::$datebook_options['activate_woocommerce_subscription']) && self::$datebook_options['activate_woocommerce_subscription'] == '2' && function_exists( 'WC' ) ) {
			$my_upgrade_page_orders_url = wc_get_endpoint_url('orders', '', get_permalink($my_upgrade_page));
			$my_upgrade_page_address_url = wc_get_endpoint_url('edit-address', '', get_permalink($my_upgrade_page));
		} else {

			$my_upgrade_page_orders_url = add_query_arg( array(
				'pagetab' => 'orders'
			), get_permalink($my_upgrade_page) );

			$my_upgrade_page_address_url = add_query_arg( array(
				'pagetab' => 'address'
			), get_permalink($my_upgrade_page) );

		}
		
		$my_cart_page = isset(self::$datebook_options['my_cart_page']) ? self::$datebook_options['my_cart_page'] : '';
		$my_checkout_page = isset(self::$datebook_options['my_checkout_page']) ? self::$datebook_options['my_checkout_page'] : '';

		?>

		<nav class="mb-4">
        	<ul class="nav nav-tabs">
            	<li class="nav-item"><a class="nav-link<?php echo esc_attr($tab_my_upgrade_page_active); ?>" href="<?php echo esc_url(get_permalink($my_upgrade_page)); ?>"><?php echo esc_html__( 'Plans', 'datebook' ); ?></a></li>
				
                <?php if (isset(self::$datebook_options['activate_woocommerce_subscription']) && self::$datebook_options['activate_woocommerce_subscription'] == '2' && function_exists( 'WC' ) ) { ?>
                	<li class="nav-item"><a class="nav-link<?php echo esc_attr($tab_my_orders_page_active); ?>" href="<?php echo esc_url($my_upgrade_page_orders_url); ?>"><?php echo esc_html__( 'Orders', 'datebook' ); ?></a></li>
	                <?php /*?><li class="nav-item"><a class="nav-link<?php echo esc_attr($tab_my_address_page_active); ?>" href="<?php echo esc_url($my_upgrade_page_address_url); ?>"><?php echo esc_html__( 'Billing address', 'datebook' ); ?></a></li><?php */?>
                <?php } ?>

				<li class="nav-item"><a class="nav-link<?php echo esc_attr($tab_my_cart_page_active); ?>" href="<?php echo esc_url(get_permalink($my_cart_page)); ?>"><?php echo esc_html__( 'Cart', 'datebook' ); ?></a></li>
                <li class="nav-item"><a class="nav-link<?php echo esc_attr($tab_my_checkout_page_active); ?>" href="<?php echo esc_url(get_permalink($my_checkout_page)); ?>"><?php echo esc_html__( 'Checkout', 'datebook' ); ?></a></li>
			</ul>
		</nav>

	<?php


	}


	// Cron functions

	/**
	 * Proccess cancelation
	 * 
	 * @access public
	 */
	public static function datebook_payment_canceled($to_customer_email, $paymenttype, $custom, $reason) {
		
		$email_sitename = isset(self::$datebook_options['email_sitename']) ? self::$datebook_options['email_sitename'] : '';

		$expiration = strtotime("+2 days");
		$emaillink = get_permalink($custom);
		$body = esc_html__( 'Hello', 'datebook' ).'<br /><br />
'.esc_html__( 'You have canceled your subscription from', 'datebook' ).' '.sanitize_email($email_sitename).' '.esc_html__( 'or your payment has been refunded', 'datebook' ).'.<br />';

		if ($paymenttype == '1') {//topad

			update_post_meta($custom, 'topad_ends', $expiration);
			delete_post_meta($custom, 'topad_extend');
			$body .= esc_html__( 'This means your Top Profile status will only be active for 2 more days', 'datebook' ).".<br />";
			$body .= esc_html__( 'If you want to renew your status please visit our website', 'datebook' ).":<br />";

		} elseif ($paymenttype == '2') {//featured

			update_post_meta($custom, 'featured_ends', $expiration);
			delete_post_meta($custom, 'featured_extend');
			$body .= esc_html__( 'This means your Featured status will only be active for 2 more days', 'datebook' ).".<br />";
			$body .= esc_html__( 'If you want to renew your status please visit our website', 'datebook' ).":<br />";

		} elseif ($paymenttype == '3') {//tour

			$post_tour = array( 'ID' => $custom, 'post_status' => 'draft' );
			wp_update_post( $post_tour );
			delete_post_meta($custom, 'tour_txn_id');
			$body .= esc_html__( 'This means we had to deactivate your tour and it won\'t be visible on our website anymore', 'datebook' ).".<br />";
			$body .= esc_html__( 'If you want to add another tour please visit our website', 'datebook' ).":<br />";

		}

		$body .= '<a href="'.esc_url($emaillink).'">'.esc_url($emaillink).'</a>';


		$subject_in_email = esc_html__( 'Payment canceled on', 'datebook' ) . ' ' . $email_sitename;

		$datebook_mail = DateBook_Utilities::datebook_email_send('', '', $to_customer_email, $subject_in_email, $body);

	}


	/**
	 * Search for profiles whos subscriptions expired or are going to expire
	 *
	 * @access private
	 * @return void
	 */
	private static function datebook_check_expired_subscription() {

		global $wpdb;

		// Check for expiring subscriptions
		$cron_subscriptions_check = isset(self::$datebook_options['cron_subscriptions_check']) ? self::$datebook_options['cron_subscriptions_check'] : 0;

		if($cron_subscriptions_check > 0){

			$time = get_option('datebook_time_check_expired');

			$current_time = time();
			
			if (!isset($time) || $time < $current_time) {

				update_option('datebook_time_check_expired', strtotime("+" . $cron_subscriptions_check . " minutes"));

				// Redirect all emails for demo profiles to admin
				$find_this_email = 'website.com';

				$redirect_demo_emails_to_admin = isset(self::$datebook_options['redirect_demo_emails_to_admin']) && self::$datebook_options['redirect_demo_emails_to_admin'] == 1 ? 1 : 0;

				$admin_email = isset(self::$datebook_options['email_website']) ? self::$datebook_options['email_website'] : get_bloginfo('admin_email');


				// Set expired subscription as pending
				// Get all member subscriptions
				$member_subscriptions = datebook_get_member_subscriptions();

				foreach( $member_subscriptions as $member_subscription ) {

					$expiration_date = isset($member_subscription->expiration_date) && $member_subscription->expiration_date != '0000-00-00 00:00:00' ? strtotime($member_subscription->expiration_date) : '0000-00-00 00:00:00';

					if (!empty($expiration_date) && $expiration_date != '0000-00-00 00:00:00' && $expiration_date < time() && isset($member_subscription->status) && $member_subscription->status == 'pending') {

						// Update subscription as pending
						$member_subscription->update(array('status' => 'canceled'));

					} else if (!empty($expiration_date) && $expiration_date != '0000-00-00 00:00:00' && $expiration_date < time() && isset($member_subscription->status) && ($member_subscription->status == 'active' || $member_subscription->status == 'completed')) {

						// Update subscription as pending
						$member_subscription->update(array('status' => 'expired'));

						// Update profile as private
						$profile_id = isset($member_subscription->payment_profile_id) && $member_subscription->payment_profile_id > 0 ? $member_subscription->payment_profile_id : 0;

						if($profile_id > 0){

							if(isset(self::$datebook_options['deactivate_profile_after_subscription_expires']) && self::$datebook_options['deactivate_profile_after_subscription_expires'] == '1'){
								$post_profile = array( 'ID' => $profile_id, 'post_status' => 'private' );
								wp_update_post( $post_profile );
							}

							$user_id = isset($member_subscription->user_id) && $member_subscription->user_id > 0 ? $member_subscription->user_id : 0;

							if (get_user_meta( $user_id, 'profile_type', true ) == DATEBOOK_POST_TYPE) {

								$profile_data = get_post($profile_id);

								if(isset($profile_data->ID) && $profile_data->ID > 0){

									$to_email = $wpdb->get_var($wpdb->prepare("SELECT `user_email` FROM `" . $wpdb->users . "` WHERE `ID` = %d", $user_id));

									if($redirect_demo_emails_to_admin == 1){
										if(preg_match("~\b{$find_this_email}\b~", $to_email)){
											$to_email = $admin_email;
										}
									}

									$subject_in_email = esc_html__( 'Your Subscription expired', 'datebook' );

									$body = esc_html__( 'Hello', 'datebook' ) . ', ' . $profile_data->post_title . '!<br /><br />';
									$body .= esc_html__( 'Your Subscription has expired.', 'datebook' ) . '<br />';
									if(isset(self::$datebook_options['deactivate_profile_after_subscription_expires']) && self::$datebook_options['deactivate_profile_after_subscription_expires'] == 1){
										$body .= esc_html__( 'Your profile has been deactivated.', 'datebook' ) . '<br /><br />';
									}
									$body .= esc_html__( 'You can subscribe to any subscription plan again by visiting the profile page', 'datebook' ) . ':<br /><a href="' . esc_url(get_permalink($profile_id)) . '">' . esc_url(get_permalink($profile_id)) . '</a>';

									$datebook_mail = DateBook_Utilities::datebook_email_send('', '', $to_email, $subject_in_email, $body);
							
								}
							}
						}
					}
				}
				
				
				$email_sitename = isset(self::$datebook_options['email_sitename']) ? self::$datebook_options['email_sitename'] : '';

		
				// Check for expired Top status
				$expired_topad = $wpdb->get_col($wpdb->prepare("SELECT `post_id` FROM `" . $wpdb->postmeta . "` WHERE `meta_key` = 'topad_ends' AND `meta_value` < %d", $current_time));

				foreach ($expired_topad as $profile_id) {

					update_post_meta($profile_id, 'topad', '0');
					delete_post_meta($profile_id, 'topad_txn_id');
					delete_post_meta($profile_id, 'topad_ends');
					delete_post_meta($profile_id, 'topad_ends_notice');

					$temp_post = get_post($profile_id);
					$post_author = $temp_post->post_author;

					if (get_user_meta( $post_author, 'profile_type', true ) == DATEBOOK_POST_TYPE) {

						$to_email = $wpdb->get_var($wpdb->prepare("SELECT `user_email` FROM `" . $wpdb->users . "` WHERE `ID` = %d", $post_author));

						if($redirect_demo_emails_to_admin == 1){
							if(preg_match("~\b{$find_this_email}\b~", $to_email)){
								$to_email = $admin_email;
							}
						}

						$body = esc_html__( 'Hello', 'datebook' ) . ', ' . $temp_post->post_title . '!<br /><br />' . esc_html__( 'Your Top status has expired and has been removed from your profile.', 'datebook' ) . '.<br />' . esc_html__( 'You can purchase Top status again at any time by visiting the profile page', 'datebook' ) . ':<br /><a href="' . esc_url(get_permalink($profile_id)) . '">' . esc_url(get_permalink($profile_id)) . '</a>';

						$subject_in_email = esc_html__( 'Expiration notice', 'datebook' ) . ' ' . $email_sitename;

						$datebook_mail = DateBook_Utilities::datebook_email_send('', '', $to_email, $subject_in_email, $body);

					}
				}


				// Check for expired Featured status
				$expired_featured = $wpdb->get_col($wpdb->prepare("SELECT `post_id` FROM `".$wpdb->postmeta."` WHERE `meta_key` = 'featured_ends' AND `meta_value` < %d", $current_time));

				foreach ($expired_featured as $profile_id) {

					update_post_meta($profile_id, 'featured', '0');
					delete_post_meta($profile_id, 'featured_txn_id');
					delete_post_meta($profile_id, 'featured_ends');
					delete_post_meta($profile_id, 'featured_ends_notice');

					$temp_post = get_post($profile_id);
					$post_author = $temp_post->post_author;

					if (get_user_meta( $post_author, 'profile_type', true ) == DATEBOOK_POST_TYPE) {

						$to_email = $wpdb->get_var($wpdb->prepare("SELECT `user_email` FROM `" . $wpdb->users . "` WHERE `ID` = %d", $post_author));

						if($redirect_demo_emails_to_admin == 1){
							if(preg_match("~\b{$find_this_email}\b~", $to_email)){
								$to_email = $admin_email;
							}
						}

						$body = esc_html__( 'Hello', 'datebook' ) . ', ' . $temp_post->post_title . '!<br /><br />' . esc_html__( 'Your Featured status has expired and has been removed from your profile.', 'datebook' ) . '.<br />' . esc_html__( 'You can purchase Featured status again at any time by visiting the profile page', 'datebook' ) . ':<br /><a href="' . esc_url(get_permalink($profile_id)) . '">' . esc_url(get_permalink($profile_id)) . '</a>';

						$subject_in_email = esc_html__( 'Expiration notice', 'datebook' ) . ' ' . $email_sitename;

						$datebook_mail = DateBook_Utilities::datebook_email_send(NULL, NULL, $to_email, $subject_in_email, $body);

					}
				}




				/////////////////////////////////////////////////////////////////////
				// Send notice emails for profiles with soon to expire statuses
				/////////////////////////////////////////////////////////////////////

				$send_expire_notification = isset(self::$datebook_options['send_expire_notification']) ? self::$datebook_options['send_expire_notification'] : 0;
		
				if($send_expire_notification > 0){

					// Top status
					$soon_to_expire_topad = $wpdb->get_col($wpdb->prepare("SELECT `post_id` FROM `" . $wpdb->postmeta . "` WHERE `meta_key` = 'topad_ends' AND `meta_value` < %d", strtotime('+' . $send_expire_notification . ' days')));

					foreach ($soon_to_expire_topad as $profile_id) {

						if (get_post_meta($profile_id, 'topad_ends_notice', true) != '1') {

							$temp_post = get_post($profile_id);
							$post_author = $temp_post->post_author;

							if (get_user_meta( $post_author, 'profile_type', true ) == DATEBOOK_POST_TYPE) {	

								$to_email = $wpdb->get_var($wpdb->prepare("SELECT `user_email` FROM `" . $wpdb->users . "` WHERE `ID` = %d", $post_author));

								if($redirect_demo_emails_to_admin == 1){
									if(preg_match("~\b{$find_this_email}\b~", $to_email)){
										$to_email = $admin_email;
									}
								}

								$body = esc_html__( 'Hello', 'datebook' ) . ', ' . $temp_post->post_title . '!<br /><br />' . esc_html__( 'Your Top status will expire very soon.', 'datebook' ) . '.<br />' . esc_html__( 'If you want to renew your status please visit your profile page', 'datebook' ) . ':<br /><a href="' . esc_url(get_permalink($profile_id)) . '">' . esc_url(get_permalink($profile_id)) . '</a>';

								$subject_in_email = esc_html__( 'Expiration notice', 'datebook' ) . ' ' . $email_sitename;

								$datebook_mail = DateBook_Utilities::datebook_email_send(NULL, NULL, $to_email, $subject_in_email, $body);

								add_post_meta($profile_id, 'topad_ends_notice', '1', true);

							}
						}
					}


					// Featured status
					$soon_to_expire_featured = $wpdb->get_col($wpdb->prepare("SELECT `post_id` FROM `" . $wpdb->postmeta . "` WHERE `meta_key` = 'featured_ends' AND `meta_value` < %d", strtotime('+' . $send_expire_notification . ' days')));

					foreach ($soon_to_expire_featured as $profile_id) {

						if (get_post_meta($profile_id, 'featured_ends_notice', true) != '1') {

							$temp_post = get_post($profile_id);
							$post_author = $temp_post->post_author;

							if (get_user_meta( $post_author, 'profile_type', true ) == DATEBOOK_POST_TYPE) {

								$to_email = $wpdb->get_var($wpdb->prepare("SELECT `user_email` FROM `" . $wpdb->users . "` WHERE `ID` = %d", $post_author));

								if($redirect_demo_emails_to_admin == 1){
									if(preg_match("~\b{$find_this_email}\b~", $to_email)){
										$to_email = $admin_email;
									}
								}

								$body = esc_html__( 'Hello', 'datebook' ) . ', ' . $temp_post->post_title . '!<br /><br />' . esc_html__( 'Your Featured status will expire very soon.', 'datebook' ) . '.<br />' . esc_html__( 'If you want to renew your status please visit your profile page', 'datebook' ) . ':<br /><a href="' . esc_url(get_permalink($profile_id)) . '">' . esc_url(get_permalink($profile_id)) . '</a>';

								$subject_in_email = esc_html__( 'Expiration notice', 'datebook' ) . ' ' . $email_sitename;

								$datebook_mail = DateBook_Utilities::datebook_email_send(NULL, NULL, $to_email, $subject_in_email, $body);

								add_post_meta($profile_id, 'featured_ends_notice', '1', true);

							}
						}
					}
				}
			}
		}
	}


	/**
	 * Check all profiles whose Top and Featured statuses expired or are going to expire
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_time_check_expired() {

		self::datebook_check_expired_subscription();

	}


}

// Let's get the party started
//DateBook_Profile_Subscription::init();

$dateBook_profile_subscription = new DateBook_Profile_Subscription($datebook_options_array);