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

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

// Required for the Checkout and Cart blocks features.
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Services\CheckoutFields;


/**
 * Frontend style and scripts.
 */
function sfwc_enqueue_frontend_js_css() {
	
	// Check if logged in user has a valid role.
	if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {
		
		// Load main CSS.
		wp_enqueue_style( 'sfwc_frontend_style', esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/css/style.css' );
		
		// Load Selectize JS and CSS.
		wp_enqueue_style( 'sfwc_selectize_style', esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/lib/selectize/selectize.css' );
		wp_enqueue_script( 'sfwc_selectize_js', esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/lib/selectize/selectize.min.js', array( 'jquery' ), '0.13.6', false );
		
		// Load jQuery Accordion JS and CSS, necessary in: My Account -> Manage Subaccounts -> Edit subaccount.
		wp_enqueue_style( 'sfwc_jquery_ui_accordion_style', esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/lib/jquery-ui-accordion/jquery-ui-accordion.css' );
		wp_enqueue_script( 'jquery-ui-accordion' );
		
		// My Account -> Manage Subaccounts -> Edit subaccount.
		wp_enqueue_script( 'selectWoo' );
		wp_enqueue_style( 'select2' );
		wp_enqueue_script( 'wc-country-select' );
	}
}
add_action('wp_enqueue_scripts', 'sfwc_enqueue_frontend_js_css');




/**
 * Set Manager / Supervisor Cookie.
 * 
 * Set 'is_manager' cookie if customer with 'Manager' Account Level Type does login.
 * Set 'is_supervisor' cookie if customer with 'Supervisor' Account Level Type does login.
 */
function sfwc_set_parent_account_cookie() {

	// Check if logged in user has has a valid role.
	if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {
		
		
		// Get ID of currently logged in user.
		$user_id = get_current_user_id();

		// Get Account Level Type of currently logged in user (Superviore | Manager | Default).
		$account_level_type = get_user_meta( $user_id, 'sfwc_account_level_type', true );

	


		// Assign variable to cookie name: wordpress_logged_in_ + hashed site URL.
		$finalUserCookieName = 'wordpress_logged_in_' . COOKIEHASH;

		if ( ! isset( $_COOKIE[$finalUserCookieName] ) ) {
			return;
		} else {
			
			// Sanitize cookie value.
			$finalUserCookieNameValue = sanitize_text_field( $_COOKIE[$finalUserCookieName] );
			
			
			$cookie_parts = explode( '|', $finalUserCookieNameValue ); // 0 => user_login, 1 => expiration, 2 => token, 3 => hmac
			// check if the cookie has the correct number of parts, if not then we can't be sure that $cookie_parts[0] is the user name
			if ( count( $cookie_parts ) !== 4 ) {
				return '';
			}
			$user_session_token = $cookie_parts[2];
		}


	

		// Check if user is a Manager.
		if ( $account_level_type == 'manager' ) {

			// If not already build and set 'is_manager' cookie.
			if ( ! isset( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager'] ) ) {
				
				// Set a trasient to check 'is_manager' cookie value against (they must be equal).
				set_transient( 'sfwc_is_or_was_manager_' . $user_session_token, $finalUserCookieNameValue, 3600 );

				// Set 'is_manager' cookie name and its value (same as 'wordpress_logged_in_...' value).
				setcookie( apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager', $finalUserCookieNameValue, [
					'expires' => '',
					'path' => COOKIEPATH,
					'domain' => COOKIE_DOMAIN,
					'secure' => is_ssl(),
					'httponly' => true,
					'samesite' => 'Strict',
				]);


				// Provide initial value to cookie otherwise frontend switcher will be shown only after page refresh.
				$_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager'] = get_transient( 'sfwc_is_or_was_manager_' . $user_session_token );
			}
		}
		
		
		// Check if user is a Supervisor.
		if ( $account_level_type == 'supervisor'  ) {

			// If is Supervisor build 'is_supervisor' cookie
			if ( ! isset($_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor'] ) ) {

				// Set transient
				set_transient( 'sfwc_is_or_was_supervisor_' . $user_session_token, $finalUserCookieNameValue, 3600 );

				// Set 'is_supervisor' cookie name and its value (same as 'wordpress_logged_in_...' value)
				setcookie( apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor', $finalUserCookieNameValue, [
					'expires' => '',
					'path' => COOKIEPATH,
					'domain' => COOKIE_DOMAIN,
					'secure' => is_ssl(),
					'httponly' => true,
					'samesite' => 'Strict',
				]);

				// Provide initial value to cookie otherwise frontend switcher will be shown only after page refresh
				$_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor'] = get_transient( 'sfwc_is_or_was_supervisor_' . $user_session_token );
			}
		}
	}
}
add_action('template_redirect', 'sfwc_set_parent_account_cookie', 20);	// Priority must be lower than sfwc_add_subaccount_form_handler function for later execution.
																		// Otherwise the user switcher pane won't show instantly after the first subaccount creation for new accounts (page refresh would be required).




// Destroy is_manager / is_supervisor cookie and transient on logout.
function sfwc_destroy_parent_account_cookie_on_logout() {

    if ( isset( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager'] ) ) {

		$cookie_value_manager = sanitize_text_field( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager'] );

		$cookie_parts = explode( '|', $cookie_value_manager ); // 0 => user_login, 1 => expiration, 2 => token, 3 => hmac
		
		// Check if the cookie has the correct number of parts, if not then we can't be sure that $cookie_parts[0] is the user name.
		if ( count( $cookie_parts ) !== 4 ) {
			return '';
		}
		
		$user_session_token = $cookie_parts[2];
		
		// Delete transient.
		delete_transient( 'sfwc_is_or_was_manager_' . $user_session_token );
		
		// Destroy is_manager cookie.
		setcookie( apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager', '', -1, COOKIEPATH);
    }
	
	if ( isset( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor'] ) ) {
		
		$cookie_value_supervisor = sanitize_text_field( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor'] );

		$cookie_parts = explode( '|', $cookie_value_supervisor ); // 0 => user_login, 1 => expiration, 2 => token, 3 => hmac
		
		// Check if the cookie has the correct number of parts, if not then we can't be sure that $cookie_parts[0] is the user name.
		if ( count( $cookie_parts ) !== 4 ) {
			return '';
		}
		
		$user_session_token = $cookie_parts[2];
		
		// Delete transient.
		delete_transient( 'sfwc_is_or_was_supervisor_' . $user_session_token );
		
		// Destroy is_supervisor cookie
		setcookie( apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor', '', -1, COOKIEPATH);
	}
}
add_action('wp_logout', 'sfwc_destroy_parent_account_cookie_on_logout');




/**
 * Display User Account Switcher.
 * 
 * Echo User Account Switcher on WooCommerce My Account page.
 */
function sfwc_user_switcher_content() {
	
	if ( isset( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager'] ) ) {

		$cookie_value_manager = sanitize_text_field( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager'] );		
		
		$cookie_parts = explode( '|', $cookie_value_manager ); // 0 => user_login, 1 => expiration, 2 => token, 3 => hmac
		// check if the cookie has the correct number of parts, if not then we can't be sure that $cookie_parts[0] is the user name
		if ( count( $cookie_parts ) !== 4 ) {
			return '';
		}
		
		$user_session_token = $cookie_parts[2];
		
		$is_or_was_manager = get_transient( 'sfwc_is_or_was_manager_' . $user_session_token );
	}
	
	
	if ( isset( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor'] ) ) {
		
		$cookie_value_supervisor = sanitize_text_field( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor'] );
		
		$cookie_parts = explode( '|', $cookie_value_supervisor ); // 0 => user_login, 1 => expiration, 2 => token, 3 => hmac
		// check if the cookie has the correct number of parts, if not then we can't be sure that $cookie_parts[0] is the user name
		if ( count( $cookie_parts ) !== 4 ) {
			return '';
		}
		
		$user_session_token = $cookie_parts[2];		
		
		$is_or_was_supervisor = get_transient( 'sfwc_is_or_was_supervisor_' . $user_session_token );
	}
	

	#echo '<strong>is_or_was_manager:</strong> '; var_dump($is_or_was_manager); echo '<br>';
	#echo '<strong>is_or_was_supervisor:</strong> '; var_dump($is_or_was_supervisor);
		
		
	
	
	
	

    // Retrieve the current user object
    $current_user = wp_get_current_user();
	
	// Get ID of currently logged in user.
	$user_id = get_current_user_id();

	// Get Account Level Type of currently logged in user (Superviore | Manager | Default).
	$account_level_type = get_user_meta( $user_id, 'sfwc_account_level_type', true );


	/**
	 * Get plugin settings
	 *
	 * Check if values have been set first to prevent 'undefined' 
	 */

    // Get 'Appearance' settings.
    $sfwc_switcher_appearance = (array) get_option('sfwc_switcher_appearance');
	
		// Get Pane Background Color.
		$sfwc_switcher_pane_bg_color = ( isset( $sfwc_switcher_appearance['sfwc_switcher_pane_bg_color'] ) ) ? $sfwc_switcher_appearance['sfwc_switcher_pane_bg_color'] : '#def6ff';
	
		// Get Pane Headline Color.
		$sfwc_switcher_pane_headline_color = ( isset( $sfwc_switcher_appearance['sfwc_switcher_pane_headline_color'] ) ) ? $sfwc_switcher_appearance['sfwc_switcher_pane_headline_color'] : '#3577c9';

		// Get Pane Text Color.
		$sfwc_switcher_pane_text_color = ( isset( $sfwc_switcher_appearance['sfwc_switcher_pane_text_color'] ) ) ? $sfwc_switcher_appearance['sfwc_switcher_pane_text_color'] : '#3b3b3b';
	
		// Get Pane Select Button Background Color.
		$sfwc_switcher_pane_select_bg_color = ( isset( $sfwc_switcher_appearance['sfwc_switcher_pane_select_bg_color'] ) ) ? $sfwc_switcher_appearance['sfwc_switcher_pane_select_bg_color'] : '#3577c9';

		// Get Pane Select Button Text Color.
		$sfwc_switcher_pane_select_text_color = ( isset( $sfwc_switcher_appearance['sfwc_switcher_pane_select_text_color'] ) ) ? $sfwc_switcher_appearance['sfwc_switcher_pane_select_text_color'] : '#ffffff';


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

		// Get Customer Display Name.
		$sfwc_option_display_name = ( isset( $sfwc_options['sfwc_option_display_name'] ) ) ? $sfwc_options['sfwc_option_display_name'] : 'username';
		
		// 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');
		
		// Check if user switcher is enabled.
		$sfwc_options_enable_user_switcher = ( isset( $sfwc_options['sfwc_options_enable_user_switcher'] ) ) ? $sfwc_options['sfwc_options_enable_user_switcher'] : 1;
		


	// Get children (array) of currently logged in user.																		
	$children_ids = get_user_meta( $user_id, 'sfwc_children', true ); // 3rd must be: true, otherwise will turn it into a two-dimensional array.

	/**
	 * Remove no longer existing users from the $children_ids array,
	 * in case a user has been deleted (but still present within 'sfwc_children' meta of an ex parent account).
	 *
	 * Also exclude users whose role is not enabled in the plugin settings.
	 */
	$existing_children_ids = array();
	
	if ( ! empty ( $children_ids ) ) {
		
		foreach ( $children_ids as $single_id ) {
			
			// Check if user still exists.
			$user_exists = get_userdata( $single_id );
			if ( $user_exists !== false ) {
				
				if ( sfwc_is_user_role_valid( $single_id ) && sfwc_is_user_role_enabled( $single_id ) ) {
					
					$existing_children_ids[] = $single_id;
				}
			}
		}
	}


	if( $sfwc_options_enable_user_switcher == 1 ) {
	
		// Check if logged in user has has a valid role.
		if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {








			// Get all users with user meta 'sfwc_account_level_type' == 'manager' and filter only the one which has 'sfwc_children' user_meta containing the child ID who made the order
			$args_manager = array(
				//'role'    => 'customer',
				//'role__in' => ['customer', 'subscriber'],
				'role__in' => $sfwc_option_selected_roles,
				'exclude' => $user_id, // Exclude ID of customer who made currently displayed order
				'orderby' => 'ID',
				'order' => 'ASC',
				'meta_key' => 'sfwc_account_level_type',
				'meta_value' => 'manager',
				'meta_query' => array(
					array(
						'key' => 'sfwc_children',
						'value' => '"'.$user_id.'"',
						'compare' => 'LIKE',
					),
				),
			);


			// The User Query
			$user_query_manager = new WP_User_Query( $args_manager );







			/**
			 * In the rare case that frontend switcher is not displayed (cookie or transient has not been properly set or expired) show 'Login Again' button.
			 */
			if ( isset( $cookie_value_manager ) && ( $cookie_value_manager !== $is_or_was_manager ) && ! isset( $cookie_value_supervisor ) ) {

				wc_print_notice(
					esc_html__( 'The user switching feature is only available for a specified period of time. You can try reloading the page or logging in again.', 'subaccounts-for-woocommerce' ) . 
					'<a class="button" href="' . esc_url( wp_logout_url( wc_get_page_permalink( 'myaccount' ) ) ) . '">' . esc_html__( 'Login Again', 'subaccounts-for-woocommerce' ) . '</a>'
					, 'notice'
				);
			}





			/**
			 * User Switcher.
			 */
			if ( isset( $cookie_value_manager ) && ( $cookie_value_manager === $is_or_was_manager ) && ! isset( $cookie_value_supervisor ) ) {


				/***
				
				// For debug.
				echo '<p><strong style="color:red;">All subaccount IDs (including no longer existing subaccounts)</strong></p>';
				if ( ! empty( $children_ids ) ) {
					echo '<pre>';
					print_r( $children_ids );
					echo '</pre>';
				} else {
					echo '<p>None.</p>';
				}
				
				// For debug.
				echo '<p><strong style="color:red;">Only existing subaccount IDs</strong></p>';
				if ( ! empty( $existing_children_ids ) ) {
					echo '<pre>';
					print_r( $existing_children_ids );
					echo '</pre>';
				} else {
					echo '<p>None.</p>';
				}

				***/



				/**
				 * Make sure the user switcher is shown based on the following conditions:
				 *
				 *	- a Manager account has got existing (not deleted or unset as subaccount by admin) subaccounts;
				 *	- or in case of a Default account, so that it can switch back to its parent.
				 */
				if ( ( $account_level_type == 'manager' && ! empty( $existing_children_ids ) ) || ( $account_level_type !== 'manager' && $account_level_type !== 'supervisor' ) ) {
					
					/**
					 * Echo Subaccounts Switcher HTML and populate it
					 */

					echo '<div id="sfwc-user-switcher-pane" style="position:relative; background-color:' . esc_attr( $sfwc_switcher_pane_bg_color ) . ';">';
					echo '<h3 style="color:' . esc_attr( $sfwc_switcher_pane_headline_color ) . ';">' . esc_html__('You are currently logged in as:', 'subaccounts-for-woocommerce') . '</h3>';
					echo '<p style="color:' . esc_attr( $sfwc_switcher_pane_text_color ) . ';">';
					
					echo wp_kses( 
						sfwc_get_customer_display_name( $user_id, true ), 
						array(
							'span' => array(
								'class' => array()
							)
						) 
					);
					
					echo '</p>';
					
					/*
					// Check 'Customer Display Name' in Subaccounts > Settings > Options and display it accordingly
					if ( ( $sfwc_option_display_name == 'full_name' ) && ( $current_user->user_firstname || $current_user->user_lastname ) ) {

						// Echo 'Full Name + Email' (if either First Name or Last Name has been set)
						echo '<p style="color:' . esc_attr( $sfwc_switcher_pane_text_color ) . ';"><strong>' . esc_html__( 'Full Name: ', 'subaccounts-for-woocommerce' ) . '</strong>' . esc_html( $current_user->user_firstname ) . ' ' . esc_html( $current_user->user_lastname ) . ' (' . esc_html( $current_user->user_email ) . ')</p>';

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

						// Echo 'Company + Email' (if Company name has been set)
						echo '<p style="color:' . esc_attr( $sfwc_switcher_pane_text_color ) . ';"><strong>' . esc_html__( 'Company: ', 'subaccounts-for-woocommerce' ) . '</strong>' . esc_html( $current_user->billing_company ) . ' (' . esc_html( $current_user->user_email ) . ')</p>';

					} else {

						// Otherwise echo 'Username + Email'
						echo '<p style="color:' . esc_attr( $sfwc_switcher_pane_text_color ) . ';"><strong>' . esc_html__( 'Username: ', 'subaccounts-for-woocommerce' ) . '</strong>' . esc_html( $current_user->user_login ) . ' (' . esc_html( $current_user->user_email ) . ')</p>';
					}
					*/
					
					$class_selectize = empty( $user_query_manager->get_results() ) ? 'sfwc_frontend_children_selectize' : '';
					?>

					<form method="post">
						<?php wp_nonce_field( 'sfwc_switch_account_frontend_action', 'sfwc_switch_account_frontend' ); ?>
						
						<select id="sfwc_frontend_children" class="<?php echo esc_attr( $class_selectize ); ?>" name="sfwc_frontend_children" onchange="this.form.submit();" style="background-color:<?php echo esc_attr( $sfwc_switcher_pane_select_bg_color ); ?>; color:<?php echo esc_attr( $sfwc_switcher_pane_select_text_color ); ?>;">
							<option value="" selected="selected" disabled><?php echo esc_html__('Select Account', 'subaccounts-for-woocommerce'); ?>&nbsp; &#8644;</option>
							
							<?php
							if ( empty( $existing_children_ids ) ) {
								
								if ( ! empty( $user_query_manager->get_results() ) ) {
									foreach ( $user_query_manager->get_results() as $user ) {
									?>
										<option style="font-weight:bold;" value="<?php echo esc_attr($user->ID); ?>">&#129044; <?php echo esc_html__('Back to Manager', 'subaccounts-for-woocommerce'); ?></option>
									<?php
									}
								}
							}							
							?>
						</select>
						<input name="setc" value="submit" type="submit" style="display:none;">
					</form>
					<img id="sfwc-loading-icon" src="<?php echo esc_url( WP_PLUGIN_URL . '/subaccounts-for-woocommerce/assets/images/loader.gif' ); ?>" style="position:absolute; left:0; right:0; top:0; bottom:0; text-align:center; margin:auto; z-index:999999;">
					</div>
					
					
					<?php
					wp_enqueue_script( 'sfwc_user_switcher_js', esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/js/user-switcher.js', array( 'jquery', 'sfwc_selectize_js' ), '', true ); // Print in footer.

					$dataToBePassed = array(
						'selectizePlaceholder'			=> esc_html__( 'Select Account', 'subaccounts-for-woocommerce' ),
						'switcherPaneSelectBgColor' 	=> esc_attr( $sfwc_switcher_pane_select_bg_color ),
						'switcherPaneSelectTextColor' 	=> esc_attr( $sfwc_switcher_pane_select_text_color ),
						'userId' 						=> absint( $user_id ),
						'adminAjaxUrl' 					=> esc_url( admin_url('admin-ajax.php') ),
						'nonce' 						=> wp_create_nonce('sfwc_nonce'),
						'accountType' 					=> $account_level_type,
					);

					wp_add_inline_script( 'sfwc_user_switcher_js', 'var sfwc_vars_user_switcher = ' . wp_json_encode( $dataToBePassed, JSON_PRETTY_PRINT ), 'before' );
				}
			}
		}
	}
}
add_shortcode( 'sfwc_user_switcher', 'sfwc_user_switcher_content');
add_action('woocommerce_before_account_navigation', 'sfwc_user_switcher_content');




/**
 * User Account Switcher: Validation and Authentication Cookies Installation.
 *
 * On WooCommerce My Account page, when selecting a subaccount or a parent account from the dropdwon list, set authentication cookies for the selected user.
 */
function sfwc_set_current_user_cookies() {
	
	
	
	if ( isset( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager'] ) ) {

		$cookie_value_manager = sanitize_text_field( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager'] );		
		
		$cookie_parts = explode( '|', $cookie_value_manager ); // 0 => user_login, 1 => expiration, 2 => token, 3 => hmac
		// check if the cookie has the correct number of parts, if not then we can't be sure that $cookie_parts[0] is the user name
		if ( count( $cookie_parts ) !== 4 ) {
			return '';
		}
		
		$user_session_token = $cookie_parts[2];
		
		$is_or_was_manager = get_transient( 'sfwc_is_or_was_manager_' . $user_session_token );
	}
	
	
	if ( isset( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor'] ) ) {
		
		$cookie_value_supervisor = sanitize_text_field( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor'] );
		
		$cookie_parts = explode( '|', $cookie_value_supervisor ); // 0 => user_login, 1 => expiration, 2 => token, 3 => hmac
		// check if the cookie has the correct number of parts, if not then we can't be sure that $cookie_parts[0] is the user name
		if ( count( $cookie_parts ) !== 4 ) {
			return '';
		}
		
		$user_session_token = $cookie_parts[2];		
		
		$is_or_was_supervisor = get_transient( 'sfwc_is_or_was_supervisor_' . $user_session_token );
	}
	
	
	
	
	
	
	// 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');
	
	



	// Get ID of currently logged in user.
	$current_user_id = get_current_user_id();
	
	// Get Account Level Type of currently logged in user (Superviore | Manager | Default).
	$account_level_type = get_user_meta( $current_user_id, 'sfwc_account_level_type', true );

	// Get children (array) of currently logged in user.																				## A SCENDERE ↓ ##		OTTIENI LISTA SUBACCOUNT RELATIVI A UTENTE ATTUALMENTE LOGGATO
	// 3rd must be: true, otherwise will turn it into a two-dimensional array and validation won't work															(VALE SIA PER SUPERVISOR CHE MANAGER)
	$children_ids = get_user_meta( $current_user_id, 'sfwc_children', true );







	/**
	 * Create an array of IDs of 'Default' users tied to Managers which are tied to Supervisors											## A SCENDERE ↓ ##
	 * to create list of whitelisted/validated Deafult users a Supervisor can directly switch to (without passing from a Manger first).
	 *
	 * Necessary in order to switch directly from Supervisor to (whitelisted/validated) Default users.
	 */

	$children_of_manager = array();

	// 
	// So basically getting Default users tied to Supervisors
	if ( ! empty( $children_ids ) ) {
		foreach ( $children_ids as $children_id ) {
			
			
			$single_array = get_user_meta( $children_id, 'sfwc_children', true );
			//$children_of_manager[] = $single_value;
			
			if ( ! empty( $single_array ) ) {
				
				foreach ( $single_array as $single_value ) {
					$children_of_manager[] = $single_value;
				}

			}
			
		}
	}
	// var_dump($children_ids);
	// var_dump($children_of_manager);
	
	
	
	
	

	/**
	 * Get the Supervisor of currently logged in Manager.																				 ## A SALIRE ↑ ##		OTTIENI SUPERVISOR RELATIVO A MANAGER ATTUALMENTE LOGGATO
	 *
	 * By querying all users with user meta 'sfwc_account_level_type' == 'supervisor' 
	 * and filtering only the one which has 'children' user_meta containing the child ID of currently logged in Manager.
	 */

	$args_supervisor = array(
		//'role'    => 'customer',
		//'role__in' => ['customer', 'subscriber'],
		'role__in' => $sfwc_option_selected_roles,
		'orderby' => 'ID',
		'order' => 'ASC',
		'meta_key' => 'sfwc_account_level_type',
		'meta_value' => 'supervisor',
		'meta_query' => array(
			array(
				'key' => 'sfwc_children',
				'value' => '"'.$current_user_id.'"',
				'compare' => 'LIKE',
			),
		),
	);


	// The User Query
	$user_query_supervisor = new WP_User_Query( $args_supervisor );



	// User Loop
	if ( ! empty( $user_query_supervisor->get_results() ) ) {
		foreach ( $user_query_supervisor->get_results() as $user ) {

			$supervisor_id = $user->ID;
		}
	}




	/**
	 * Get the Manager of currently logged in Default user.																					## A SALIRE ↑ ##		OTTIENI MANAGER RELATIVO A DEFAULT USER ATTUALMENTE LOGGATO
	 *
	 * By querying all users with user meta 'sfwc_account_level_type' == 'manager' 
	 * and filtering only the one which has 'children' user_meta containing the child ID of currently logged in Default user.
	 */
	 
	$args_manager = array(
		//'role'    => 'customer',
		//'role__in' => ['customer', 'subscriber'],
		'role__in' => $sfwc_option_selected_roles,
		'orderby' => 'ID',
		'order' => 'ASC',
		'meta_key' => 'sfwc_account_level_type',
		'meta_value' => 'manager',
		'meta_query' => array(
			array(
				'key' => 'sfwc_children',
				'value' => '"'.$current_user_id.'"',
				'compare' => 'LIKE',
			),
		),
	);


	// The User Query
	$user_query_manager = new WP_User_Query( $args_manager );






	// User Loop
	if ( ! empty( $user_query_manager->get_results() ) ) {
		foreach ( $user_query_manager->get_results() as $user ) {

			$manager_id = $user->ID;
		}
	}


	// Check if nonce is in place and verfy it.
	if ( ! isset( $_POST['sfwc_switch_account_frontend'] ) ) {
		return;
	}
	elseif( isset( $_POST['sfwc_switch_account_frontend'] ) && ! wp_verify_nonce( $_POST['sfwc_switch_account_frontend'], 'sfwc_switch_account_frontend_action' ) ) {
																									
		wc_add_notice( esc_html__( 'Nonce could not be verified.', 'subaccounts-for-woocommerce' ), 'error');

	} else {


		/**
		 * Validation before account switch.
		 */
		if ( isset( $_POST['sfwc_frontend_children'] ) ) {

			$selected = sanitize_text_field( $_POST['sfwc_frontend_children'] );


			/**
			 * Check if $selected (numeric string) is a positive number.
			 *
			 * 3			true
			 * 03			false
			 * 3.5			false
			 * 3,5			false
			 * +3			false
			 * -3			false
			 * 1337e0		false
			 */
			if ( is_numeric( $selected ) && $selected >= 1 && preg_match( '/^[1-9][0-9]*$/', $selected ) ) {


				/**
				 * Check if logged in user is Supervisor.
				 *
				 * In this case this should be enough:
				 * if ( is_user_logged_in() && $account_level_type == 'supervisor' ) {...}
				 *
				 * Anyway...
				 */
				if ( ( is_user_logged_in() && $account_level_type == 'supervisor' ) && ( isset( $cookie_value_supervisor ) && ( $cookie_value_supervisor === $is_or_was_supervisor ) ) ) {

					/**
					 * Check if selected user is a subaccount of currently logged Supervisor.
					 *
					 * Or, in case Supervisor has switched to a Manager, check if selected user is a sub-acount of currently logged Mangaer (tied to the initially logged Supervisor).
					 */
					if ( in_array( $selected, $children_ids, true ) || in_array( $selected, $children_of_manager, true ) ) {

						// Clears the cart session when called.
						wc_empty_cart(); // Necessary in order for the cart to be auto-populated with correct data after the switch.
						
						// Removes all of the cookies associated with authentication.
						wp_clear_auth_cookie();
											
						wp_set_current_user( $selected );
						wp_set_auth_cookie( $selected );
											
						// Fix cart not populating after switch from user with empty cart to user with data in cart.
						wc_setcookie( 'woocommerce_cart_hash', md5( wp_json_encode( WC()->cart->get_cart() ) ) );

						//wc_setcookie( 'woocommerce_items_in_cart', 1 );
						//do_action( 'woocommerce_set_cart_cookies', true );

					} else {

						wc_add_notice( esc_html__( 'You are not authorized to access the chosen account.', 'subaccounts-for-woocommerce' ), 'error' );
					}

				}
				/**
				 * Check if logged in user is Manager.
				 */
				elseif ( is_user_logged_in() && $account_level_type == 'manager' ) {

					/**
					 * Check if currently logged in 'Manager' has come to its account after switching from 'Supervisor'.
					 *
					 * Checking this by verifying if 'is_supervisor' cookie is set on its browser.
					 */
					if ( isset( $cookie_value_supervisor ) && ( $cookie_value_supervisor === $is_or_was_supervisor ) ) {

						if ( ( ! empty( $children_ids ) && in_array( $selected, $children_ids, true ) ) || $selected == $supervisor_id ) {

							// Clears the cart session when called.
							wc_empty_cart(); // Necessary in order for the cart to be auto-populated with correct data after the switch.
							
							// Removes all of the cookies associated with authentication.
							wp_clear_auth_cookie();
												
							wp_set_current_user( $selected );
							wp_set_auth_cookie( $selected );
												
							// Fix cart not populating after switch from user with empty cart to user with data in cart.
							wc_setcookie( 'woocommerce_cart_hash', md5( wp_json_encode( WC()->cart->get_cart() ) ) );

							//wc_setcookie( 'woocommerce_items_in_cart', 1 );
							//do_action( 'woocommerce_set_cart_cookies', true );

						} else {

							wc_add_notice( esc_html__( 'You are not authorized to access the chosen account.', 'subaccounts-for-woocommerce' ), 'error' );
						}
					}
					/**
					 * Otherwise it means that 'Manager' has logged in from its own account (without switching from Supervisor).
					 *
					 * Therefore do not provide him access to its 'Supervisor' by removing: $selected == $supervisor_id.
					 */				
					elseif ( ! isset( $cookie_value_supervisor ) || ( $cookie_value_supervisor !== $is_or_was_supervisor ) ) {
						
						// Make sure 'is_manager' cookie is set and its value is equal to transient stored in DB
						if ( isset( $cookie_value_manager ) && ( $cookie_value_manager === $is_or_was_manager ) ) {

							if ( ! empty( $children_ids ) && in_array( $selected, $children_ids, true ) ) {

								// Clears the cart session when called.
								wc_empty_cart(); // Necessary in order for the cart to be auto-populated with correct data after the switch.
								
								// Removes all of the cookies associated with authentication.
								wp_clear_auth_cookie();
													
								wp_set_current_user( $selected );
								wp_set_auth_cookie( $selected );
													
								// Fix cart not populating after switch from user with empty cart to user with data in cart.
								wc_setcookie( 'woocommerce_cart_hash', md5( wp_json_encode( WC()->cart->get_cart() ) ) );

								//wc_setcookie( 'woocommerce_items_in_cart', 1 );
								//do_action( 'woocommerce_set_cart_cookies', true );

							} else {

								wc_add_notice( esc_html__( 'You are not authorized to access the chosen account.', 'subaccounts-for-woocommerce' ), 'error' );
							}

						}
					}
				}
				/**
				 * Check if currently logged in 'Default' user has come to its account after switching from 'Supervisor' or 'Manager'.
				 *
				 * Checking this by verifying if either 'is_supervisor' or 'is_manager' cookie is set on its browser.
				 */
				elseif (
							( is_user_logged_in() && $account_level_type !== 'supervisor' || $account_level_type !== 'manager' ) 
							&& ( ( isset( $cookie_value_supervisor ) && ($cookie_value_supervisor === $is_or_was_supervisor ) ) || ( isset( $cookie_value_manager ) && ( $cookie_value_manager === $is_or_was_manager ) ) ) 
						) {


					// Get Supervisor's ID from Default user's Manager ID
					$args_supervisor = array(
						//'role'    => 'customer',
						//'role__in' => ['customer', 'subscriber'],
						'role__in' => $sfwc_option_selected_roles,
						//'exclude'  => $user_id,	// Exclude ID of customer who made currently displayed order
						'orderby' => 'ID',
						'order' => 'ASC',
						'meta_key' => 'sfwc_account_level_type',
						'meta_value' => 'supervisor',
						'meta_query' => array(
							array(
								'key' => 'sfwc_children',
								'value' => '"'.$manager_id.'"',
								'compare' => 'LIKE',
							),
						),
					);


					// The User Query
					$user_query_supervisor = new WP_User_Query( $args_supervisor );



					// User Loop
					if ( ! empty( $user_query_supervisor->get_results() ) ) {
						foreach ( $user_query_supervisor->get_results() as $user ) {

							$supervisor_id = $user->ID;
						}
					}


					if ( ( ! empty( $children_ids ) && in_array( $selected, $children_ids, true ) ) || isset( $supervisor_id ) && $supervisor_id == $selected || isset( $manager_id ) && $manager_id == $selected ) {

						// Clears the cart session when called.
						wc_empty_cart(); // Necessary in order for the cart to be auto-populated with correct data after the switch.
						
						// Removes all of the cookies associated with authentication.
						wp_clear_auth_cookie();
											
						wp_set_current_user( $selected );
						wp_set_auth_cookie( $selected );
											
						// Fix cart not populating after switch from user with empty cart to user with data in cart.
						wc_setcookie( 'woocommerce_cart_hash', md5( wp_json_encode( WC()->cart->get_cart() ) ) );

						//wc_setcookie( 'woocommerce_items_in_cart', 1 );
						//do_action( 'woocommerce_set_cart_cookies', true );

					} else {
						
						wc_add_notice( esc_html__( 'You are not authorized to access the chosen account.', 'subaccounts-for-woocommerce' ), 'error' );

					}
				} else {

					wc_add_notice( esc_html__( 'You are not authorized to access the chosen account.', 'subaccounts-for-woocommerce' ), 'error' );

				}
			}

			// If $selected is not a positive integer.
			else {
				
				wc_add_notice( esc_html__( 'Incorrect data sent.', 'subaccounts-for-woocommerce' ), 'error' );
				
			}
		}
	}
}
add_action('wp', 'sfwc_set_current_user_cookies');




/**
 * Add "Subaccounts" menu item and content to My Account page (Pt.1).
 *
 * Declare "subaccounts" endpoint as query vars.
 *
 * To allow the composite filter hook woocommerce_endpoint_{$endpoint}_title to work with custom My Account endpoints,
 * you need to declare the new endpoint as query vars in woocommerce_get_query_vars filter hook.
 *
 * Also required in order to be able to detect if "subaccounts" is the current page with is_wc_endpoint_url() function.
 */
function sfwc_subaccounts_endpoint_query_vars( $query_vars ) {
	$query_vars['subaccounts'] = sanitize_text_field( get_option( 'woocommerce_myaccount_subaccounts_endpoint', 'subaccounts' ) );
	
	return $query_vars;
}
add_filter( 'woocommerce_get_query_vars', 'sfwc_subaccounts_endpoint_query_vars' );




/**
 * Add "Subaccounts" menu item and content to My Account page (Pt.2).
 *
 * Insert the new endpoint into the My Account menu.
 */
function sfwc_insert_subaccounts_link_my_account( $items ) {
	
	// Get ID of currently logged-in user
	$current_user_id = get_current_user_id();

	// Get account type of currently logged-in user
	$user_account_level_type = get_user_meta( $current_user_id, 'sfwc_account_level_type', true );
	
	// Get Options settings.
	$sfwc_options = (array) get_option('sfwc_options');
						
	// Get 'Choose who can create and add new subaccounts' from Options settings.
	$sfwc_options_subaccount_creation = ( isset( $sfwc_options['sfwc_options_subaccount_creation'] ) ) ? $sfwc_options['sfwc_options_subaccount_creation'] : 'customer';
	
	// 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');

		
		/* Query of all Managers */
		$args_are_managers = array(
			'role__in' => $sfwc_option_selected_roles,
			'orderby' => 'ID',
			'order' => 'ASC',
			'meta_query' => array(
				array(
					'key' => 'sfwc_account_level_type',
					'value' => 'manager',
					'compare' => '=',
				),
			),
		);
		// The User Query
		$customers_are_managers = new WP_User_Query( $args_are_managers );
					
					
					
		// User Loop
		if ( ! empty( $customers_are_managers->get_results() ) ) {

			foreach ( $customers_are_managers->get_results() as $user ) {

				$list_of_children_for_single_user = get_user_meta( $user->ID, 'sfwc_children', true );

				if ( ! empty( $list_of_children_for_single_user ) ) {
					
					foreach ( $list_of_children_for_single_user as $single_id ) {

						$list_of_children_for_all_managers[] = $single_id;
					}
				}
			}
		}


	if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {
		
		// Show 'Add Subaccount' menu item if logged in user is a Manager.
		if ( $user_account_level_type == "manager" ) {

			unset( $items[ 'customer-logout' ] ); // Remove Logout link.
			$items['subaccounts'] = esc_html__( 'Subaccounts', 'subaccounts-for-woocommerce' );
			$items['customer-logout'] = __( 'Logout', 'woocommerce' ); // Put Logout link back after Subaccounts item.
			
			/*
			// Or set a specific position of the item.			
			$new_item = array ( 'subaccounts' => esc_html__( 'Subaccounts', 'subaccounts-for-woocommerce' ) );
			$items = array_slice($items, 0, 5, true) +
			$new_item +
			array_slice($items, 5, null, true);
			*/
		}
		/**
		 * Also show 'Add Subaccount' menu item if we are in one of these situations:
		 *
		 *	- First condition is for those cases where the plugin has been recently installed (first-time installations), thus no manager (or children of managers) have been set yet
		 *	- User logged in as default user that has not got a manager above him (in this case the user should be turned into a manager itself while adding a subaccount)
		 *
		 * If one of these conditions is verified it is possible to show 'Add Subaccount' tab.
		 */
		elseif (
			( ( $user_account_level_type == "default" || $user_account_level_type == "" ) && ! isset( $list_of_children_for_all_managers ) ) ||
			( ( $user_account_level_type == "default" || $user_account_level_type == "" ) && ( isset( $list_of_children_for_all_managers ) && is_array( $list_of_children_for_all_managers ) && ! in_array( $current_user_id, $list_of_children_for_all_managers ) ) )
		) {
			/**
			 * Only in this case (for Default users) we need to check if the option to allow subaccounts creation in front end is allowed.
			 *
			 * For a Manager user this is not necessary because the "Subaccounts" menu item can be always shown,
			 * regardless of whether the option to allow subaccounts creation in front end is enabled or not.
			 * This because of the fact that the "Subaccounts" menu item will be always populated with the "Subaccount Orders" tab content.
			 * 
			 * In the case of a Default user (where the "Subaccount Orders" tab content will never be shown) the only available tab under "Subaccounts" menu item would be the "Add Subaccount" tab,
			 * but this should be shown only if the option to allow subaccounts creation in front end is allowed.
			 */
			if ( $sfwc_options_subaccount_creation == 'customer' || $sfwc_options_subaccount_creation == 'admin_customer' ) {
				
				unset( $items[ 'customer-logout' ] ); // Remove Logout link.
				$items['subaccounts'] = esc_html__( 'Subaccounts', 'subaccounts-for-woocommerce' );
				$items['customer-logout'] = __( 'Logout', 'woocommerce' ); // Put Logout link back after Subaccounts item.
				
				/*
				// Or set a specific position of the item.			
				$new_item = array ( 'subaccounts' => esc_html__( 'Subaccounts', 'subaccounts-for-woocommerce' ) );
				$items = array_slice($items, 0, 5, true) +
				$new_item +
				array_slice($items, 5, null, true);
				*/
			}
			
		}
	}

	return $items;
}
add_filter( 'woocommerce_account_menu_items', 'sfwc_insert_subaccounts_link_my_account' );




/**
 * Add "Subaccounts" menu item and content to My Account page (Pt.3).
 *
 * Add content conditionally based on selected tab.
 */
function sfwc_insert_subaccounts_endpoint_content( $value ) {
	
	$sanitized_value = sanitize_text_field( $value );
	
	// 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 'Choose who can create and add new subaccounts' from Options settings.
	$sfwc_options_subaccount_creation = ( isset( $sfwc_options['sfwc_options_subaccount_creation'] ) ) ? $sfwc_options['sfwc_options_subaccount_creation'] : 'customer';
	
	// 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');
	
	// Get 'Appearance' settings.
	$sfwc_switcher_appearance = (array) get_option('sfwc_switcher_appearance');

	// Get Pane Select Button Background Color.
	$sfwc_switcher_pane_select_bg_color = ( isset( $sfwc_switcher_appearance['sfwc_switcher_pane_select_bg_color'] ) ) ? $sfwc_switcher_appearance['sfwc_switcher_pane_select_bg_color'] : '#3577c9';
	
	// Get ID of currently logged-in user
	$current_user_id = get_current_user_id();
	
	// Get account type of currently logged-in user
	$user_account_level_type = get_user_meta( $current_user_id, 'sfwc_account_level_type', true );

	
	// Query of all Managers.
	$args_are_managers = array(
		'role__in' => $sfwc_option_selected_roles,
		'orderby' => 'ID',
		'order' => 'ASC',
		'meta_query' => array(
			array(
				'key' => 'sfwc_account_level_type',
				'value' => 'manager',
				'compare' => '=',
			),
		),
	);
	
	// The User Query.
	$customers_are_managers = new WP_User_Query( $args_are_managers );
				
	// User Loop.
	if ( ! empty( $customers_are_managers->get_results() ) ) {

		foreach ( $customers_are_managers->get_results() as $user ) {

			$list_of_children_for_single_user = get_user_meta( $user->ID, 'sfwc_children', true );

			if ( ! empty( $list_of_children_for_single_user ) ) {
				
				foreach ( $list_of_children_for_single_user as $single_id ) {

					$list_of_children_for_all_managers[] = $single_id;
				}
			}
		}
	}
	
	if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {
		
		/**
		 * For Managers (and Supervisors) show tabbed menu only if at least two menu items are available:
		 *
		 *	- Manage Subaccounts
		 *	- Subaccount Orders (displayed oonly in Sub-User mode)
		 */
		if ( ( $user_account_level_type == "supervisor" && sfwc_is_plugin_active( 'sfwc-supervisor-addon.php' ) || $user_account_level_type == 'manager' ) && $sfwc_option_subaccount_mode == 'sub_user' ) {
			?>
			<ul class="sfwc_my_account_tabrow">
				<li class="sfwc_my_account_tab manage_subaccounts_tab <?php if ( $sanitized_value == '' ) { echo 'selected'; } ?>" <?php echo $sanitized_value == '' ? 'style="border-bottom-color:' . $sfwc_switcher_pane_select_bg_color  . ';"' : '' ?>>
					<a href="<?php echo esc_url( wc_get_endpoint_url( 'subaccounts' ) ); ?>">
						<?php echo esc_html__( 'Manage Subaccounts', 'subaccounts-for-woocommerce' ); ?>
					</a>
				</li>
				<li class="sfwc_my_account_tab subaccount_orders_tab <?php if ($sanitized_value == 'subaccount-orders') { echo 'selected'; } ?>" <?php echo $sanitized_value == 'subaccount-orders' ? 'style="border-bottom-color:' . $sfwc_switcher_pane_select_bg_color  . ';"' : '' ?>>
					<a href="<?php echo esc_url( wc_get_endpoint_url( 'subaccounts', 'subaccount-orders' ) ); ?>">
						<?php echo esc_html__( 'Subaccount Orders', 'subaccounts-for-woocommerce' ); ?>
					</a>
				</li>
			</ul>
			<?php
		}
		
		
		if ( $sanitized_value === '' ) {
			// Echo shortcode content.
			echo do_shortcode( '[sfwc_manage_subaccounts]' );
		} elseif ( $sanitized_value === 'subaccount-orders' ) {
			// Echo shortcode content.
			echo do_shortcode( '[sfwc_subaccount_orders]' );
		} elseif ( $sanitized_value === 'add-subaccount' ) {
			// Echo shortcode content.
			echo do_shortcode( '[sfwc_add_subaccount]' );
		} else {
			echo '<p>' . esc_html__( 'There is no content available on this page.', 'subaccounts-for-woocommerce' ) . '</p>';
		}
	}
}
add_action( 'woocommerce_account_subaccounts_endpoint', 'sfwc_insert_subaccounts_endpoint_content' );









/**
 * Add "Manage Subaccounts" shortcode.
 *
 * Create the shortcode for the "Manage Subaccounts" page content.
 */
function sfwc_manage_subaccounts_content () {
	
	// When inserting the shortcode in the backend Gutenberg page editor, 
	// prevent the following error from being thrown:
	// "Updating failed. The response is not a valid JSON response."
	if( defined( 'REST_REQUEST' ) ) {
		return;
	}
	
	if ( ! is_user_logged_in() ) {
		echo '<p>' . esc_html__( 'This content is only available to logged in users.', 'subaccounts-for-woocommerce' ) . '</p>';
		return;
	}
	
	if ( isset( $_GET['user'] ) ) {
		$sanitized_user_id = absint( sanitize_text_field( $_GET['user'] ) ); // Subaccount user.
	}
	
	if ( isset( $_GET['user_page'] ) ) {
		$sanitized_user_page = absint( sanitize_text_field( $_GET['user_page'] ) );
	}
	
	// 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');
	
	// Required in order to get the pagination to work on "Manage Subaccounts" tab.
	$sanitized_current_page_users = isset( $sanitized_user_page ) ? $sanitized_user_page : 1;
	
	// Get ID of currently logged-in user
	$current_user_id = get_current_user_id();
	
	// Get account type of currently logged-in user
	$user_account_level_type = get_user_meta( $current_user_id, 'sfwc_account_level_type', true );
	
	
	/* Query of all Managers */
	$args_are_managers = array(
		'role__in' => $sfwc_option_selected_roles,
		'orderby' => 'ID',
		'order' => 'ASC',
		'meta_query' => array(
			array(
				'key' => 'sfwc_account_level_type',
				'value' => 'manager',
				'compare' => '=',
			),
		),
	);
	// The User Query
	$customers_are_managers = new WP_User_Query( $args_are_managers );
				
	$list_of_children_for_all_managers = array();			
				
	// User Loop
	if ( ! empty( $customers_are_managers->get_results() ) ) {

		foreach ( $customers_are_managers->get_results() as $user ) {

			$list_of_children_for_single_user = get_user_meta( $user->ID, 'sfwc_children', true );

			if ( ! empty( $list_of_children_for_single_user ) ) {
				
				foreach ( $list_of_children_for_single_user as $single_id ) {

					$list_of_children_for_all_managers[] = $single_id;
				}
			}
		}
	}
	
	
	if ( sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {
		
		/**
		 * "Manage Subaccounts" tab content should be displayed only if logged in customer is a Supervisor, a Manager or a Deafult user with no parent assigned.
		 *
		 * Check to see if we are in one of these situations:
		 *
		 *	1. Logged-in user is a Supervisor
		 *	2. Logged-in user is a Manager
		 *	3. Logged-in user is a Default user with no Manager assigned (thus eligible for becoming a Manager)
		 *	4. Last condition is for those cases where the plugin has been recently installed (first-time installations), thus no manager (or children of managers) have been set yet
		 */
		if ( 
			( $user_account_level_type == "supervisor" && sfwc_is_plugin_active( 'sfwc-supervisor-addon.php' ) )
			|| $user_account_level_type == 'manager'
			|| ( ( $user_account_level_type == "default" || $user_account_level_type == "" ) && ( isset( $list_of_children_for_all_managers ) && is_array( $list_of_children_for_all_managers ) && ! in_array( $current_user_id, $list_of_children_for_all_managers ) ) )
			|| ( ( $user_account_level_type == "default" || $user_account_level_type == "" ) && ! isset( $list_of_children_for_all_managers ) ) 
		) {

			echo '<div id="frontend_manage_subaccounts">';
		
			echo '<img id="sfwc-loading-icon" src="' . esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/images/loader.gif">';
				
				// If the query string ?user=n is not set, display the list of subaccounts.
				if ( ! isset( $sanitized_user_id ) ) {

					wp_enqueue_script( 'sfwc_manage_subaccounts_js', esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/js/manage-subaccounts.js', array( 'jquery' ), '', true ); // Print in footer.

					$dataToBePassed = array(
						'adminAjaxUrl' 	=> esc_url( admin_url('admin-ajax.php') ),
						'nonce' 		=> wp_create_nonce('sfwc_nonce_frontend_manage_subaccounts'),
						'currentPage'	=> $sanitized_current_page_users
					);

					wp_add_inline_script( 'sfwc_manage_subaccounts_js', 'var sfwc_vars_manage_subaccounts = ' . wp_json_encode( $dataToBePassed, JSON_PRETTY_PRINT ), 'before' );
	
				} 
				// If the query string ?user=n is set, retrieve the user ID of the subaccount and display the "Edit Subaccount" page.
				elseif ( isset( $sanitized_user_id ) ) {
					
					wp_enqueue_script( 'sfwc_edit_subaccount_js', esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/js/edit-subaccount.js', array( 'jquery' ), '', true ); // Print in footer.

					$dataToBePassed = array(
						'adminAjaxUrl' 	=> esc_url( admin_url('admin-ajax.php') ),
						'nonce' 		=> wp_create_nonce('sfwc_nonce_frontend_manage_subaccounts'),
						'currentPage'	=> $sanitized_current_page_users,
						'userId'		=> $sanitized_user_id,
					);

					wp_add_inline_script( 'sfwc_edit_subaccount_js', 'var sfwc_vars_edit_subaccount = ' . wp_json_encode( $dataToBePassed, JSON_PRETTY_PRINT ), 'before' );
				}
			
				echo '</div>'; // END #frontend_manage_subaccounts.
		}
	} else {
		echo '<p>' . esc_html__( 'This content is not available for the currently logged in user.', 'subaccounts-for-woocommerce' ) . '</p>';
	}
}
add_shortcode( 'sfwc_manage_subaccounts', 'sfwc_manage_subaccounts_content');
	
	
/**
 * Add "Subaccount Orders" shortcode.
 *
 * Create the shortcode for the "Subaccount Orders" page content.
 */
function sfwc_subaccount_orders_content () {
	
	// When inserting the shortcode in the backend Gutenberg page editor, 
	// prevent the following error from being thrown:
	// "Updating failed. The response is not a valid JSON response."
	if( defined( 'REST_REQUEST' ) ) {
		return;
	}
	
	if ( ! is_user_logged_in() ) {
		echo '<p>' . esc_html__( 'This content is only available to logged in users.', 'subaccounts-for-woocommerce' ) . '</p>';
		return;
	}
	
	if ( isset( $_GET['order'] ) ) {
		$sanitized_order_id = absint( sanitize_text_field( $_GET['order'] ) );
	}

	if ( isset( $_GET['order_page'] ) ) {
		$sanitized_order_page = absint( sanitize_text_field( $_GET['order_page'] ) );
	}
	
	// Required in order to get the pagination to work on "Subaccount Orders" tab.
	$sanitized_current_page_orders = isset( $sanitized_order_page ) ? $sanitized_order_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');
	
	// 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 'Choose who can create and add new subaccounts' from Options settings.
	$sfwc_options_subaccount_creation = ( isset( $sfwc_options['sfwc_options_subaccount_creation'] ) ) ? $sfwc_options['sfwc_options_subaccount_creation'] : 'customer';	
	
	// Get ID of currently logged-in user
	$current_user_id = get_current_user_id();
	
	// Get account type of currently logged-in user
	$user_account_level_type = get_user_meta( $current_user_id, 'sfwc_account_level_type', true );
	
	// Required in order to get the pagination to work on "Subaccount Orders" tab.
	$sanitized_current_page_orders = isset( $sanitized_order_page ) ? $sanitized_order_page : 1;
	
	// Get current permalink structure.
	$permalink_structure = get_option( 'permalink_structure' );
	
	// Get children (array) of currently logged in user.																		
	$children_ids = get_user_meta( $current_user_id, 'sfwc_children', true ); // 3rd must be: true, otherwise will turn it into a two-dimensional array.	
	
	/**
	 * Remove no longer existing users from the $children_ids array
	 * in case a user has been deleted (but still present within 'sfwc_children' meta of an ex parent account).
	 *
	 * Also exclude users whose role is not enabled in the plugin settings.
	 */
	$existing_children_ids = array();
	
	if ( ! empty ( $children_ids ) ) {
		
		if ( $user_account_level_type == 'manager' ) {
		
			foreach ( $children_ids as $single_id ) {
				
				// Check if user still exists.
				$user_exists = get_userdata( $single_id );
				if ( $user_exists !== false ) {
					
					// Check if user role is valid and enabled from plugin settings.
					if ( sfwc_is_user_role_valid( $single_id ) && sfwc_is_user_role_enabled( $single_id ) &&
						 get_user_meta( $single_id, 'sfwc_account_level_type', true ) !== 'supervisor' && 
						 get_user_meta( $single_id, 'sfwc_account_level_type', true ) !== 'manager' )
					{
						$existing_children_ids[] = $single_id;
					}
				}
			}
		} elseif ( $user_account_level_type == "supervisor" && sfwc_is_plugin_active( 'sfwc-supervisor-addon.php' ) ) {
			
			foreach ( $children_ids as $single_id ) {
				
				// Check if user still exists.
				$user_exists = get_userdata( $single_id );
				if ( $user_exists !== false ) {
					
					if ( sfwc_is_user_role_valid( $single_id ) && sfwc_is_user_role_enabled( $single_id ) && get_user_meta( $single_id, 'sfwc_account_level_type', true ) == 'manager' ) {
						
						$existing_children_ids[] = $single_id;
						
						
						// Get children (array).																		
						$children_of_manager = get_user_meta( $single_id, 'sfwc_children', true ); // 3rd must be: true, otherwise will turn it into a two-dimensional array.
						
						/**
						 * Remove no longer existing users from the $children_of_manager array
						 * in case a user has been deleted (but still present within 'sfwc_children' meta of an ex parent account).
						 *
						 * Also exclude users whose role is not enabled in the plugin settings.
						 */
						$existing_children_of_manager = array();
						
						if ( ! empty ( $children_of_manager ) ) {
							
							foreach ( $children_of_manager as $child_of_manager ) {
								
								// Check if user still exists.
								$user_exists = get_userdata( $child_of_manager );
								if ( $user_exists !== false ) {
									
									if ( sfwc_is_user_role_valid( $child_of_manager ) && sfwc_is_user_role_enabled( $child_of_manager ) && get_user_meta( $child_of_manager, 'sfwc_account_level_type', true ) !== 'supervisor' && get_user_meta( $child_of_manager, 'sfwc_account_level_type', true ) !== 'manager' ) {
										
										$existing_children_ids[] = $child_of_manager;
									}
								}
							}
						}
					}
				}
			}			
		}
	}
	
	
	
	/**
	 * Page content.
	 */
	 
	if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {

		echo '<div id="frontend_subaccount_orders">';
		
		// The "Subaccount Orders" tab content can be displayed only if Sub-User mode is enabled.
		if ( $sfwc_option_subaccount_mode == 'sub_user' ) {
			
			if ( $user_account_level_type == "supervisor" && sfwc_is_plugin_active( 'sfwc-supervisor-addon.php' ) || $user_account_level_type == 'manager' ) {

				if ( ! empty( $existing_children_ids ) ) {	// Prevent showing the Subaccounts Order form in case the logged in customer has no subaccounts.
															// This was happening in versions prior to 1.1.3, when the account type for a customer was set to 'Manager' 
															// by the admin (Pro version is/was installed) but no subaccounts were set.
			
					if ( ! isset( $sanitized_order_id ) ) {
						
						echo '<h2 style="margin: 0 0 10px 0;">' . esc_html__( 'Subaccount Orders', 'subaccounts-for-woocommerce' ) . '</h2>';

						// Query for counting total number of orders of selected subaccounts.
						$customer__all_orders = wc_get_orders( apply_filters( 'woocommerce_my_account_my_orders_query',
							array(
								'customer' => $existing_children_ids,	// Filtered IDs retrived from function: sfwc_my_account_orders_query_subaccounts_orders
								'limit' => -1, // Query all orders
							)
						));

						// Count total number of pages to show for pagination.
						$posts_per_page = 10;
						$total_records = count( $customer__all_orders );
						$total_pages = ceil( $total_records / $posts_per_page );


						// Query subaccounts orders.
						$customer_orders = wc_get_orders( apply_filters( 'woocommerce_my_account_my_orders_query',
							array(
								'customer' => $existing_children_ids,	// Filtered IDs retrived from function: sfwc_my_account_orders_query_subaccounts_orders
								'page'     => $sanitized_current_page_orders,
								'paginate' => true,
								'posts_per_page' => $posts_per_page,
							)
						));


						$has_orders = 0 < $customer_orders->total;


						// Load orders.php template to use for "Subaccount Orders" section.
						wc_get_template(
							'myaccount/orders.php',
							array(
								'current_page'    => $sanitized_current_page_orders,
								'customer_orders' => $customer_orders,
								'has_orders'      => $has_orders,
								'wp_button_class' => ' view', 	// Add class to "view" order button (required, othrwise throwing undefined).
																// Leave initial space to separate this class from previous one(s).
							)
						);
					

						// Custom pagination.
						// Default one would redirect to the default My Account -> Orders section.
						$args = array(
							'base' => esc_url( @add_query_arg( 'order_page','%#%' ) ),
							'format' => $permalink_structure == '' ? '&order_page=%#%' : '?order_page=%#%', 			// If permalink structure is set to "Plain", use '&order_page=%#%' format.
							'total' => $total_pages,
							'current' => $sanitized_current_page_orders,
							'show_all' => false,
							'mid_size' => 2,
							'end_size' => 2,
							'prev_next' => true,
							'prev_text' => __( '&laquo; Previous', 'subaccounts-for-woocommerce' ),
							'next_text' => __( 'Next &raquo;', 'subaccounts-for-woocommerce' ),
							'type' => 'plain',
							'add_args' => false,
							'add_fragment' => ''
						);

					   
						// Check if there are orders before echoing pagination.
						if ( $has_orders && $total_records > $posts_per_page ) {
							 echo '<div class="pagination">' . paginate_links( $args ) . '</div>';
						}
					

						/***
						Or instead of wc_get_template, load custom template:

						include( WP_PLUGIN_DIR . '/subaccounts-for-woocommerce/templates/custom-orders-template.php' );
						***/
						
					} elseif ( isset( $sanitized_order_id ) ) {
						
						// Prevent ?order=0.
						if ( $sanitized_order_id <= 0 ) {
							
							echo esc_html__( 'Order is not valid.', 'subaccounts-for-woocommerce' );
							return;
						}
						
						// Get ID of currently logged-in user.
						#$user_id = get_current_user_id();
						
						// Get children (array) of currently logged in user.																		
						#$children_ids = get_user_meta( $user_id, 'sfwc_children', true );
					
						// Get Order data.
						$order = wc_get_order( $sanitized_order_id );
						
						// Check if order exists.
						if( ! empty( $order ) ) {
							
							// Get ID of user tied to selected Order
							// as a string otherwise below in_array not working for validation.
							$user_id_tied_to_order = (string) $order->get_user_id(); // or $order->get_customer_id();
						
							// Validation: verify that the order belongs to a subaccount of the currently logged parent account.
							if ( in_array( $user_id_tied_to_order, $existing_children_ids, true ) ) {
				
				
								// Show the order.
								wc_get_template(
									'myaccount/view-order.php',
									array(
										 'order' => $order,
										 'order_id' => $sanitized_order_id,
									)
								);			
								
								// IMPORTANT: Remove "Order Again" button,	
								// see anonymous function below.
							
							} else {
								echo esc_html__( 'You are not allowed to view this order.', 'subaccounts-for-woocommerce' );
							}
							
						} else {
							echo esc_html__( 'Selected order does not exist.', 'subaccounts-for-woocommerce' );
						}
					}
				} else {
					
					//In case there is no subaccount yet add a notice.
					if ( $sfwc_options_subaccount_creation == 'customer' || $sfwc_options_subaccount_creation == 'admin_customer' ) {
						
						wc_print_notice(
							esc_html__( 'No subaccounts available yet.', 'subaccounts-for-woocommerce' ), 'notice' );
						
					} elseif ( $sfwc_options_subaccount_creation == 'admin' ) {
						wc_print_notice( esc_html__( 'No subaccounts available yet. Ask the site administrator to add one for you.', 'subaccounts-for-woocommerce' ), 'notice' );
					}
					else {
						
						wc_print_notice(
							esc_html__( 'No subaccounts available yet.', 'subaccounts-for-woocommerce' ) . 
							'<a class="button" href="' . esc_url( wc_get_endpoint_url( 'subaccounts', 'add-subaccount', wc_get_page_permalink( 'myaccount' ) ) ) . '">' . esc_html__( 'Add Subaccount', 'subaccounts-for-woocommerce' ) . '</a>'
						, 'notice');
					}
				}
			}
			// Currently logged-in user has Default account type.
			else {
				
				// Query of all Managers.
				$args_are_managers = array(
					'role__in' => $sfwc_option_selected_roles,
					'orderby' => 'ID',
					'order' => 'ASC',
					'meta_query' => array(
						array(
							'key' => 'sfwc_account_level_type',
							'value' => 'manager',
							'compare' => '=',
						),
					),
				);
				
				// The User Query.
				$customers_are_managers = new WP_User_Query( $args_are_managers );
				
				$list_of_children_for_all_managers = array();
							
				// User Loop.
				if ( ! empty( $customers_are_managers->get_results() ) ) {

					foreach ( $customers_are_managers->get_results() as $user ) {

						$list_of_children_for_single_user = get_user_meta( $user->ID, 'sfwc_children', true );

						if ( ! empty( $list_of_children_for_single_user ) ) {
							
							foreach ( $list_of_children_for_single_user as $single_id ) {

								$list_of_children_for_all_managers[] = $single_id;
							}
						}
					}
				}
				
				
				/**
				 * If the Default user doesn't have a Manager already assigned, provide the possibility to add a subaccount.
				 *
				 *	1. Logged-in Default user has no Manager assigned (thus eligible for becoming a Manager)
				 *	2. Last condition is for those cases where the plugin has been recently installed (first-time installations), thus no manager (or children of managers) have been set yet
				 */
				if ( ! in_array( $current_user_id, $list_of_children_for_all_managers ) || ( empty( $list_of_children_for_all_managers ) ) ) {
					
						wc_print_notice(
							esc_html__( 'No subaccounts available yet.', 'subaccounts-for-woocommerce' ) . 
							'<a class="button" href="' . esc_url( wc_get_endpoint_url( 'subaccounts', 'add-subaccount', wc_get_page_permalink( 'myaccount' ) ) ) . '">' . esc_html__( 'Add Subaccount', 'subaccounts-for-woocommerce' ) . '</a>'
						, 'notice');					
				}

				
			}
		}
		echo '</div>';
	} else {
		echo '<p>' . esc_html__( 'This content is not available for the currently logged in user.', 'subaccounts-for-woocommerce' ) . '</p>';
	}
	
	?>
	<script type="text/javascript">
	<!--
	// Hide default WC pagination.
	var woocommercePagination = document.getElementsByClassName('woocommerce-pagination');
	
	if ( woocommercePagination.length > 0 ) {
	  woocommercePagination[0].style.visibility = 'hidden';
	}
	//-->
	</script>
	<?php
}
add_shortcode( 'sfwc_subaccount_orders', 'sfwc_subaccount_orders_content');




/**
 * Grant the Manager permission to view subaccount orders when using the [sfwc_subaccount_orders] shortcode.
 * 
 * Allow Managers to view subaccount orders when Sub-User mode is enabled and the order list page is rendered via the [sfwc_subaccount_orders] shortcode.
 *
 */
function sfwc_sub_user_allow_manager_to_view_subaccount_orders( $allcaps, $caps, $args, $user ) {
	
	global $wp;
	
	if ( is_view_order_page() ) {
		// Get ID of currently viewed order in: My Account -> Orders -> View Order.
		$order_id = absint( $wp->query_vars['view-order'] );
		
		if ( $order_id <= 0 ) {
			return $allcaps;
		}
		
		// Create an order instance.
		$order = new WC_Order( $order_id );
		
		if ( ! is_a( $order, 'WC_Order' ) ) {
		   return $allcaps;
		}		
	} else {
		return $allcaps;
	}
	
	// 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 ID of currently logged in user.
	$user_id = get_current_user_id();
	
	// Get Account Level Type of currently logged in user.
	$account_level_type = get_user_meta( $user_id, 'sfwc_account_level_type', true );
	
	// Get children (array) of currently logged in user.																		
	$children_ids = get_user_meta( $user_id, 'sfwc_children', true );
	
	/**
	 * Remove no longer existing users from the $children_ids array,
	 * in case a user has been deleted (but still present within 'sfwc_children' meta of an ex parent account).
	 *
	 * Also exclude users whose role is not enabled in the plugin settings.
	 */
	$existing_children_ids = array();
	
	if ( ! empty ( $children_ids ) ) {
		
		foreach ( $children_ids as $single_id ) {
			
			// Check if user still exists.
			$user_exists = get_userdata( $single_id );
			if ( $user_exists !== false ) {
				
				if ( sfwc_is_user_role_valid( $single_id ) && sfwc_is_user_role_enabled( $single_id ) &&
					 get_user_meta( $single_id, 'sfwc_account_level_type', true ) !== 'supervisor' &&
					 get_user_meta( $single_id, 'sfwc_account_level_type', true ) !== 'manager' )
				{
					
					$existing_children_ids[] = $single_id;
				}
			}
		}
	}

	if ( ! empty( $existing_children_ids ) ) {
		
		// Check if user is a Manager.
		if ( $account_level_type == 'manager' ) {
		
			// Make sure Sub-User mode is active and that we are in: My Account -> Subaccounts -> Subaccount Orders
			// or in any other page the [sfwc_subaccount_orders] shortcode is present.
			if ( ! is_wc_endpoint_url( 'orders' ) && $sfwc_option_subaccount_mode !== 'multi_user' ) {
				
				// Check if order exists.
				if( ! empty( $order ) ) {
					
					// Get ID of user tied to selected Order
					// as a string otherwise below in_array not working for validation.
					$user_id_tied_to_order = (string) $order->get_user_id(); // or $order->get_customer_id();
				
					// Validation: verify that the order belongs to the currently logged-in user or to a subaccount of the currently logged-in user.
					if ( $user_id_tied_to_order == $user_id || in_array( $user_id_tied_to_order, $existing_children_ids, true ) ) {

						if ( $caps[0] == 'view_order' 
							 #|| $caps[0] == 'order_again'
						) {		
							$allcaps[ $caps[0] ] = true;
						}
					
					} else {
						echo esc_html__( 'You are not allowed to view this order.', 'subaccounts-for-woocommerce' );
					}
					
				} else {
					echo esc_html__( 'Selected order does not exist.', 'subaccounts-for-woocommerce' );
				}
			}
		}
	}
	
    return $allcaps;
}
add_action('wp', function() {
	add_filter( 'user_has_cap', 'sfwc_sub_user_allow_manager_to_view_subaccount_orders', 10, 4 );
});




/**
 * Add "Subaccounts" menu item and content to My Account page (Pt.5).
 *
 * Remove "Order Again" button when viewing an order of a subaccount, in: Subaccounts > Subaccount Orders -> View -> Order Again.
 */
add_action('init', function() {
	
	if ( is_wc_endpoint_url( 'subaccounts' ) . '?order' ) {
		remove_action( 'woocommerce_order_details_after_order_table', 'woocommerce_order_again_button' );
	}
});




/**
 * Add "Subaccounts" menu item and content to My Account page (Pt.6).
 *
 * Remove default order number column, in: Subaccounts > Subaccount Orders.
 * We need to remove it and add our own order number column in order to change the URL of the order number links.
 */
function sfwc_remove_defualt_order_number_column( $columns ) {

	if ( is_wc_endpoint_url( 'subaccounts' ) ) {
		unset( $columns['order-number'] );
		$custom_order_number = array( 'sfwc-order-number' => esc_html( __( 'Order', 'woocommerce' ) ) );
		$columns = array_merge( $custom_order_number, $columns );
	}
    return $columns;
}
add_filter( 'woocommerce_account_orders_columns', 'sfwc_remove_defualt_order_number_column', 10, 1 );




/**
 * Add "Subaccounts" menu item and content to My Account page (Pt.7).
 *
 * Add our own order number column, in: Subaccounts > Subaccount Orders.
 * We need to customize the URL of the order number links, otherwise if clicked will point to the default My Account > Orders page.
 */
function sfwc_add_custom_order_number_column( $order ) {
	
	if ( is_wc_endpoint_url( 'subaccounts' ) ) {
		$order_number_url = add_query_arg( 'order', $order->get_id(), wc_get_endpoint_url( 'subaccounts', 'subaccount-orders' ) );
		echo '<a href="' . esc_url( $order_number_url ) . '">' . esc_html( _x( '#', 'hash before order number', 'woocommerce' ) ) . sanitize_text_field( $order->get_order_number() ) . '</a>';
	}
}
add_action( 'woocommerce_my_account_my_orders_column_sfwc-order-number', 'sfwc_add_custom_order_number_column', 10, 1 );




/**
 * Add "Add Subaccounts" shortcode.
 *
 * Create the shortcode for the "Add Subaccounts" page content.
 */
function sfwc_add_subaccount_form_content () {
	
	// When inserting the shortcode in the backend Gutenberg page editor, 
	// prevent the following error from being thrown:
	// "Updating failed. The response is not a valid JSON response."
	if( defined( 'REST_REQUEST' ) ) {
		return;
	}
	
	if ( ! is_user_logged_in() ) {
		echo '<p>' . esc_html__( 'This content is only available to logged in users.', 'subaccounts-for-woocommerce' ) . '</p>';
		return;
	}
	
	// Get Options settings.
	$sfwc_options = (array) get_option('sfwc_options');
	
	// Get 'Subaccount Mode' 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' from Options settings.
	$sfwc_option_display_name = ( isset( $sfwc_options['sfwc_option_display_name'] ) ) ? $sfwc_options['sfwc_option_display_name'] : 'username';
	
	// Get 'Subaccounts Number Limit' from Options settings.
	$sfwc_option_subaccounts_number_limit = ( isset( $sfwc_options['sfwc_option_subaccounts_number_limit'] ) ) ? $sfwc_options['sfwc_option_subaccounts_number_limit'] : 10;
						
	// Get 'Choose who can create and add new subaccounts' from Options settings.
	$sfwc_options_subaccount_creation = ( isset( $sfwc_options['sfwc_options_subaccount_creation'] ) ) ? $sfwc_options['sfwc_options_subaccount_creation'] : 'customer';
	
	// 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');
	
	// Get ID of currently logged-in user
	$parent_user_id = get_current_user_id();
	
	// Get the user object.
	$parent_user_data = get_userdata( $parent_user_id );
	
	// Get account type of currently logged-in user
	$user_account_level_type = get_user_meta( $parent_user_id, 'sfwc_account_level_type', true );
	
	

	// Query all Managers.
	$args_are_managers = array(
		'role__in' => $sfwc_option_selected_roles,
		'orderby' => 'ID',
		'order' => 'ASC',
		'meta_query' => array(
			array(
				'key' => 'sfwc_account_level_type',
				'value' => 'manager',
				'compare' => '=',
			),
		),
	);
	
	// The User Query.
	$customers_are_managers = new WP_User_Query( $args_are_managers );
				
	// User Loop.
	if ( ! empty( $customers_are_managers->get_results() ) ) {

		foreach ( $customers_are_managers->get_results() as $user ) {

			$list_of_children_for_single_user = get_user_meta( $user->ID, 'sfwc_children', true );

			if ( ! empty( $list_of_children_for_single_user ) ) {
				
				foreach ( $list_of_children_for_single_user as $single_id ) {

					$list_of_children_for_all_managers[] = $single_id;
				}
			}
		}
	}	

	
	// Check if option is enabled.
	if ( $sfwc_options_subaccount_creation == 'customer' || $sfwc_options_subaccount_creation == 'admin_customer' ) {
		
		if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {
			
			
			 # Check to see if we are in one of these situations:
			 #
			 #	- User logged in as supervisor
			 #	- User logged in as manager
			 #	- 2nd condition is for those cases where the plugin has been recently installed (first-time installations), thus no manager (or children of managers) have been set yet
			 #	- User logged in as default user that has not got a manager above him (in this case the user should be turned into a manager itself while adding a subaccount)
			 #
			 # If one of these conditions is verified it is possible to show 'Add Subaccount' tab.
			 
			if ( ( $user_account_level_type == "supervisor" && sfwc_is_plugin_active( 'sfwc-supervisor-addon.php' ) )
				 || $user_account_level_type == "manager" 
				 || ( ( $user_account_level_type == "default" || $user_account_level_type == "" ) && ! isset( $list_of_children_for_all_managers ) )
				 || ( ( $user_account_level_type == "default" || $user_account_level_type == "" ) && ( isset( $list_of_children_for_all_managers ) && is_array( $list_of_children_for_all_managers ) && ! in_array( $parent_user_id, $list_of_children_for_all_managers ) ) ) 
			) {
				/*
				//Check 'Customer Display Name' in Subaccounts > Settings > Options and display it accordingly.
				if ( ( $sfwc_option_display_name == 'full_name' ) && ( $parent_user_data->user_firstname || $parent_user_data->user_lastname ) ) {

					// Echo 'Full Name + Email' (if either First Name or Last Name has been set).
					$user_parent_name = '<strong>' . esc_html( $parent_user_data->user_firstname ) . ' ' . esc_html( $parent_user_data->user_lastname ) . '</strong>';

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

					// Echo 'Company + Email' (if Company name has been set).
					$user_parent_name = '<strong>' . esc_html( $parent_user_data->billing_company ) . '</strong>';

				} else {

					// Otherwise echo 'Username + Email'.
					$user_parent_name = '<strong>' . esc_html( $parent_user_data->user_login ) . '</strong>';
				}
				*/
				
				$user_parent_name = '<strong>';
				$user_parent_name .= wp_kses( 
					sfwc_get_customer_display_name( $parent_user_id, false ), 
					array(
						'span' => array(
							'class' => array()
						)
					) 
				);
				$user_parent_name .= '</strong>';
				

				/**
				 * Get subaccounts of the currently logged in user.
				 *
				 * This array might include empty values, aka users that are still set as subaccounts of the current user,
				 * but no longer exist (have been deleted from admin).
				 */
				$already_children = get_user_meta( $parent_user_id, 'sfwc_children', true );
				
				$already_children_existing = array();
				
				// Exclude possible empty values (no longer existing users) from array.
				if ( ! empty( $already_children ) ) {

					foreach ( $already_children as $key => $value ) {
						
						// Prevent empty option values within the frontend dropdown user switcher 
						// in case a user has been deleted (but still present within 'sfwc_children' meta of an ex parent account).
						$user_exists = get_userdata( $value );
						if ( $user_exists !== false ) {

							$already_children_existing[] = $value;
						}
					}
					
					if ( isset( $already_children_existing ) && is_array( $already_children_existing ) ) {
					
						$qty_subaccount_already_set = count( $already_children_existing );
						
						if ( 	
								( ( $qty_subaccount_already_set >= $sfwc_option_subaccounts_number_limit || $qty_subaccount_already_set >= 10 ) && ! sfwc_is_plugin_active( 'subaccounts-for-woocommerce-pro.php' ) ) ||
								( $qty_subaccount_already_set >= $sfwc_option_subaccounts_number_limit && $sfwc_option_subaccounts_number_limit != 0 )
						
							) {
							
							wc_print_notice(
								sprintf(
									esc_html__( 'Maximum number of subaccounts already reached for %1$s. Please contact the site administrator and ask to increase this value.', 'subaccounts-for-woocommerce' ), 
									$user_parent_name
								)
							, 'error');
							
							return;
						}
					}
				}

				/**
				 * In case form submit was unsuccessful, re-populate input fields with previously posted (wrong) data,
				 * so that user can correct it.
				 *
				 * If successful, input fields cleared with $_POST = array(); in above validation function.
				 */
				$user_login = isset( $_POST['user_login'] ) && $_POST['user_login'] != "" ? sanitize_user( $_POST['user_login'] ) : "";
				$email = isset( $_POST['email'] ) && $_POST['email'] != "" ? sanitize_email( $_POST['email'] ) : "";
				$first_name = isset( $_POST['first_name'] ) && $_POST['first_name'] != "" ? sanitize_text_field( $_POST['first_name'] ) : "";
				$last_name = isset( $_POST['last_name'] ) && $_POST['last_name'] != "" ? sanitize_text_field( $_POST['last_name'] ) : "";
				$company = isset( $_POST['company'] ) && $_POST['company'] != "" ? sanitize_text_field( $_POST['company'] ) : "";
				?>
				
				<div id="frontend_add_subaccount">
					<img id="sfwc-loading-icon" src="<?php echo esc_url( WP_PLUGIN_URL . '/subaccounts-for-woocommerce/assets/images/loader.gif' ); ?>">
					<?php
					wp_enqueue_script( 'sfwc_add_subaccount_js', esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/js/add-subaccount.js', array( 'jquery' ), '', true ); // Print in footer.

					$dataToBePassed = array(
						'adminAjaxUrl' 	=> esc_url( admin_url('admin-ajax.php') ),
						'nonce' 		=> wp_create_nonce('sfwc_nonce_frontend_add_subaccount'),
					);

					wp_add_inline_script( 'sfwc_add_subaccount_js', 'var sfwc_vars_add_subaccount = ' . wp_json_encode( $dataToBePassed, JSON_PRETTY_PRINT ), 'before' );
					?>
				</div>
			<?php
			}
		} else {
			echo '<p>' . esc_html__( 'This content is not available for the currently logged in user.', 'subaccounts-for-woocommerce' ) . '</p>';
		}
	}
}
add_shortcode( 'sfwc_add_subaccount', 'sfwc_add_subaccount_form_content');




/**
 * Add "Subaccounts" menu item and content to My Account page (Pt.9).
 *
 * Handle form submitted data when adding a new subaccount.
 *
 * My Account -> Subaccounts -> Add Subaccount.
 *
 * See also: sfwc_validate_additional_fields_for_supervisor_in_frontend_add_subaccount_form function in Supervisor Add-On.
 */
function sfwc_add_subaccount_form_handler() {
	
	// 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');
	
	// Get 'New Subaccount Default Role' value.
	$sfwc_option_subaccount_default_role = ( isset( $sfwc_options['sfwc_option_subaccount_default_role'] ) ) ? $sfwc_options['sfwc_option_subaccount_default_role'] : 'select_role';
	
	// Get 'Select new subaccount default role(s)' option value.
	$sfwc_option_subaccount_default_role_select_role = ( isset( $sfwc_options['sfwc_option_subaccount_default_role_select_role'] ) ) ? $sfwc_options['sfwc_option_subaccount_default_role_select_role'] : array( 'customer' );
	
    // Check if user switcher is enabled.
    $sfwc_options_enable_user_switcher = ( isset( $sfwc_options['sfwc_options_enable_user_switcher'] ) ) ? $sfwc_options['sfwc_options_enable_user_switcher'] : 1;

	// Get ID of currently logged-in user.
	$parent_user_id = get_current_user_id();
	
	// Get account type of currently logged-in user
	$parent_user_account_type = get_user_meta( $parent_user_id, 'sfwc_account_level_type', true );
	
	// Get parent account roles.
	$parent_roles = sfwc_is_user_role_valid( $parent_user_id );
	
	// Sanitize posted data.
	$user_login = ""; // For validation and sanitization see below
	$email = ""; // For validation and sanitization see below
	$first_name = isset( $_POST['first_name'] ) && $_POST['first_name'] != "" ? sanitize_text_field( $_POST['first_name'] ) : "";
	$last_name = isset( $_POST['last_name'] ) && $_POST['last_name'] != "" ? sanitize_text_field( $_POST['last_name'] ) : "";
	$company = isset( $_POST['company'] ) && $_POST['company'] != "" ? sanitize_text_field( $_POST['company'] ) : "";
	
	
	// Validation and sanitization of Username input field.
	if ( isset( $_POST['user_login'] ) && $_POST['user_login'] == "" ) {

		wc_add_notice( esc_html__( 'Username is required.', 'subaccounts-for-woocommerce' ), 'error');
	
	} elseif ( isset( $_POST['user_login'] ) && $_POST['user_login'] != "" ) {
		
		if ( ! validate_username( $_POST['user_login'] ) ) {
																			
			wc_add_notice( esc_html__( 'Username is not valid.', 'subaccounts-for-woocommerce' ), 'error');

		} else {
			$user_login = sanitize_user( $_POST['user_login'] );
		}
	}
	
	
	// Validation and sanitization of Email input field.
	if ( isset( $_POST['email'] ) && $_POST['email'] == "" ) {

		wc_add_notice( esc_html__( 'Email is required.', 'subaccounts-for-woocommerce' ), 'error');

	} elseif ( isset( $_POST['email'] ) && $_POST['email'] != "" ) {
		
		if ( ! is_email( $_POST['email'] ) ) {

			wc_add_notice( esc_html__( 'Email is not valid.', 'subaccounts-for-woocommerce' ), 'error');

		} else {
			$email = sanitize_email( $_POST['email'] );
		}
	}	
	

	/**
	 * Validate Supervisor Add-On posted data.
	 * See function: sfwc_validate_additional_fields_for_supervisor_in_frontend_add_subaccount_form.
	 */
	if( isset( $_POST['account_type'] ) && $_POST['account_type'] == 'default' ) {
			
		/**
		 * Supervsior is adding a new Subaccount (Default account type).
		 */
		if( ! isset( $_POST['assigned_manager'] ) ) {
			
			wc_add_notice( esc_html__( 'Assigned Manager is required.', 'subaccounts-for-woocommerce' ), 'error');
			return;
		}
	}
	

	/**
	 * If at least basic required information for subaccount creation is provided and validated:
	 * 
	 * 	- $user_login
	 * 	- $email
	 *
	 * proceed with subaccount creation.
	 */
	if ( ( isset( $user_login ) && $user_login != "" && validate_username( $user_login ) ) && ( isset( $email ) && $email != "" && is_email( $email ) ) ) {
		
		// Check if nonce is in place and verfy it.
		if ( ! isset( $_POST['sfwc_add_subaccount_frontend'] ) || isset( $_POST['sfwc_add_subaccount_frontend'] ) && ! wp_verify_nonce( $_POST['sfwc_add_subaccount_frontend'], 'sfwc_add_subaccount_frontend_action' ) ) {
																										
			wc_add_notice( esc_html__( 'Nonce could not be verified.', 'subaccounts-for-woocommerce' ), 'error');

		} else {
			
			/**
			 * Everything looks fine, we can proceed with subaccount creation.
			 */
		
			// Generate a password for the subaccount.
			$password = wp_generate_password();
			
			
			$userinfo = array(
				'user_login' => $user_login,
				'user_email' => $email,
				'first_name' => $first_name,
				'last_name' => $last_name,
				'user_pass' => $password,
				'role' => '', // wp_insert_user() function does not support adding multiple roles directly, so we'll handle this later...
			);

			/*
			// Check 'New User Default Role' in: Dashboard -> Settings -> General -> New User Default Role.
			$default_user_role = get_option('default_role');
			
			// Set user role.
			
			if ( in_array( $default_user_role, sfwc_get_valid_roles() ) ) {
				$userinfo['role'] = $default_user_role;
			}
			else {
				$userinfo['role'] = 'customer';
			}
			*/
			
			// Create the WordPress User object with the basic required information.
			$user_id = wp_insert_user( $userinfo );

			// If wp_insert_user executes successfully, it will return the id of the created user.
			if ( ! $user_id || is_wp_error( $user_id ) ) {

				// In case something went wrong with wp_insert_user, throw related errors.
				wc_add_notice( $user_id->get_error_message(), 'error');

			} else {
				
				// Get the user object.
				$subaccount = get_userdata( $user_id );
				
				// Set subaccount role(s).
				if ( $sfwc_option_subaccount_default_role === 'select_role' ) {
					
					foreach ( $sfwc_option_subaccount_default_role_select_role as $role ) {
						$subaccount->add_role( $role );
					}
				} elseif ( $sfwc_option_subaccount_default_role === 'inherit_role' ) {
					
					if( ! empty( $parent_roles ) ) {
						
						foreach( $parent_roles as $parent_role ) {

							$subaccount->add_role( $parent_role );
						}
					} else {
						$subaccount->add_role( 'customer' );
					}
				}
				
				// If wp_insert_user has executed successfully and the id of the created user has been returned, use that id to insert Company name.
				update_user_meta( $user_id, 'billing_company', $company ); // Already sanitized.
				
				
				$switcher_notice = ( $sfwc_options_enable_user_switcher == 1 ) ? '<br>' . esc_html__( 'You can now switch to the newly added subaccount by selecting it from the drop-down menu.', 'subaccounts-for-woocommerce' ) : '';

				wc_add_notice( '<strong>' . esc_html__( 'Subaccount successfully added.', 'subaccounts-for-woocommerce' ) . '</strong>' . $switcher_notice, 'success');			
			






				/**
				 * In case the logged in user has a "default" (or "") account level type AND has not got a manager above him,
				 * turn the user itself into a manager while adding a subaccount.
				 */


				/* Query of all Managers */
				$args_are_managers = array(
					'role__in' => $sfwc_option_selected_roles,
					'orderby' => 'ID',
					'order' => 'ASC',
					'meta_query' => array(
						array(
							'key' => 'sfwc_account_level_type',
							'value' => 'manager',
							'compare' => '=',
						),
					),
				);
				// The User Query
				$customers_are_managers = new WP_User_Query( $args_are_managers );
							
							
				$list_of_children_of_all_managers = array();
				
				// User Loop
				if ( ! empty( $customers_are_managers->get_results() ) ) {

					foreach ( $customers_are_managers->get_results() as $user ) {

						$list_of_children_for_single_user = get_user_meta( $user->ID, 'sfwc_children', true );

						if ( ! empty( $list_of_children_for_single_user ) ) {
							
							foreach ( $list_of_children_for_single_user as $single_id ) {

								$list_of_children_of_all_managers[] = $single_id;
							}
						}
					}
				}

				// If loggedin user has a "default" account type and has not got a manager above him, turn it into a Manager.
				if ( ( $parent_user_account_type == "default" || $parent_user_account_type == "" ) && ! in_array( $parent_user_id, $list_of_children_of_all_managers ) ) {

					update_user_meta( $parent_user_id, 'sfwc_account_level_type', 'manager' );
				}
					
				




				if( $parent_user_account_type !== 'supervisor' ) {
					
					$already_children = get_user_meta( $parent_user_id, 'sfwc_children', true ); // We need to get the value of the array and update it by adding the new ID,
																								 // otherwise array values which are already present will be overwritten and only the last ID will be added.
					// Check to see if thare are children already set...
					if ( is_array( $already_children ) && ! empty( $already_children ) ) {
					
						array_push( $already_children, (string)$user_id );
					  
					// ... If not, create a single element array and store it.
					} else {
						$already_children = array();
						$already_children[] = (string)$user_id;
					}

					update_user_meta( $parent_user_id, 'sfwc_children', $already_children );
				}






				/**
				 * Hook: sfwc_frontend_after_add_subaccount_validation.
				 *
				 * Allow developers to save extra data on frontend subaccount creation.
				 *
				 * @param int         $user_id User ID of subaccount being created.
				 * @since 1.4.1
				 */
				do_action( 'sfwc_frontend_after_add_subaccount_validation', $parent_user_id, $user_id );




				/**
				 * Send WooCommerce "Customer New Account" email notification to newly created subaccount with username and link to set its the password.
				 *
				 * Make sure it's enabled:
				 *
				 * WooCommerce > Settings > Account and privacy 
				 * 
				 * 		- When creating an account, automatically generate an account password
				 *
				 * WooCommerce > Settings > Emails
				 *
				 *		- 'New Account' email
				 *
				 * https://stackoverflow.com/questions/61576356/send-an-email-notification-with-the-generated-password-on-woocommerce-user-creat/#answer-61582804
				 */
				 
				// Get all WooCommerce emails Objects from WC_Emails Object instance
				$emails = WC()->mailer()->get_emails();

				// Send "Customer New Account" email notification.
				$emails['WC_Email_Customer_New_Account']->trigger( $user_id, $password, true );




				// If subaccount has been successfully created, clear the form.
				if ( isset( $user_id ) && !is_wp_error( $user_id ) ) {
					
					$_POST = array();
				}
			}
		}
	}

	/**
	 * Debug.
	 */
	 
	//echo $parent_user_id;

	// $already_children = get_user_meta( $parent_user_id, 'sfwc_children', true );
	// echo '<pre>',print_r($already_children,1),'</pre>';

	// $check_account_type = get_user_meta( $parent_user_id, 'sfwc_account_level_type', true );
	// var_dump( $check_account_type );

}

/**
 * Do not change template_redirect as hook here.
 * 
 * This function needs to run before than:
 *
 *		woocommerce_before_account_navigation, see: add_action('woocommerce_before_account_navigation', 'sfwc_action_woocommerce_account_dashboard');
 *
 * so that the newly created subaccount will appear immediately after form submission within the user switcher (no page refresh required).
 */
add_action( 'template_redirect', 'sfwc_add_subaccount_form_handler', 10);	// Priority must be higher than sfwc_set_parent_account_cookie function for earlier execution.
																			// Otherwise the user switcher pane won't show instantly after the first subaccount creation for new accounts (page refresh would be required).




/**
 * Add "Subaccounts" menu item and content to My Account page (Pt.10).
 *
 * Handle form submitted data when editing subaccount.
 *
 * My Account -> Subaccounts -> Manage Subaccounts -> Edit Subaccount.
 */
function sfwc_frontend_edit_subaccount_form_handler() {
	
	// Make sure we don't interfere My Account -> Addresses forms.
	if ( ! isset( $_POST['update-subaccount'] ) )
		return;

	// Retrieve (Ajax) user_id of customer which is currently being edited My Account -> Subaccounts -> Manage Subaccounts.
	if ( isset( $_POST['sfwc_frontend_edit_subaccount_user_id'] ) ) {
		$user_id = absint( sanitize_text_field( $_POST['sfwc_frontend_edit_subaccount_user_id'] ) );
	} else {
		return;
	}
	
	// Before proceeding check if nonce is in place and verfy it. Leave this after checking: isset( $_POST['sfwc_frontend_edit_subaccount_user_id'] )
	if ( ! isset( $_POST['sfwc_nonce_frontend_edit_subaccount_form'] ) || isset( $_POST['sfwc_nonce_frontend_edit_subaccount_form'] ) && ! wp_verify_nonce( $_POST['sfwc_nonce_frontend_edit_subaccount_form'], 'sfwc_nonce_frontend_edit_subaccount_action' ) ) {
		wc_add_notice( esc_html__( 'Nonce could not be verified.', 'subaccounts-for-woocommerce' ), 'error');
		return;
	}
	
	
	$parent_id = get_current_user_id();
	
	$sfwc_options = (array) get_option('sfwc_options');
	
    $sfwc_option_selected_roles = ( isset( $sfwc_options['sfwc_option_selected_roles'] ) ) ? $sfwc_options['sfwc_option_selected_roles'] : array('customer', 'subscriber');
	
	$parent_account_level_type = get_user_meta( $parent_id, 'sfwc_account_level_type', true );
	
	$subaccount_account_level_type = get_user_meta( $user_id, 'sfwc_account_level_type', true );
	
	
		
	if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() && ( $parent_account_level_type == 'supervisor' || $parent_account_level_type == 'manager' ) ) {
		
		
		/**
		 * Validation.
		 *
		 */
		
		// Get children (array) of currently logged in user.																		
		$children_ids = get_user_meta( $parent_id, 'sfwc_children', true );

		/**
		 * Remove no longer existing users from the $children_ids array
		 * in case a user has been deleted (but still present within 'sfwc_children' meta of an ex parent account).
		 */
		$existing_children_ids = array();
		
		if ( ! empty ( $children_ids ) ) {
			
			if ( $parent_account_level_type == 'supervisor' ) {
			
				foreach ( $children_ids as $single_id ) {
					
					// Check if user still exists.
					$user_exists = get_userdata( $single_id );
					if ( $user_exists !== false ) {
						
						// Check if user role is valid and enabled from plugin settings.
						if ( sfwc_is_user_role_valid( $single_id ) && sfwc_is_user_role_enabled( $single_id ) && get_user_meta( $single_id, 'sfwc_account_level_type', true ) == 'manager' ) {
								
							$existing_children_ids[] = $single_id;
							
							// In case currently logged in user is a Supervisor we get also subaccounts of the Manager.																		
							$children_ids_deep = get_user_meta( $single_id, 'sfwc_children', true );
							
							if ( ! empty ( $children_ids_deep ) ) {
			
								foreach ( $children_ids_deep as $single_id_deep ) {
									
									// Check if user still exists.
									$user_exists = get_userdata( $single_id_deep );
									if ( $user_exists !== false ) {
										
										// Check if user role is valid and enabled from plugin settings.
										if ( sfwc_is_user_role_valid( $single_id_deep ) && sfwc_is_user_role_enabled( $single_id_deep ) && 
											 get_user_meta( $single_id_deep, 'sfwc_account_level_type', true ) !== 'supervisor' &&
											 get_user_meta( $single_id_deep, 'sfwc_account_level_type', true ) !== 'manager' ) 
										{
											$existing_children_ids[] = $single_id_deep;
										}
									}
								}
							}
						}
					}
				}
			} elseif ( $parent_account_level_type == 'manager' ) {
				
				foreach ( $children_ids as $single_id ) {
					
					// Check if user still exists.
					$user_exists = get_userdata( $single_id );
					if ( $user_exists !== false ) {
						
						// Check if user role is valid and enabled from plugin settings.
						if ( sfwc_is_user_role_valid( $single_id ) && sfwc_is_user_role_enabled( $single_id ) && 
							 get_user_meta( $single_id, 'sfwc_account_level_type', true ) !== 'supervisor' &&
							 get_user_meta( $single_id, 'sfwc_account_level_type', true ) !== 'manager' )
						{
							$existing_children_ids[] = $single_id;
						}
					}
				}
			}
		}
		

		

		/**
		 * Validation
		 * 
		 * - Verify that the ID of the user being edited belongs to a subaccount of the currently logged-in parent account;
		 * - Verify the account level type of the subaccount.
		 */
		if ( 
			! in_array( $user_id, $existing_children_ids ) || 
			( $parent_account_level_type == 'supervisor' && $subaccount_account_level_type == 'supervisor' ) || 
			( $parent_account_level_type == 'manager' && ( $subaccount_account_level_type == 'supervisor' || $subaccount_account_level_type == 'manager' ) )
		) {			
			wc_add_notice( esc_html__( 'You are not allowed to edit this user.', 'subaccounts-for-woocommerce' ), 'error');
			return;
		}
		
		
		
		
		/**
		 * Handling of "Account Details" submitted data.
		 * 
		 */ 
		 

		// Sanitize and update user first_name.
		if ( isset( $_POST['first_name'] ) ) {
			$user_first_name_sanitized = sanitize_text_field( $_POST['first_name'] );
			update_user_meta( $user_id, 'first_name', $user_first_name_sanitized );
		}
		
		// Sanitize and update user last_name.
		if ( isset( $_POST['last_name'] ) ) {
			$user_last_name_sanitized = sanitize_text_field( $_POST['last_name'] );
			update_user_meta( $user_id, 'last_name', $user_last_name_sanitized );
		}
		
		// Sanitize and update user password.
		if ( isset( $_POST['password'] ) && $_POST['password'] != "" ) {
			
			$user_password = $_POST['password'];	// No need to sanitize here.
				
			$user_pass = array (
				'ID' => $user_id, 
				'user_pass' => $user_password,
			);

			$result = wp_update_user( $user_pass ); // wp_update_user() already take care of sanitizing with trim() and hashing.
			
			// Throw an error if the email is already used by another user.
			if ( is_wp_error( $result ) ) {
				$error_password = $result->get_error_message();
				wc_add_notice( esc_html__( $error_password, 'subaccounts-for-woocommerce' ), 'error');
			}
		}
		
		// Sanitize, validate and update user email.
		if ( isset( $_POST['email'] ) && $_POST['email'] != "" ) {
			
			$user_email_sanitized = sanitize_email( $_POST['email'] );
			
			// Verify that provided email is valid.
			if ( ! is_email( $user_email_sanitized ) ) {

				wc_add_notice( esc_html__( 'Email is not valid.', 'subaccounts-for-woocommerce' ), 'error');

			} else {
				
                $user_email = array (
                    'ID' => $user_id, 
                    'user_email' => $user_email_sanitized,
                );

                $result = wp_update_user( $user_email );
				
				// Throw an error if the email is already used by another user.
				if ( is_wp_error( $result ) ) {
					$error_email = $result->get_error_message();
					wc_add_notice( esc_html__( $error_email, 'subaccounts-for-woocommerce' ), 'error');
				}
			}
		}		
		
		
		/**
		 * Hook: sfwc_frontend_after_edit_subaccount_validation.
		 *
		 * Allow developers to save extra data when editing a subaccount on frontend.
		 *
		 * @param int         $user_id User ID of subaccount being edited.
		 * @since 1.5.5
		 */
		do_action( 'sfwc_frontend_after_edit_subaccount_validation', $user_id );		
		

		/**
		 * Handling of Billing and Shipping submitted data.
		 *
		 * Quick and dirty adaptation of the sanitization/validation code present in:
		 * woocommerce > includes > class-wc-form-handler.php
		 *
		 * Code taken from WooCommerce 7.8.0.
		 * Part of the original code left as reference (commented out).
		 * 
		 */ 
		
		
		
		/*		
		global $wp;

		$nonce_value = wc_get_var( $_REQUEST['woocommerce-edit-address-nonce'], wc_get_var( $_REQUEST['_wpnonce'], '' ) ); // @codingStandardsIgnoreLine.

		if ( ! wp_verify_nonce( $nonce_value, 'woocommerce-edit_address' ) ) {
			return;
		}

		if ( empty( $_POST['action'] ) || 'edit_address' !== $_POST['action'] ) {
			return;
		}
		*/
		wc_nocache_headers();
		/*
		$user_id = get_current_user_id();
		*/
		if ( $user_id <= 0 ) {
			return;
		}

		$customer = new WC_Customer( $user_id );

		if ( ! $customer ) {
			return;
		}
		
		




		/**
		 * Handling of Billing submitted data.
		 *
		 * Quick and dirty adaptation of the sanitization/validation code present in:
		 * woocommerce > includes > class-wc-form-handler.php
		 *
		 * Code taken from WooCommerce 7.8.0.
		 * Part of the original code left as reference (commented out).
		 * 
		 */ 

		
		/*
		$load_address = isset( $wp->query_vars['edit-address'] ) ? wc_edit_address_i18n( sanitize_title( $wp->query_vars['edit-address'] ), true ) : 'billing';

		if ( ! isset( $_POST[ $load_address . '_country' ] ) ) {
			return;
		}
		*/
		$load_billing_address = 'billing';

		if ( ! isset( $_POST[ $load_billing_address . '_country' ] ) ) {
			return;
		}


		$address = WC()->countries->get_address_fields( wc_clean( wp_unslash( $_POST[ $load_billing_address . '_country' ] ) ), $load_billing_address . '_' );

		foreach ( $address as $key => $field ) {
			if ( ! isset( $field['type'] ) ) {
				$field['type'] = 'text';
			}

			// Get Value.
			if ( 'checkbox' === $field['type'] ) {
				$value = (int) isset( $_POST[ $key ] );
			} else {
				$value = isset( $_POST[ $key ] ) ? wc_clean( wp_unslash( $_POST[ $key ] ) ) : ''; // Sanitization.
			}

			// Hook to allow modification of value.
			$value = apply_filters( 'woocommerce_process_myaccount_field_' . $key, $value );

			// Validation: Required fields.
			if ( ! empty( $field['required'] ) && empty( $value ) ) {
				/* translators: %s: Field name. */
				wc_add_notice( sprintf( __( '%s is a required field.', 'woocommerce' ), $field['label'] ), 'error', array( 'id' => $key ) );
			}

			if ( ! empty( $value ) ) {
				// Validation and formatting rules.
				if ( ! empty( $field['validate'] ) && is_array( $field['validate'] ) ) {
					foreach ( $field['validate'] as $rule ) {
						switch ( $rule ) {
							case 'postcode':
								$country = wc_clean( wp_unslash( $_POST[ $load_billing_address . '_country' ] ) );
								$value   = wc_format_postcode( $value, $country );

								if ( '' !== $value && ! WC_Validation::is_postcode( $value, $country ) ) {
									switch ( $country ) {
										case 'IE':
											$postcode_validation_notice = __( 'Please enter a valid Eircode.', 'woocommerce' );
											break;
										default:
											$postcode_validation_notice = __( 'Please enter a valid postcode / ZIP.', 'woocommerce' );
									}
									wc_add_notice( $postcode_validation_notice, 'error' );
								}
								break;
							case 'phone':
								if ( '' !== $value && ! WC_Validation::is_phone( $value ) ) {
									/* translators: %s: Phone number. */
									wc_add_notice( sprintf( __( '%s is not a valid phone number.', 'woocommerce' ), '<strong>' . $field['label'] . '</strong>' ), 'error' );
								}
								break;
							case 'email':
								$value = strtolower( $value );

								if ( ! is_email( $value ) ) {
									/* translators: %s: Email address. */
									wc_add_notice( sprintf( __( '%s is not a valid email address.', 'woocommerce' ), '<strong>' . $field['label'] . '</strong>' ), 'error' );
								}
								break;
						}
					}
				}
			}

			try {
				// Set prop in customer object.
				if ( is_callable( array( $customer, "set_$key" ) ) ) {
					$customer->{"set_$key"}( $value );
				} else {
					$customer->update_meta_data( $key, $value );
				}
			} catch ( WC_Data_Exception $e ) {
				// Set notices. Ignore invalid billing email, since is already validated.
				if ( 'customer_invalid_billing_email' !== $e->getErrorCode() ) {
					wc_add_notice( $e->getMessage(), 'error' );
				}
			}
		}
		
		
		

		
		
		/**
		 * Handling of Shipping submitted data.
		 *
		 * Quick and dirty adaptation of the sanitization/validation code present in:
		 * woocommerce > includes > class-wc-form-handler.php
		 *
		 * Code taken from WooCommerce 7.8.0.
		 * Part of the original code left as reference (commented out).
		 * 
		 */ 

		
		/*
		$load_address = isset( $wp->query_vars['edit-address'] ) ? wc_edit_address_i18n( sanitize_title( $wp->query_vars['edit-address'] ), true ) : 'billing';

		if ( ! isset( $_POST[ $load_address . '_country' ] ) ) {
			return;
		}
		*/
		$load_shipping_address = 'shipping';

		if ( ! isset( $_POST[ $load_shipping_address . '_country' ] ) ) {
			return;
		}


		$address = WC()->countries->get_address_fields( wc_clean( wp_unslash( $_POST[ $load_shipping_address . '_country' ] ) ), $load_shipping_address . '_' );

		foreach ( $address as $key => $field ) {
			if ( ! isset( $field['type'] ) ) {
				$field['type'] = 'text';
			}

			// Get Value.
			if ( 'checkbox' === $field['type'] ) {
				$value = (int) isset( $_POST[ $key ] );
			} else {
				$value = isset( $_POST[ $key ] ) ? wc_clean( wp_unslash( $_POST[ $key ] ) ) : ''; // Sanitization.
			}

			// Hook to allow modification of value.
			$value = apply_filters( 'woocommerce_process_myaccount_field_' . $key, $value );

			// Validation: Required fields.
			if ( ! empty( $field['required'] ) && empty( $value ) ) {
				/* translators: %s: Field name. */
				wc_add_notice( sprintf( __( '%s is a required field.', 'woocommerce' ), $field['label'] ), 'error', array( 'id' => $key ) );
			}

			if ( ! empty( $value ) ) {
				// Validation and formatting rules.
				if ( ! empty( $field['validate'] ) && is_array( $field['validate'] ) ) {
					foreach ( $field['validate'] as $rule ) {
						switch ( $rule ) {
							case 'postcode':
								$country = wc_clean( wp_unslash( $_POST[ $load_shipping_address . '_country' ] ) );
								$value   = wc_format_postcode( $value, $country );

								if ( '' !== $value && ! WC_Validation::is_postcode( $value, $country ) ) {
									switch ( $country ) {
										case 'IE':
											$postcode_validation_notice = __( 'Please enter a valid Eircode.', 'woocommerce' );
											break;
										default:
											$postcode_validation_notice = __( 'Please enter a valid postcode / ZIP.', 'woocommerce' );
									}
									wc_add_notice( $postcode_validation_notice, 'error' );
								}
								break;
							case 'phone':
								if ( '' !== $value && ! WC_Validation::is_phone( $value ) ) {
									/* translators: %s: Phone number. */
									wc_add_notice( sprintf( __( '%s is not a valid phone number.', 'woocommerce' ), '<strong>' . $field['label'] . '</strong>' ), 'error' );
								}
								break;
							case 'email':
								$value = strtolower( $value );

								if ( ! is_email( $value ) ) {
									/* translators: %s: Email address. */
									wc_add_notice( sprintf( __( '%s is not a valid email address.', 'woocommerce' ), '<strong>' . $field['label'] . '</strong>' ), 'error' );
								}
								break;
						}
					}
				}
			}

			try {
				// Set prop in customer object.
				if ( is_callable( array( $customer, "set_$key" ) ) ) {
					$customer->{"set_$key"}( $value );
				} else {
					$customer->update_meta_data( $key, $value );
				}
			} catch ( WC_Data_Exception $e ) {
				// Set notices. Ignore invalid billing email, since is already validated.
				if ( 'customer_invalid_billing_email' !== $e->getErrorCode() ) {
					wc_add_notice( $e->getMessage(), 'error' );
				}
			}
		}
		
		

		/**
		 * Hook: woocommerce_after_save_address_validation.
		 *
		 * Allow developers to add custom validation logic and throw an error to prevent save.
		 *
		 * @param int         $user_id User ID being saved.
		 * @param string      $load_address Type of address e.g. billing or shipping.
		 * @param array       $address The address fields.
		 * @param WC_Customer $customer The customer object being saved. @since 3.6.0
		 */
		#do_action( 'woocommerce_after_save_address_validation', $user_id, $load_address, $address, $customer );

		if ( 0 < wc_notice_count( 'error' ) ) {
			return;
		}

		$customer->save();

		wc_add_notice( __( 'Address changed successfully.', 'woocommerce' ) );		
	
	}
}
add_action( 'template_redirect', 'sfwc_frontend_edit_subaccount_form_handler' );




/**
 * Check if the user is switching to another account and if so redirect him to the Dashboard endpoint after the user swtch.
 *
 * Premise: by default after an account switch a user is automatically redirected to the same My Account page endpoint he was before the switch.
 * 
 * This was causing a couple of issues:
 *
 *	1. If a Manager account was visiting the "Add Subaccount" endpoint before the switch,
 *	   after the switch to a subaccount was still on the "Add Subaccount" endpoint, despite of the page being blank (content conditionally removed, see above).
 *
 *	2. Also, if the above Manager decided to go back to its account (while still visiting the above subaccount's blank page),
 *	   was still redirected to its "Add Subaccount" endpoint. 
 *	   But at that point if he tried to add a new subaccount would get nonce error: "Nonce could not be verified".
 *
 * To prevent all of this, here it is the redirect.
 */
function sfwc_redirect_to_dashboard_after_account_switch () {
	if ( isset( $_POST['sfwc_frontend_children'] ) ) {
		wp_safe_redirect( esc_url( get_permalink( get_option( 'woocommerce_myaccount_page_id' ) ) ) );
		exit;
	}
}
add_action('template_redirect', 'sfwc_redirect_to_dashboard_after_account_switch');




/**
 * For the following function DO NOT move validation of supervisor related values,
 * so that if Supervisor Add-on is deactivated and there are still customers with account level type set to 'supervisor'
 * the plugin will continue to store/display correct data.
 */
function sfwc_store_subaccounts_meta_data_on_order_creation( $order ) {
	
	// 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');
	
	// Get 'Subaccount Mode' from Options settings.
	$sfwc_option_subaccount_mode = ( isset( $sfwc_options['sfwc_option_subaccount_mode'] ) ) ? $sfwc_options['sfwc_option_subaccount_mode'] : 'sub_user';
	
	
	// Check if logged in user has a valid role.
	if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {
	
		// Get user id from the order.
		$customer_id = $order->get_user_id();
		
		// Get Account Level Type.
		$customer_account_level_type = get_user_meta( $customer_id, 'sfwc_account_level_type', true );
		







		if ( $customer_account_level_type == 'manager' || $customer_account_level_type == 'supervisor' ) {
	
			$manager_id = 'none';

		} else {
			
			
			/**
			 * Retrieve the ID of the manager related to Customer.
			 */
	
			// Get all users with user meta 'sfwc_account_level_type' == 'manager' and filter only the one which has 'sfwc_children' user_meta containing the child ID who made the order
			$args_manager = array(
				//'role'    => 'customer',
				//'role__in' => ['customer', 'subscriber'],
				'role__in' => $sfwc_option_selected_roles,
				'exclude' => $customer_id, // Exclude ID of customer who made currently displayed order
				'orderby' => 'ID',
				'order' => 'ASC',
				'meta_key' => 'sfwc_account_level_type',
				'meta_value' => 'manager',
				'meta_query' => array(
					array(
						'key' => 'sfwc_children',
						'value' => '"'.$customer_id.'"',
						'compare' => 'LIKE',
					),
				),
			);


			// The User Query
			$user_query_manager = new WP_User_Query( $args_manager );


			// User Loop
			if ( ! empty( $user_query_manager->get_results() ) ) {

				foreach ( $user_query_manager->get_results() as $user ) {
					
					$manager_id = $user->ID;
				}

			} else {
				
				$manager_id = 'not_set';
			}
				
		}		
				



 
		
	if ( $customer_account_level_type == 'supervisor' ) {
		
		$supervisor_id = 'none';
	}
	
	elseif ( $customer_account_level_type == 'manager' ) {
		
		/**
		 * Retrieve the Supervisor's ID related to Customer.
		 */

		// Get all users with user meta 'sfwc_account_level_type' == 'supervisor' and filter only the one which has 'sfwc_children' user_meta containing the ID of the Manager
		$args_supervisor = array(
			//'role'    => 'customer',
			//'role__in' => ['customer', 'subscriber'],
			'role__in' => $sfwc_option_selected_roles,
			'exclude' => $customer_id, // Exclude ID of customer who made currently displayed order
			'orderby' => 'ID',
			'order' => 'ASC',
			'meta_key' => 'sfwc_account_level_type',
			'meta_value' => 'supervisor',
			'meta_query' => array(
				array(
					'key' => 'sfwc_children',
					'value' => '"'.$customer_id.'"',
					'compare' => 'LIKE',
				),
			),
		);


		// The User Query
		$user_query_supervisor = new WP_User_Query( $args_supervisor );


		// User Loop
		if ( ! empty( $user_query_supervisor->get_results() ) ) {

			foreach ( $user_query_supervisor->get_results() as $user ) {
				
				$supervisor_id = $user->ID;
			}

		} else {
			
			$supervisor_id = 'not_set';
		}

	}

	elseif ( $customer_account_level_type == 'default' || $customer_account_level_type == '' || empty( $customer_account_level_type ) ) {

		// Get all users with user meta 'sfwc_account_level_type' == 'supervisor' and filter only the one which has 'sfwc_children' user_meta containing the ID of the Manager
		$args_supervisor = array(
			//'role'    => 'customer',
			//'role__in' => ['customer', 'subscriber'],
			'role__in' => $sfwc_option_selected_roles,
			'exclude' => $customer_id, // Exclude ID of customer who made currently displayed order
			'orderby' => 'ID',
			'order' => 'ASC',
			'meta_key' => 'sfwc_account_level_type',
			'meta_value' => 'supervisor',
			'meta_query' => array(
				array(
					'key' => 'sfwc_children',
					'value' => '"'.$manager_id.'"',
					'compare' => 'LIKE',
				),
			),
		);


		// The User Query
		$user_query_supervisor = new WP_User_Query( $args_supervisor );


		if ( ! empty( $user_query_manager->get_results() ) ) {
		
			// User Loop
			if ( ! empty( $user_query_supervisor->get_results() ) ) {

				foreach ( $user_query_supervisor->get_results() as $user ) {
					
					$supervisor_id = $user->ID;
				}

			} else {
				
				$supervisor_id = 'not_set';
			}
		
		} else {
				
				$supervisor_id = 'not_set';
		}
		
	}





		if ( isset($_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor'] ) ) {
			

			if ( $customer_account_level_type == 'supervisor' ) {
				
				// The order was placed by a supervisor for himself.
				$order_placed_by = 'supervisor_for_himself';

				
			} elseif ( $customer_account_level_type == 'manager' ) {
				
				// The order was placed by a manager for himself.
				$order_placed_by = 'supervisor_for_manager';

				
			} elseif ( $customer_account_level_type == 'default' || $customer_account_level_type == '' || $customer_account_level_type == null ) {
				
				// The order was placed by a manager on behalf of his subaccount.
				$order_placed_by = 'supervisor_for_default';
			}
			
		} elseif ( ! isset($_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor'] )  && isset($_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager'] ) ) {
			
			
			if ( $customer_account_level_type == 'manager' ) {
				
				// The order was placed by a manager for himself.
				$order_placed_by = 'manager_for_himself';
				
			} elseif ( $customer_account_level_type == 'default' || $customer_account_level_type == '' || $customer_account_level_type == null ) {
				
				// The order was placed by a manager on behalf of his subaccount.
				$order_placed_by = 'manager_for_default';
			}
			
		} else {
			
			// The order was placed by a 'default' customer for himself.
			$order_placed_by = 'default_for_himself';

		}




        $valid_customer_account_level_type = array( 'supervisor', 'manager', 'default', '' );

        if ( in_array( $customer_account_level_type, $valid_customer_account_level_type ) ) {
		
			// Store the customer's account level type.
			$order->update_meta_data( '_sfwc_customer_account_level_type', $customer_account_level_type );
		}



		if ( ( $supervisor_id && is_numeric( $supervisor_id ) && $supervisor_id >= 1 && preg_match( '/^[1-9][0-9]*$/', $supervisor_id ) ) || ( $supervisor_id && $supervisor_id == 'not_set' ) || ( $supervisor_id && $supervisor_id == 'none' ) ) {
		
			$valid_supervisor_id = sanitize_text_field( $supervisor_id );
			
			// Store the ID of the Supervisor related to the Customer.
			$order->update_meta_data( '_sfwc_customer_related_supervisor', $valid_supervisor_id );
		}
		
		
		/**
		 * Check if $manager_id (numeric string) is a positive number.
		 *
		 * 3			true
		 * 03			false
		 * 3.5			false
		 * 3,5			false
		 * +3			false
		 * -3			false
		 * 1337e0		false
		 */
		if ( ( $manager_id && is_numeric( $manager_id ) && $manager_id >= 1 && preg_match( '/^[1-9][0-9]*$/', $manager_id ) ) || ( $manager_id && $manager_id == 'not_set' )  || ( $manager_id && $manager_id == 'none' ) ) {
		
			$valid_manager_id = sanitize_text_field( $manager_id );
			
			// Store the ID of the Manager related to the Customer.
			$order->update_meta_data( '_sfwc_customer_related_manager', $valid_manager_id );
		}
		
		

		// Store info about who actually placed the order.
        $valid_order_placed_by = array( 'manager_for_himself', 'manager_for_default', 'default_for_himself', 'supervisor_for_himself', 'supervisor_for_manager', 'supervisor_for_default' );

        if ( in_array( $order_placed_by, $valid_order_placed_by ) ) {

			$order->update_meta_data( '_sfwc_order_placed_by', $order_placed_by );
        }
		
		
		/**
		 * In Multi-User mode, the customer ID associated with an order is replaced with the Manager's user ID:
		 *
		 *		$order->set_customer_id( absint( $manager_id ) );
		 *
		 * For this reason, in order to keep track of the ID of the customer who did place the order,
		 * we need to store it somewhere.
		 *
		 * _sfwc_order_placed_by_user_id meta has been added for this purpose.
		 *
		 * From version 1.4.3 this value is always saved on order creation (even if Sub-User mode is enabled).
		 * This is to provide more compatibility in case of switch from Sub-User mode to Multi-User mode and vice versa.
		 *
		 * Note: Despite being similar to _sfwc_order_placed_by, _sfwc_order_placed_by_user_id and _sfwc_order_placed_by
		 * have completely different purposes and store different kinds of values.
		 */
		$order->update_meta_data( '_sfwc_order_placed_by_user_id', absint( $customer_id ) );
		
		
		/**
		 * Stores the active subaccount mode at the time the order is placed.
		 *
		 * Useful to determine if one or more orders have been placed in a mode other than the one currently active
		 * and in this case perform some actions.
		 */
		$order->update_meta_data( '_sfwc_order_placed_during_subaccount_mode', sanitize_text_field( $sfwc_option_subaccount_mode ) );

		$order->save();
	}
}
add_action('woocommerce_checkout_create_order', 'sfwc_store_subaccounts_meta_data_on_order_creation', 20, 1);
add_action('woocommerce_store_api_checkout_update_order_meta', 'sfwc_store_subaccounts_meta_data_on_order_creation', 20, 1); // For block enabled themes using Checkout block instead of shortcode.







/**
 * In case an order is created on backend by Admin, _sfwc_order_placed_by order meta will be empty,
 * so update it with the proper value after customer has payed the order.
 *
 */
function sfwc_order_placed_by_update_order_meta_after_payment( $order_id ) {

    // Create an order instance.
    $order = wc_get_order( $order_id );
	
	// Get user id from order
	$customer_id = $order->get_user_id();
	
	
	// Get Account Level Type
	$customer_account_level_type = get_user_meta( $customer_id, 'sfwc_account_level_type', true );
	
	
	if ( ! isset($_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor'] )  && isset($_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager'] ) ) {
		
		
		if ( $customer_account_level_type == 'manager' ) {
			
			// The order was placed by a manager for himself.
			$order_placed_by = 'manager_for_himself';
			
		} elseif ( $customer_account_level_type == 'default' || $customer_account_level_type == '' || $customer_account_level_type == null ) {
			
			// The order was placed by a manager on behalf of his subaccount.
			$order_placed_by = 'manager_for_default';
		}
		
	} elseif ( ! isset($_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_supervisor'] )  && ! isset($_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'is_manager'] ) ) {
		
		// The order was placed by a 'default' customer for himself.
		$order_placed_by = 'default_for_himself';

	}
	
	
	if ( isset( $order_placed_by ) ) {	// Avoid undefined variable in case 
										// $customer_account_level_type == supervisor
										// which is handled by sfwc_order_placed_by_update_order_meta_after_payment_supervisor in Supervisor add-on

		// Store info about who actually placed the order.
		// In case of supervisor, see function: sfwc_order_placed_by_update_order_meta_after_payment_supervisor in Supervisor add-on
		$valid_order_placed_by = array( 'manager_for_himself', 'manager_for_default', 'default_for_himself' );

		if ( in_array( $order_placed_by, $valid_order_placed_by ) ) {
			
			$order->update_meta_data( '_sfwc_order_placed_by', $order_placed_by );
			$order->save();
		}
	}
}
add_action('woocommerce_thankyou', 'sfwc_order_placed_by_update_order_meta_after_payment', 5, 1); // Priority 5: run earlier then sfwc_save_approved_order from Order Approval Add-On.




/**
 * Adds new columns to the "Orders" table in the account.
 *
 * @param string[] $columns the columns in the orders table
 * @return string[] updated columns
 */
function sfwc_add_my_account_orders_column( $columns ) {

	$new_columns = array();

	foreach ( $columns as $key => $name ) {

		$new_columns[ $key ] = $name;
		
		if ( sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {

			// Add new columns after order status column.
			if ( 'order-status' === $key ) {
				
				// Add order-account column only when we viewing in "Subaccount Orders" table (no need for main "Orders" table).
				if ( is_wc_endpoint_url( 'subaccounts' ) ) {
					$new_columns['order-account'] = esc_html__( 'Account', 'subaccounts-for-woocommerce' );
				}
				
				// Add order-placed-by column.
				$new_columns['order-placed-by'] = esc_html__( 'Placed by', 'subaccounts-for-woocommerce' );
			}
		}
	}
	return $new_columns;
}
add_filter( 'woocommerce_account_orders_columns', 'sfwc_add_my_account_orders_column' );




/**
 * Adds data to the custom "Account" column.
 *
 */
function sfwc_my_account_orders_order_account( $order ) {
	
	$customer_id = $order->get_user_id();
	
	// Retrieve user data for customer related to order.
	$userdata_customer = get_userdata( $customer_id );
	
	// Get 'Customer Display Name' from Options settings.
	$sfwc_options = (array) get_option('sfwc_options');

	// Avoid undefined $sfwc_option_display_name in case related setting has not been saved yet.
	$sfwc_option_display_name = ( isset( $sfwc_options['sfwc_option_display_name'] ) ) ? $sfwc_options['sfwc_option_display_name'] : 'username';
	
	// Add content to column only when we viewing in "Subaccount Orders" table (no need for main "Orders" table).
	if ( is_wc_endpoint_url( 'subaccounts' ) ) {
		
		/*
		if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_customer->ID )->user_firstname || get_userdata( $userdata_customer->ID )->user_lastname ) ) {

			// Echo 'Full Name' (if either First Name or Last Name has been set)
			printf( '%1$s %2$s', esc_html( $userdata_customer->user_firstname ), esc_html( $userdata_customer->user_lastname ) );

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

			// Echo 'Company' (if Company name has been set)
			printf( '%1$s', esc_html( $userdata_customer->billing_company ) );
		
		} else {

			// Otherwise echo 'Username'
			printf( '%1$s', esc_html( $userdata_customer->user_login ) );
		}
		*/
		
		echo wp_kses( 
			sfwc_get_customer_display_name( $customer_id, false ), 
			array(
				'span' => array(
					'class' => array()
				)
			) 
		);
	}
}
add_action( 'woocommerce_my_account_my_orders_column_order-account', 'sfwc_my_account_orders_order_account' );




/**
 * Adds data to the custom "Order Placed By" column.
 *
 * For the following function DO NOT move validation of supervisor related values
 * so that if Supervisor Add-on is deactivated and there are still customers with account level type set to 'supervisor'
 * the plugin will continue to store/display correct data.
 */
function sfwc_my_account_orders_order_placed_by( $order ) {
	
	// Get Options settings.
	$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';
	
	// Get 'Subaccount Mode' from Options settings.
	$sfwc_option_subaccount_mode = ( isset( $sfwc_options['sfwc_option_subaccount_mode'] ) ) ? $sfwc_options['sfwc_option_subaccount_mode'] : 'sub_user';

	// Get order ID.
	$order_id = $order->get_id();
	
	// Retrieve the customer who actually placed the order.
	$order_placed_by = $order->get_meta('_sfwc_order_placed_by');
	
	// 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' );
	
	// Retrieve user data for customer who placed the order (Multi-User mode).
	$userdata_customer_placing_order = get_userdata( $order_placed_by_user_id );
	
	$customer_id = $order->get_user_id();
	
	// Retrieve user data for customer related to order.
	$userdata_customer = get_userdata( $customer_id );

	// 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 );
	
	// Retrieve the ID of the Supervisor related to the Customer.
	$customer_related_supervisor_id = $order->get_meta('_sfwc_customer_related_supervisor');
	
	// Retrieve user data for Supervisor.
	$userdata_supervisor = get_userdata( $customer_related_supervisor_id );
	
	
	if ( $order_placed_by ) {
	
		if ( $order_placed_by == 'default_for_himself' ) {
			
			// Multi-User mode.
			if ( $sfwc_option_subaccount_mode == 'multi_user' || $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order_id ) == 'multi_user') {
				
				if ( ! empty( $userdata_customer_placing_order ) ) { // $userdata_customer_placing_order may not be available if the order was placed before enabling Multi-User mode with plugin version prior to 1.4.3.
					$userdata_customer = $userdata_customer_placing_order;
				}
				
				echo( '<small><strong>' . esc_html__( 'Subaccount', 'subaccounts-for-woocommerce' ) . '</strong></small><br>' );
			}
			
			if ( $sfwc_option_subaccount_mode == 'sub_user' || ( $sfwc_option_subaccount_mode == 'multi_user' ) ) {
				
				if ( $userdata_customer ) {
					
					/*
					if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_customer->ID )->user_firstname || get_userdata( $userdata_customer->ID )->user_lastname ) ) {
						
						printf( '%1$s %2$s', esc_html( $userdata_customer->user_firstname ), esc_html( $userdata_customer->user_lastname ) );
						
					} elseif ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata( $userdata_customer->ID )->billing_company ) ) {

						// Echo 'Company' (if Company name has been set)
						printf( '%1$s', esc_html( $userdata_customer->billing_company ) );
				
					} else {

						// Otherwise echo 'Username'
						printf( '%1$s', esc_html( $userdata_customer->user_login ) );
					}
					*/
					
					echo wp_kses( 
						sfwc_get_customer_display_name( $userdata_customer->ID, false ), 
						array(
							'span' => array(
								'class' => array()
							)
						) 
					);
				}
			} 
			else {
				echo esc_html__( 'No information available', 'subaccounts-for-woocommerce' );
			}
			
		} elseif ( $order_placed_by == 'supervisor_for_himself' || $order_placed_by == 'manager_for_himself' ) {
			
			// Multi-User mode.
			if ( $sfwc_option_subaccount_mode == 'multi_user' || $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order_id ) == 'multi_user') {
				
				if ( $userdata_customer && ! empty( $userdata_customer_placing_order ) ) { // $userdata_customer_placing_order may not be available if the order was placed before enabling Multi-User mode with plugin version prior to 1.4.3.
					$userdata_customer = $userdata_customer_placing_order;
				}
				
				if ( $order_placed_by == 'supervisor_for_himself' ) {
					echo( '<small><strong>' . esc_html__( 'Supervisor', 'subaccounts-for-woocommerce' ) . '</strong></small><br>' );
				}
				elseif( $order_placed_by == 'manager_for_himself' ) {
					echo( '<small><strong>' . esc_html__( 'Manager', 'subaccounts-for-woocommerce' ) . '</strong></small><br>' );
				}
			}
			
			if ( $userdata_customer ) {
				/*
				if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_customer->ID )->user_firstname || get_userdata( $userdata_customer->ID )->user_lastname ) ) {
					
					printf( '%1$s %2$s', esc_html( $userdata_customer->user_firstname ), esc_html( $userdata_customer->user_lastname ) );
					
				} elseif ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata( $userdata_customer->ID )->billing_company ) ) {

					// Echo 'Company' (if Company name has been set)
					printf( '%1$s', esc_html( $userdata_customer->billing_company ) );
			
				} else {

					// Otherwise echo 'Username'
					printf( '%1$s', esc_html( $userdata_customer->user_login ) );
				}
				*/
				
				echo wp_kses( 
					sfwc_get_customer_display_name( $userdata_customer->ID, false ), 
					array(
						'span' => array(
							'class' => array()
						)
					) 
				);
			}
			
		} elseif ( $order_placed_by == 'supervisor_for_manager' || $order_placed_by == 'supervisor_for_default' ) {
			/*
			if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_supervisor->ID )->user_firstname || get_userdata( $userdata_supervisor->ID )->user_lastname ) ) {
				
				printf( '<small><strong>' . esc_html__( 'Supervisor', 'subaccounts-for-woocommerce' ) . '</strong></small><br>' . '%1$s %2$s', esc_html( $userdata_supervisor->user_firstname ), esc_html( $userdata_supervisor->user_lastname ) );
			
			} elseif ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata( $userdata_supervisor->ID )->billing_company ) ) {

				printf( '<small><strong>' . esc_html__( 'Supervisor', 'subaccounts-for-woocommerce' ) . '</strong></small><br>' . '%1$s', esc_html( $userdata_supervisor->billing_company ) );
		
			} else {

				printf( '<small><strong>' . esc_html__( 'Supervisor', 'subaccounts-for-woocommerce' ) . '</strong></small><br>' . '%1$s', esc_html( $userdata_supervisor->user_login ) );
			}
			*/
			
			echo '<small><strong>' . esc_html__( 'Supervisor', 'subaccounts-for-woocommerce' ) . '</strong></small><br>';
			
			echo wp_kses( 
				sfwc_get_customer_display_name( $userdata_supervisor->ID, false ), 
				array(
					'span' => array(
						'class' => array()
					)
				) 
			);
			
			// Multi-User mode.
			if ( $sfwc_option_subaccount_mode == 'multi_user' || $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order_id ) == 'multi_user') {

				echo '<br><small><strong>' . esc_html__( 'On behalf of', 'subaccounts-for-woocommerce' ) . '</strong></small><br>';
				
				if ( ! empty( $userdata_customer_placing_order ) ) {
					/*
					if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_customer_placing_order->ID )->user_firstname || get_userdata( $userdata_customer_placing_order->ID )->user_lastname ) ) {
						
						printf( '%1$s %2$s', esc_html( $userdata_customer_placing_order->user_firstname ), esc_html( $userdata_customer_placing_order->user_lastname ) );
						
					} elseif ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata( $userdata_customer_placing_order->ID )->billing_company ) ) {
						
						if ( get_userdata($userdata_supervisor->ID)->billing_company === get_userdata( $userdata_customer_placing_order->ID )->billing_company ) {
							
							
							 # If both the supervisor and the subaccount have the same Company Name,
							 # for the subaccount we print the Full Name.
							 #
							 # This to avoid confusion, e.g.
							 # Order placed by: Supervisor (Company Name Inc.) on behalf of subaccount (Company Name Inc.).
							 
							printf( '%1$s %2$s', esc_html( $userdata_customer_placing_order->user_firstname ), esc_html( $userdata_customer_placing_order->user_lastname ) );
						} else {
								
							// Echo 'Company' (if Company name has been set)
							printf( '%1$s', esc_html( $userdata_customer_placing_order->billing_company ) );
						}
				
					} else {

						// Otherwise echo 'Username'
						printf( '%1$s', esc_html( $userdata_customer_placing_order->user_login ) );
					}
					*/
					
					
					
					
					/**
					 * If both the supervisor and the subaccount have the same Company Name,
					 * for the subaccount we print the Full Name.
					 *
					 * This to avoid confusion, e.g.
					 * Order placed by: Supervisor (Company Name Inc.) on behalf of subaccount (Company Name Inc.).
					 */					
					if ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata( $userdata_customer_placing_order->ID )->billing_company ) && ( get_userdata($userdata_supervisor->ID)->billing_company === get_userdata( $userdata_customer_placing_order->ID )->billing_company ) ) {
						echo esc_html( $userdata_customer_placing_order->user_firstname ) . ' ' . esc_html( $userdata_customer_placing_order->user_lastname );
					} else {
						
						echo wp_kses(
							sfwc_get_customer_display_name( $userdata_customer_placing_order->ID, false ), 
							array(
								'span' => array(
									'class' => array()
								)
							) 
						);
					}
				}
				
				/**
				 * If $userdata_customer_placing_order is empty, it means the order was placed in one of the following situation:
				 *
				 *		- Order was placed before installing/activating the plugin (even if instantly put in Multi-User mode after activation);
				 *		- Order was placed before switching from Sub-User to Multi-User mode with plugin version lower than 1.4.3 (*)
				 *
				 *		(*) Since v.1.4.3, _sfwc_order_placed_by_user_id order meta value is always stored, regardless of whether Sub-User or Multi-User mode is active.
				 *
				 * In both cases the customer tied to the order can be normally retrieved with: $order->get_customer_id();
				 */
				else {
					
					if ( $userdata_customer ) {
						/*
						if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_customer->ID )->user_firstname || get_userdata( $userdata_customer->ID )->user_lastname ) ) {
							
							printf( '%1$s %2$s', esc_html( $userdata_customer->user_firstname ), esc_html( $userdata_customer->user_lastname ) );
							
						} elseif ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata( $userdata_customer->ID )->billing_company ) ) {

							// Echo 'Company' (if Company name has been set)
							printf( '%1$s', esc_html( $userdata_customer->billing_company ) );
					
						} else {

							// Otherwise echo 'Username'
							printf( '%1$s', esc_html( $userdata_customer->user_login ) );
						}
						*/
						
						echo wp_kses(
							sfwc_get_customer_display_name( $userdata_customer->ID, false ), 
							array(
								'span' => array(
									'class' => array()
								)
							) 
						);
					}
				}
			}
			
		} elseif ( $order_placed_by == 'manager_for_default' ) {
			
			echo '<small><strong>' . esc_html__( 'Manager', 'subaccounts-for-woocommerce' ) . '</strong></small><br>';
			
			if ( $userdata_manager ) {
				/*
				if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_manager->ID )->user_firstname || get_userdata( $userdata_manager->ID )->user_lastname ) ) {
					
					printf( '%1$s %2$s', esc_html( $userdata_manager->user_firstname ), esc_html( $userdata_manager->user_lastname ) );
				
				} elseif ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata( $userdata_manager->ID )->billing_company ) ) {

					printf( '%1$s', esc_html( $userdata_manager->billing_company ) );
			
				} else {

					printf(  '%1$s', esc_html( $userdata_manager->user_login ) );
				}
				*/
				
				echo wp_kses(
					sfwc_get_customer_display_name( $userdata_manager->ID, false ), 
					array(
						'span' => array(
							'class' => array()
						)
					) 
				);
			}
			
			
			
			// Multi-User mode.
			if ( $sfwc_option_subaccount_mode == 'multi_user' || $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order_id ) == 'multi_user') {

				echo '<br><small><strong>' . esc_html__( 'On behalf of', 'subaccounts-for-woocommerce' ) . '</strong></small><br>';
				
				if ( ! empty( $userdata_customer_placing_order ) ) {
					/*
					if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_customer_placing_order->ID )->user_firstname || get_userdata( $userdata_customer_placing_order->ID )->user_lastname ) ) {
						
						printf( '%1$s %2$s', esc_html( $userdata_customer_placing_order->user_firstname ), esc_html( $userdata_customer_placing_order->user_lastname ) );
						
					} elseif ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata( $userdata_customer_placing_order->ID )->billing_company ) ) {
						
						if ( $userdata_manager && ( get_userdata($userdata_manager->ID)->billing_company === get_userdata( $userdata_customer_placing_order->ID )->billing_company ) ) {
							
							
							 # If both the manager and the subaccount have the same Company Name,
							 # for the subaccount we print the Full Name.
							 #
							 # This to avoid confusion, e.g.
							 # Order placed by: Manager (Company Name Inc.) on behalf of subaccount (Company Name Inc.).
							 
							printf( '%1$s %2$s', esc_html( $userdata_customer_placing_order->user_firstname ), esc_html( $userdata_customer_placing_order->user_lastname ) );
							
						} else {

							// Echo 'Company' (if Company name has been set)
							printf( '%1$s', esc_html( $userdata_customer_placing_order->billing_company ) );
						}
				
					} else {

						// Otherwise echo 'Username'
						printf( '%1$s', esc_html( $userdata_customer_placing_order->user_login ) );
					}
					*/
					
					
					/**
					 * If both the manager and the subaccount have the same Company Name,
					 * for the subaccount we print the Full Name.
					 *
					 * This to avoid confusion, e.g.
					 * Order placed by: Manager (Company Name Inc.) on behalf of subaccount (Company Name Inc.).
					 */					
					if ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata( $userdata_customer_placing_order->ID )->billing_company ) && ( $userdata_manager && ( get_userdata($userdata_manager->ID)->billing_company === get_userdata( $userdata_customer_placing_order->ID )->billing_company ) ) ) {
						echo esc_html( $userdata_customer_placing_order->user_firstname ) . ' ' . esc_html( $userdata_customer_placing_order->user_lastname );
					} else {

						echo wp_kses(
							sfwc_get_customer_display_name( $userdata_customer_placing_order->ID, false ), 
							array(
								'span' => array(
									'class' => array()
								)
							) 
						);
					}
				}
				/**
				 * If $userdata_customer_placing_order is empty, it means the order was placed in one of the following situation:
				 *
				 *		- Order was placed before installing/activating the plugin (even if instantly put in Multi-User mode after activation);
				 *		- Order was placed before switching from Sub-User to Multi-User mode with plugin version lower than 1.4.3 (*)
				 *
				 *		(*) Since v.1.4.3, _sfwc_order_placed_by_user_id order meta value is always stored, regardless of whether Sub-User or Multi-User mode is active.
				 *
				 * In both cases the customer tied to the order can be normally retrieved with: $order->get_customer_id();
				 */
				else {
					
					if ( $userdata_customer ) {
						/*
						if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_customer->ID )->user_firstname || get_userdata( $userdata_customer->ID )->user_lastname ) ) {
							
							printf( '%1$s %2$s', esc_html( $userdata_customer->user_firstname ), esc_html( $userdata_customer->user_lastname ) );
							
						} elseif ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata( $userdata_customer->ID )->billing_company ) ) {

							// Echo 'Company' (if Company name has been set)
							printf( '%1$s', esc_html( $userdata_customer->billing_company ) );
					
						} else {

							// Otherwise echo 'Username'
							printf( '%1$s', esc_html( $userdata_customer->user_login ) );
						}
						*/
						
						echo wp_kses(
							sfwc_get_customer_display_name( $userdata_customer->ID, false ), 
							array(
								'span' => array(
									'class' => array()
								)
							) 
						);
					}
				}
			}
		}
	} else {
		echo esc_html__( 'No information available', 'subaccounts-for-woocommerce' );
	}
}
add_action( 'woocommerce_my_account_my_orders_column_order-placed-by', 'sfwc_my_account_orders_order_placed_by' );




/**
 * Show subaccount orders in My Account area of parent account (Pt.1).
 *
 * If Sub-User mode is enabled, show the form in: My Account -> Subaccounts -> Subaccount Orders.
 * If instead Multi-User mode is enabled, show the form in: My Account -> Orders.
 */
function sfwc_my_account_orders_add_select_subaccount_orders_form( $has_orders ) {

	// Sanitize cookie value.
	if ( isset( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'subaccount_ids'] ) ) {

		// Decode cookie
		$subaccount_ids_cookie_decoded = json_decode( str_replace ('\"','', $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'subaccount_ids']), true );
		
		// Sanitize cookie value
		$subaccount_ids_cookie_sanitized = preg_replace('/[^0-9]/', '', $subaccount_ids_cookie_decoded);
	}
	
	$valid_selected_ids = array();
	
	// Validation of pre-selected items.
	if ( isset( $subaccount_ids_cookie_sanitized ) && ! empty ( $subaccount_ids_cookie_sanitized ) ) {
		
		foreach ( $subaccount_ids_cookie_sanitized as $single_id ) {
			
			// Check if user still exists.
			$user_exists = get_userdata( $single_id );
			if ( $user_exists !== false ) {
				
				if ( sfwc_is_user_role_valid( $single_id ) && sfwc_is_user_role_enabled( $single_id ) ) {
					
					$valid_selected_ids[] = $single_id;
				}
			}
		}
	}
	
	
	// 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' from Options settings
	$sfwc_option_display_name = ( isset( $sfwc_options['sfwc_option_display_name'] ) ) ? $sfwc_options['sfwc_option_display_name'] : 'username';
	
	// Get ID of currently logged in user.
	$user_id = get_current_user_id();

	// Get Account Level Type of currently logged in user.
	$account_level_type = get_user_meta( $user_id, 'sfwc_account_level_type', true );
	
	// Build the array containing pre-selected users data.
	$selected_users_data_arr = array();
	if( ! empty( $valid_selected_ids ) ) {

		foreach ( $valid_selected_ids as $id ) {
			/*
			$user = get_userdata( $id );
			
			//Check 'Customer Display Name' in Subaccounts > Settings > Options and display it accordingly
			if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata($user->ID)->user_firstname || get_userdata($user->ID)->user_lastname ) ) {
				$optionText = 'ID: ' . esc_html( $id ) . ' - ' . esc_html( $user->user_firstname ) . ' ' . esc_html( $user->user_lastname ) . ' (' .  esc_html( $user->user_email ) . ')';
			} elseif ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata($user->ID)->billing_company ) ) {
				$optionText = 'ID: ' . esc_html( $id ) . ' - ' . esc_html( $user->billing_company ) . ' (' .  esc_html( $user->user_email ) . ')';
			} else {
				$optionText = 'ID: ' . esc_html( $id ) . ' - ' . esc_html( $user->user_login ) . ' (' .  esc_html( $user->user_email ) . ')';
			}
			*/
			
			$optionText = wp_strip_all_tags( sfwc_get_customer_display_name( $id, true ) );
			
			$selected_users_data_arr[] = array(
				'optionValue' => esc_attr( $id ),
				'optionText'  => esc_html( $optionText )
			);
		}
	}
	
	
	// Only show the form to manager account types.
	if ( $account_level_type == 'manager' && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {
	
		/**
		 * If Multi-User mode is enabled, show the form in: My Account -> Orders.
		 * If instead Sub-User mode is enabled, show the form in: My Account -> Subaccounts -> Subaccount Orders and in any other page the [sfwc_subaccount_orders] shortcode is present.
		 */
		if ( ( ! is_wc_endpoint_url( 'orders' ) && $sfwc_option_subaccount_mode !== 'multi_user' ) || ( is_wc_endpoint_url( 'orders' ) && $sfwc_option_subaccount_mode == 'multi_user' ) ) {
		?>
			
			<div id="sfwc-select-subaccount-orders-form-wrap">
			
				<?php echo '<h4 style="font-size:22px; font-weight:400">' . esc_html__( 'Filter Orders', 'subaccounts-for-woocommerce' ) . '</h4>'; ?>
				
				<form method="post">

					<?php wp_nonce_field( 'sfwc_filter_subaccount_orders_action', 'sfwc_filter_subaccount_orders' ); ?>
					
					<label for="sfwc-select-subaccount-orders" class="screen-reader-text">
						<?php echo esc_html__( 'Select Account', 'subaccounts-for-woocommerce' ); ?>
					</label>
					
					<select id="sfwc-select-subaccount-orders" name="sfwc_subaccount_orders[]" multiple placeholder="<?php esc_attr_e( 'Select account...', 'subaccounts-for-woocommerce' ); ?>"></select>
					
					<?php
					/**
					 * Hook: sfwc_frontend_filter_orders_form_before_submit_button.
					 *
					 * Allow developers to add extra fields on frontend Filter Orders form.
					 *
					 * 
					 * @since 1.8.0
					 */					  
					do_action( 'sfwc_frontend_filter_orders_form_before_submit_button' );
					?>
					
					<input name="submit" type="submit" value="<?php esc_attr_e( 'Filter', 'subaccounts-for-woocommerce' ); ?>" class="woocommerce-button">
					
				</form>
				<img id="sfwc-loading-icon" src="<?php echo esc_url( WP_PLUGIN_URL . '/subaccounts-for-woocommerce/assets/images/loader.gif' ); ?>">
			</div>
		<?php
		}
		?>
		
		<?php
		wp_enqueue_script( 'sfwc_filter_orders_js', esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/js/filter-orders.js', array( 'jquery', 'sfwc_selectize_js' ), '', true ); // Print in footer.

		$dataToBePassed = array(
			'userId' 			=> absint( $user_id ),
			'adminAjaxUrl' 		=> esc_url( admin_url('admin-ajax.php') ),
			'nonce' 			=> wp_create_nonce('sfwc_nonce'),
			'accountType' 		=> $account_level_type,
			'deselectAll'		=> esc_html__( 'Deselect All', 'subaccounts-for-woocommerce' ),
			'preSelectedUsers'	=> $selected_users_data_arr 		
		);

		wp_add_inline_script( 'sfwc_filter_orders_js', 'var sfwc_vars_filter_orders = ' . wp_json_encode( $dataToBePassed, JSON_PRETTY_PRINT ), 'before' );
	}
}
add_action('woocommerce_before_account_orders', 'sfwc_my_account_orders_add_select_subaccount_orders_form');




/**
 * Show subaccount orders in My Account area of parent account (Pt.2).
 *
 * Sanitize, validate submitted data and show orders in: My Account -> Subaccounts -> Subaccount Orders.
 */
function sfwc_my_account_orders_query_subaccounts_orders( $args ) {
	
	
	
	// Sanitize cookie value.
	if ( isset( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'subaccount_ids'] ) ) {

		// Decode cookie
		$subaccount_ids_cookie_decoded = json_decode( str_replace ('\"','', $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'subaccount_ids']), true );
		
		// Sanitize cookie value
		$subaccount_ids_cookie_sanitized = preg_replace('/[^0-9]/', '', $subaccount_ids_cookie_decoded);
	}
	
	// Sanitize posted values.
	if ( isset( $_POST['sfwc_subaccount_orders'] ) ) {			
		/**
		 * sanitize_text_field() only works for strings, so this is not the case.
		 * preg_replace: If subject (3rd parameter) is an array, then the search and replace is performed on every entry of subject,
		 * and the return value is an array as well.
		 */
		$selected_subaccount_ids_sanitized = preg_replace('/[^0-9]/', '', $_POST['sfwc_subaccount_orders']);
	}																						
																							


	// Get ID of currently logged in user.
	$user_id = get_current_user_id();
	
	// Get account type of currently logged in user.
	$account_level_type = get_user_meta( $user_id, 'sfwc_account_level_type', true );
	
	// Get children (array) of currently logged in user.																		
	$children_ids = get_user_meta( $user_id, 'sfwc_children', true );
	
	
	// Make sure we are not in: My Account -> Orders.
	if ( ! is_wc_endpoint_url( 'orders' ) ) {
		
		// Check if user is a Manager.
		if ( $account_level_type == 'manager' ) {

			/**
			 * Validation start.
			 *
			 * Only orders that belong to the currently logged in parent account ID or orders that belong to the parent's subaccount IDs are valid
			 */
			if ( isset( $selected_subaccount_ids_sanitized ) ) {
				
				
				// Check if nonce is in place and verfy it.
				if ( ! isset( $_POST['sfwc_filter_subaccount_orders'] ) || isset( $_POST['sfwc_filter_subaccount_orders'] ) && ! wp_verify_nonce( $_POST['sfwc_filter_subaccount_orders'], 'sfwc_filter_subaccount_orders_action' ) ) {
																														
					wc_print_notice( esc_html__( 'Nonce could not be verified.', 'subaccounts-for-woocommerce' ), 'error');

				} else {

					// Validate posted values.
					if ( ! empty( $selected_subaccount_ids_sanitized ) ) {

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

							// Prevent empty option values in case a user has been deleted,
							// but is still present within 'sfwc_children' meta of an ex parent account.
							$user_exists = get_userdata( $value );
							if ( $user_exists !== false ) {
								
								// Check if submitted data is valid.
								if ( in_array( $value, $children_ids, true ) || $value ==  $user_id ) {

									$validated_subaccount_orders[] = $value;
								
								} else {
									
									$not_valid_subaccount_orders[] = $value;
									
								}
							} else {
								$not_existing_subaccount_orders[] = $value;
							}
						}
					}





					if ( ! empty( $not_valid_subaccount_orders ) ) {

						foreach ( $not_valid_subaccount_orders as $key => $value ) {
							wc_print_notice( esc_html__( 'You are not allowed to select orders for user ID: ', 'subaccounts-for-woocommerce' ) . $value . '.', 'error');
						}
						
					}

					if ( ! empty( $not_existing_subaccount_orders ) ) {

						foreach ( $not_existing_subaccount_orders as $key => $value ) {
							wc_print_notice( esc_html__( 'Selected user ID: ', 'subaccounts-for-woocommerce' ) . $value . esc_html__( ' does not exist.', 'subaccounts-for-woocommerce' ), 'error');
						}
						
					}

					if ( ! empty( $validated_subaccount_orders ) ) {
					
						$args['customer'] = $validated_subaccount_orders;
					}
				}
			} 
			
			// Cookie validation.
			elseif ( isset( $subaccount_ids_cookie_sanitized ) && ! empty( $subaccount_ids_cookie_sanitized ) ) {

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

					// Prevent empty option values in case a user has been deleted,
					// but is still present within 'sfwc_children' meta of an ex parent account.
					$user_exists = get_userdata( $value );
					if ( $user_exists !== false ) {
						
						// Check if submitted data is valid.
						if ( in_array( $value, $children_ids, true ) || $value ==  $user_id ) {

							$validated_subaccount_orders[] = $value;
						
						} else {
							
							$not_valid_subaccount_orders[] = $value;
							
						}
					} else {
						$not_existing_subaccount_orders[] = $value;
					}
				}






				if ( ! empty( $not_valid_subaccount_orders ) ) {

					foreach ( $not_valid_subaccount_orders as $key => $value ) {
						wc_print_notice( esc_html__( 'You are not allowed to select orders for user ID: ', 'subaccounts-for-woocommerce' ) . $value . '.', 'error');
					}
					
				}

				if ( ! empty( $not_existing_subaccount_orders ) ) {

					foreach ( $not_existing_subaccount_orders as $key => $value ) {
						wc_print_notice( esc_html__( 'Selected user ID: ', 'subaccounts-for-woocommerce' ) . $value . esc_html__( ' does not exist.', 'subaccounts-for-woocommerce' ), 'error');
					}
					
				}

				if ( ! empty( $validated_subaccount_orders ) ) {
				
					$args['customer'] = $validated_subaccount_orders;
				}
			}
					
					
						
			/***
			
			// For debug.
			if ( ! empty( $validated_subaccount_orders ) ) {
				echo '<p><strong>Validated</strong></p><pre>';
				print_r( $validated_subaccount_orders );
				echo '</pre>';
			}
			
			// For debug.
			if ( ! empty( $not_valid_subaccount_orders ) ) {
				echo '<p><strong>Not Validated</strong></p><pre>';
				print_r( $not_valid_subaccount_orders );
				echo '</pre>';
			}
			
			// For debug.
			if ( ! empty( $not_existing_subaccount_orders ) ) {
				echo '<p><strong>Not Existing</strong></p><pre>';
				print_r( $not_existing_subaccount_orders );
				echo '</pre>';
			}		

			// For debug.
			if ( ! empty( $args ) ) {
				echo '<pre>';
				print_r( $args );
				echo '</pre>';
			}
			
			***/
		}
	}
				
	return $args;
}
add_filter('woocommerce_my_account_my_orders_query', 'sfwc_my_account_orders_query_subaccounts_orders');






/**
 * Show subaccount orders in My Account area of parent account (Pt.3).
 *
 * Set a cookie storing an array of IDs of subaccounts submitted in the Filter Subaccount Orders form.
 *
 * This is necessary because otherwise those IDs are not kept in memory for alterating the orders query
 * when navigating through order pages with paginate_links().
 */
function sfwc_set_selected_subaccount_orders_cookie() {
	
	// 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';
	
	
	
	$slug = 'wc-pending-approval';
	
	
	if ( isset( $_POST['submit'] ) ) {
		
		if ( ! empty( $_POST['sfwc_subaccount_orders'] ) ) {
		
			// Sanitizing
			$selected_subaccount_ids_sanitized = preg_replace('/[^0-9]/', '', $_POST['sfwc_subaccount_orders']);
			
			// Set cookie as an array (json encoded).
			setcookie( apply_filters( 'sfwc_cookie_prefix', '' ) . 'subaccount_ids', wp_json_encode( $selected_subaccount_ids_sanitized ), [
				'expires' => '',
				'path' => COOKIEPATH,
				'domain' => COOKIE_DOMAIN,
				'secure' => is_ssl(),
				'httponly' => true,
				'samesite' => 'Strict',
			]);
		
		} else {
			// Destroy subaccount_ids cookie to show all subaccounts orders.
			setcookie( apply_filters( 'sfwc_cookie_prefix', '' ) . 'subaccount_ids', '', -1, COOKIEPATH);
		}


		/**
		 * In My Account -> Subaccounts -> Subaccount Orders or any other page where the [sfwc_subaccount_orders] shortcode is present
		 * redirect to first page after each form submission. 
		 * 
		 * This is to prevent the following scenario:
		 *
		 * If for example we are viewing page 4 of paginated orders of a particular subaccount and then we select another subaccount,
		 * after the form is submitted we are still on page 4. 
		 * The problem here is that if the selected subaccount has not made enough orders to be displayed on page 4, we get "No order has been made yet."
		 */
		if ( ( ! is_wc_endpoint_url( 'orders' ) && $sfwc_option_subaccount_mode !== 'multi_user' ) ) {
			
			if ( isset( $_POST['sfwc_query_orders_require_approval'] ) ) {
				wp_safe_redirect( esc_url_raw( add_query_arg( 'sfwc-status', $slug, wc_get_endpoint_url( 'subaccounts', 'subaccount-orders' ) ) ) );
				exit;				
			}
			else {
				wp_safe_redirect( esc_url( remove_query_arg( 'order_page' ) ) );
				exit;
			}
		}
		
		/**
		 * The same applies for My Account -> Orders (Multi-User mode enabled).
		 */		
		elseif ( is_wc_endpoint_url( 'orders' ) && $sfwc_option_subaccount_mode == 'multi_user' ) {
			
			if ( isset( $_POST['sfwc_query_orders_require_approval'] ) ) {
				wp_safe_redirect( esc_url_raw( add_query_arg( 'sfwc-status', $slug, wc_get_endpoint_url( 'orders' ) ) ) );
				exit;				
			}
			else {
				wp_safe_redirect( esc_url_raw( wc_get_endpoint_url( 'orders' ) ) );
				exit;		
			}			
		}
	}
}
add_action( 'template_redirect', 'sfwc_set_selected_subaccount_orders_cookie' );




/**
 * Show subaccount orders in My Account area of parent account (Pt.4).
 *
 * When a parent account is viewing subaccount orders list table display the view_subaccount_order action only.
 */
function sfwc_modify_available_action_buttons( $actions, $order ){

	if ( is_wc_endpoint_url( 'subaccounts' ) ) {
		
		// Add "View Subaccount Order" button.
		$actions['view_subaccount_order'] = array(
			'url'  => esc_url( add_query_arg( 'order', $order->get_id(), wc_get_endpoint_url( 'subaccounts', 'subaccount-orders' ) ) ),
			'name' => esc_html__( 'View', 'subaccounts-for-woocommerce' ),
		);
		
		// Unset all other buttons.
		foreach ( $actions as $key => $action ) {
			
			if ( 
				$key !== 'view_subaccount_order' &&
				$key !== 'edit_subaccount_order' // In case Order Approval Add-On is active.
			) {
				unset( $actions[$key] );
			}
		}
	}
	
	return $actions;
}
add_filter('woocommerce_my_account_my_orders_actions', 'sfwc_modify_available_action_buttons', 9999, 2);




/**
 * Add "Account", "Account Type" and "Order placed by" information in "Order Details" page.
 *  
 * 		- My Account -> Orders -> Single Order
 *		- My Account -> Subaccounts -> Subaccount Orders -> Single Order
 *		- Order Received (Thank You Page)
 */
function sfwc_add_subaccounts_related_information_in_order_details_page( $order_id ) {

	$order = wc_get_order( $order_id );
	
	$customer_id = $order->get_user_id();
	
	// Retrieve user data for customer related to order.
	$userdata_customer = get_userdata( $customer_id );

	// Retrieve the customer who actually placed the order.
	$order_placed_by = $order->get_meta('_sfwc_order_placed_by');
	
	// Retrieve the customer who actually placed the order (Multi-User mode).
	$order_placed_by_user_id = $order->get_meta( '_sfwc_order_placed_by_user_id' );
	
	// Retrieve user data for customer who placed the order (Multi-User mode).
	$userdata_customer_placing_order = get_userdata( $order_placed_by_user_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 );
	
	
	// Retrieve the ID of the Supervisor related to the Customer.
	// Leave it here even if Supervisor related.
	$customer_related_supervisor_id = $order->get_meta('_sfwc_customer_related_supervisor');
	
	// Retrieve user data for Supervisor.
	// Leave it here even if Supervisor related.
	$userdata_supervisor = get_userdata( $customer_related_supervisor_id );
	
	
	// Get 'Customer Display Name' from Options settings.
	$sfwc_options = (array) get_option('sfwc_options');

	// Avoid undefined $sfwc_option_display_name in case related setting has not been saved yet.
	$sfwc_option_display_name = ( isset( $sfwc_options['sfwc_option_display_name'] ) ) ? $sfwc_options['sfwc_option_display_name'] : 'username';
	
	// 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';

	/*
	if ( $customer_id ) {
		// Get roles the user who made the order is part of (as an array).
		$role_user_current_order = $userdata_customer->roles;
	}
	*/
	
	/**
	#FOR DEBUG
	echo '<strong>order placed by user id:</strong>';
	var_dump((int)$order->get_meta( '_sfwc_order_placed_by_user_id' ));
	echo '<br>';
	echo '<strong>$order->get_user_id:</strong>';
	var_dump($order->get_user_id());
	echo '<br>';
	**/
	
	/**
	 * 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 a valid role. Otherwise weird things might happen.
	 * E.g. If order was made by an Administrator (borderline case, but possible) wrong data is displayed.
	 */
	if ( $customer_id && ( sfwc_is_user_role_valid( $customer_id ) && sfwc_is_user_role_enabled( $customer_id ) ) ) {

		echo '<div id="sfwc-order-details">';
		
		if ( $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order->get_id() ) == 'sub_user' ) {

			/**
			 * Display Account tied to order.
			 */
			
/*			
			//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 '<strong>' . esc_html__( 'Account', 'subaccounts-for-woocommerce' ) . ':</strong> ' . esc_html( $userdata_customer->user_firstname ) . ' ' . esc_html( $userdata_customer->user_lastname ) . ' (' . esc_html( $userdata_customer->user_email ) . ')';

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

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

			} else {

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


			echo '<hr style="background-color: #e3e3e3; border: 0; height: 1px; margin: 10px 0 10px;">';


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


			if ( $customer_account_level == 'supervisor' ) {

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

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

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

			} else {

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

			}


			echo '<hr style="background-color: #e3e3e3; border: 0; height: 1px; margin: 10px 0 10px;">';
		}

		/**
		 * Display "Order placed by" information.
		 */
		echo '<strong>' . esc_html__( 'Order placed by', 'subaccounts-for-woocommerce' ) . ':</strong> ';

		if ( $order_placed_by ) {

			if ( $order_placed_by == 'manager_for_himself' ) {
				
				// Multi-User mode.
				if ( $sfwc_option_subaccount_mode == 'multi_user' || $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order_id ) == 'multi_user') {
	
					if ( ! empty( $userdata_customer_placing_order ) ) { // $userdata_customer_placing_order may not be available if the order was placed before enabling Multi-User mode with plugin version prior to 1.4.3.
						$userdata_customer = $userdata_customer_placing_order;
					}
				}

				echo esc_html__( 'Manager', 'subaccounts-for-woocommerce' ) . ' <span style="background:#fdfdfd; padding:3px; border:1px solid #ebebeb; border-radius:6px; white-space:nowrap;">';
				
					/*
					if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_customer->ID )->user_firstname || get_userdata( $userdata_customer->ID )->user_lastname ) ) {

						// Echo 'Full Name' (if either First Name or Last Name has been set)
						printf( '%1$s %2$s', esc_html( $userdata_customer->user_firstname ), esc_html( $userdata_customer->user_lastname ) );
						

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

						// Echo 'Company' (if Company name has been set)
						printf( '%1$s', esc_html( $userdata_customer->billing_company ) );
						

					} else {

						// Otherwise echo 'Username'
						printf( '%1$s', esc_html( $userdata_customer->user_login ) );
						
					}
					*/
					
					echo wp_kses(
						sfwc_get_customer_display_name( $userdata_customer->ID, false ),
						array(
							'span' => array(
								'class' => array()
							)
						) 
					);
					
					echo '</span>';
					
					/*
					// Sub-User mode.
					if ( $sfwc_option_subaccount_mode == 'sub_user' ) {
						
						echo ' ' . esc_html__( 'for himself', 'subaccounts-for-woocommerce' );
					}
					*/
					
					echo '.';	
			
			} elseif ( $order_placed_by == 'manager_for_default' ) {
				
				// Multi-User mode.
				if ( $sfwc_option_subaccount_mode == 'multi_user' || $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order_id ) == 'multi_user') {
				
					if ( ! empty( $userdata_customer_placing_order ) ) { // $userdata_customer_placing_order may not be available if the order was placed before enabling Multi-User mode with plugin version prior to 1.4.3.
						$userdata_customer = $userdata_customer_placing_order;
					}
				}
			
				echo esc_html__( 'Manager', 'subaccounts-for-woocommerce' ) . ' <span style="background:#fdfdfd; padding:3px; border:1px solid #ebebeb; border-radius:6px; white-space:nowrap;">';
					
					/*
					if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata($userdata_manager->ID)->user_firstname || get_userdata($userdata_manager->ID)->user_lastname ) ) {

						// Echo 'Full Name' (if either First Name or Last Name has been set)
						printf( '%1$s %2$s', esc_html( $userdata_manager->user_firstname ), esc_html( $userdata_manager->user_lastname ) );
						

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

						// Echo 'Company' (if Company name has been set)
						printf( '%1$s', esc_html( $userdata_manager->billing_company ) );
						

					} else {

						// Otherwise echo 'Username'
						printf( '%1$s', esc_html( $userdata_manager->user_login ) );
						
					}
					*/
					
					echo wp_kses(
						sfwc_get_customer_display_name( $userdata_manager->ID, false ),
						array(
							'span' => array(
								'class' => array()
							)
						) 
					);
					
				echo '</span> ' . esc_html__( 'on behalf of', 'subaccounts-for-woocommerce' ) . ' ' . esc_html__( 'subaccount', 'subaccounts-for-woocommerce' ) . ' <span style="background:#fdfdfd; padding:3px; border:1px solid #ebebeb; border-radius:6px; white-space:nowrap;">';
					
					if ( $sfwc_option_subaccount_mode == 'sub_user' || ( $sfwc_option_subaccount_mode == 'multi_user' ) ) {
						
						/*
						if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_customer->ID )->user_firstname || get_userdata( $userdata_customer->ID )->user_lastname ) ) {

							// Echo 'Full Name' (if either First Name or Last Name has been set)
							printf( '%1$s %2$s', esc_html( $userdata_customer->user_firstname ), esc_html( $userdata_customer->user_lastname ) );
							

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

							if ( get_userdata($userdata_manager->ID)->billing_company === get_userdata( $userdata_customer->ID )->billing_company ) {
								
								
								 # If both the manager and the subaccount have the same Company Name,
								 # for the subaccount we print the Full Name.
								 #
								 # This to avoid confusion, e.g.
								 # Order placed by: Manager (Company Name Inc.) on behalf of subaccount (Company Name Inc.)
								 
								printf( '%1$s %2$s', esc_html( $userdata_customer->user_firstname ), esc_html( $userdata_customer->user_lastname ) );
								
							} else {
								// Echo 'Company' (if Company name has been set)
								printf( '%1$s', esc_html( $userdata_customer->billing_company ) );
							}
							
						} else {

							// Otherwise echo 'Username'
							printf( '%1$s', esc_html( $userdata_customer->user_login ) );
						}
						*/
						
						
						
						
						
					/**
					 * If both the manager and the subaccount have the same Company Name,
					 * for the subaccount we print the Full Name.
					 *
					 * This to avoid confusion, e.g.
					 * Order placed by: Manager (Company Name Inc.) on behalf of subaccount (Company Name Inc.)
					 */					
					if ( ( $sfwc_option_display_name == 'company_name' ) && ( get_userdata( $userdata_customer->ID )->billing_company ) && ( $userdata_manager && ( get_userdata($userdata_manager->ID)->billing_company === get_userdata( $userdata_customer->ID )->billing_company ) ) ) {
						echo esc_html( $userdata_customer->user_firstname ) . ' ' . esc_html( $userdata_customer->user_lastname );
					} else {

						echo wp_kses(
							sfwc_get_customer_display_name( $userdata_customer->ID, false ), 
							array(
								'span' => array(
									'class' => array()
								)
							) 
						);
					}
						
						
						
						
						
					} else {
						echo esc_html__( 'No information available', 'subaccounts-for-woocommerce' );
					}
					
				echo '</span>';
				
			} elseif ( $order_placed_by == 'default_for_himself' ) {
				
				// Multi-User mode.
				if ( $sfwc_option_subaccount_mode == 'multi_user' || $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order_id ) == 'multi_user' ) {
					
					if ( ! empty( $userdata_customer_placing_order ) ) { // $userdata_customer_placing_order may not be available if the order was placed before enabling Multi-User mode with plugin version prior to 1.4.3.
						$userdata_customer = $userdata_customer_placing_order;
					}
				}
				
				if ( $sfwc_option_subaccount_mode == 'multi_user' ) {
					echo esc_html__( 'Subaccount', 'subaccounts-for-woocommerce' );
				} 
				elseif ( $sfwc_option_subaccount_mode == 'sub_user' ) {
					echo esc_html__( 'Customer', 'subaccounts-for-woocommerce' );
				}
				
				echo ' <span style="background:#fdfdfd; padding:3px; border:1px solid #ebebeb; border-radius:6px; white-space:nowrap;">';
				
				/*
				if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata($userdata_customer->ID)->user_firstname || get_userdata($userdata_customer->ID)->user_lastname ) ) {

					// Echo 'Full Name' (if either First Name or Last Name has been set)
					printf( '%1$s %2$s', esc_html( $userdata_customer->user_firstname ), esc_html( $userdata_customer->user_lastname ) );
					

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

					// Echo 'Company' (if Company name has been set)
					printf( '%1$s', esc_html( $userdata_customer->billing_company ) );
					

				} else {

					// Otherwise echo 'Username'
					printf( '%1$s', esc_html( $userdata_customer->user_login ) );
					
				}
				*/
				
				echo wp_kses(
					sfwc_get_customer_display_name( $userdata_customer->ID, false ), 
					array(
						'span' => array(
							'class' => array()
						)
					) 
				);
				
				echo '</span>';
				
				/*
				if ( $sfwc_option_subaccount_mode == 'sub_user' ) {
					echo ' ' . esc_html__( 'for himself', 'subaccounts-for-woocommerce' );
				}
				*/
				
				echo '.';
			}

			/**
			 * Even if Supervisor related, DO NOT move the following code to the Supervisor Add-On,
			 * so that if the Supervisor Add-on is deactivated and there are old orders placed by a supervisor
			 * the plugin will continue to display correct data.
			 */
			elseif ( $order_placed_by == 'supervisor_for_himself' ) {

				echo esc_html__( 'Supervisor', 'subaccounts-for-woocommerce' ) . ' <span style="background:#fdfdfd; padding:3px; border:1px solid #ebebeb; border-radius:6px; white-space:nowrap;">';
					
					/*
					if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_customer->ID )->user_firstname || get_userdata( $userdata_customer->ID )->user_lastname ) ) {

						// Echo 'Full Name' (if either First Name or Last Name has been set)
						printf( '%1$s %2$s', esc_html( $userdata_customer->user_firstname ), esc_html( $userdata_customer->user_lastname ) );
						

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

						// Echo 'Company' (if Company name has been set)
						printf( '%1$s', esc_html( $userdata_customer->billing_company ) );
						

					} else {

						// Otherwise echo 'Username'
						printf( '%1$s', esc_html( $userdata_customer->user_login ) );
						
					}
					*/
					
					echo wp_kses(
						sfwc_get_customer_display_name( $userdata_customer->ID, false ), 
						array(
							'span' => array(
								'class' => array()
							)
						) 
					);
				
					echo '</span>';
					
					/*
					// Sub-User mode.
					if ( $sfwc_option_subaccount_mode == 'sub_user' ) {
						
						echo ' ' . esc_html__( 'for himself', 'subaccounts-for-woocommerce' );
					}
					*/
					
					echo '.';	
			
			} elseif ( $order_placed_by == 'supervisor_for_manager' ) {
				
				// Multi-User mode.
				if ( $sfwc_option_subaccount_mode == 'multi_user' || $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order_id ) == 'multi_user') {
				
					if ( ! empty( $userdata_customer_placing_order ) ) { // $userdata_customer_placing_order may not be available if the order was placed before enabling Multi-User mode with plugin version prior to 1.4.3.
						$userdata_customer = $userdata_customer_placing_order;
					}
				}
			
				echo esc_html__( 'Supervisor', 'subaccounts-for-woocommerce' ) . ' <span style="background:#fdfdfd; padding:3px; border:1px solid #ebebeb; border-radius:6px; white-space:nowrap;">';
					
					/*
					if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_supervisor->ID )->user_firstname || get_userdata( $userdata_supervisor->ID )->user_lastname ) ) {

						// Echo 'Full Name' (if either First Name or Last Name has been set)
						printf( '%1$s %2$s', esc_html( $userdata_supervisor->user_firstname ), esc_html( $userdata_supervisor->user_lastname ) );
						

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

						// Echo 'Company' (if Company name has been set)
						printf( '%1$s', esc_html( $userdata_supervisor->billing_company ) );
						

					} else {

						// Otherwise echo 'Username'
						printf( '%1$s', esc_html( $userdata_supervisor->user_login ) );
						
					}
					*/
					
					echo wp_kses(
						sfwc_get_customer_display_name( $userdata_supervisor->ID, false ), 
						array(
							'span' => array(
								'class' => array()
							)
						) 
					);

				echo '</span> ';
				
				/**
				 * Below check is to prevent showing "on behalf of + customer name" in case an order is placed by a Supervisor on behalf of a Manager (or a Subaccount) in Multi-User mode, 
				 * but for some reasons the admin switches to Sub-User mode afterwards.
				 *
				 * If not checked the following would show up:
				 *
				 *		Order placed by:
				 *		Supervisor (John Doe) on behalf of Manager (John Doe) 		// which of course doesn't make sense.
				 */
				if ( sfwc_order_placed_during_subaccount_mode( $order_id ) == 'multi_user' && $sfwc_option_subaccount_mode == 'multi_user' ) {

					echo esc_html__( 'on behalf of', 'subaccounts-for-woocommerce' ) . ' ' . esc_html__( 'Manager', 'subaccounts-for-woocommerce' ) . ' <span style="background:#fdfdfd; padding:3px; border:1px solid #ebebeb; border-radius:6px; white-space:nowrap;">';
					
					if ( $sfwc_option_subaccount_mode == 'sub_user' || ( $sfwc_option_subaccount_mode == 'multi_user' ) ) {
						
						/*
						if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata($userdata_customer->ID)->user_firstname || get_userdata($userdata_customer->ID)->user_lastname ) ) {

							// Echo 'Full Name' (if either First Name or Last Name has been set)
							printf( '%1$s %2$s', esc_html( $userdata_customer->user_firstname ), esc_html( $userdata_customer->user_lastname ) );
							

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

							// Echo 'Company' (if Company name has been set)
							printf( '%1$s', esc_html( $userdata_customer->billing_company ) );

						} else {

							// Otherwise echo 'Username'
							printf( '%1$s', esc_html( $userdata_customer->user_login ) );
						}
						*/
						
						echo wp_kses(
							sfwc_get_customer_display_name( $userdata_customer->ID, false ), 
							array(
								'span' => array(
									'class' => array()
								)
							) 
						);
					} else {
						echo esc_html__( 'No information available', 'subaccounts-for-woocommerce' );
					}
					
					echo '</span>';
				}
			
			} elseif ( $order_placed_by == 'supervisor_for_default' ) {
				
				// Multi-User mode.
				if ( $sfwc_option_subaccount_mode == 'multi_user' || $sfwc_option_subaccount_mode == 'sub_user' && sfwc_order_placed_during_subaccount_mode( $order_id ) == 'multi_user') {
				
					if ( ! empty( $userdata_customer_placing_order ) ) { // $userdata_customer_placing_order may not be available if the order was placed before enabling Multi-User mode with plugin version prior to 1.4.3.
						$userdata_customer = $userdata_customer_placing_order;
					}
				}
			
				echo esc_html__( 'Supervisor', 'subaccounts-for-woocommerce' ) . ' <span style="background:#fdfdfd; padding:3px; border:1px solid #ebebeb; border-radius:6px; white-space:nowrap;">';
					
					/*
					if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_supervisor->ID )->user_firstname || get_userdata($userdata_supervisor->ID)->user_lastname ) ) {

						// Echo 'Full Name' (if either First Name or Last Name has been set)
						printf( '%1$s %2$s', esc_html( $userdata_supervisor->user_firstname ), esc_html( $userdata_supervisor->user_lastname ) );
						

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

						// Echo 'Company' (if Company name has been set)
						printf( '%1$s', esc_html( $userdata_supervisor->billing_company ) );
						

					} else {

						// Otherwise echo 'Username'
						printf( '%1$s', esc_html( $userdata_supervisor->user_login ) );
						
					}
					*/
					
					echo wp_kses(
						sfwc_get_customer_display_name( $userdata_supervisor->ID, false ), 
						array(
							'span' => array(
								'class' => array()
							)
						) 
					);

				echo '</span> ';
				
				/**
				 * Below check is to prevent showing "on behalf of + customer name" in case an order is placed by a Supervisor on behalf of a Subaccount in Multi-User mode, 
				 * but for some reasons the admin switches to Sub-User mode afterwards.
				 *
				 * If not checked the following would show up:
				 *
				 *		Order placed by:
				 *		Supervisor (John Doe) on behalf of Subaccount (John Doe) 		// which of course doesn't make sense.
				 */
				if ( sfwc_order_placed_during_subaccount_mode( $order_id ) == 'multi_user' && $sfwc_option_subaccount_mode == 'multi_user' ) {

					echo esc_html__( 'on behalf of', 'subaccounts-for-woocommerce' ) . ' ' . esc_html__( 'subaccount', 'subaccounts-for-woocommerce' ) . ' <span style="background:#fdfdfd; padding:3px; border:1px solid #ebebeb; border-radius:6px; white-space:nowrap;">';
					
					if ( $sfwc_option_subaccount_mode == 'sub_user' || ( $sfwc_option_subaccount_mode == 'multi_user' ) ) {
						
						/*
						if ( ( $sfwc_option_display_name == 'full_name' ) && ( get_userdata( $userdata_customer->ID )->user_firstname || get_userdata( $userdata_customer->ID )->user_lastname ) ) {

							// Echo 'Full Name' (if either First Name or Last Name has been set)
							printf( '%1$s %2$s', esc_html( $userdata_customer->user_firstname ), esc_html( $userdata_customer->user_lastname ) );
							

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

							// Echo 'Company' (if Company name has been set)
							printf( '%1$s', esc_html( $userdata_customer->billing_company ) );
							
						} else {

							// Otherwise echo 'Username'
							printf( '%1$s', esc_html( $userdata_customer->user_login ) );
						}
						*/
						
						echo wp_kses(
							sfwc_get_customer_display_name( $userdata_customer->ID, false ), 
							array(
								'span' => array(
									'class' => array()
								)
							) 
						);
					} else {
						echo esc_html__( 'No information available', 'subaccounts-for-woocommerce' );
					}
					
					echo '</span>';
				}
			}
			
		} else {
			
			// In case order has been created by admin from backend
			// see also: sfwc_order_placed_by_update_order_meta_after_payment function in: subaccounts-for-woocommerce > public > my-account.php.
			
			
			if( ! $order->get_date_paid() ) {
				
				// Order has NOT been paid for yet.

				
				// If an order is created by an admin on backend, we will know who actually placed the order (who paid for it) only after the order has been paid (from frontend My Account area).
				echo esc_html__( 'No information yet available', 'subaccounts-for-woocommerce' ) . '. <br>' . esc_html__( 'This information will be available after the customer has paid for the order.', 'subaccounts-for-woocommerce' );


			} else {
				
				// Order is paid.
				
				
				// Most probably the order was marked as processing/completed by the admin from backend.
				echo esc_html__( 'No information available', 'subaccounts-for-woocommerce' ) . '. <br>' . esc_html__( 'This order was probably marked by the administrator as Completed or Processing.', 'subaccounts-for-woocommerce' );
			}
		}

	echo '</div>';	
	}
}
add_action( 'woocommerce_order_details_before_order_table', 'sfwc_add_subaccounts_related_information_in_order_details_page' );




/**
 * Multi-User mode A.K.A. Company Accounts (Pt.1).
 * 
 * Populate subaccount's checkout fields with "Billing Firstname", "Billing Lastname" and "Billing Email" of the Manager.
 *
 * == Checkout Shortcode version ==
 */
function sfwc_multi_user_populate_subaccount_checkout_fields_with_manager_billing_firstname_lastname_email( $checkout_fields ) {
	
	if ( is_plugin_active( 'sfwc-supervisor-addon/sfwc-supervisor-addon.php' ) ) {
		// In case Supervisor Add-On is active, use "Billing Firstname", "Billing Lastname" and "Billing Email" 
		// of the Supervisor (or Manager in case there is no Supervisor set).
		// See function: sfwc_multi_user_populate_subaccount_checkout_fields_with_parent_billing_firstname_lastname_email
		return $checkout_fields;
	}
	
	// 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 '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');

	// Get currently logged in user ID.
	$current_user_id = get_current_user_id();
	
	// Get account type of currently logged in user.
	$user_account_level_type = get_user_meta( $current_user_id, 'sfwc_account_level_type', true );
	
	// Get the user object of the current user from the user ID.
	$current_user = new WC_Customer( $current_user_id );
	
	// If no Billing First Name is set, use First Name of the user as a fallback.
	$current_user_billing_first_name = '' !== $current_user->get_billing_first_name() ? $current_user->get_billing_first_name() : $current_user->get_first_name();

	// If no Billing Last Name is set, use Last Name of the user as a fallback.
	$current_user_billing_last_name = '' !== $current_user->get_billing_last_name() ? $current_user->get_billing_last_name() : $current_user->get_last_name();
	
	// If no Billing Email is set, use Email of the user as a fallback.
	$current_user_billing_email = '' !== $current_user->get_billing_email() ? $current_user->get_billing_email() : $current_user->get_email();
	
	
	
	if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {

		// Check if currently logged in user has a Default account type.
		if ( $user_account_level_type != 'supervisor' && $user_account_level_type != 'manager' ) {
			
			/**
			* Retrieve the ID of the manager related to the subaccount.
			*/

			// Get all users with user meta 'sfwc_account_level_type' == 'manager' and filter only the one which has 'sfwc_children' user_meta containing the child ID corrisponding to the subaccount.
			$args_manager = array(
				'role__in' => $sfwc_option_selected_roles,
				'exclude' => $current_user_id, 
				'orderby' => 'ID',
				'order' => 'ASC',
				'meta_key' => 'sfwc_account_level_type',
				'meta_value' => 'manager',
				'meta_query' => array(
				   array(
					'key' => 'sfwc_children',
					'value' => '"'.$current_user_id.'"',
					'compare' => 'LIKE',
				   ),
				),
			);


			// The User Query.
			$user_query_manager = new WP_User_Query( $args_manager );


			// User Loop.
			if ( ! empty( $user_query_manager->get_results() ) ) {

				foreach ( $user_query_manager->get_results() as $user ) {
										   
					$manager_id = $user->ID;
				}
			} else {		   
				return $checkout_fields; // If the user being edited has not a Manager above him,
										 // there's no need to proceed.
			}
			
			// Get the user object of the Manager from the user ID.
			$manager = new WC_Customer( $manager_id );
			
			
			/**
			 * On the checkout page, the "Billing First Name" and "Billing Last Name" of the subaccount are shown (even if
			 * with function sfwc_multi_user_assign_order_to_manager_after_successful_order we are replacing the User ID of the customer tied to the order.
			 *
			 * And this happens regardless of whether the PRO version is installed or not and whether the billing address inheritance is enabled or not.
			 * In fact in Sub-User Mode the "Billing First Name", "Billing Last Name" and "Billing Email" are deliberately left out from the inheritance function.
			 * 
			 * So in multi-user mode it is necessary to programmatically set the "Billing First Name", "Billing Last Name" and "Billing Email" of the Manager.
			 *
			 * If we also need billing/shipping addresses to be inherited from the parent, we need to force this from the plugin settings (PRO required).
			 * Or, in case the Pro version is not installed, it is necessary to set the addresses of the subaccount manually so that they are identical to those of the parent.
			 */
			 
			// If no Billing First Name is set, use First Name of the user as a fallback.
			$manager_billing_first_name = '' !== $manager->get_billing_first_name() ? $manager->get_billing_first_name() : $manager->get_first_name();
		
			// If no Billing Last Name is set, use Last Name of the user as a fallback.
			$manager_billing_last_name = '' !== $manager->get_billing_last_name() ? $manager->get_billing_last_name() : $manager->get_last_name();
			
			// If no Billing Email is set, use Email of the user as a fallback.
			$manager_billing_email = '' !== $manager->get_billing_email() ? $manager->get_billing_email() : $manager->get_email();
			
			if ( $sfwc_option_subaccount_mode ==  'multi_user' ) {
				
				$billing_fileds = $checkout_fields['billing'];
				
				if ( ! empty( $billing_fileds ) ) {
					foreach( $billing_fileds as $key => $value ) {
						
						if( $key  == 'billing_first_name' ) {
							
							// We need this check to prevent checkout validation errors.
							if ( ! empty( $manager_billing_first_name ) ) {
								$_POST[$key] = sanitize_text_field( $manager_billing_first_name );
							}
						}
						elseif( $key == 'billing_last_name' ) {
							
							// We need this check to prevent checkout validation errors.
							if ( ! empty( $manager_billing_last_name ) ) {
								$_POST[$key] = sanitize_text_field( $manager_billing_last_name );
							}
						}
						elseif( $key == 'billing_email' ) {
							
							// We need this check to prevent checkout validation errors.
							if ( ! empty( $manager_billing_email ) ) {
								$_POST[$key] = sanitize_email( $manager_billing_email );
							}
						}
					}
				}
			}
			// We need to explicitly set the subaccount details back in case multi_user is disabled, to avoid checkout fields 
			// continuing to popolate with Manager's details after previously placed orders with multi_user option enabled.
			else {
				
				$billing_fileds = $checkout_fields['billing'];
				
				if ( ! empty( $billing_fileds ) ) {
					foreach( $billing_fileds as $key => $value ) {
						
						// Set billing details from previous order.
						if( $key  == 'billing_first_name' ) {
							
							// We need this check to prevent checkout validation errors in case.
							if ( ! empty( $current_user_billing_first_name ) ) {
								$_POST[$key] = sanitize_text_field( $current_user_billing_first_name );
							}
						}
						elseif( $key == 'billing_last_name' ) {
							
							// We need this check to prevent checkout validation errors.
							if ( ! empty( $current_user_billing_last_name ) ) {
								$_POST[$key] = sanitize_text_field( $current_user_billing_last_name );
							}
						}
						elseif( $key == 'billing_email' ) {
							
							// We need this check to prevent checkout validation errors.
							if ( ! empty( $current_user_billing_email ) ) {
								$_POST[$key] = sanitize_email( $current_user_billing_email );
							}
						}
					}
				}
			}
		}
	}				
	
	return $checkout_fields;
}
add_filter( 'woocommerce_checkout_fields', 'sfwc_multi_user_populate_subaccount_checkout_fields_with_manager_billing_firstname_lastname_email', 25, 1); // Priority 25: must run after function
																																						// sfwc_populate_subaccount_checkout_fields_with_manager_data (priority 20).



/**
 * Multi-User mode A.K.A. Company Accounts (Pt.2).
 * 
 * Populate subaccount's checkout fields with "Billing Firstname", "Billing Lastname" and "Billing Email" of the Manager.
 *
 * == Checkout Block version ==
 *
 *
 * Note: Although this function could be used for both the shortcode-based and the block-based checkout,
 * based on our tests it works intermittently with the checkout shortcode.
 * For example: if you update customer billing/shipping data from the admin side and then visit the checkout page (shortcode),
 * the parent account data is not displayed on first page load.
 */
function sfwc_multi_user_checkout_block_populate_subaccount_checkout_fields_with_manager_billing_firstname_lastname_email() {

	if ( is_plugin_active( 'sfwc-supervisor-addon/sfwc-supervisor-addon.php' ) ) {
		// In case Supervisor Add-On is active, use "Billing Firstname", "Billing Lastname" and "Billing Email" 
		// of the Supervisor (or Manager in case there is no Supervisor set).
		// See function: sfwc_multi_user_checkout_block_populate_subaccount_checkout_fields_with_parent_billing_firstname_lastname_email
		return;
	}
	
	// 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 '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');

	// Get currently logged in user ID.
	$current_user_id = get_current_user_id();
	
	// Get account type of currently logged in user.
	$user_account_level_type = get_user_meta( $current_user_id, 'sfwc_account_level_type', true );
	
	// Get the user object of the current user from the user ID.
	$current_user = new WC_Customer( $current_user_id );
	
	// If no Billing First Name is set, use First Name of the user as a fallback.
	$current_user_billing_first_name = '' !== $current_user->get_billing_first_name() ? $current_user->get_billing_first_name() : $current_user->get_first_name();

	// If no Billing Last Name is set, use Last Name of the user as a fallback.
	$current_user_billing_last_name = '' !== $current_user->get_billing_last_name() ? $current_user->get_billing_last_name() : $current_user->get_last_name();
	
	// If no Billing Email is set, use Email of the user as a fallback.
	$current_user_billing_email = '' !== $current_user->get_billing_email() ? $current_user->get_billing_email() : $current_user->get_email();
	
	
	
	if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {

		// Check if currently logged in user has a Default account type.
		if ( $user_account_level_type != 'supervisor' && $user_account_level_type != 'manager' ) {
			
			/**
			* Retrieve the ID of the manager related to the subaccount.
			*/

			// Get all users with user meta 'sfwc_account_level_type' == 'manager' and filter only the one which has 'sfwc_children' user_meta containing the child ID corrisponding to the subaccount.
			$args_manager = array(
				'role__in' => $sfwc_option_selected_roles,
				'exclude' => $current_user_id, 
				'orderby' => 'ID',
				'order' => 'ASC',
				'meta_key' => 'sfwc_account_level_type',
				'meta_value' => 'manager',
				'meta_query' => array(
				   array(
					'key' => 'sfwc_children',
					'value' => '"'.$current_user_id.'"',
					'compare' => 'LIKE',
				   ),
				),
			);
			
			// The User Query.
			$user_query_manager = new WP_User_Query( $args_manager );

			// User Loop.
			if ( ! empty( $user_query_manager->get_results() ) ) {

				foreach ( $user_query_manager->get_results() as $user ) {
					$manager_id = $user->ID;
				}
			} else {
				return; // If currently logged-in user has no Manager above him, there's no need to proceed.
			}
			
			// Get the user object of the Manager from the user ID.
			$manager = new WC_Customer( $manager_id );
			
			
			/**
			 * On the checkout page, the "Billing First Name" and "Billing Last Name" of the subaccount are shown (even if
			 * with function sfwc_multi_user_assign_order_to_manager_after_successful_order we are replacing the User ID of the customer tied to the order.
			 *
			 * And this happens regardless of whether the PRO version is installed or not and whether the billing address inheritance is enabled or not.
			 * In fact in Sub-User Mode the "Billing First Name", "Billing Last Name" and "Billing Email" are deliberately left out from the inheritance function.
			 * 
			 * So in multi-user mode it is necessary to programmatically set the "Billing First Name", "Billing Last Name" and "Billing Email" of the Manager.
			 *
			 * If we also need billing/shipping addresses to be inherited from the parent, we need to force this from the plugin settings (PRO required).
			 * Or, in case the Pro version is not installed, it is necessary to set the addresses of the subaccount manually so that they are identical to those of the parent.
			 */
			 
			// If no Billing First Name is set, use First Name of the user as a fallback.
			$manager_billing_first_name = '' !== $manager->get_billing_first_name() ? $manager->get_billing_first_name() : $manager->get_first_name();
		
			// If no Billing Last Name is set, use Last Name of the user as a fallback.
			$manager_billing_last_name = '' !== $manager->get_billing_last_name() ? $manager->get_billing_last_name() : $manager->get_last_name();
			
			// If no Billing Email is set, use Email of the user as a fallback.
			$manager_billing_email = '' !== $manager->get_billing_email() ? $manager->get_billing_email() : $manager->get_email();
			
			if ( $sfwc_option_subaccount_mode ==  'multi_user' ) {
				
				/**
				 * Store original subaccount details in a WC session.
				 *
				 * This is only required for the Checkout Block.
				 *
				 * Since we couldn't find a reliable way to prevent the checkout process from updating user metadata when using the Checkout Block,
				 * we store original subaccount data in a WC session, so that it can be restored after the checkout process is completed.
				 */
				$subaccount_original_data = array();
				$subaccount_original_data['billing_first_name'] = $current_user_billing_first_name;
				$subaccount_original_data['billing_last_name'] = $current_user_billing_last_name;
				$subaccount_original_data['billing_email'] = $current_user_billing_email;
				
				WC()->session->set( 'sfwc_subaccount_data_to_be_restored_after_checkout', $subaccount_original_data );
				
				// Set parent account details in checkout fields.
				WC()->customer->set_billing_first_name( sanitize_text_field( $manager_billing_first_name ) );
				WC()->customer->set_billing_last_name( sanitize_text_field( $manager_billing_last_name ) );
				WC()->customer->set_billing_email( sanitize_email( $manager_billing_email ) );
				
				
				add_action('wp_footer', function () {
					?>
					<script type="text/javascript">
					<!--

					function readOnlyFields() {
						const billingFirstName = document.querySelector('#billing-first_name');
						if ( billingFirstName && ( billingFirstName.value || ! billingFirstName.hasAttribute('required') ) ) {
							billingFirstName.setAttribute( 'readonly', true );
							billingFirstName.style.cursor = "not-allowed";
						}
						
						const billingLastName = document.querySelector('#billing-last_name');
						if ( billingLastName && ( billingLastName.value || ! billingLastName.hasAttribute('required') ) ) {
							billingLastName.setAttribute( 'readonly', true );
							billingLastName.style.cursor = "not-allowed";
						}
						
						const billingEmail = document.querySelector('#email');
						if ( billingEmail && ( billingEmail.value || ! billingEmail.hasAttribute('required') ) ) {
							billingEmail.setAttribute( 'readonly', true );
							billingEmail.style.cursor = "not-allowed";
						}	
					}
					
					window.addEventListener('load', readOnlyFields);
					
					window.addEventListener('load', function() {
						const element = document.querySelector(".wc-block-checkout__form");
						element.addEventListener('change', readOnlyFields);
					});
					
					//-->
					</script>
					<?php
				});
			}
			else {
				/**
				 * We explicitly set the subaccount details back in case multi_user is disabled, to avoid checkout fields 
				 * continuing to popolate with Manager's details after previously placed orders with multi_user option enabled.
				 */
				WC()->customer->set_billing_first_name( sanitize_text_field( $current_user_billing_first_name ) );
				WC()->customer->set_billing_last_name( sanitize_text_field( $current_user_billing_last_name ) );
				WC()->customer->set_billing_email( sanitize_email( $current_user_billing_email ) );
			}
		}
	}
}
add_filter( 'woocommerce_checkout_init', 'sfwc_multi_user_checkout_block_populate_subaccount_checkout_fields_with_manager_billing_firstname_lastname_email', 25, 1 ); // Priority 25: must run after function
																																									  // sfwc_populate_subaccount_checkout_fields_with_manager_data_checkout_block (priority 20).



/**
 * Multi-User mode A.K.A. Company Accounts (Pt.3).
 *
 * Retore original subaccount metadata after the checkout process.
 * This is only required for the Checkout Block.
 *
 * Since we couldn't find a reliable way to prevent the checkout process from updating user metadata when using the Checkout Block,
 * we get original subaccount data from the WC session and restore it after the checkout process is completed.
 */
function sfwc_multi_user_checkout_block_restore_checkout_fields_values_from_session( $order ) {
	
	$sfwc_options = (array) get_option('sfwc_options');
	
	$sfwc_option_subaccount_mode = ( isset( $sfwc_options['sfwc_option_subaccount_mode'] ) ) ? $sfwc_options['sfwc_option_subaccount_mode'] : 'sub_user';
	
	$user_id = get_current_user_id();
	
	// Get original subaccount data from the WC session.
	$subaccount_original_data = WC()->session->get('sfwc_subaccount_data_to_be_restored_after_checkout');
	
	// Make sure Multi-User mode is enabled.
	if ( $sfwc_option_subaccount_mode !== 'multi_user' )
		return;
	
	if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) { 	// Do not check
																												// ! wp_doing_ajax()
		if ( ! empty( $subaccount_original_data ) ) {
				
			update_user_meta( $user_id, "billing_first_name", sanitize_text_field( $subaccount_original_data['billing_first_name'] ) );
			update_user_meta( $user_id, "billing_last_name", sanitize_text_field( $subaccount_original_data['billing_last_name'] ) );
			update_user_meta( $user_id, "billing_email", sanitize_email( $subaccount_original_data['billing_email'] ) );
		}
	}
}
add_action('woocommerce_store_api_checkout_order_processed', 'sfwc_multi_user_checkout_block_restore_checkout_fields_values_from_session' ); // QUESTO HOOK OK: VIENE ESEGUITO SOLO AL COMPLETAMENTO DELL'ORDINE TRAMITE CHECKOUT BLOCK




/**
 * Multi-User mode A.K.A. Company Accounts (Pt.4).
 * 
 * Make "Billing Firstname", "Billing Lastname" and "Billing Email" checkout fields not editable.
 */
 function sfwc_multi_user_make_certain_fields_readonly( $checkout_fields ) {
	
	$sfwc_options = (array) get_option('sfwc_options');
	
    $sfwc_option_selected_roles = ( isset( $sfwc_options['sfwc_option_selected_roles'] ) ) ? $sfwc_options['sfwc_option_selected_roles'] : array('customer', 'subscriber');
	
	$sfwc_option_subaccount_mode = ( isset( $sfwc_options['sfwc_option_subaccount_mode'] ) ) ? $sfwc_options['sfwc_option_subaccount_mode'] : 'sub_user';
	
	
	// Verify options.
	if ( $sfwc_option_subaccount_mode !== 'multi_user' ) {
		return $checkout_fields;
	}

	if ( ! is_admin() && is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) { 	// Do not check
																																// ! wp_doing_ajax() 
																																// here, otherwise Manager's address details
																																// will not be saved in place of subaccount's address details.
		
		// Get currently logged in user ID.
		$current_user_id = get_current_user_id();
		
		// Get account type of currently logged in user.
		$user_account_level_type = get_user_meta( $current_user_id, 'sfwc_account_level_type', true );

		
		/**
		* Check to see if the user currently being edited is a subaccount (by verifying if has a Manager above him),
		* or a simple standalone customer.
		*/

		// Get all users with user meta 'sfwc_account_level_type' == 'manager' and filter only the one which has 'sfwc_children' user_meta containing the child ID corrisponding to the subaccount.
		$args_manager = array(
			'role__in' => $sfwc_option_selected_roles,
			'exclude' => $current_user_id, 
			'orderby' => 'ID',
			'order' => 'ASC',
			'meta_key' => 'sfwc_account_level_type',
			'meta_value' => 'manager',
			'meta_query' => array(
			   array(
				'key' => 'sfwc_children',
				'value' => '"'.$current_user_id.'"',
				'compare' => 'LIKE',
			   ),
			),
		);


		// The User Query
		$user_query_manager = new WP_User_Query( $args_manager );


		// User Loop
		if ( ! empty( $user_query_manager->get_results() ) ) {

			foreach ( $user_query_manager->get_results() as $user ) {
									   
				$manager_id = $user->ID;
			}
		} else {		   
			return $checkout_fields;	// If the user being edited has not a Manager above him, there's no need to proceed and checkout fields can be normally edited.
		}
		
		// Get the user object of the Manager from the user ID.
		$manager = new WC_Customer( $manager_id );
		
		// If no Billing First Name is set, use First Name of the user as a fallback.
		$manager_billing_first_name = '' !== $manager->get_billing_first_name() ? $manager->get_billing_first_name() : $manager->get_first_name();
		
		// If no Billing Last Name is set, use Last Name of the user as a fallback.
		$manager_billing_last_name = '' !== $manager->get_billing_last_name() ? $manager->get_billing_last_name() : $manager->get_last_name();
		

		// Check if currently logged in user has a Default account type.
		if ( $user_account_level_type != 'supervisor' && $user_account_level_type != 'manager' ) {
	
			foreach ( $checkout_fields['billing'] as $key => $field ){
				
				/**
				 * Email is mandatory when creating an account, so it is present for sure.
				 *
				 * Billing First Name and Billing Last Name instead, are not mandatory when adding new users (customers) from the backend.
				 * So those values may not be present at checkout. But at checkout Billing First Name and Billing Last Name instead are mandatory instead.
				 * For this reason we need to check that those values exist before making the fields readonly.
				 */
				if ( $key == 'billing_email' || ( $key == 'billing_first_name' && $manager_billing_first_name !== '' )  || ( $key == 'billing_last_name' && $manager_billing_last_name !== '' )  ) {

					$checkout_fields['billing'][$key]['custom_attributes'] = array( 'readonly'=>'readonly' ); // Using 'disabled' will cause validation error during checkout.
				}
			}
		}
	}
	
	// Return checkout fields.
	return $checkout_fields;
}
add_filter( 'woocommerce_checkout_fields','sfwc_multi_user_make_certain_fields_readonly' );




/**
 * Multi-User mode A.K.A. Company Accounts (Pt.5).
 *
 * Prevent WooCommerce from updating user data after checkout.
 */
 function sfwc_multi_user_prevent_woocommerce_from_updating_user_data_after_checkout() {
	
	$sfwc_options = (array) get_option('sfwc_options');
	
    $sfwc_option_selected_roles = ( isset( $sfwc_options['sfwc_option_selected_roles'] ) ) ? $sfwc_options['sfwc_option_selected_roles'] : array('customer', 'subscriber');
	
	$sfwc_option_subaccount_mode = ( isset( $sfwc_options['sfwc_option_subaccount_mode'] ) ) ? $sfwc_options['sfwc_option_subaccount_mode'] : 'sub_user';
	
	$sfwc_options_subaccounts_inherit_shipping_address_from_manager	= ( isset( $sfwc_options['sfwc_options_subaccounts_inherit_shipping_address_from_manager'] ) ) ? 
																		$sfwc_options['sfwc_options_subaccounts_inherit_shipping_address_from_manager'] : 0;
	
	$sfwc_options_subaccounts_inherit_billing_address_from_manager 	= ( isset( $sfwc_options['sfwc_options_subaccounts_inherit_billing_address_from_manager'] ) ) ? 
																		$sfwc_options['sfwc_options_subaccounts_inherit_billing_address_from_manager'] : 0;
																			
	if ( ! is_admin() && is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) { 	// Do not check
																																// ! wp_doing_ajax() 
																																// here.
		
		// Get currently logged in user ID.
		$current_user_id = get_current_user_id();
		
		// Get account type of currently logged in user.
		$user_account_level_type = get_user_meta( $current_user_id, 'sfwc_account_level_type', true );

		
		/**
		* Check to see if the user currently being edited is a subaccount (by verifying if has a Manager above him),
		* or a simple standalone customer.
		*/

		// Get all users with user meta 'sfwc_account_level_type' == 'manager' and filter only the one which has 'sfwc_children' user_meta containing the child ID corrisponding to the subaccount.
		$args_manager = array(
			//'role'    => 'customer',
			//'role__in' => ['customer', 'subscriber'],
			'role__in' => $sfwc_option_selected_roles,
			'exclude' => $current_user_id, 
			'orderby' => 'ID',
			'order' => 'ASC',
			'meta_key' => 'sfwc_account_level_type',
			'meta_value' => 'manager',
			'meta_query' => array(
			   array(
				'key' => 'sfwc_children',
				'value' => '"'.$current_user_id.'"',
				'compare' => 'LIKE',
			   ),
			),
		);


		// The User Query
		$user_query_manager = new WP_User_Query( $args_manager );


		// User Loop
		if ( ! empty( $user_query_manager->get_results() ) ) {

			foreach ( $user_query_manager->get_results() as $user ) {
									   
				$manager_id = $user->ID;
			}
		} else {		   
			return;	// If the user being edited has not a Manager above him, it means it's a default standalone customer and there's no need to proceed.
		}
		

		// Check if currently logged in user has a Default account type.
		if ( $user_account_level_type != 'supervisor' && $user_account_level_type != 'manager' ) {
		
			// Verify options.
			if ( $sfwc_option_subaccount_mode == 'multi_user' ) {
	
				add_filter( 'woocommerce_checkout_update_customer_data', '__return_false' );
			}
		}
	}
}
add_action( 'init', 'sfwc_multi_user_prevent_woocommerce_from_updating_user_data_after_checkout' );




/**
 * Multi-User mode A.K.A. Company Accounts (Pt.6).
 * 
 * Assign the order placed by a subaccount to its Manager after a successful order.
 */
function sfwc_multi_user_assign_order_to_manager_after_successful_order( $order_id ) {
	
	if ( is_plugin_active( 'sfwc-supervisor-addon/sfwc-supervisor-addon.php' ) ) {
		// In case Supervisor Add-On is active, the order placed by a Manager or a Subaccount must be assigned to the Supervior.
		// (or to the Manager in case there is no Supervisor set).
		// See function: sfwc_multi_user_assign_order_to_parent_after_successful_order
		return;
	}
	
	// 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 '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');
	
	// Get order object from order ID.
	$order = wc_get_order( $order_id );
	
	// Get user ID from the order.
	$user_id = $order->get_user_id();
	
	// Get account level type from user ID.
	$user_account_level_type = get_user_meta( $user_id, 'sfwc_account_level_type', true );
	
	if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {
		
		if ( $sfwc_option_subaccount_mode ==  'multi_user' ) {
		
			// Check if currently logged in user has a Default account type.
			if ( $user_account_level_type != 'supervisor' && $user_account_level_type != 'manager' ) {
				
				/**
				 * Retrieve the ID of the manager related to the subaccount.
				 */

				// Get all users with user meta 'sfwc_account_level_type' == 'manager' and filter only the one which has 'sfwc_children' user_meta containing the child ID corrisponding to the subaccount.
				$args_manager = array(
					'role__in' => $sfwc_option_selected_roles,
					'exclude' => $user_id, 
					'orderby' => 'ID',
					'order' => 'ASC',
					'meta_key' => 'sfwc_account_level_type',
					'meta_value' => 'manager',
					'meta_query' => array(
					   array(
						'key' => 'sfwc_children',
						'value' => '"'.$user_id.'"',
						'compare' => 'LIKE',
					   ),
					),
				);


				// The User Query.
				$user_query_manager = new WP_User_Query( $args_manager );


				// User Loop.
				if ( ! empty( $user_query_manager->get_results() ) ) {

					foreach ( $user_query_manager->get_results() as $user ) {
											   
						$manager_id = $user->ID;
					}
				} else {		   
					return; // If the user being edited has not a Manager above him,
							// there's no need to proceed.
				}
				
				// Get user object from user ID.
				$manager = new WC_Customer( $manager_id );
				
				
				/**
				 * In the order list on the admin side, the "Billing First Name" and "Billing Last Name" of the subaccount is shown in the "Order" column (even if
				 * with this function we are replacing the User ID of the customer tied to the order.
				 *
				 * And this happens regardless of whether the PRO version is installed or not and whether the billing address inheritance is enabled or not.
				 * In fact in Sub-User Mode the "Billing First Name", "Billing Last Name" and "Billing Email" are deliberately left out from the inheritance function.
				 * 
				 * So in multi-user mode it is necessary to programmatically set the "Billing First Name", "Billing Last Name" and "Billing Email" of the Manager.
				 *
				 * If we also need billing/shipping addresses to be inherited from the parent, we need to force this from the plugin settings (PRO required).
				 * Or, in case the Pro version is not installed, it is necessary to set the addresses of the subaccount manually so that they are identical to those of the parent.
				 */
				 
				// If no Billing First Name is set, use First Name of the user as a fallback.
				$manager_billing_first_name = '' !== $manager->get_billing_first_name() ? $manager->get_billing_first_name() : $manager->get_first_name();
			
				// If no Billing Last Name is set, use Last Name of the user as a fallback.
				$manager_billing_last_name = '' !== $manager->get_billing_last_name() ? $manager->get_billing_last_name() : $manager->get_last_name();
				
				// If no Billing Email is set, use Email of the user as a fallback.
				$manager_billing_email = '' !== $manager->get_billing_email() ? $manager->get_billing_email() : $manager->get_email();
				
				// Set data.
				$order->set_billing_first_name( sanitize_text_field( $manager_billing_first_name ) );
				$order->set_billing_last_name( sanitize_text_field( $manager_billing_last_name ) );
				$order->set_billing_email( sanitize_email( $manager_billing_email ) );
				$order->set_customer_id( absint( $manager_id ) );
				
				// Update the order.
				$order->save();
			}
		}
	}
}
add_action( 'woocommerce_thankyou', 'sfwc_multi_user_assign_order_to_manager_after_successful_order', 20, 1 ); // Both woocommerce_new_order and woocommerce_thankyou hooks can be used.




/**
 * Multi-User mode A.K.A. Company Accounts (Pt.7).		// Maybe integrate this function with: sfwc_my_account_orders_query_subaccounts_orders
 * 
 * Sanitize, validate submitted data and show orders in: My Account -> Orders for Managers.
 *
 * See also: sfwc_multi_user_my_account_orders_query_subaccounts_orders_for_supervisors function in Supervisor Add-On.
 */
function sfwc_multi_user_my_account_orders_query_subaccounts_orders( $args ) {

	// Sanitize cookie value.
	if ( isset( $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'subaccount_ids'] ) ) {

		// Decode cookie
		$subaccount_ids_cookie_decoded = json_decode( str_replace ('\"','', $_COOKIE[ apply_filters( 'sfwc_cookie_prefix', '' ) . 'subaccount_ids']), true );
		
		// Sanitize cookie value
		$subaccount_ids_cookie_sanitized = preg_replace('/[^0-9]/', '', $subaccount_ids_cookie_decoded);
	}
	
	// Sanitize posted values.
	if ( isset( $_POST['sfwc_subaccount_orders'] ) ) {
		$selected_subaccount_ids_sanitized = preg_replace('/[^0-9]/', '', $_POST['sfwc_subaccount_orders']);	// sanitize_text_field() only works for strings, so this is not the case.
	}																											// preg_replace: If subject (3rd parameter) is an array, then the search and replace 
																												// is performed on every entry of subject, and the return value is an array as well.
																							
	// 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 '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');
	
	// Get ID of currently logged in user.
	$user_id = get_current_user_id();
	
	// Get Account Level Type of currently logged in user.
	$account_level_type = get_user_meta( $user_id, 'sfwc_account_level_type', true );
	

	
	if ( is_wc_endpoint_url( 'orders' ) && $sfwc_option_subaccount_mode == 'multi_user' ) {	// <--- NOT is_wc_endpoint_url( 'subaccounts' ) here,
																							// see: sfwc_my_account_orders_query_subaccounts_orders.
		// Check if user is a Manager.
		if ( $account_level_type == 'manager' ) {
			
			
			// Get children (array) of currently logged in user.																		
			$children_ids = get_user_meta( $user_id, 'sfwc_children', true );
			
			// Retrieve all orders of the Manager (in Multi-User mode this will include also orders placed by subaccounts).
			$args_manager_orders = array(
				'customer_id' => $user_id,
				'limit' => -1, // Retrieve all orders.
			);
			$orders = wc_get_orders( $args_manager_orders );
			
			/**
			 * Remove no longer existing users from the $children_ids array,
			 * in case a user has been deleted (but still present within 'sfwc_children' meta of an ex parent account).
			 *
			 * Also exclude users whose role is not enabled in the plugin settings.
			 */
			$existing_children_ids = array();
			
			if ( ! empty ( $children_ids ) ) {
				
				foreach ( $children_ids as $single_id ) {
					
					// Check if user still exists.
					$user_exists = get_userdata( $single_id );
					if ( $user_exists !== false ) {
						
						if ( sfwc_is_user_role_valid( $single_id ) && sfwc_is_user_role_enabled( $single_id ) &&
							 get_user_meta( $single_id, 'sfwc_account_level_type', true ) !== 'supervisor' &&
							 get_user_meta( $single_id, 'sfwc_account_level_type', true ) !== 'manager' )
						{
							
							$existing_children_ids[] = $single_id;
						}
					}
				}
			}
			
			// Include the user ID of the Manager among the orders to show.
			array_push( $existing_children_ids, $user_id );
			
			

			
			/**
			 * If the Supervisor Add-On is active, include the user ID of the Supervisor.
			 *
			 * In case the Supervisor Add-On is active, when a Manager or a Subaccount places an order it will be assigned to the Supervisor afterwards.
			 * For this reason it is necessary to include the user ID of the Supervisor among the IDs of the users to show orders for.
			 */
			if ( sfwc_is_plugin_active( 'sfwc-supervisor-addon.php' ) ) {
		
				// Get Supervisor's ID.
				$args_supervisor = array(
					'role__in' => $sfwc_option_selected_roles,
					'orderby' => 'ID',
					'order' => 'ASC',
					'meta_key' => 'sfwc_account_level_type',
					'meta_value' => 'supervisor',
					'meta_query' => array(
						array(
							'key' => 'sfwc_children',
							'value' => '"'.$user_id.'"',
							'compare' => 'LIKE',
						),
					),
				);

				// The User Query.
				$user_query_supervisor = new WP_User_Query( $args_supervisor );

				// User Loop.
				if ( ! empty( $user_query_supervisor->get_results() ) ) {
					foreach ( $user_query_supervisor->get_results() as $user ) {

						$supervisor_id = $user->ID;
					}
					array_push( $existing_children_ids, $supervisor_id );
				}
			}
			
			
			


	
			if ( ! isset( $selected_subaccount_ids_sanitized ) ) {
			
				if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
			
					// HPOS usage is enabled.
					
					if( isset( $supervisor_id ) ) {
					
						$excluded_order_ids = wc_get_orders( array(
							'return'		=> 'ids', // Return order IDs.
							'limit'			=> -1,
							'customer_id' 	=> $supervisor_id,
							'meta_query' 	=> array(
								'relation'	=> 'OR',
								array( // Select those orders placed by Supervisor for himself in Sub-User mode (_sfwc_order_placed_by_user_id is missing). 								hides #140
									'key' 		=> '_sfwc_order_placed_by_user_id',
									'compare'	=> 'NOT EXISTS',
								),
								array( // Select those orders placed by Supervisor for himself in Multi-User mode (_sfwc_order_placed_by_user_id equals to user ID of Supervisor). 			hides #146
									'key' 		=> '_sfwc_order_placed_by_user_id',
									'value' 	=> $supervisor_id,
									'compare'	=> 'LIKE',
								),
							)
						) );
					}					

				} else {
				
					// Traditional CPT-based orders are in use.
					
					if( isset( $supervisor_id ) ) {
					
						$excluded_order_ids = get_posts( array(
							'post_type'		=> 'shop_order',
							'fields'		=> 'ids', // Return order IDs.
							'post_status'	=> array_keys( wc_get_order_statuses() ),
							'numberposts'	=> -1,
							'meta_query' 	=> array(
								'relation'	=> 'AND',
								array( // Select all orders of Supervisor.
									'key'		=> '_customer_user',
									'value'		=> $supervisor_id,
									'compare'	=> 'LIKE',
								),
								array(
									'relation'	=> 'OR',
									array( // Select those orders placed by Supervisor for himself in Sub-User mode (_sfwc_order_placed_by_user_id is missing). 								hides #140
										'key' 		=> '_sfwc_order_placed_by_user_id',
										'compare'	=> 'NOT EXISTS',
									),
									array( // Select those orders placed by Supervisor for himself in Multi-User mode (_sfwc_order_placed_by_user_id equals to user ID of Supervisor). 			hides #146
										'key' 		=> '_sfwc_order_placed_by_user_id',
										'value' 	=> $supervisor_id,
										'compare'	=> 'LIKE',
									),
								)
							)
						) );
					}
				}
				
				
				$args['customer'] = $existing_children_ids; // Initially show all results: both Manager and subaccount orders
															// and even those orders placed by a Manager or by a Subaccount 
															// and assigned to the Supervisor afterwards (Multi-User mode) if/when Supervisor Add-On is active.
					
				if( ! empty( $excluded_order_ids) ) {
					// We need to exclude all those orders placed by a Supervisor for himself during both Sub-User and Multi-User mode.
					// This because by default a Manager should not be able to see those orders.
					$args['exclude'] = $excluded_order_ids;
				}
				
			}

			/**
			 * Validation start.
			 *
			 * Only orders that belong to the currently logged in parent account ID or orders that belong to the parent's subaccount IDs are valid.
			 */
			if ( isset( $selected_subaccount_ids_sanitized ) || isset( $subaccount_ids_cookie_sanitized ) ) {
					
				$validated_subaccount_orders = array();
				$not_valid_subaccount_orders = array();
				
				// Validate posted values.
				if ( isset( $selected_subaccount_ids_sanitized ) && ! empty( $selected_subaccount_ids_sanitized ) ) {
					
					// Check if nonce is in place and verfy it.
					if ( ! isset( $_POST['sfwc_filter_subaccount_orders'] ) || isset( $_POST['sfwc_filter_subaccount_orders'] ) && ! wp_verify_nonce( $_POST['sfwc_filter_subaccount_orders'], 'sfwc_filter_subaccount_orders_action' ) ) {
																															
						wc_print_notice( esc_html__( 'Nonce could not be verified.', 'subaccounts-for-woocommerce' ), 'error');
						return $args;
					}

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

						// Check if submitted data is valid.
						if ( in_array( $value, $existing_children_ids, true ) || $value == $user_id ) {	// $existing_children_ids should already include $user_id,
																										// but for some reasons fails to validate.
																										// So keep there: $value == $user_id.
							$validated_subaccount_orders[] = absint( $value );
						} else {
							$not_valid_subaccount_orders[] = absint( $value );
						}
					}
				}
				// Validate cookie values.
				elseif ( isset( $subaccount_ids_cookie_sanitized ) && ! empty( $subaccount_ids_cookie_sanitized ) ) {
					
					foreach ( $subaccount_ids_cookie_sanitized as $key => $value ) {

						// Check if submitted data is valid.
						if ( in_array( $value, $existing_children_ids, true ) || $value ==  $user_id ) {	// $existing_children_ids should already include $user_id,
																											// but for some reasons fails to validate.
																											// So keep there: $value == $user_id.
							$validated_subaccount_orders[] = $value;
						} else {
							$not_valid_subaccount_orders[] = $value;
						}
					}
				}


				if ( ! empty( $not_valid_subaccount_orders ) ) {

					foreach ( $not_valid_subaccount_orders as $key => $value ) {
						wc_print_notice( esc_html__( 'You are not allowed to select orders for user ID: ', 'subaccounts-for-woocommerce' ) . $value . '.', 'error');
					}
				}



				if ( ! empty( $validated_subaccount_orders ) ) {

					if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
						
						// HPOS usage is enabled.
						
						/**
						 * Retrieve orders placed by subaccounts that have been assigned to the Manager after successful order.
						 *
						 * Retrieve them by checking _sfwc_order_placed_by_user_id meta value.
						 */
						$order_ids = wc_get_orders( array(
							'return'		=> 'ids', // Return order IDs.
							'limit'			=> -1,
							#'customer_id' 	=> $manager_id,
							'meta_query' 	=> array(
								array(
									'key' 		=> '_sfwc_order_placed_by_user_id',
									'value' 	=> $validated_subaccount_orders,
									'compare'	=> 'IN',
								)
							)
						) );


						/**
						 * Retrieve orders placed by subaccounts before enabling Multi-User mode and/or orders directly tied to the selected user.
						 */
						$order_ids_previous = wc_get_orders( array(
							'return' => 'ids', // Return order IDs.
							'limit' => -1,
							'customer_id' => $validated_subaccount_orders,
						) );


						// Marge orders.
						$all_order_ids = array_merge( $order_ids, $order_ids_previous );
						
						

						if ( ! empty( $all_order_ids ) ) {
							$args['customer'] = $existing_children_ids; // Includes Manager ID and subaccount IDs.
							$args['post__in'] = $all_order_ids;
						}
						else {
							$args['customer'] = false;	// If the search did not produce any results, don't show any orders.
						}
						
					} else {
			
						// Traditional CPT-based orders are in use.
						
						$order_ids = get_posts( array(
							'post_type'		=> 'shop_order',
							'fields'		=> 'ids', // Return order IDs.
							'post_status'	=> array_keys( wc_get_order_statuses() ),
							'numberposts'	=> -1,
							'meta_query' 	=> array(
								'relation'	=> 'OR',
								array(
									'key'		=> '_customer_user',
									'value'		=> $validated_subaccount_orders,
									'compare'	=> 'IN',
								),
								array(
									'key' 		=> '_sfwc_order_placed_by_user_id',
									'value' 	=> $validated_subaccount_orders,
									'compare'	=> 'IN',
								)
							)
						) );
						
						if ( ! empty( $order_ids ) ) {
							$args['customer'] = $existing_children_ids; // Includes Manager ID and subaccount IDs.
							$args['post__in'] = $order_ids;
						}
						else {
							$args['customer'] = false;	// If the search did not produce any results, don't show any orders.
						}
					}
				}
				else {
					$args['customer'] = false;	// If the search did not produce any results, don't show any orders.
				}
			}
		}
		elseif ( $account_level_type !== 'manager' && $account_level_type !== 'supervisor' && ! sfwc_is_plugin_active( 'sfwc-supervisor-addon.php' ) ) { // In case Supervisor Add-On is active, see:
																																						 // sfwc_multi_user_my_account_orders_query_subaccounts_orders_for_supervisors
			
			/**
			* Check to see if the user currently being edited is a subaccount (by verifying if has a Manager above him),
			* or a simple standalone customer.
			*/

			// Get all users with user meta 'sfwc_account_level_type' == 'manager' and filter only the one which has 'sfwc_children' user_meta containing the child ID corrisponding to the subaccount.
			$args_manager = array(
				//'role'    => 'customer',
				//'role__in' => ['customer', 'subscriber'],
				'role__in' => $sfwc_option_selected_roles,
				'exclude' => $user_id, 
				'orderby' => 'ID',
				'order' => 'ASC',
				'meta_key' => 'sfwc_account_level_type',
				'meta_value' => 'manager',
				'meta_query' => array(
				   array(
					'key' => 'sfwc_children',
					'value' => '"'.$user_id.'"',
					'compare' => 'LIKE',
				   ),
				),
			);


			// The User Query
			$user_query_manager = new WP_User_Query( $args_manager );


			// User Loop
			if ( ! empty( $user_query_manager->get_results() ) ) {

				foreach ( $user_query_manager->get_results() as $user ) {
										   
					$manager_id = $user->ID;
				}
			} else {		   
				return $args;	// If the user being edited has not a Manager above him, 
								// it means it's a default standalone customer and there's no need to alter the query.
			}

			
			

			if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
				
				// HPOS usage is enabled.
				
				
				/**
				 * Retrieve orders placed by the subaccount that have been assigned to the Manager after successful order.
				 *
				 * Retrieve them by checking _sfwc_order_placed_by_user_id meta value.
				 */
				$order_ids = wc_get_orders( array(
					'return'		=> 'ids', // Return order IDs.
					'limit'			=> -1,
					'customer_id' 	=> $manager_id,
					'meta_query' 	=> array(
						array(
							'key' 		=> '_sfwc_order_placed_by_user_id',
							'value' 	=> $user_id,
							'compare'	=> 'LIKE',
						)
					)
				) );
				
				
				/**
				 * Retrieve orders placed by subaccount before enabling Multi-User mode.
				 *
				 * In this case orders are still tied to the subaccount itself (they were not assigned to the Manager afterwards).
				 */
				$order_ids_previous = wc_get_orders( array(
					'return' => 'ids', // Return order IDs.
					'limit' => -1,
					'customer_id' => $user_id,
				) );
				
				
				// Marge orders.
				$all_order_ids = array_merge( $order_ids_previous, $order_ids );
				

				$args['customer'] = array( $manager_id, $user_id );
				$args['post__in'] = $all_order_ids;
				
				
			} else {
				
				// Traditional CPT-based orders are in use.
				
				
				/**
				 * Retrieve orders placed by the subaccount that have been assigned to the Manager after successful order.
				 * Retrieve them by checking _sfwc_order_placed_by_user_id meta value.
				 *
				 * Also retrieve orders placed by subaccount before enabling Multi-User mode.
				 * In this case orders are still tied to the subaccount itself (they were not assigned to the Manager afterwards).
				 */
				$order_ids = get_posts( array(
					'post_type'		=> 'shop_order',
					'fields'		=> 'ids', // Return order IDs.
					'post_status'	=> array_keys( wc_get_order_statuses() ),
					'numberposts'	=> -1,
					'meta_query' 	=> array(
						'relation'	=> 'OR',
						array(
							'key' 		=> '_customer_user',
							'value' 	=> $user_id,
							'compare'	=> 'LIKE',
						),
						array(
							'relation'	=> 'AND',
							array(
								'key'		=> '_customer_user',
								'value'		=> $manager_id,
								'compare'	=> 'LIKE',
							),
							array(
								'key' 		=> '_sfwc_order_placed_by_user_id',
								'value' 	=> $user_id,
								'compare'	=> 'LIKE',
							)
						)
					)
				) );
				
				$args['customer'] = array( $manager_id, $user_id );
				$args['post__in'] = $order_ids;
				
			}
		}
	}
				
	return $args;
}
add_filter('woocommerce_my_account_my_orders_query', 'sfwc_multi_user_my_account_orders_query_subaccounts_orders');




/**
 * Multi-User mode A.K.A. Company Accounts (Pt.8).
 * 
 * Set permissions to view orders on front end when Multi-User mode is enabled.
 *
 * See also function: sfwc_multi_user_allow_subaccount_to_view_manager_orders_supervisor
 * in Supervisor Add-On.
 */
function sfwc_multi_user_allow_subaccount_to_view_manager_orders( $allcaps, $caps, $args, $user ) {
	
	global $wp;

	// 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 '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');
	
	// Get ID of currently logged in user.
	$user_id = get_current_user_id();
	
	// Get Account Level Type of currently logged in user.
	$account_level_type = get_user_meta( $user_id, 'sfwc_account_level_type', true );
	
	
	if ( $sfwc_option_subaccount_mode == 'multi_user' && is_wc_endpoint_url( 'view-order' ) ) {
		
		// Get ID of currently viewed order in: My Account -> Orders -> View Order.
		$order_id = absint( $wp->query_vars['view-order'] );
		
		// Create an order instance.
		$order = new WC_Order( $order_id );
		
		// Get the costumer ID from order object.
		$customer_id = $order->get_user_id();
		
		
		if ( is_user_logged_in() && sfwc_is_current_user_role_valid() && sfwc_is_current_user_role_enabled() ) {
	
			/**
			 * Logged user is a Subaccount.
			 * 
			 * Allow subaccount to view Manager orders in: My Account -> Orders -> View.
			 *
			 * When Multi-User mode is enabled, all orders placed by a subaccount are assigned to its Manager 
			 * and displayed in My Account -> Orders area of the subaccount based on the _sfwc_order_placed_by_user_id order meta value.
			 *
			 * For this reason it is necessary to guarantee the subaccount the appropriate permissions to be able to view the order.
			 */
			if ( $account_level_type !== 'manager' && $account_level_type !== 'supervisor' ) {
				
				// Retrieve the ID of the customer who did actually placed the order.
				$sfwc_order_placed_by_user_id = $order->get_meta('_sfwc_order_placed_by_user_id');
				
				
				/**
				* Check to see if the user currently being edited is a subaccount (by verifying if has a Manager above him),
				* or a simple standalone customer.
				*/

				// Get all users with user meta 'sfwc_account_level_type' == 'manager' and filter only the one which has 'sfwc_children' user_meta containing the child ID corrisponding to the subaccount.
				$args_manager = array(
					//'role'    => 'customer',
					//'role__in' => ['customer', 'subscriber'],
					'role__in' => $sfwc_option_selected_roles,
					'exclude' => $user_id, 
					'orderby' => 'ID',
					'order' => 'ASC',
					'meta_key' => 'sfwc_account_level_type',
					'meta_value' => 'manager',
					'meta_query' => array(
					   array(
						'key' => 'sfwc_children',
						'value' => '"'.$user_id.'"',
						'compare' => 'LIKE',
					   ),
					),
				);


				// The User Query
				$user_query_manager = new WP_User_Query( $args_manager );


				// User Loop
				if ( ! empty( $user_query_manager->get_results() ) ) {	// Logged-in user has a Manager above him,
																		// so we can proceed.
				
				
					foreach ( $user_query_manager->get_results() as $user ) {
											   
						$manager_id = $user->ID;
					}
					
					
					// Some permission checks.
					if ( $manager_id == $customer_id ) {
						
						if ( absint( $sfwc_order_placed_by_user_id ) ===  $user_id ) {
						
							if ( $caps[0] == 'view_order' 
								 #|| $caps[0] == 'order_again'
							) {		
								$allcaps[ $caps[0] ] = true;
							}
						}
					}
				}
			}
			
			/**
			 * Logged user is a Manager.
			 * 
			 * Allow the Manager to view Subaccount orders in: My Account -> Orders -> View, in case those orders were placed before Multi-User mode was enabled.
			 *
			 * Orders placed by a subaccount before Multi-User mode was enabled are still tied to the subaccount (they were not assigned to the Manager afterwards).
			 *
			 * For this reason it is necessary to guarantee the Manager the appropriate permissions to be able to view the order.
			 */
			elseif ( $account_level_type == 'manager' ) {
				
				// Get children (array) of currently logged in user.
				$children_ids = get_user_meta( $user_id, 'sfwc_children', true );
					
				// Check if selected order is tied to a subaccount of currently logged Manager.
				if ( ! empty( $children_ids ) && in_array( strval($customer_id), $children_ids, true ) ) {
					
					if ( $caps[0] == 'view_order' 
						 #|| $caps[0] == 'order_again'
					) {		
						$allcaps[ $caps[0] ] = true;
					}
				}
			}
		}
	}
	
    return $allcaps;
}
add_filter( 'user_has_cap', 'sfwc_multi_user_allow_subaccount_to_view_manager_orders', 10, 4 );




/**
 * WC Email notifications changes when Multi-User mode is enabled (Pt.1).
 * 
 * In email notifications sent to customers, set the subaccount email as the recipient.
 * 
 * 
 * In Multi-User mode, whenever a subaccount places an order, the order is assigned to the Manager afterwards.
 * For this reason the order email notifications sent to the customer are sent to the Manager. However we need to prevent this behavior.
 *
 * What we do with this functions is: whenever a subaccount places an order (with Multi-User mode enabled), send order notifications to the subaccount itself,
 * indipendently from who the order is assigned to afterwards.
 */
function sfwc_multi_user_force_order_notifications_to_be_sent_to_subaccount( $recipient, $order = false ) {
	
    if ( ! $order || ! is_a( $order, 'WC_Order' ) )
        return $recipient;
	
	$order_id = $order->get_id();

	// Get Options settings.
	$sfwc_options = (array) get_option('sfwc_options');
	
	// Get '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 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' );
	
	// Get Account Level Type of currently logged in user (Superviore | Manager | Default).
	$account_level_type = get_user_meta( $order_placed_by_user_id, 'sfwc_account_level_type', true );
	
	
	
	$billing_first_name = $order->get_billing_first_name();
	
	
	// Multi-User mode.
	if ( $sfwc_option_subaccount_mode == 'multi_user' ) {
		
		if ( $order_placed_by_user_id ) { 	// There is no user ID available for guest customers, 
											// so this control ensures that the order confirmation email is sent to the guest customer as normal.
		
			// Make sure the user is not a parent.
			if( $account_level_type !== 'supervisor' && $account_level_type !== 'manager' ) {
				
				$subaccount_object = new WC_Customer( $order_placed_by_user_id );
				
				// If no Billing Email is set, use Email of the user as a fallback.
				$subaccount_email = '' !== $subaccount_object->get_billing_email() ? $subaccount_object->get_billing_email() : $subaccount_object->get_email();
				
				$subaccount_billing_first_name = $subaccount_object->get_billing_first_name();

				// Set subaccount email as recipient.
				$recipient = $subaccount_email;
			}
			
			add_filter( 'wp_mail', function( $args ) use ( $order_id ) {
					return sfwc_swap_manager_first_name_with_subaccount_first_name( $args, $order_id );
				}, 10, 1
			);
		}
	}
	return $recipient;
}
// Composite hook: 'woocommerce_email_recipient_' . $email_id
add_filter( 'woocommerce_email_recipient_customer_on_hold_order', 'sfwc_multi_user_force_order_notifications_to_be_sent_to_subaccount', 10, 2 );
add_filter( 'woocommerce_email_recipient_customer_processing_order', 'sfwc_multi_user_force_order_notifications_to_be_sent_to_subaccount', 10, 2 );
add_filter( 'woocommerce_email_recipient_customer_completed_order', 'sfwc_multi_user_force_order_notifications_to_be_sent_to_subaccount', 10, 2 );
add_filter( 'woocommerce_email_recipient_customer_partially_refunded_order', 'sfwc_multi_user_force_order_notifications_to_be_sent_to_subaccount', 10, 2 );
add_filter( 'woocommerce_email_recipient_customer_invoice', 'sfwc_multi_user_force_order_notifications_to_be_sent_to_subaccount', 10, 2 );
add_filter( 'woocommerce_email_recipient_customer_note', 'sfwc_multi_user_force_order_notifications_to_be_sent_to_subaccount', 10, 2 );




/**
 * WC Email notifications changes when Multi-User mode is enabled (Pt.2).
 *
 * In email notifications sent to customers, replace the Manager name with the subaccount name.
 *
 * In the "Hi Name," part of the email, swap the Manager first name with the subaccount first name.
 */
function sfwc_swap_manager_first_name_with_subaccount_first_name( $args, $order_id ) {
			
	// Get the order object.
	$order = wc_get_order( $order_id );
	
	// Retrieve the Manager's first name from the order object (in Multi-User mode the order is assigned to the Manager afterwards).
	$billing_first_name = $order->get_billing_first_name();
	
	// Retrieve the ID of the customer who did actually place the order (Multi-User mode).
	$order_placed_by_user_id = $order->get_meta( '_sfwc_order_placed_by_user_id' );
	
	// Get the subaccount user object.
	$subaccount_object = new WC_Customer( $order_placed_by_user_id );
	
	// Retrieve the subaccount's first name from the user object.
	$subaccount_billing_first_name = $subaccount_object->get_billing_first_name();
	
	/**
	 * Replace the Manager first name only in the "Hi Name," part of the email.
	 * Better not to just replace the first name:
	 * 
	 *		strpos( $args['message'], $billing_first_name )
	 *
	 * This to prevent replacing wrong strings in the email, e.g. cases where the customer's name is Violet
	 * but that's also the value of a color attribute.
	 */
	if ( strpos( $args['message'], 'Hi '. $billing_first_name . ',' ) !== false ) {
		$args['message'] = str_replace( 'Hi '. $billing_first_name . ',', 'Hi '. $subaccount_billing_first_name . ',', $args['message'] );
	}

	return $args;
}




/**
 * WC Email notifications changes when Multi-User mode is enabled (Pt.3).
 *
 * In email notifications sent to the admin, set the subaccount email address as the "reply-to" included in the email header.
 * This is to prevent the "reply-to" from being set to the Manager's email address.
 */
function sfwc_multi_user_change_reply_to_email_header_for_admin_notifications( $header, $email_id, $order ) {
	
	// Get Options settings.
	$sfwc_options = (array) get_option('sfwc_options');
	
	// Get 'Subaccount Mode' from Options settings.
	$sfwc_option_subaccount_mode = ( isset( $sfwc_options['sfwc_option_subaccount_mode'] ) ) ? $sfwc_options['sfwc_option_subaccount_mode'] : 'sub_user';
	
    // Only target emails sent to admin.
    if ( in_array( $email_id, array( 'new_order', 'cancelled_order', 'failed_order' ) ) ) {
		
		if ( is_a( $order, 'WC_Order' ) ) {
		
			// 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' );
			
			// Get Account Level Type of currently logged in user (Supervior | Manager | Default).
			$account_level_type = get_user_meta( $order_placed_by_user_id, 'sfwc_account_level_type', true );
		

			// Multi-User mode.
			if ( $sfwc_option_subaccount_mode == 'multi_user' ) {
				
				if ( $order_placed_by_user_id ) {
					
					// Make sure the user is not a parent.
					if( $account_level_type !== 'supervisor' && $account_level_type !== 'manager' ) {
						
						$subaccount_object = new WC_Customer( $order_placed_by_user_id );
						
						// If no Billing Email is set, use Email of the user as a fallback.
						$subaccount_email = '' !== $subaccount_object->get_billing_email() ? $subaccount_object->get_billing_email() : $subaccount_object->get_email();
						
						// Get subaccount display name.
						$subaccount_name = $subaccount_object->get_display_name();
						
						$email = new WC_Email($email_id);

						$header = "Content-Type: " . $email->get_content_type() . "\r\n";
						
						if ( '' !== $subaccount_name ) {
							$header .= 'Reply-to: ' . sanitize_text_field( $subaccount_name ) . ' <' . sanitize_email( $subaccount_email ) . ">\r\n";
						} else {
							$header .= 'Reply-to: ' . sanitize_email( $subaccount_email ) . "\r\n";
						}
					}
				}
			}
		}
	}
    return $header;
}
add_filter( 'woocommerce_email_headers', 'sfwc_multi_user_change_reply_to_email_header_for_admin_notifications', 20, 3 );