<?php

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

if( !is_plugin_active( 'woocommerce-subscriptions/woocommerce-subscriptions.php' ) ){
	return;
}

class ACUI_WooCommerceSubscriptions{
	private $all_virtual;

	function __construct(){
		add_filter( 'acui_restricted_fields', array( $this, 'restricted_fields' ), 10, 1 );
		add_action( 'acui_header_table_extra_rows', array( $this, 'header_table_extra_rows' ) );
		add_action( 'acui_documentation_after_plugins_activated', array( $this, 'documentation' ) );
		add_action( 'after_acui_import_users', array( $this, 'end' ) );		
		add_action( 'acui_post_import_single_user', array( $this, 'import' ), 10, 3 );

		$this->all_virtual = true;
	}

	function header_table_extra_rows(){
		?>
		<th><?php _e( "WooCommerce Subscriptions import warnings", 'import-users-from-csv-with-meta' ); ?></th>
		<th><?php _e( "WooCommerce Subscriptions import errors", 'import-users-from-csv-with-meta' ); ?></th>
		<?php
	}

	function restricted_fields( $acui_restricted_fields ){
		return array_merge( $acui_restricted_fields, $this->fields() );
	}

	function fields(){
		return array_merge( $this->order_totals_fields(), array( 'subscription_status', 'start_date', 'trial_end_date', 'next_payment_date', 'end_date', 'billing_period', 'billing_interval', 'order_items', 'coupon_items', 'fee_items', 'tax_items', 'order_currency', 'shipping_method', 'download_permissions', 'order_notes', 'payment_method', 'payment_method_title', 'payment_method_post_meta', 'payment_method_user_meta', 'customer_note', 'custom_post_meta', 'custom_user_post_meta' ) );
	}

	function order_totals_fields(){
		return array(
			'order_shipping',
			'order_shipping_tax',
			'cart_discount',
			'cart_discount_tax',
			'order_total',
			'order_tax',
		);
	}

	function user_meta_fields(){
		return array(
			'billing_first_name', // Billing Address Info
			'billing_last_name',
			'billing_company',
			'billing_address_1',
			'billing_address_2',
			'billing_city',
			'billing_state',
			'billing_postcode',
			'billing_country',
			'billing_email',
			'billing_phone',

			'shipping_first_name', // Shipping Address Info
			'shipping_last_name',
			'shipping_company',
			'shipping_address_1',
			'shipping_address_2',
			'shipping_city',
			'shipping_state',
			'shipping_postcode',
			'shipping_country',
		);
	}

	function documentation(){
	?>
		<tr valign="top">
			<th scope="row"><?php _e( "WooCommerce Subscriptions is activated", 'import-users-from-csv-with-meta' ); ?></th>
			<td>
				<ol>
					<li><?php _e( 'You can import subscriptions with their info', 'import-users-from-csv-with-meta' ); ?>.</li>
					<li><?php printf( __( 'Data format: use the column names <a href="%1$s">described here</a>, except the ones unused because we have our own:', 'import-users-from-csv-with-meta' ), "https://github.com/woocommerce/woocommerce-subscriptions-importer-exporter#csv-columns" ); ?> customer_id, customer_email and customer_username.</li>
					<li><?php printf( __( 'Download <a href="%1$s">this sample file</a> to see how it works', 'import-users-from-csv-with-meta' ), esc_url( plugins_url( 'samples/wcs-import-sample.csv', dirname( __FILE__ ) ) ) ); ?>.</li>
					<li><?php printf( __( 'This subscription importer is based in the official <a href="%1$s">WooCommerce Subscription Importer Exporter</a>.', 'import-users-from-csv-with-meta' ), "https://github.com/woocommerce/woocommerce-subscriptions-importer-exporter" ); ?></li>
				</ol>
			</td>
		</tr>
		<?php
	}

	function end(){
		$this->add_order_key_post_meta_if_missing();
	}

	function add_order_key_post_meta_if_missing() {
		global $wpdb;

		// Get the post_ids of the subscriptions whose order_key post meta is NULL or empty or missing
		$subscription_ids_needing_order_key = $wpdb->get_results( "
			SELECT ID FROM {$wpdb->prefix}posts WHERE
				post_type = 'shop_subscription'
					AND
				ID NOT IN (
					SELECT post_id FROM {$wpdb->prefix}postmeta WHERE
						meta_key = '_order_key'
							AND
						meta_value IS NOT NULL
							AND
						meta_value <> ''
				)
					AND
				post_status IN ( '" . implode( "','", array_keys( wcs_get_subscription_statuses() ) ) . "' )"
		);

		//Set the order_key post meta for each of them
		foreach( $subscription_ids_needing_order_key as $key => $post ) {
			update_post_meta( $post->ID, '_order_key', uniqid( 'order_' ) );
		}
	}

	function import( $headers, $row, $user_id ){
		foreach ( $this->fields() as $key ) {
			$pos = array_search( $key, $headers );

			if( $pos !== FALSE ){
				$columns[ $key ] = $pos;
				$data[ $key ] = $row[ $columns[ $key ] ];
			}
		}

		global $wpdb;

		$set_manual = $requires_manual_renewal = false;
		$post_meta  = $order_items = array();
		$result     = array(
			'warning'    => array(),
			'error'      => array(),
			'items'      => '',
		);
		
		$missing_shipping_addresses = $missing_billing_addresses = array();

		foreach ( array_merge( $this->order_totals_fields(), $this->user_meta_fields(), array( 'payment_method' ) ) as $column ) {
			switch ( $column ) {
				case 'cart_discount':
				case 'cart_discount_tax':
				case 'order_shipping':
				case 'order_shipping_tax':
				case 'order_total':
					$value       = ( ! empty( $data[ $column ] ) ) ? $data[ $column ] : 0;
					$post_meta[] = array( 'key' => '_' . $column, 'value' => $value );
					break;

				case 'payment_method':
					$payment_method = ( ! empty( $data[ $column ] ) ) ? strtolower( $data[ $column ] ) : '';
					$title          = ( ! empty( $data[ 'payment_method_title' ] ) ) ? $data[ 'payment_method_title' ] : $payment_method;

					if ( ! empty( $payment_method ) && 'manual' != $payment_method ) {
						$post_meta[] = array( 'key' => '_' . $column, 'value' => $payment_method );
						$post_meta[] = array( 'key' => '_payment_method_title', 'value' => $title );
					} else {
						$set_manual = true;
					}

					if ( ! empty( $data[ 'requires_manual_renewal'] ) && 'true' == $data[ 'requires_manual_renewal'] ) {
						$requires_manual_renewal = true;
					}
					break;

				case 'shipping_address_1':
				case 'shipping_city':
				case 'shipping_postcode':
				case 'shipping_state':
				case 'shipping_country':
				case 'billing_address_1':
				case 'billing_city':
				case 'billing_postcode':
				case 'billing_state':
				case 'billing_country':
				case 'billing_phone':
				case 'billing_company':
				case 'billing_email':
					$value = ( ! empty( $data[ $column ] ) ) ? $data[ $column ] : '';

					if ( empty( $value ) ) {
						$metadata = get_user_meta( $user_id, $column );
						$value    = ( ! empty( $metadata[0] ) ) ? $metadata[0] : '';
					}

					if ( empty( $value ) && 'billing_email' == $column ) {
						$value = ( ! empty( $data[ 'customer_email'] ) ) ? $data[ 'customer_email'] : get_userdata( $user_id )->user_email;
					}

					if ( empty( $value ) ) {
						if ( 0 === strpos( $column, 'billing_' ) ) {
							$missing_billing_addresses[] = $column;
						} else {
							$missing_shipping_addresses[] = $column;
						}
					}

					$post_meta[] = array( 'key' => '_' . $column, 'value' => $value );
					break;

				default:
					$value       = ( ! empty( $data[ $column ] ) ) ? $data[ $column ] : '';
					$post_meta[] = array( 'key' => '_' . $column, 'value' => $value );
			}
		}

		if ( empty( $data[ 'subscription_status'] ) ) {
			$status              = 'pending';
			$result['warning'][] = esc_html__( 'No subscription status was specified. The subscription will be created with the status "pending". ', 'import-users-from-csv-with-meta' );
		} else {
			$status = ( 'wc-' === substr( $data[ 'subscription_status'], 0, 3 ) ) ? substr( $data[ 'subscription_status'], 3 ) : $data[ 'subscription_status'];
		}

		$dates_to_update = array( 'start' => ( ! empty( $data[ 'start_date'] ) ) ? gmdate( 'Y-m-d H:i:s', strtotime( $data[ 'start_date'] ) ) : gmdate( 'Y-m-d H:i:s', time() - 1 ) );

		foreach ( array( 'trial_end_date', 'next_payment_date', 'end_date', 'last_payment_date' ) as $date_type ) {
			$dates_to_update[ $date_type ] = ( ! empty( $data[  $date_type ] ) ) ? gmdate( 'Y-m-d H:i:s', strtotime( $data[  $date_type ] ) ) : '';
		}

		foreach ( $dates_to_update as $date_type => $datetime ) {

			if ( empty( $datetime ) ) {
				continue;
			}

			switch ( $date_type ) {
				case 'end_date' :
					if ( ! empty( $dates_to_update['next_payment_date'] ) && strtotime( $datetime ) <= strtotime( $dates_to_update['next_payment_date'] ) ) {
						$result['error'][] = sprintf( __( 'The %s date must occur after the next payment date.', 'import-users-from-csv-with-meta' ), $date_type );
					}
				case 'next_payment_date' :
					if ( ! empty( $dates_to_update['trial_end_date'] ) && strtotime( $datetime ) < strtotime( $dates_to_update['trial_end_date'] ) ) {
						$result['error'][] = sprintf( __( 'The %s date must occur after the trial end date.', 'import-users-from-csv-with-meta' ), $date_type );
					}
				case 'trial_end_date' :
					if ( strtotime( $datetime ) <= strtotime( $dates_to_update['start'] ) ) {
						$result['error'][] = sprintf( __( 'The %s must occur after the start date.', 'import-users-from-csv-with-meta' ), $date_type );
					}
			}
		}

		// make the sure end of prepaid term exists for subscription that are about to be set to pending-cancellation - continue to use the next payment date if that exists
		if ( 'pending-cancel' == $status && ( empty( $dates_to_update['next_payment_date'] ) || strtotime( $dates_to_update['next_payment_date'] ) < current_time( 'timestamp', true ) ) ) {
			if ( ! empty( $dates_to_update['end_date'] ) && strtotime( $dates_to_update['end_date'] ) > current_time( 'timestamp', true ) ) {
				$dates_to_update['next_payment_date'] = $dates_to_update['end_date'];
				unset( $dates_to_update['end_date'] );
			} else {
				$result['error'][] = __( 'Importing a pending cancelled subscription requires an end date in the future.', 'import-users-from-csv-with-meta' );
			}
		}

		if ( empty( $result['error'] ) ) {
			try {
				$wpdb->query( 'START TRANSACTION' );

				if( !function_exists( 'wcs_create_subscription' ) ){
					require_once( WP_PLUGIN_DIR . '/woocommerce-subscriptions/wcs-functions.php' );
				}

				$subscription = wcs_create_subscription( array(
						'customer_id'      => $user_id,
						'start_date'       => $dates_to_update['start'],
						'billing_interval' => ( ! empty( $data[ 'billing_interval'] ) ) ? $data[ 'billing_interval'] : 1,
						'billing_period'   => ( ! empty( $data[ 'billing_period'] ) ) ? $data[ 'billing_period'] : '',
						'created_via'      => 'importer',
						'customer_note'    => ( ! empty( $data[ 'customer_note'] ) ) ? $data[ 'customer_note'] : '',
						'currency'         => ( ! empty( $data[ 'order_currency'] ) ) ? $data[ 'order_currency'] : '',
					)
				);

				if ( is_wp_error( $subscription ) ) {
					throw new Exception( sprintf( esc_html__( 'Could not create subscription: %s', 'import-users-from-csv-with-meta' ), $subscription->get_error_message() ) );
				}

				$subscription_id = version_compare( WC()->version, '3.0', '>=' ) ? $subscription->get_id() : $subscription->id;

				foreach ( $post_meta as $meta_data ) {
					update_post_meta( $subscription_id, $meta_data['key'], $meta_data['value'] );
				}

				if( !empty( $data['custom_post_meta'] ) ){
					foreach ( $data['custom_post_meta'] as $meta_key ) {
						if ( ! empty( $data[ $meta_key ] ) ) {
							update_post_meta( $subscription_id, $meta_key, $data[ $meta_key ] );
						}
					}
				}

				if( !empty( $data['custom_user_post_meta'] ) ){
					foreach ( $data['custom_user_post_meta'] as $meta_key ) {
						if ( ! empty( $data[ $meta_key ] ) ) {
							update_post_meta( $subscription_id, $meta_key, $data[ $meta_key ] );
							update_user_meta( $user_id, $meta_key, $data[ $meta_key ] );
						}
					}
				}
				
				// Now that we've set all the meta data, reinit the object so the data is set
				$subscription = wcs_get_subscription( $subscription_id );

				$subscription->update_dates( $dates_to_update );

				if ( ! $set_manual && ! in_array( $status, wcs_get_subscription_ended_statuses() ) ) { // don't bother trying to set payment meta on a subscription that won't ever renew
					$result['warning'] = array_merge( $result['warning'], $this->set_payment_meta( $subscription, $data ) );
				}

				if ( $set_manual || $requires_manual_renewal ) {
					$subscription->set_requires_manual_renewal( true );
				}

				if ( ! empty( $data[ 'order_notes'] ) ) {
					$order_notes = explode( ';', $data[ 'order_notes'] );

					foreach ( $order_notes as $order_note ) {
						$subscription->add_order_note( $order_note );
					}
				}

				if ( $set_manual ) {
					$result['warning'][] = esc_html__( 'No payment method was given in the CSV and so the subscription has been set to manual renewal.', 'import-users-from-csv-with-meta' );
				} else if ( $requires_manual_renewal ) {
					$result['warning'][] = esc_html__( 'Import forced manual renewal.', 'import-users-from-csv-with-meta' );
				}

				if ( ! empty( $data[ 'coupon_items'] ) ) {
					$this->add_coupons( $subscription, $data );
				}

				$chosen_tax_rate_id = 0;
				if ( ! empty( $data[ 'tax_items'] ) ) {
					$chosen_tax_rate_id = $this->add_taxes( $subscription, $data );
				}

				if ( ! empty( $data[ 'order_items'] ) ) {
					if ( is_numeric( $data[ 'order_items'] ) ) {
						$product_id      = absint( $data[ 'order_items'] );
						$result['items'] = $this->add_product( $subscription, array( 'product_id' => $product_id ), $chosen_tax_rate_id );
						$order_items[]   = $product_id;
					} else {
						$order_items_row = explode( ';', $data[ 'order_items'] );

						if ( ! empty( $order_items_row ) ) {
							foreach ( $order_items_row as $order_item ) {
								$item_data = array();

								foreach ( explode( '|', $order_item ) as $item ) {
									list( $name, $value ) = explode( ':', $item );
									$item_data[ trim( $name ) ] = trim( $value );
								}

								$result['items'] .= $this->add_product( $subscription, $item_data, $chosen_tax_rate_id ) . '<br/>';
								$order_items[]    = $item_data['product_id'];
							}
						}
					}
				}

				if ( ! empty( $data[ 'fee_items'] ) ) {
					$this->add_fees( $subscription, $data, $chosen_tax_rate_id );
				}

				if ( ! empty( $data[ 'shipping_method'] ) ) {
					$shipping_method = $this->add_shipping_lines( $subscription, $data, $chosen_tax_rate_id );
				}

				// only show the following warnings on the import when the subscription requires shipping
				if ( ! $this->all_virtual ) {
					if ( ! empty( $missing_shipping_addresses ) ) {
						$result['warning'][] = sprintf( esc_html__( 'The following shipping address fields have been left empty: %s. ', 'import-users-from-csv-with-meta' ), rtrim( implode( ', ', $missing_shipping_addresses ), ',' ) );
					}

					if ( ! empty( $missing_billing_addresses ) ) {
						$result['warning'][] = sprintf( esc_html__( 'The following billing address fields have been left empty: %s. ', 'import-users-from-csv-with-meta' ), rtrim( implode( ', ', $missing_billing_addresses ), ',' ) );
					}

					if ( empty( $shipping_method ) ) {
						$result['warning'][] = esc_html__( 'Shipping method and title for the subscription have been left empty.', 'import-users-from-csv-with-meta' );
					}
				}
				
				add_filter( 'woocommerce_can_subscription_be_updated_to_cancelled', '__return_true' );
				add_filter( 'woocommerce_can_subscription_be_updated_to_pending-cancel', '__return_true' );

				$subscription->update_status( $status );

				remove_filter( 'woocommerce_can_subscription_be_updated_to_cancelled', '__return_true' );
				remove_filter( 'woocommerce_can_subscription_be_updated_to_pending-cancel', '__return_true' );

				foreach ( $order_items as $product_id ) {
					$this->maybe_add_memberships( $user_id, $subscription->id, $product_id );
				}
			
				$subscription->save();
				
				$wpdb->query( 'COMMIT' );

			} catch ( Exception $e ) {
				$wpdb->query( 'ROLLBACK' );
				$result['error'][] = $e->getMessage();
			}
		}

		if ( empty( $result['error'] ) ) {
			$result['status']              = 'success';
			$result['subscription']        = sprintf( '<a href="%s">#%s</a>', esc_url( admin_url( 'post.php?post=' . absint( $subscription_id ) . '&action=edit' ) ), $subscription->get_order_number() );
			$result['subscription_status'] = $subscription->get_status();

		}

		// print result
		if( !empty( $result['warning'] ) ){
			foreach ( $result['warning'] as $warning ) {
				echo "<td>" . $warning . "</td>";
			}
		}
		else{
			echo "<td></td>";
		}

		if( !empty( $result['error'] ) ){
			foreach ( $result['error'] as $error ) {
				echo "<td>" . $error . "</td>";
			}
		}
		else{
			echo "<td></td>";
		}		
	}

	function set_payment_meta( $subscription, $data ) {
		$warnings         = array();
		$payment_gateways = WC()->payment_gateways->get_available_payment_gateways();
		$subscription_id  = version_compare( WC()->version, '3.0', '>=' ) ? $subscription->get_id() : $subscription->id;
		$payment_method   = version_compare( WC()->version, '3.0', '>=' ) ? $subscription->get_payment_method() : $subscription->payment_method;

		if ( ! empty( $payment_method ) ) {
			$payment_method_table = apply_filters( 'woocommerce_subscription_payment_meta', array(), $subscription );
			$payment_gateway      = ( isset( $payment_gateways[ $payment_method ] ) ) ? $payment_gateways[ $payment_method ] : '';

			if ( ! empty( $payment_gateway ) && isset( $payment_method_table[ $payment_gateway->id ] ) ) {
				$payment_post_meta = $payment_user_meta = array();

				if ( ! empty( $data[ 'payment_method_post_meta'] ) ) {
					foreach ( explode( '|', $data[ 'payment_method_post_meta'] ) as $meta ) {
						list( $name, $value ) = explode( ':', $meta );
						$payment_post_meta[ trim( $name ) ] = trim( $value );
					}
				}

				if ( ! empty( $data[ 'payment_method_user_meta'] ) ) {
					foreach ( explode( '|', $data[ 'payment_method_user_meta'] ) as $meta ) {
						list( $name, $value ) = explode( ':', $meta );
						$payment_user_meta[ trim( $name ) ] = trim( $value );
					}
				}

				$payment_method_data = $payment_method_table[ $payment_gateway->id ];
				$meta_set            = false;

				foreach ( $payment_method_data as $meta_table => &$meta ) {
					if ( ! is_array( $meta ) ) {
						continue;
					}

					foreach ( $meta as $meta_key => &$meta_data ) {
						switch ( $meta_table ) {
							case 'post_meta':
							case 'postmeta':
								$value = ( ! empty( $payment_post_meta[ $meta_key ] ) ) ? $payment_post_meta[ $meta_key ] : '';
								break;
							case 'user_meta':
							case 'usermeta':
								$value = ( ! empty( $payment_user_meta[ $meta_key ] ) ) ? $payment_user_meta[ $meta_key ] : '';
								break;
							default :
								$value = '';
						}

						if ( ! empty( $value ) ) {
							$meta_data['value'] = $value;
							$meta_set = true;
						}
					}
				}

				if ( $meta_set ) {
					// Reload the subscription to update the meta values.
					$subscription  = wcs_get_subscription( $subscription->get_id() );
					$subscription->set_payment_method( $payment_gateway, $payment_method_data );
					$subscription->save();
				} else {
					$warnings[] = sprintf( esc_html__( 'No payment meta was set for your %1$s subscription (%2$s). The next renewal is going to fail if you leave this as-is.', 'import-users-from-csv-with-meta' ), $payment_method, $subscription_id );
				}
			} else {
				if ( 'paypal' == $payment_method ) {
					$warnings[] = sprintf( esc_html__( 'Could not set payment method as PayPal, defaulted to manual renewal. Either PayPal was not enabled or your PayPal account does not have Reference Transaction set up. Learn more about enabling Reference Transactions %1$shere%2$s.', 'import-users-from-csv-with-meta' ), '<a href="https://support.woocommerce.com/hc/en-us/articles/205151193-PayPal-Reference-Transactions-for-Subscriptions">', '</a>' );
				} else {
					$warnings[] = sprintf( esc_html__( 'The payment method "%s" is either not enabled or does not support the new features of Subscriptions 2.0 and can not be properly attached to your subscription. This subscription has been set to manual renewal.', 'import-users-from-csv-with-meta' ), $payment_method );
				}
				$subscription->set_requires_manual_renewal( true );
			}
		}
		return $warnings;
	}

	function save_download_permissions( $subscription, $product, $quantity = 1 ) {

		if ( $product && $product->exists() && $product->is_downloadable() ) {
			$downloads = $product->get_downloads();

			foreach ( array_keys( $downloads ) as $download_id ) {
				wc_downloadable_file_permission( $download_id, $product->get_id(), $subscription, $quantity );
			}
		}
	}

	function maybe_add_memberships( $user_id, $subscription_id, $product_id ) {
		if ( function_exists( 'wc_memberships_get_membership_plans' ) ) {
			$membership_plans = wc_memberships_get_membership_plans();

			foreach ( $membership_plans as $plan ) {
				if ( $plan->has_product( $product_id ) ) {
					$plan->grant_access_from_purchase( $user_id, $product_id, $subscription_id );
				}

				// if the product is a variation we want to also check if the parent variable product has any plans as well and add them
				$product   = wc_get_product( $product_id );
				$parent_id = wcs_get_objects_property( $product, 'parent_id' );
				if ( $product && $product->is_type( 'variation' ) && ! empty( $parent_id ) && $plan->has_product( $parent_id ) ) {
					$plan->grant_access_from_purchase( $user_id, $product->parent->id, $subscription_id );
				}
			}
		}
	}

	function add_coupons( $subscription, $data ) {
		$coupon_items = explode( ';', $data[ 'coupon_items'] );

		if ( ! empty( $coupon_items ) ) {
			foreach ( $coupon_items as $coupon_item ) {
				$coupon_data = array();

				foreach ( explode( '|', $coupon_item ) as $item ) {
					list( $name, $value ) = explode( ':', $item );
					$coupon_data[ trim( $name ) ] = trim( $value );
				}

				$coupon_code = isset( $coupon_data['code'] ) ? $coupon_data['code'] : '';
				$coupon      = new WC_Coupon( $coupon_code );

				if ( ! $coupon ) {
					throw new Exception( sprintf( esc_html__( 'Could not find coupon with code "%s" in your store.', 'import-users-from-csv-with-meta' ), $coupon_code ) );
				} elseif ( isset( $coupon_data['amount'] ) ) {
					$discount_amount = floatval( $coupon_data['amount'] );
				} else {
					$discount_amount = version_compare( WC()->version, '3.0', '>=' ) ? $coupon->get_discount_amount( 0 ) : $coupon->discount_amount;
				}


				$coupon_line_item = new WC_Order_Item_Coupon();
				$coupon_line_item->set_props( array(
					'code'         => $coupon_code,
					'discount'     => $discount_amount,
					'discount_tax' => 0,
					'order_id'     => $subscription->get_id(),
				) );
				$coupon_line_item->save();
				$subscription->add_item( $coupon_line_item );
				$coupon_id =  $coupon_line_item->get_id();

				if ( ! $coupon_id ) {
					throw new Exception( sprintf( esc_html__( 'Coupon "%s" could not be added to the subscription.', 'import-users-from-csv-with-meta' ), $coupon_code ) );
				}
			}
		}
	}

	function add_product( $subscription, $data, $chosen_tax_rate_id ) {
		$item_args        = array();
		$item_args['qty'] = isset( $data['quantity'] ) ? $data['quantity'] : 1;

		if ( ! isset( $data['product_id'] ) ) {
			throw new Exception( __( 'The product_id is missing from the CSV.', 'import-users-from-csv-with-meta' ) );
		}

		$_product = wc_get_product( $data['product_id'] );

		if ( ! $_product ) {
			throw new Exception( sprintf( __( 'No product or variation in your store matches the product ID #%s.', 'import-users-from-csv-with-meta' ), $data['product_id'] ) );
		}

		$_product_id    = version_compare( WC()->version, '3.0', '>=' ) ? $_product->get_id() : $_product->id;
		$line_item_name = ( ! empty( $data['name'] ) ) ? $data['name'] : $_product->get_title();
		$product_string = sprintf( '<a href="%s">%s</a>', get_edit_post_link( $_product_id ), $line_item_name );

		foreach ( array( 'total', 'tax', 'subtotal', 'subtotal_tax' ) as $line_item_data ) {

			switch ( $line_item_data ) {
				case 'total' :
					$default = WC_Subscriptions_Product::get_price( $data['product_id'] );
					break;
				case 'subtotal' :
					$default = ( ! empty( $data['total'] ) ) ? $data['total'] : WC_Subscriptions_Product::get_price( $data['product_id'] );
					break;
				default :
					$default = 0;
			}
			$item_args['totals'][ $line_item_data ] = ( ! empty( $data[ $line_item_data ] ) ) ? $data[ $line_item_data ] : $default;
		}

		// Add this site's variation meta data if no line item meta data was specified in the CSV
		if ( empty( $data['meta'] ) && $_product->is_type( 'variable' ) ) {
			$_product_variation_data = version_compare( WC()->version, '3.0', '>=' ) ? $_product->get_available_variations() : $_product->variation_data;

			$item_args['variation'] = array();

			foreach ( $_product_variation_data as $attribute => $variation ) {
				$item_args['variation'][ $attribute ] = $variation;
			}
			$product_string .= ' [#' . $data['product_id'] . ']';
		}

		if ( $this->all_virtual && ! $_product->is_virtual() ) {
			$this->all_virtual = false;
		}

		if ( ! empty( $item_args['totals']['tax'] ) && ! empty( $chosen_tax_rate_id ) ) {
			$item_args['totals']['tax_data']['total']    = array( $chosen_tax_rate_id => $item_args['totals']['tax'] );
			$item_args['totals']['tax_data']['subtotal'] = array( $chosen_tax_rate_id => $item_args['totals']['tax'] );
		}

		$item_id = $subscription->add_product( $_product, $item_args['qty'], $item_args );

		// Set the name used in the CSV if it's different to the product's current title (which is what WC_Abstract_Order::add_product() uses)
		if ( ! empty( $data['name'] ) && $_product->get_title() != $data['name'] ) {
			wc_update_order_item( $item_id, array( 'order_item_name' => $data['name'] ) );
		}

		// Add any meta data for the line item
		if ( ! empty( $data['meta'] ) ) {
			foreach ( explode( '+', $data['meta'] ) as $meta ) {
				$meta = explode( '=', $meta );
				wc_update_order_item_meta( $item_id, $meta[0], $meta[1] );
			}
		}

		if ( ! $item_id ) {
			throw new Exception( __( 'An unexpected error occurred when trying to add product "%s" to your subscription. The error was caught and no subscription for this row will be created. Please fix the data from your CSV and try again.', 'import-users-from-csv-with-meta' ) );
		}

		if ( ! empty( $data[ 'download_permissions'] ) && ( 'true' == $data[ 'download_permissions'] || 1 == (int) $data[ 'download_permissions'] ) ) {
			$this->save_download_permissions( $subscription, $_product, $item_args['qty'] );
		}

		return $product_string;
	}

	function add_fees( $subscription, $data, $chosen_tax_rate_id ) {
		$fee_items = explode( ';', $data[ 'fee_items'] );

		if ( ! empty( $fee_items ) ) {
			foreach ( $fee_items as $fee_item ) {
				$fee_data = array();

				foreach ( explode( '|', $fee_item ) as $item ) {
					list( $name, $value ) = explode( ':', $item );
					$fee_data[ trim( $name ) ] = trim( $value );
				}

				if ( empty( $fee_data['name'] ) ) {
					throw new Exception( __( 'Fee name is missing from your CSV. This subscription has not been imported.', 'import-users-from-csv-with-meta' ) );
				}

				$fee            = new stdClass();
				$fee->id        = sanitize_title( $fee_data['name'] );
				$fee->name      = $fee_data['name'];
				$fee->amount    = isset( $fee_data['total'] ) ? floatval( $fee_data['total'] ) : 0;
				$fee->taxable   = false;
				$fee->tax       = 0;
				$fee->tax_data  = array();
				$fee->tax_class = 0;

				if ( ! empty( $fee_data['tax'] ) ) {
					$fee->tax       = wc_format_decimal( $fee_data['tax'] );
					$fee->tax_class = ( ! empty( $fee_data['tax_class'] ) ) ? $fee_data['tax_class'] : 0;
					$fee->taxable   = true;

					if ( ! empty( $chosen_tax_rate_id ) ) {
						$fee->tax_data = array( 'total' => array( $chosen_tax_rate_id => $fee->tax ), 'subtotal' => array( $chosen_tax_rate_id => $fee->tax ) );
					}
				}


				$fee_line_item = new WC_Order_Item_Fee();
				$fee_line_item->set_props( array(
					'name'      => $fee->name,
					'tax_class' => $fee->taxable ? $fee->tax_class : 0,
					'total'     => $fee->amount,
					'total_tax' => $fee->tax,
					'taxes'     => array(
						'total' => $fee->tax_data,
					),
					'order_id'  => $subscription->get_id(),
				) );
				$fee_line_item->save();
				$subscription->add_item( $fee_line_item );

				$fee_id = $fee_line_item->get_id();

				if ( ! $fee_id ) {
					throw new Exception( __( 'Could not add the fee to your subscription. The subscription has not been imported.', 'import-users-from-csv-with-meta' ) );
				}
			}
		}
	}

	function add_shipping_lines( $subscription, $data, $chosen_tax_rate_id ) {
		$shipping_items   = explode( ';', $data[ 'shipping_method'] );
		$shipping_method  = '';
		$default_total    = ( ! empty( $data[ 'order_shipping'] ) ) ? $data[ 'order_shipping'] : 0;

		if ( ! empty( $shipping_items ) ) {
			foreach ( $shipping_items as $shipping_item ) {
				$shipping_line = array();

				if ( false !== strpos( $shipping_item, ':' ) ) {
					foreach ( explode( '|', $shipping_item ) as $item ) {
						list( $name, $value ) = explode( ':', $item );
						$shipping_line[ trim( $name ) ] = trim( $value );
					}
				} else {
					$shipping_line['method_id'] = $shipping_item;
				}

				$shipping_method = isset( $shipping_line['method_id'] ) ? $shipping_line['method_id'] : '';
				$shipping_title  = isset( $shipping_line['method_title'] ) ? $shipping_line['method_title'] : $shipping_method;
				$shipping_rate = new WC_Shipping_Rate( $shipping_method, $shipping_title, isset( $shipping_line['total'] ) ? floatval( $shipping_line['total'] ) : $default_total, array(), $shipping_method );

				if ( ! empty( $data[ 'order_shipping_tax'] ) && ! empty( $chosen_tax_rate_id ) ) {
					$shipping_rate->taxes = array( $chosen_tax_rate_id => $data[ 'order_shipping_tax'] );
				}

				$shipping_line_item = new WC_Order_Item_Shipping();
				$shipping_line_item->set_props( array(
					'method_title' => $shipping_rate->label,
					'method_id'    => $shipping_rate->id,
					'total'        => wc_format_decimal( $shipping_rate->cost ),
					'taxes'        => $shipping_rate->taxes,
					'order_id'     => $subscription->get_id(),
				) );
				foreach ( $shipping_rate->get_meta_data() as $key => $value ) {
					$shipping_line_item->add_meta_data( $key, $value, true );
				}
				$shipping_line_item->save();
				$subscription->add_item( $shipping_line_item );
				wc_do_deprecated_action( 'woocommerce_order_add_shipping', array( $subscription->get_id(), $shipping_line_item->get_id(), $shipping_rate ), '3.0', 'woocommerce_new_order_item action instead.' );
				$shipping_id = $shipping_line_item->get_id();

				if ( ! $shipping_id ) {
					throw new Exception( __( 'An error occurred when trying to add the shipping item to the subscription. A subscription has not been created for this row.', 'import-users-from-csv-with-meta' ) );
				}

				update_post_meta( $subscription->get_id(), '_shipping_method', $shipping_method );
				update_post_meta( $subscription->get_id(), '_shipping_method_title', $shipping_title );
			}
		}

		return $shipping_method;
	}

	function add_taxes( $subscription, $data ) {
		global $wpdb;

		$tax_items          = explode( ';', $data[ 'tax_items'] );
		$chosen_tax_rate_id = 0;

		if ( ! empty( $tax_items ) ) {
			foreach ( $tax_items as $tax_item ) {
				$tax_data = array();

				if ( false !== strpos( $tax_item, ':' ) ) {
					foreach ( explode( '|', $tax_item ) as $item ) {
						list( $name, $value ) = explode( ':', $item );
						$tax_data[ trim( $name ) ] = trim( $value );
					}
				} elseif ( 1 == count( $tax_items ) ) {
					if ( is_numeric( $tax_item ) ) {
						$tax_data['id'] = $tax_item;
					} else {
						$tax_data['code'] = $tax_item;
					}
				}

				if ( ! empty( $tax_data['id'] ) ) {
					$tax_rate = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_id = %s", $tax_data['id'] ) );
				} elseif ( ! empty( $tax_data['code'] ) ) {
					$tax_rate = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_name = %s ORDER BY tax_rate_priority LIMIT 1", $tax_data['code'] ) );
				} else {
					$result['warning'][] = sprintf( esc_html__( 'Missing tax code or ID from column: %s', 'import-users-from-csv-with-meta' ), $data['tax_items'] );
				}

				if ( ! empty( $tax_rate ) ) {
					$tax_rate = array_pop( $tax_rate );

					$tax_line_item = new WC_Order_Item_Tax();
					$tax_line_item->set_props( array(
						'rate_id'            => $tax_rate->tax_rate_id,
						'tax_total'          => ( ! empty( $data[ 'order_tax'] ) ) ? $data[ 'order_tax'] : 0,
						'shipping_tax_total' => ( ! empty( $data[ 'order_shipping_tax'] ) ) ? $data[ 'order_shipping_tax'] : 0,
					) );
					$tax_line_item->set_rate( $tax_rate->tax_rate_id );
					$tax_line_item->set_order_id( $subscription->get_id() );
					$tax_line_item->save();
					$subscription->add_item( $tax_line_item );
					$tax_id = $tax_line_item->get_id();

					$chosen_tax_rate_id = $tax_rate->tax_rate_id;
				}
			}
		}

		return $chosen_tax_rate_id;
	}
}
new ACUI_WooCommerceSubscriptions();