<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}




// Required to detect if HPOS is enabled or not.
use Automattic\WooCommerce\Utilities\OrderUtil;




/**
 * Helper function to echo the user Display Name according to the "Customer Display Name" admin setting.
 * 
 * ----------
 * Parameters
 * ----------
 *
 *	$user_id	int 	The ID of the user we want to get/echo the display name
 *	$email		bool	Whether to display the user email (default: true)
 *
 * ------
 * Return
 * ------
 *
 *	The processed string.
 *
 * ---------------
 * Usage and Notes
 * ---------------
 *
 *	The function itself wraps the Display Name and the Email in two separate <span> tags, each with a class, for styling purpose.
 *	For this reason, the output of this function should NOT be escaped using esc_html(), but using wp_kses() as in the example below:
 *
 *		echo wp_kses( 
 *			sfwc_get_customer_display_name( $user_id, true ), 
 *			array(
 *				'span' => array(
 *					'class' => array()
 *				)
 *			) 
 *		);
 *
 *
 *	However it is possible to completely strip HTML tags, as in the example below:
 *
 *		echo esc_html( wp_strip_all_tags( sfwc_get_customer_display_name( $child_id, true ) ) );
 * 
 *
 * 	Also, this function is filterable so that it's possible to customize the display name output.
 * 	E.g.
 *
 *		function customize_display_name( $display_name, $user ) {
 *			return esc_html( $user->billing_company ) . ' (ID: ' .  esc_html( $user->ID ) . ')';
 *		}
 *		add_filter( 'sfwc_change_display_name', 'customize_display_name', 10, 2 );
 *
 *
 * @since 2.0.0
 */
function sfwc_get_customer_display_name( $user_id, $email = true ) {
	
	// Get options.
	$sfwc_options = (array) get_option('sfwc_options');
	
	// Get 'Customer Display Name' from Options settings.
	$sfwc_option_display_name = ( isset( $sfwc_options['sfwc_option_display_name'] ) ) ? $sfwc_options['sfwc_option_display_name'] : 'username';
	
	if( ! $user_id )
		return;
	
	$user_id = absint( $user_id );
	
	// Get the user object.
	$user = get_userdata( $user_id );

	// If no Billing Email is set, use Email of the user as a fallback.
	$user_email = '' !== $user->billing_email ? $user->billing_email : $user->user_email;

	
	if ( ( $sfwc_option_display_name == 'full_name' ) && ( $user->user_firstname || $user->user_lastname ) ) {
		$display_name = '<span class="sfwc-display-name">' . esc_html( $user->user_firstname ) . ' ' . esc_html( $user->user_lastname ) . '</span>';
	} elseif ( ( $sfwc_option_display_name == 'company_name' ) && ( $user->billing_company ) ) {
		$display_name = '<span class="sfwc-display-name">' . esc_html( $user->billing_company ) . '</span>';
	} else {
		$display_name = '<span class="sfwc-display-name">' . esc_html( $user->user_login )  . '</span>';
	}
	
	$display_name .= $email === true ?  ' <span class="sfwc-email">(' . esc_html( $user_email ) . ')</span>' : '';
	
	/**
	 * Filter hook: sfwc_change_display_name.
	 *
	 * Allow developers to change the output of the Customer Display Name.
	 *
	 * @param	string	$display_name	Customer Display Name.
	 * @since	2.0.0
	 */			
	$display_name = apply_filters( 'sfwc_change_display_name', $display_name, $user );
	
	return $display_name;
}



/**
 * Helper function to determine if a subaccount is deactivated.
 *
 * This is a wrapper for the _sfwc_is_subaccount_deactivated() function,
 * available in the Pro version of the plugin.
 *
 * @since 2.0.0
 *
 * @param int	$user_id		The ID of the user.
 *
 * @return 		true|false		True if the user is dactivated, otherwise false.
 */
function sfwc_is_account_deactivated( $user_id ) {
	if( ! $user_id )
		return false;
	
	$user_id = absint( $user_id );
	
	if ( ! sfwc_is_plugin_active( 'subaccounts-for-woocommerce-pro.php' ) ) {
		return false;
	} else {
		if ( function_exists( '_sfwc_is_subaccount_deactivated' ) ) {
			return _sfwc_is_subaccount_deactivated( $user_id );
		} else {
			return false;
		}
	}
}




/**
 * Helper function to determine if current user role is eligible/valid for the subaccount system.
 * 
 * User Role should not have higher permissions than a Customer (or Subscriber) role, whose only capability is (by default) 'read'.
 * Two verification modes are available.
 *
 * @since 1.3.0
 */
function sfwc_is_current_user_role_valid() {
	
	if ( is_user_logged_in() ) {
		
		// Get the User Object.
		$user = wp_get_current_user();
		
		// Get User's Roles.
		// User might has more than one role assigned.
		$current_user_roles = ( array ) $user->roles;
		
		if ( empty( array_diff( $current_user_roles, sfwc_get_valid_roles() ) ) ) { // sfwc_get_valid_roles() contains all $current_user_roles values.
			
			return $current_user_roles;
		}
		else {
			return false;
		}		
	}
}




/**
 * Helper function to determine if current user role is enabled from plugin settings.
 *
 * This function is strictly related and dependent on the sfwc_is_current_user_role_valid() function.
 *
 * @since 1.3.0
 */
function sfwc_is_current_user_role_enabled() {
	
	// Get Options settings.
	$sfwc_options = (array) get_option('sfwc_options');

	// Get 'Select the buyer role(s) to enable the subaccount system for' option value.
	$sfwc_option_selected_roles = ( isset( $sfwc_options['sfwc_option_selected_roles'] ) ) ? $sfwc_options['sfwc_option_selected_roles'] : array('customer', 'subscriber');


	// For debug.
	/*
	echo '<h4>Roles enabled from settings</h4><pre>';
	print_r( $sfwc_option_selected_roles  );
	echo '</pre><h4>Valid roles assigned to user:</h4><pre>';
	print_r( sfwc_is_current_user_role_valid() );
	echo '</pre><h4>Common stuff</h4><pre>';
	print_r( array_intersect( sfwc_is_current_user_role_valid(), $sfwc_option_selected_roles ) );
	echo '</pre>';
	*/


	if ( is_user_logged_in() ) {
		
		if ( function_exists( 'sfwc_is_current_user_role_valid' ) ) {

			// Checking if any of an array's elements are in another array.
			if ( ! empty( array_intersect( sfwc_is_current_user_role_valid(), $sfwc_option_selected_roles ) ) ) {
				
				return true;
			}
			else {
				return false;
			}
		}
		else {
			return false;
		}
	}
}




/**
 * Helper function to determine if a user role is eligible/valid for the subaccount system (by passing $user_id).
 * 
 * User Role should not have higher permissions than a Customer (or Subscriber) role, whose only capability is (by default) 'read'.
 * Two verification modes are available.
 *
 * @since 1.3.0
 *
 * Returns:
 *
 * 	- Array containing user's role(s)	if all user roles are valid.
 *	- False								if not all user roles are valid.
 * 
 */
function sfwc_is_user_role_valid( $user_id ) {

	// Get the User Object by ID.
	$user = get_userdata( $user_id );
	

	if ( !empty( $user ) ) {
		
		// Get the user roles. Users might have more than one role assigned.
		$user_roles = ( array ) $user->roles;
		
		if ( empty( array_diff( $user_roles, sfwc_get_valid_roles() ) ) ) { // sfwc_get_valid_roles() contains all $user_roles values.
			
			return $user_roles;
		}
		else {
			return false;
		}
	} else {
		return false;
	}
}




/**
 * Helper function to determine if user role is enabled from plugin settings (by passing $user_id).
 *
 * This function is strictly related and dependent on the sfwc_is_user_role_valid() function.
 *
 * @since 1.3.0
 */
function sfwc_is_user_role_enabled( $user_id ) {

	// Get Options settings.
	$sfwc_options = (array) get_option('sfwc_options');

	// Get 'Select the buyer role(s) to enable the subaccount system for' option value.
	$sfwc_option_selected_roles = ( isset( $sfwc_options['sfwc_option_selected_roles'] ) ) ? $sfwc_options['sfwc_option_selected_roles'] : array('customer', 'subscriber');


	// For debug.
	/*
	echo '<h4>Roles enabled from settings</h4><pre>';
	print_r( $sfwc_option_selected_roles  );
	echo '</pre><h4>Valid roles assigned to user:</h4><pre>';
	print_r( sfwc_is_user_role_valid( $user_id ) );
	echo '</pre><h4>Common stuff</h4><pre>';
	print_r( array_intersect( sfwc_is_user_role_valid( $user_id ), $sfwc_option_selected_roles ) );
	echo '</pre>';
	*/

	if ( function_exists( 'sfwc_is_user_role_valid' ) ) {
		// Checking if any of an array's elements are in another array.
		if ( ! empty( array_intersect( sfwc_is_user_role_valid( $user_id ), $sfwc_option_selected_roles ) ) ) {
			
			return true;
		}
		else {
			return false;
		}
	}
	else {
		return false;
	}
}




/**
 * Helper function to determine which roles are valid.
 *
 * If valid roles are found, this function returns an array containg all valid roles, otherwise returns false.
 *
 * Note: If the Loose Method is enabled in wp-config.php, the roles made valid via the "sfwc_add_valid_roles" filter are also returned.
 *
 * @since 1.6.0
 *
 *
 *  -------------
 * | Strict Mode |
 *  -------------
 * 
 * It is the default mode.
 * 
 * We basically get all the roles assigned to the current user (a user could have more than one role assigned),
 * for each role assigned we get all the capabilities and merge them into a single array.
 * 
 * After that, we compare all the (merged) user capabilities against another array containing all potential WordPress user capabilities,
 * including those added by WooCommerce.
 *
 * If the only capability in common is the 'read' one, the current user role is eligible/valid for the subaccount system.
 * 
 *  ------------
 * | Loose Mode |
 *  ------------
 *
 * Since the Strict Mode is quite restrictive, we provide a way to loosen it up a bit.
 * 
 * To enable Loose Mode, it is necessary to define the following constant in wp-config.php file:
 *
 * define( 'SFWC_VALID_ROLE_LOOSE_MODE', true );
 * 
 * With Loose Mode enabled, the only conditions necessary for a user role to be valid are that it has 'read' capability and that it does
 * not have 'edit_posts' capability (Contributors and above). 
 */
function sfwc_get_valid_roles() {
	
	global $wp_roles;

	if ( ! isset( $wp_roles ) ) {
		$wp_roles = new WP_Roles();
	}
	
	$roles = $wp_roles->get_names();
	
	$valid_roles = array();
	
	// All potential WordPress user capabilities (excluding Super Admin ones), including those added by WooCommerce.
	// Following capabilities, if all present, represent capabilities granted for Admin users.
	$all_potential_wp_capabilities = array( 'switch_themes'=>1, 'edit_themes'=>1, 'activate_plugins'=>1, 'edit_plugins'=>1, 'edit_users'=>1, 
	'edit_files'=>1, 'manage_options'=>1, 'moderate_comments'=>1, 'manage_categories'=>1, 'manage_links'=>1, 'upload_files'=>1, 'import'=>1, 
	'unfiltered_html'=>1, 'edit_posts'=>1, 'edit_others_posts'=>1, 'edit_published_posts'=>1, 'publish_posts'=>1, 'edit_pages'=>1, 
	'read'=>1, 'edit_others_pages'=>1, 'edit_published_pages'=>1, 'publish_pages'=>1, 'delete_pages'=>1, 'delete_others_pages'=>1, 
	'delete_published_pages'=>1, 'delete_posts'=>1, 'delete_others_posts'=>1, 'delete_published_posts'=>1, 'delete_private_posts'=>1, 
	'edit_private_posts'=>1, 'read_private_posts'=>1, 'delete_private_pages'=>1, 'edit_private_pages'=>1, 'read_private_pages'=>1, 
	'delete_users'=>1, 'create_users'=>1, 'unfiltered_upload'=>1, 'edit_dashboard'=>1, 'update_plugins'=>1, 'delete_plugins'=>1, 
	'install_plugins'=>1, 'update_themes'=>1, 'install_themes'=>1, 'update_core'=>1, 'list_users'=>1, 'remove_users'=>1, 'promote_users'=>1, 
	'edit_theme_options'=>1, 'delete_themes'=>1, 'export'=>1, 'manage_woocommerce'=>1, 'view_woocommerce_reports'=>1, 'edit_product'=>1, 
	'read_product'=>1, 'delete_product'=>1, 'edit_products'=>1, 'edit_others_products'=>1, 'publish_products'=>1, 'read_private_products'=>1, 
	'delete_products'=>1, 'delete_private_products'=>1, 'delete_published_products'=>1, 'delete_others_products'=>1, 'edit_private_products'=>1, 
	'edit_published_products'=>1, 'manage_product_terms'=>1, 'edit_product_terms'=>1, 'delete_product_terms'=>1, 'assign_product_terms'=>1, 
	'edit_shop_order'=>1, 'read_shop_order'=>1, 'delete_shop_order'=>1, 'edit_shop_orders'=>1, 'edit_others_shop_orders'=>1, 'publish_shop_orders'=>1, 
	'read_private_shop_orders'=>1, 'delete_shop_orders'=>1, 'delete_private_shop_orders'=>1, 'delete_published_shop_orders'=>1, 
	'delete_others_shop_orders'=>1, 'edit_private_shop_orders'=>1, 'edit_published_shop_orders'=>1, 'manage_shop_order_terms'=>1, 
	'edit_shop_order_terms'=>1, 'delete_shop_order_terms'=>1, 'assign_shop_order_terms'=>1, 'edit_shop_coupon'=>1, 'read_shop_coupon'=>1, 
	'delete_shop_coupon'=>1, 'edit_shop_coupons'=>1, 'edit_others_shop_coupons'=>1, 'publish_shop_coupons'=>1, 'read_private_shop_coupons'=>1, 
	'delete_shop_coupons'=>1, 'delete_private_shop_coupons'=>1, 'delete_published_shop_coupons'=>1, 'delete_others_shop_coupons'=>1, 
	'edit_private_shop_coupons'=>1, 'edit_published_shop_coupons'=>1, 'manage_shop_coupon_terms'=>1, 'edit_shop_coupon_terms'=>1, 
	'delete_shop_coupon_terms'=>1, 'assign_shop_coupon_terms'=>1, 'ure_edit_roles'=>1, 'ure_create_roles'=>1, 'ure_delete_roles'=>1, 
	'ure_create_capabilities'=>1, 'ure_delete_capabilities'=>1, 'ure_manage_options'=>1, 'ure_reset_roles'=>1, 'create_posts'=>1, 
	'install_languages'=>1, 'resume_plugins'=>1, 'resume_themes'=>1, 'view_site_health_checks'=>1 );
	
	if ( ! empty( $roles ) ) {
		
		if ( defined( 'SFWC_VALID_ROLE_LOOSE_MODE' ) && SFWC_VALID_ROLE_LOOSE_MODE == true ) {
			
			/*****************
			 * Loose Method  *
			 *****************/

			foreach ( $roles as $role => $value ) {
				
				$role_capabilities = get_role( $role )->capabilities;
				
				if ( ! empty( $role_capabilities ) ) {
					
					if ( array_key_exists( 'read', $role_capabilities ) && ! array_key_exists( 'edit_posts', $role_capabilities ) ) {
						
						$valid_roles[] = $role;
					}
					
				}
			}
			
			/**
			 * Filter hook: sfwc_add_valid_roles.
			 *
			 * Allow developers to enable additional roles for the subaccount system.
			 *
			 * @param	array	$user_roles		Array containing valid user roles.
			 * @since	1.6.0
			 */			
			$valid_roles = apply_filters( 'sfwc_add_valid_roles', $valid_roles );
			
			if ( ! empty( $valid_roles ) ) {
				
				return $valid_roles;
				
			} else {
				return false;
			}
		}
		else {
				
			/*****************
			 * Strict Method *
			 *****************/
			 
			foreach ( $roles as $role => $value ) {
				
				$role_capabilities = get_role( $role )->capabilities;
				
				if ( ! empty( $role_capabilities ) ) {

					$result = array_intersect_key( $role_capabilities, $all_potential_wp_capabilities );
					
					if ( ! empty( $result ) && count( $result ) === 1 && key( $result ) == 'read' ) {
					
						$valid_roles[] = $role;
					}
				}
			}
			
			if ( !empty( $valid_roles ) ) {
				
				return $valid_roles;				
				
			} else {
				return false;
			}
		}
	}
	return false;
}




/**
 * Helper function to determine if an order was placed while the plugin was in Sub-User or Multi-User mode (by passing $order_id).
 *
 * @since 1.4.4
 *
 * @return string 'sub_user' || 'multi_user'.
 *
 * ---------
 * Important
 * ---------
 *
 * Always check with:
 *
 *	sfwc_order_placed_during_subaccount_mode( $order_id ) == 'sub_user'
 *	sfwc_order_placed_during_subaccount_mode( $order_id ) == 'multi_user'
 *
 * and not with:
 *
 *	sfwc_order_placed_during_subaccount_mode( $order_id ) !== 'sub_user'
 *	sfwc_order_placed_during_subaccount_mode( $order_id ) !== 'multi_user'
 *
 * If checked with the latter method, the statement will result TRUE also for NULL values, see below (*).
 */
function sfwc_order_placed_during_subaccount_mode( $order_id ) {
	
	$order = new WC_Order( $order_id );
		
	// Retrieve the currently active 'Subaccount Mode' from Options settings.
	$sfwc_option_subaccount_mode = ( isset( $sfwc_options['sfwc_option_subaccount_mode'] ) ) ? $sfwc_options['sfwc_option_subaccount_mode'] : 'sub_user';

	// Retrieve the active subaccount mode at the time the order is placed.
	$order_placed_during_subaccount_mode = $order->get_meta( '_sfwc_order_placed_during_subaccount_mode' );
	
	// Retrieve the ID of the customer who actually placed the order (Multi-User mode).
	$order_placed_by_user_id = $order->get_meta( '_sfwc_order_placed_by_user_id' );
	
	$customer_id = $order->get_customer_id();
	
	if ( ! empty( $order_placed_during_subaccount_mode ) ) {
		
		if ( $order_placed_during_subaccount_mode == 'sub_user' ) {
			return 'sub_user';
		} else {
			return 'multi_user';
		}
	} else {
		/**
		 * _sfwc_order_placed_during_subaccount_mode is stored in order meta since v.1.4.4,
		 * so may be empty for previuosly placed orders.
		 *
		 * For previuosly placed orders, we can check if _sfwc_order_placed_by_user_id order meta is present.
		 *
		 * From v. 1.4.0 (Multi-User mode feature released as beta) to 1.4.2 _sfwc_order_placed_by_user_id was stored in the order meta
		 * only in case multi-user mode was enabled.
		 * So if this meta value is empty it means the order was placed while Sub-User mode was enabled.
		 */
		if ( empty( $order_placed_by_user_id ) ) {
			return 'sub_user';
		} else {
			
			/**
			 * Here we need to handle the situation where an order was placed with plugin v.1.4.3 installed,
			 * where _sfwc_order_placed_by_user_id is always stored (both in Sub-User and Multi-User modes) 
			 * and we have no _sfwc_order_placed_during_subaccount_mode meta to rely on.
			 */
			if ( (int)$order_placed_by_user_id !== $customer_id ) {
				/**
				 * In Sub-User mode $order_placed_by_user_id and $customer_id cannot be different.
				 * So if they are different the order was certainly placed while Multi-User mode was enabled.
				 */
				return 'multi_user';
			}
			
			/**
			 * (*) There are only 3 types of orders that we are unable to understand whether they were placed in Multi-User or Sub-User mode:
			 *
			 *		- Orders placed by a Manager for himself
			 *		- With plugin version 1.4.3
			 *		- And Supervisor Add-On not installed/active
			 *
			 *		- Orders placed by a Manager for himself
			 *		- With plugin version 1.4.3
			 *		- And Supervisor Add-On installed/active, but the manager does not have a Supervisor above him
			 *
			 *		- Orders placed by a Supervisor for himself
			 *		- With plugin version 1.4.3
			 *		- And Supervisor Add-On installed/active
			 *
			 * In all three situations above: $order_placed_by_user_id === $customer_id regardless of whether Sub-User or Multi-User
			 * mode was enabled at the time the order was placed.
			 *
			 * However, it is not necessary to distinguish the subaccount mode for the 3 types of orders above, since the relevant
			 * metadata is valid on both modes.
			 */
			else {
				return $sfwc_option_subaccount_mode;
			}
		}
	}
}




/**
 * Generic user query for subaccounts selection.
 *
 * Generic User Query to display users list for possible selection as subaccounts.
 *
 * From version 1.6.2, below function has been moved here from Subaccounts Pro,
 * so it's best to check that the function doesn't already exist.
 *
 * (!) IMPORTANT: users returned by this function need to be filtered with both sfwc_is_user_role_valid() and sfwc_is_user_role_enabled().
 */
if ( ! function_exists( 'sfwc_query_users_for_possible_selection_as_subaccounts' ) ) {
	function sfwc_query_users_for_possible_selection_as_subaccounts( $meta_query_value = array( 'supervisor' ), $meta_query_operator = 'NOT IN', $meta_query_key_existence = 'EXISTS', $meta_query_relation = 'AND', $page = 1 ) {
		
		// Get 'Options' settings
		$sfwc_options = (array) get_option('sfwc_options');

		// Get 'Select the buyer role(s) to enable the subaccount system for' option value.
		$sfwc_option_selected_roles = ( isset( $sfwc_options['sfwc_option_selected_roles'] ) ) ? $sfwc_options['sfwc_option_selected_roles'] : array('customer', 'subscriber');

		// Retrieve (Ajax) user_id of customer which is currently being edited on user-edit.php
		$user_idx = isset( $_POST['ajax_user_id'] ) ? absint( $_POST['ajax_user_id'] ) : absint( $_GET['user_id'] );
		
		$ajax_search = isset( $_POST['ajax_search'] ) ? sanitize_text_field( $_POST['ajax_search'] ) : false;

		/*
		 * We start by doing a query to retrieve all users.
		 * We need a total user count so that we can calculate how many pages there are.
		 */

		$count_args  = array(
			'role__in'      => $sfwc_option_selected_roles,
			'fields'    => 'all_with_meta',
			'number'    => 999999      
		);
		$user_count_query = new WP_User_Query( $count_args );
		$user_count = $user_count_query->get_results();

		// count the number of users found in the query
		$total_users = $user_count ? count($user_count) : 1;

		// How many users to show per page.
		$users_per_page = 30;

		// Calculate the total number of pages.
		$offset = $users_per_page * ($page - 1);
		$total_pages = ceil( $total_users / $users_per_page );







		$args_customers = array(

			'role__in' => $sfwc_option_selected_roles,		// Only user roles enabled from plugin settings.
			'exclude' => $user_idx,							// Exclude Customer which admin is currently editing.
			//'exclude' => $list_of_children_for_all_users,	// Exclude users which already have parents set above them. Insted of excluding them, decided to make them 'disabled' (see below).
			'orderby' => 'ID',
			'order' => 'ASC',
			'number' => $users_per_page,
			'offset' => $offset,
			'meta_query' => array(

				'relation' => $meta_query_relation,			// This will be 'OR' only when Manager radio button is selected, to show also users where the 'sfwc_account_level_type' is missing in DB (*).
				array(
					'key' => 'sfwc_account_level_type',		// All customers with meta: Account Level Type = $meta_query_value
					'value' => $meta_query_value,
					'compare' => $meta_query_operator,
				),
				array(
					// (*) After a new user is created (but its profile has not been updated yet) the 'sfwc_account_level_type' is missing in DB,
					// but we need to include this user for possible selection as subaccount in case 'Manager' radio button is selected (while this shoud not be included if 'Supervisor' radio button is selected).
					'key' => 'sfwc_account_level_type',
					'compare' => $meta_query_key_existence,	// This will be 'NOT EXISTS' only when Manager radio button is selected.
				)
				
			),
		);
		


		// Search users for partial match.
		if( $ajax_search ) {
			
			$args_customers['search'] = '*'.esc_attr( $ajax_search ).'*';
			
			$args_customers['search_columns'] = array(
					'user_login',
					'user_nicename',
					'user_email',
					'user_url',
			);
		}
		
		
		return new WP_User_Query( $args_customers );
	}
}



/**
 * Adding Meta fields in the meta container admin shop_order pages.
 * 
 * Used also for 'Subaccounts Info' section on WC order email (sfwc_add_subaccounts_info_to_order_email function from Pro).
 */
function sfwc_add_meta_box_content( $order ) { // Leave $order, otherwise getting error on checkout page while placing an order.

	global $post; // Keep it there, otherwise getting 'ID was called incorrectly' in emails when order is created from backend.
	
	// Get 'Options' settings.
    $sfwc_options = (array) get_option( 'sfwc_options' );
	
	// Get Subaccount Mode option value from Options settings.
	$sfwc_option_subaccount_mode = ( isset( $sfwc_options['sfwc_option_subaccount_mode'] ) ) ? $sfwc_options['sfwc_option_subaccount_mode'] : 'sub_user';
	
	// Get Customer Display Name mode.
	$sfwc_option_display_name = ( isset( $sfwc_options['sfwc_option_display_name'] ) ) ? $sfwc_options['sfwc_option_display_name'] : 'username';
	
	
	if ( is_admin() ) { // Admin side only otherwise emails won't get sent.
		if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
			$order = wc_get_order( $order->get_id() );
		} else {
			$order = new WC_Order( $post->ID );
		}
	}
	
	if ( ! is_a( $order, 'WC_Order' ) ) {
	   return;
	}
	
	$customer_id = $order->get_user_id();
	
	// Retrieve user data for customer related to order.
	$userdata_customer = get_userdata( $customer_id );


	// Get Account Level Type.
	$customer_account_level = $order->get_meta('_sfwc_customer_account_level_type');
	
	// Retrieve the ID of the Manager related to the Customer.
	$customer_related_manager_id = $order->get_meta('_sfwc_customer_related_manager');
	
	// Retrieve user data for Manager.
	$userdata_manager = get_userdata( $customer_related_manager_id );
	
	// Slightly change the background color of the meta box based on Subaccount Mode setting.
	$order_placed_by_css_background = $sfwc_option_subaccount_mode == 'sub_user' ? '#e4e4e4' : '#f5f5f5';


 
	/**
	 * Check if order has still a user id associated ($customer_id). 
	 * If not checked, in case a customer is deleted after he made an order they appear wrong values.
	 * 
	 * Also check if the user who made the order has role of Customer or Subscriber. Otherwise weird things might happen.
	 * E.g. If order was made by an Administrator wrong data is displayed within the meta box.
	 */

	if ( $customer_id && ( sfwc_is_user_role_valid( $customer_id ) && sfwc_is_user_role_enabled( $customer_id ) ) ) {
		
		if ( $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order->get_id() ) == 'sub_user' ) {

			echo '<div style="background:#f5f5f5;padding:2px 8px;margin-top:12px;">';
			
			/*
			//Check 'Customer Display Name' in Subaccounts > Settings > Options and display it accordingly
			if ( ( $sfwc_option_display_name == 'full_name' ) && ( $userdata_customer->user_firstname || $userdata_customer->user_lastname ) ) {

				// Echo 'Full Name + Email' (if either First Name or Last Name has been set)
				echo '<p><strong>' . esc_html__( 'Customer', 'subaccounts-for-woocommerce' ) . ':</strong><br>' . esc_html( $userdata_customer->user_firstname ) . ' ' . esc_html( $userdata_customer->user_lastname ) . '<br>[' . esc_html( $userdata_customer->user_email ) . ']</p>';

			} elseif (($sfwc_option_display_name == 'company_name') && ($userdata_customer->billing_company)) {

				// Echo 'Company + Email' (if Company name has been set)
				echo '<p><strong>' . esc_html__( 'Customer', 'subaccounts-for-woocommerce' ) . ':</strong><br>' . esc_html( $userdata_customer->billing_company ) . '<br>[' . esc_html( $userdata_customer->user_email ) . ']</p>';

			} else {

				// Otherwise echo 'Username + Email'
				echo '<p><strong>' . esc_html__( 'Customer', 'subaccounts-for-woocommerce' ) . ':</strong><br>' . esc_html( $userdata_customer->user_login ) . '<br>[' . esc_html( $userdata_customer->user_email ) . ']</p>';
			}
			*/
			
			echo '<p><strong>' . esc_html__( 'Customer', 'subaccounts-for-woocommerce' ) . ':</strong><br>';
			
			echo wp_kses( 
				sfwc_get_customer_display_name( $customer_id, true ), 
				array(
					'span' => array(
						'class' => array()
					)
				) 
			);
			
			echo '</p>';

			// Display Account Type
			echo '<p><strong>' . esc_html__( 'Account Type', 'subaccounts-for-woocommerce' ) . ':</strong> ';


			if ( $customer_account_level == 'supervisor' ) {

				echo esc_html__('Supervisor', 'subaccounts-for-woocommerce');

				if ( ! sfwc_is_plugin_active( 'woocommerce.php' ) ) {

					echo '<div style="background:#fff4bd; padding:5px; margin-bottom:.5em;">';
					
					$sup_deactivated_warning = '<strong>' . esc_html__( 'WARNING:', 'subaccounts-for-woocommerce' ) . '</strong>';
					$sup_deactivated_supervisor = '<strong><em>' . esc_html__( 'Supervisor', 'subaccounts-for-woocommerce' ) . '</em></strong>';
					$sup_deactivated_addon = '<strong><em>' . esc_html__( 'Supervisor Add-on', 'subaccounts-for-woocommerce' ) . '</em></strong>';
					
					printf(
						esc_html__( '%1$s This User\'s Account Type is set as %2$s, but the %3$s is either uninstalled or not active. You may want to install and activate the add-on or change the User\'s Account Type.', 'subaccounts-for-woocommerce' ), 
						$sup_deactivated_warning,
						$sup_deactivated_supervisor,
						$sup_deactivated_addon
					);			
				
					echo '</div>';
				}

			} elseif ( $customer_account_level == 'manager' ) {

				echo esc_html__( 'Manager', 'subaccounts-for-woocommerce' );

			} else {

				echo esc_html__( 'Default', 'subaccounts-for-woocommerce' );

			}

			echo '</p>';
		
		}
		
		// Display Order Placed By
		echo '<p style="background:' . esc_attr( $order_placed_by_css_background ) . '; border-radius: 3px; padding: 8px;"><strong>' . esc_html__( 'Order placed by', 'subaccounts-for-woocommerce' ) . ':</strong><br>';
		
		
		// Check if Pro version is active.
		if ( ! sfwc_is_plugin_active( 'subaccounts-for-woocommerce-pro.php' ) ) {
					
			echo '<a style="font-weight: 600; color: #e67d23; background: #fff; padding: 5px; display: block; margin-top: 5px; border-radius: 3px; width: 100%; box-sizing: border-box; text-align: center;" href="'
					. esc_url( admin_url( '/admin.php?checkout=true&page=subaccounts-pricing&plugin_id=10457&plan_id=17669&pricing_id=19941&billing_cycle=annual' ) ) . '">'
					. esc_html__( 'Upgrade to Subaccounts Pro', 'subaccounts-for-woocommerce' ) . '</a>';
		}


		do_action('admin_order_page_before_manager_info', $order, $sfwc_option_display_name, $userdata_customer, $userdata_manager );
		

		echo '</p>';
		
		if ( $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order->get_id() ) == 'sub_user' ) {

			echo '</div>';
		
		}

		if ( $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order->get_id() ) == 'sub_user' ) {

			// Display Related Supervisor or Manager Account (if any)
			if ( $customer_account_level == 'supervisor' ) {

				//echo '<p><strong>' . __('Manager Account', 'subaccounts-for-woocommerce') . ':</strong><br> ' . __('None', 'subaccounts-for-woocommerce') . wc_help_tip( esc_attr__('Supervisor account types cannot have Managers above them', 'subaccounts-for-woocommerce') ) . '</p>';
				echo '<p><strong>' . esc_html__( 'Manager Account', 'subaccounts-for-woocommerce' ) . ':</strong><br> ' . esc_html__( 'None', 'subaccounts-for-woocommerce' ) . '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'Supervisor account types cannot have Managers above them.', 'subaccounts-for-woocommerce' ) . '"></span></p>';

				#if ( is_plugin_active( 'sfwc-supervisor-addon/sfwc-supervisor-addon.php' ) ) {
				if ( sfwc_is_plugin_active( 'sfwc-supervisor-addon.php' ) ) {
					//echo '<p><strong>' . __('Supervisor Account', 'subaccounts-for-woocommerce') . ':</strong><br> ' . __('None', 'subaccounts-for-woocommerce') . wc_help_tip( esc_attr__('Supervisor account types cannot have Supervisors above them', 'subaccounts-for-woocommerce') ) . '</p>';
					echo '<p><strong>' . esc_html__( 'Supervisor Account', 'subaccounts-for-woocommerce' ) . ':</strong><br> ' . esc_html__( 'None', 'subaccounts-for-woocommerce' ) . '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'Supervisor account types cannot have Supervisors above them.', 'subaccounts-for-woocommerce' ) . '"></span></p>';
				}
			} elseif ( $customer_account_level == 'manager' ) {


				//echo '<p><strong>' . __('Manager Account', 'subaccounts-for-woocommerce') . ':</strong><br> ' . __('None', 'subaccounts-for-woocommerce') . wc_help_tip( esc_attr__('Manager account types cannot have Managers above them', 'subaccounts-for-woocommerce') ) . '</p>';
				echo '<p><strong>' . esc_html__( 'Manager Account', 'subaccounts-for-woocommerce' ) . ':</strong><br> ' . esc_html__( 'None', 'subaccounts-for-woocommerce' ) . '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'Manager account types cannot have Managers above them.', 'subaccounts-for-woocommerce' ) . '"></span></p>';


				do_action('order_page_after_manager_info_when_customer_is_manager', $order, $customer_account_level, $sfwc_option_display_name );


			} elseif ( ( $customer_account_level !== 'supervisor' ) && ( $customer_account_level !== 'manager' ) ) {

				echo '<p style="padding-left:20px;"><span style="-moz-transform: scale(-1, 1); -o-transform: scale(-1, 1); -webkit-transform: scale(-1, 1); transform: scale(-1, 1);" class="dashicons dashicons-editor-break"></span><strong>' . esc_html__('Manager Account', 'subaccounts-for-woocommerce') . ':</strong><br>';

				if ( $customer_related_manager_id && ($customer_related_manager_id !== 'not_set') ) {
						
					/*
					//Check 'Customer Display Name' in Subaccounts > Settings > Options and display it accordingly
					if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata($userdata_manager->ID)->user_firstname || get_userdata($userdata_manager->ID)->user_lastname ) ) {

						// Echo 'Full Name + Email' (if either First Name or Last Name has been set)
						printf( 'ID: %1$s - %2$s %3$s <br>[%4$s]</p>', esc_html( $userdata_manager->ID ), esc_html( $userdata_manager->user_firstname ), esc_html( $userdata_manager->user_lastname ), esc_html( $userdata_manager->user_email ) );
						

					} elseif ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata($userdata_manager->ID)->billing_company ) ) {

						// Echo 'Company + Email' (if Company name has been set)
						printf( 'ID: %1$s - %2$s <br>[%3$s]</p>', esc_html( $userdata_manager->ID ), esc_html( $userdata_manager->billing_company ), esc_html( $userdata_manager->user_email ) );
						

					} else {

						// Otherwise echo 'Username + Email'
						printf( 'ID: %1$s - %2$s <br>[%3$s]</p>', esc_html( $userdata_manager->ID ), esc_html( $userdata_manager->user_login ), esc_html( $userdata_manager->user_email ) );
						
					}
					*/
					
					echo wp_kses( 
						sfwc_get_customer_display_name( $customer_related_manager_id, true ), 
						array(
							'span' => array(
								'class' => array()
							)
						) 
					);
					
				} else {
					//echo __('Not set', 'subaccounts-for-woocommerce') . wc_help_tip( esc_attr__('No Manager has been set yet', 'subaccounts-for-woocommerce') ) . '</p>';
					echo esc_html__( 'Not set', 'subaccounts-for-woocommerce' ) . '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'No Manager has been set yet.', 'subaccounts-for-woocommerce' ) . '"></span>';
				}

				echo '</p>';

				( isset( $userdata_manager ) ) ? $userdata_manager = $userdata_manager : $userdata_manager = ''; // Prevent: Undefined variable: $userdata_manager (wp_debug enabled) // Check if still needed.
				do_action('order_page_after_manager_info_when_customer_is_default', $order, $customer_account_level, $sfwc_option_display_name );

			}
		}

	} else {
		echo '<p>' . esc_html__( 'No data available for this order.', 'subaccounts-for-woocommerce' ) . '</p>';
	}
}