woocommerce-subscriptions.php 32.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
<?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( 'post_acui_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="%s">described here</a>, except the ones that are not used because we have the own ones:', '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="%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="%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 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 as 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.', '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 renewals. Either PayPal was not enabled or your PayPal account does not have Reference Transaction setup. 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 renewals.', '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 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 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 up 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 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();