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




/**
 * After plugin update, store updated plugin information in sfwc_plugin_info option
 * and perform after update required tasks (e.g. set transient for notices to show up).
 *
 * Since 1.1.0
 */
function sfwc_set_plugin_info_option() {
	
	if ( ! wp_doing_ajax() ) {

		$existing_values = get_option('sfwc_plugin_info');

		// Avoid undefined $existing_values_version
		$existing_values_version = ( isset( $existing_values['version'] ) ) ? $existing_values['version'] : '0.0.0'; // On clean installs $existing_values_version is not set,
																													 // so providing '0.0.0' as value will allow below code
																													 // within version_compare conditional to run.

		
		// Check current version of the plugin against version which was stored in database from previously installed release.
		if ( version_compare( SFWC_CURRENT_VERSION, $existing_values_version, '>' ) ) {
		
			/**
			 * If curently installed version of the plugin is greater than previous one, perform following tasks.
			 *
			 */

			
			// Current Release Values.
			// Pay attention: in case a key-value pair is removed from below array,
			// it will be removed from database as well after option is updated.
			$current_values = array(
				'version' => SFWC_CURRENT_VERSION,
				// Maybe add more.
			);
			
			
			/**
			 * Insert data in database.
			 */
			
			// If option doesn't exist yet (introduced since 1.1.0).
			if ( empty( $existing_values ) ){
				add_option( 'sfwc_plugin_info', $current_values );
			}
			// If option already exists.
			else {
				// Add to current values.
				$new_values = array_merge( $existing_values, $current_values );

				// Update Option.
				update_option( 'sfwc_plugin_info', $new_values );
			}
			
			// Flush permalinks to avoid possible 'Error 404' on front-end 'subaccounts' endpoint.
			// Especially useful for first time installs.
			flush_rewrite_rules();
		}

		/***
		// For debug
		if ( ! empty( $existing_values ) ) {
			echo '<div style="margin-left:200px;"><pre>';
			print_r( $existing_values );
			echo '</pre></div>';
		}
		***/
	}
}
add_action('admin_init', 'sfwc_set_plugin_info_option', 20); // Priority must be lower than before sfwc_ignore_permalink_update_required_notice() 
															 // otherwise changes visible after page refresh.



/**
 * Set WooCommerce screen IDs.
 *
 * This will enqueue WooCommerce CSS/JS and allow to show tooltips text on hover on:
 *
 *	- Plugin settings page
 *	- Admin users list
 */
function sfwc_set_wc_screen_ids( $screen ){
      $screen[] = 'woocommerce_page_subaccounts';
	  $screen[] = 'users';
      return $screen;
}
add_filter('woocommerce_screen_ids', 'sfwc_set_wc_screen_ids' );

/**
 * For debug. Keep commented.
 * For each admin page show current screen ID.
 */
/*
function sfwc_dump_screen_ids() {
	var_dump( get_current_screen()->id );
}
add_action('admin_notices', 'sfwc_dump_screen_ids');
*/




/**
 * Add Custom Links.
 *
 * Add following links next to 'Deactivate Plugin' option on plugins list page:
 *
 *	- Settings
 *	- Premium version of Subaccounts
 */
function sfwc_settings_plugin_link( $links, $file ) {

	if ( $file == 'subaccounts-for-woocommerce/subaccounts-for-woocommerce.php' ) {
		
        // Insert "Settings" link at the beginning.
        $sfwc_settings_link = '<a href="admin.php?page=subaccounts">' . esc_html__( 'Settings', 'subaccounts-for-woocommerce' ) . '</a>';
        array_unshift( $links, $sfwc_settings_link );

		$links['get_subaccounts_pro'] = '<nobr style="padding-top:2px; display:block;">
											<a href="' . admin_url( '/admin.php?checkout=true&page=subaccounts-pricing&plugin_id=10457&plan_id=17669&pricing_id=19941&billing_cycle=annual' ) . '" style="font-weight:bold;">'
												. esc_html__( 'Get Subaccounts Pro', 'subaccounts-for-woocommerce' ) . ' ★
											</a>
										</nobr>';
    }
    return $links;
}
add_filter('plugin_action_links', 'sfwc_settings_plugin_link', 10, 2);




/**
 * Backend style
 */
function sfwc_enqueue_backend_js_css() {
	
	global $pagenow;
	
	$plugin_settings_page = isset( $_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : '';
	
	$active_settings_tab = isset( $_GET['tab'] ) ? sanitize_text_field( $_GET['tab'] ) : '';

	/**
	 * Enqueue main backend style.
	 */	
	wp_enqueue_style( 'sfwc_backend_style', WP_PLUGIN_URL . '/subaccounts-for-woocommerce/assets/css/admin.css' );

	
	/**
	 * Enqueue Selectize JS and CSS on plugin Options page.
	 */
	if ( ! wp_doing_ajax() && current_user_can( 'administrator' ) && $pagenow == 'admin.php' && $plugin_settings_page == 'subaccounts' ) {

		// Load Selectize JS and CSS, necessary in: Dashboard -> Users -> Edit.
		wp_enqueue_style( 'sfwc_selectize_style', WP_PLUGIN_URL . '/subaccounts-for-woocommerce/assets/lib/selectize/selectize.css' );
		wp_enqueue_script( 'sfwc_selectize_js', WP_PLUGIN_URL . '/subaccounts-for-woocommerce/assets/lib/selectize/selectize.min.js', array( 'jquery' ), '0.13.6', false );
		
		// Load admin.js. Last parameter TRUE (print in footer) otherwise not working.
		wp_enqueue_script( 'sfwc_admin_js', esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/js/admin.js', array( 'jquery', 'sfwc_selectize_js', 'wp-color-picker' ), false, true );
	}

}
add_action('admin_enqueue_scripts', 'sfwc_enqueue_backend_js_css');




/**
 * Display Subaccounts information on Order page.
 *
 * Add a meta box showing information about 'Manager' (and 'Supervisor' if 'Supervisor Add-on' installed) for the customer who made the order.
 */
// Required for the add_meta_box to show the meta box in case HPOS is enabled.
use Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController;
// Adding Meta container admin shop_order pages
function sfwc_add_meta_box() {
	
	if ( ! wp_doing_ajax() ) {
		
		// Detect if HPOS is enabled or not and assign value to the $screen variable accordingly.
		$screen = wc_get_container()->get( CustomOrdersTableController::class )->custom_orders_table_usage_is_enabled()
				? wc_get_page_screen_id( 'shop-order' )
				: 'shop_order';

		$sfwc_options = (array) get_option('sfwc_options');
		
		// Avoid undefined $sfwc_options_show_order_meta_box in case related setting has not been saved yet.
		$sfwc_options_show_order_meta_box = ( isset( $sfwc_options['sfwc_options_show_order_meta_box'] ) ) ? $sfwc_options['sfwc_options_show_order_meta_box'] : '0';

		// Check if option enabled in Subaccounts > Settings > Options
		if ( $sfwc_options_show_order_meta_box == '1' ) {
			add_meta_box('woocommerce-order-subaccounts', esc_html__( 'Subaccounts Info', 'subaccounts-for-woocommerce' ), 'sfwc_add_meta_box_content', $screen, 'side', 'core');
		}
	}
}
add_action('add_meta_boxes', 'sfwc_add_meta_box'); // sfwc_add_meta_box_content in: includes > functions.php




/**
 * Save Manager info in Order's post meta when order is created from backend.
 * 
 * In case of order created from backend by admin, save Manager information in Order's post meta.
 *
 * See also: sfwc_order_placed_by_update_order_meta_after_payment function from my-account.php,
 * for updating Order's post meta with "order placed by" information (after the customer completes the order).
 */
function sfwc_store_subaccounts_meta_data_on_order_creation_admin_side( $order_id ) {
	
	// Get Options settings.
	$sfwc_options = (array) get_option('sfwc_options');

	// Get 'Select the buyer role(s) to enable the subaccount system for' option value.
	$sfwc_option_selected_roles = ( isset( $sfwc_options['sfwc_option_selected_roles'] ) ) ? $sfwc_options['sfwc_option_selected_roles'] : array('customer', 'subscriber');
	
	// 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';
	
	if ( ! wp_doing_ajax() ) {
	
		// Get an instance of the WC_Order Object from the Order ID
		$order = wc_get_order( $order_id );

		// Get the Customer ID (User ID)
		$customer_id = $order->get_user_id();
		
		// Get Account Level Type
		$customer_account_level_type = get_user_meta( $customer_id, 'sfwc_account_level_type', true );
		
		
		$user_query_manager = []; // Prevent undefined variable when doing action below.
		
		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__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';
			}
				
		}


		do_action('sfwc_store_additional_subaccounts_meta_on_order_creation_admin_side', $order_id, $customer_account_level_type, $customer_id, $user_query_manager, $manager_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 );
		}
		
		
		
		
		/**
		 * Validate the value of 'account level type' for 'manager' and 'default' account types. 
		 *
		 * For the validation of 'supervisor' see function: sfwc_store_subaccounts_meta_data_on_order_creation_admin_side_supervisor in Supervisor add-on
		 */	
		$valid_customer_account_level_type = array( '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 );
		}
		
		
		/**
		 * 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_new_order', 'sfwc_store_subaccounts_meta_data_on_order_creation_admin_side', 10, 1);	// woocommerce_new_order triggered both for frontend
																												// and backend order creation; for backend only check with is_admin.
																												
																												// Also, woocommerce_new_order triggered only on order creation,
																												// but not on order update.

/**
 * woocommerce_process_shop_order_meta
 *
 * Triggered only for backend order creation.
 * Triggered for both order creation and order update; to trigger it only in one of the two cases,
 * check if order already exists.
 */

/*
function save_order_custom_field_meta( $order_id ) {

	// Do something...
}
add_action( 'woocommerce_process_shop_order_meta', 'save_order_custom_field_meta' );
*/




/**
 * Create admin plugin pages/subpages:
 *
 *	- Subaccounts
 * 		-- Settings
 */
function sfwc_admin_menu() {

	// Add WooCommerce menu sub-page.
	add_submenu_page(
		'woocommerce',															// $parent_slug
		esc_html__( 'Subaccounts Options Page', 'subaccounts-for-woocommerce' ),// $page_title
		esc_html__( 'Subaccounts', 'subaccounts-for-woocommerce' ),				// $menu_title
		'manage_woocommerce',													// $capability
		'subaccounts',															// $menu_slug
		'sfwc_admin_page_contents',												// $function
		//9999																	// $position
	);

}
add_action('admin_menu', 'sfwc_admin_menu', 50);





/**
 * Create plugin's settings.
 *
 * 
 */
function sfwc_settings_init() {
	
	// Create Appearance Settings

	$args_sfwc_switcher_appearance = array(
		'type' => 'array',
		'sanitize_callback' => 'sfwc_switcher_appearance_validate' // validation callback
	);


	register_setting(
			'sfwc_switcher_appearance_group',	// group, used for settings_fields()
			'sfwc_switcher_appearance',			// option name, used as key in database
			$args_sfwc_switcher_appearance		// $args
	);



	add_settings_section(
			'sfwc_switcher_appearance_section',														// HTML ID tag for the section
			esc_html__( 'Frontend User Switcher Pane Appearance', 'subaccounts-for-woocommerce' ),	// Title for the section
			'', 																					//'sfwc_setting_section_callback_function'
			'subaccounts'                    														// Menu slug, same as 4th parameter of add_menu_page or 5th parameter of add_submenu_page
	);


	add_settings_field(
			'sfwc_switcher_pane_bg_color',										// HTML ID of the input element
			esc_html__( 'Background Color:', 'subaccounts-for-woocommerce' ),	// Title displayed at the left of input element
			'sfwc_switcher_pane_bg_color_html',									// Callback function for HTML input markup
			'subaccounts',
			'sfwc_switcher_appearance_section'
	);

	add_settings_field(
			'sfwc_switcher_pane_headline_color',
			esc_html__( 'Headline Color:', 'subaccounts-for-woocommerce' ),
			'sfwc_switcher_pane_headline_color_html',
			'subaccounts',
			'sfwc_switcher_appearance_section'
	);

	add_settings_field(
			'sfwc_switcher_pane_text_color',
			esc_html__( 'Text Color:', 'subaccounts-for-woocommerce' ),
			'sfwc_switcher_pane_text_color_html',
			'subaccounts',
			'sfwc_switcher_appearance_section'
	);

	add_settings_field(
			'sfwc_switcher_pane_select_bg_color',
			esc_html__( 'Button Background Color:', 'subaccounts-for-woocommerce' ),
			'sfwc_switcher_pane_select_bg_color_html',
			'subaccounts',
			'sfwc_switcher_appearance_section'
	);

	add_settings_field(
			'sfwc_switcher_pane_select_text_color',
			esc_html__( 'Button Text Color:', 'subaccounts-for-woocommerce' ),
			'sfwc_switcher_pane_select_text_color_html',
			'subaccounts',
			'sfwc_switcher_appearance_section'
	);




	// Create Options Settings

	$args_sfwc_options = array(
		'type' => 'array',
		'sanitize_callback' => 'sfwc_options_validate' // validation callback
	);

	register_setting(
			'sfwc_options_group',	// group, used for settings_fields()
			'sfwc_options',			// option name, used as key in database
			$args_sfwc_options		// $args
	);


	add_settings_section(
			'sfwc_options_section',								// HTML ID tag for the section
			'',													// Title for the section
			'',													//'sfwc_setting_section_callback_function' Callback for section description
			'subaccounts&tab=options'							// Menu slug, same as 4th parameter of add_menu_page or 5th parameter of add_submenu_page
	);

    // Check if function exists from PRO plugin
    if ( ! function_exists( 'sfwc_pro_settings_init' ) ) {
		
		add_settings_field(
				'sfwc_option_subaccount_mode',
				esc_html__('Subaccount Mode', 'subaccounts-for-woocommerce')
				. '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'The way the whole subaccount system should work.', 'subaccounts-for-woocommerce' ) . '"></span>',
				'sfwc_option_subaccount_mode_html',
				'subaccounts&tab=options',
				'sfwc_options_section'
		);
		
		// Dummy: only available in Pro.
		add_settings_field(
				'sfwc_option_subaccount_creation_dummy',
				esc_html__('Choose who can create and add new subaccounts', 'subaccounts-for-woocommerce') 
					. '<br><a style="color:#148ff3;" href="' 
					. admin_url( '/admin.php?checkout=true&page=subaccounts-pricing&plugin_id=10457&plan_id=17669&pricing_id=19941&billing_cycle=annual' ) . '">' 
					. esc_html__( 'Get Subaccounts Pro', 'subaccounts-for-woocommerce' ) . '</a> <span style="font-weight:400;">' 
					. esc_html__( 'and unlock this feature!', 'subaccounts-for-woocommerce' ) . '</span>',
				'sfwc_option_subaccount_creation_html_dummy',
				'subaccounts&tab=options',
				'sfwc_options_section'
		);
		
		// Dummy: only available in Pro.
		add_settings_field(
				'sfwc_option_allow_subaccount_deactivation_dummy',
				esc_html__('Allow parent accounts to deactivate subaccounts', 'subaccounts-for-woocommerce')
				. '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'Disabled subaccounts cannot access the customer area. They can be reactivated at any time by the parent account or an administrator. The parent account can still switch to the subaccount if the User Switcher is enabled.', 'subaccounts-for-woocommerce' ) . '"></span>' 
					. '<br><a style="color:#148ff3;" href="' 
					. admin_url( '/admin.php?checkout=true&page=subaccounts-pricing&plugin_id=10457&plan_id=17669&pricing_id=19941&billing_cycle=annual' ) . '">' 
					. esc_html__( 'Get Subaccounts Pro', 'subaccounts-for-woocommerce' ) . '</a> <span style="font-weight:400;">' 
					. esc_html__( 'and unlock this feature!', 'subaccounts-for-woocommerce' ) . '</span>',
				'sfwc_option_allow_subaccount_deactivation_html_dummy',
				'subaccounts&tab=options',
				'sfwc_options_section'
		);
	

		add_settings_field(
				'sfwc_option_selected_roles',
				esc_html__('Select the user role(s) for which to enable the subaccount system', 'subaccounts-for-woocommerce')
				. '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'If the parent account has a different role than the subaccount, select both the parent account and subaccount roles.', 'subaccounts-for-woocommerce' ) . '"></span>',
				'sfwc_option_selected_roles_html',
				'subaccounts&tab=options',
				'sfwc_options_section'
		);
		
		add_settings_field(
				'sfwc_option_subaccount_default_role',
				esc_html__('New Subaccount Default Role', 'subaccounts-for-woocommerce')
				. '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'Select the role(s) that should be assigned to subaccounts.', 'subaccounts-for-woocommerce' ) . '"></span>',
				'sfwc_option_subaccount_default_role_html',
				'subaccounts&tab=options',
				'sfwc_options_section'
		);
		
		add_settings_field(
				'sfwc_option_subaccount_default_role_select_role',
				'',
				'sfwc_option_subaccount_default_role_select_role_html',
				'subaccounts&tab=options',
				'sfwc_options_section',
				array( 'class' => 'hidden' )
		);
		
		add_settings_field(
				'sfwc_option_subaccount_default_role_inherit_role',
				'',
				'sfwc_option_subaccount_default_role_inherit_role_html',
				'subaccounts&tab=options',
				'sfwc_options_section',
				array( 'class' => 'hidden' )
		);
		
		add_settings_field(
				'sfwc_option_subaccounts_number_limit',
				esc_html__('Maximum number of subaccounts allowed', 'subaccounts-for-woocommerce')
				. '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'Limit the number of subaccounts that a parent account can create/add.', 'subaccounts-for-woocommerce' ) . '"></span>',
				'sfwc_option_subaccounts_number_limit_html',
				'subaccounts&tab=options',
				'sfwc_options_section'
		);

		add_settings_field(
				'sfwc_option_display_name',
				esc_html__('Customer Display Name', 'subaccounts-for-woocommerce')
				. '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'Set Customer\'s Display Name across the Subaccounts Plugin.', 'subaccounts-for-woocommerce' ) . '"></span>',
				'sfwc_option_display_name_html',
				'subaccounts&tab=options',
				'sfwc_options_section'
		);
		
		add_settings_field(
				'sfwc_options_enable_user_switcher',
				esc_html__('Enable User Switcher', 'subaccounts-for-woocommerce')
				. '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'Allow a parent account to log-in as a subaccount.', 'subaccounts-for-woocommerce' ) . '"></span>',
				'sfwc_options_enable_user_switcher_html',
				'subaccounts&tab=options',
				'sfwc_options_section'
		);
	
		add_settings_field(
				'sfwc_options_show_order_meta_box',
				esc_html__('Show subaccounts information on WooCommerce order page', 'subaccounts-for-woocommerce')
				. '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'Add the \'Subaccount Info\' box on WooCommerce Order pages in WordPress admin area.', 'subaccounts-for-woocommerce' ) . '"></span>',
				'sfwc_options_show_order_meta_box_html',
				'subaccounts&tab=options',
				'sfwc_options_section'
		);
	}
}
add_action('admin_init', 'sfwc_settings_init');




/*
function sfwc_setting_section_callback_function() {
echo '<p>Intro text for our settings section</p>';
}
*/




/**
 * Appearance Tab markup
 */
function sfwc_switcher_pane_bg_color_html() {
	
	// 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';
	?>
	
	<!-- <label for="my-input"><?php esc_html_e( 'My Input', 'subaccounts-for-woocommerce' ); ?></label> -->
	<input type="text" id="sfwc_switcher_pane_bg_color" name="sfwc_switcher_appearance[sfwc_switcher_pane_bg_color]" value="<?php echo esc_attr( $sfwc_switcher_pane_bg_color ); ?>" class="sfwc-color-field" data-default-color="#def6ff" />
	
	<?php
}

function sfwc_switcher_pane_headline_color_html() {
	
	// Get 'Appearance' settings
	$sfwc_switcher_appearance = (array) get_option('sfwc_switcher_appearance');

	// 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';
	?>

	<input type="text" id="sfwc_switcher_pane_headline_color" name="sfwc_switcher_appearance[sfwc_switcher_pane_headline_color]" value="<?php echo esc_attr( $sfwc_switcher_pane_headline_color ); ?>" class="sfwc-color-field" data-default-color="#3577c9" />

	<?php
}

function sfwc_switcher_pane_text_color_html() {
	
	// Get 'Appearance' settings
	$sfwc_switcher_appearance = (array) get_option('sfwc_switcher_appearance');

	// 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';
	?>

	<input type="text" id="sfwc_switcher_pane_text_color" name="sfwc_switcher_appearance[sfwc_switcher_pane_text_color]" value="<?php echo esc_attr( $sfwc_switcher_pane_text_color ); ?>" class="sfwc-color-field" data-default-color="#3b3b3b" />

	<?php
}

function sfwc_switcher_pane_select_bg_color_html() {

	// 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';
	?>

	<input type="text" id="sfwc_switcher_pane_select_bg_color" name="sfwc_switcher_appearance[sfwc_switcher_pane_select_bg_color]" value="<?php echo esc_attr( $sfwc_switcher_pane_select_bg_color ); ?>" class="sfwc-color-field" data-default-color="#3577c9" />

	<?php
}

function sfwc_switcher_pane_select_text_color_html() {

	// Get 'Appearance' settings.
	$sfwc_switcher_appearance = (array) get_option('sfwc_switcher_appearance');

	// 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';
	?>

	<input type="text" id="sfwc_switcher_pane_select_text_color" name="sfwc_switcher_appearance[sfwc_switcher_pane_select_text_color]" value="<?php echo esc_attr( $sfwc_switcher_pane_select_text_color ); ?>" class="sfwc-color-field" data-default-color="#ffffff" />

	<?php
}

/**
 * Options Tab markup
 */
function sfwc_option_subaccount_mode_html() {

	// Get 'Options' settings.
    $sfwc_options = (array) get_option( 'sfwc_options' );
	
	// Get Subaccount mode.
	$sfwc_option_subaccount_mode = ( isset( $sfwc_options['sfwc_option_subaccount_mode'] ) ) ? $sfwc_options['sfwc_option_subaccount_mode'] : 'sub_user';
    ?>

    <input style="float:left;clear:left;position:relative;top:5px;" type="radio" name="sfwc_options[sfwc_option_subaccount_mode]" value="sub_user" id="sub_user" <?php checked('sub_user', $sfwc_option_subaccount_mode, true); ?> >
    <label style="float:left;clear:right;margin-bottom:15px;" for="sub_user"><?php esc_html_e( 'Sub-User', 'subaccounts-for-woocommerce' ); ?>
		<br>
		<span style="color:#74808c;"><?php echo esc_html__( "Multiple separate accounts grouped together under one parent account (e.g. Holding Company).", 'subaccounts-for-woocommerce' ); ?></span><br>
	</label>

	
    <input style="float:left;clear:left;position:relative;top:5px;" type="radio" name="sfwc_options[sfwc_option_subaccount_mode]" value="multi_user" id="multi_user" <?php checked('multi_user', $sfwc_option_subaccount_mode, true); ?> >
    <label style="float:left;clear:right;margin-bottom:15px;" for="multi_user"><?php esc_html_e( 'Multi-User', 'subaccounts-for-woocommerce' ); ?>
		<br>
		<span style="color:#74808c;"><?php echo esc_html__( "Multiple users have access to a same master account (useful in case of Corporate Accounts).", 'subaccounts-for-woocommerce' ); ?></span><br>
	</label>

    <?php
}




function sfwc_option_subaccount_creation_html_dummy() {	// Dummy: only available in Pro. 
	?>
	<input title="<?php esc_attr_e( 'This feature is only available on Subaccounts Pro', 'subaccounts-for-woocommerce'); ?>" type="radio" name="sfwc_set_subaccounts_option" value="" disabled>
	<label for=""><?php esc_html_e('Admin Only', 'subaccounts-for-woocommerce'); ?></label><br>

	<input title="<?php esc_attr_e( 'This feature is only available on Subaccounts Pro', 'subaccounts-for-woocommerce'); ?>" type="radio" name="sfwc_set_subaccounts_option" value="" disabled checked>
	<label for=""><?php esc_html_e('Customers Only', 'subaccounts-for-woocommerce'); ?></label><br>

	<input title="<?php esc_attr_e( 'This feature is only available on Subaccounts Pro', 'subaccounts-for-woocommerce'); ?>" type="radio" name="sfwc_set_subaccounts_option" value="" disabled>
	<label for=""><?php esc_html_e('Both Admin and Customers', 'subaccounts-for-woocommerce'); ?></label>
	
	<p style="margin-top:8px;">
	
	<?php
		$important_strong = '<strong>' . esc_html__( 'Important:', 'subaccounts-for-woocommerce' ) . '</strong>';
		$subaccounts_menu_item = '<em>' . esc_html__( 'Subaccounts', 'subaccounts-for-woocommerce' ) . '</em>';
		$my_account_translation = '<em>' . esc_html__( 'My Account', 'subaccounts-for-woocommerce' ) . '</em>';
		$permalink_path = '<em>' . esc_html__( 'Settings', 'subaccounts-for-woocommerce' ) . '</em> ➝ <em>' . esc_html__( 'Permalinks', 'subaccounts-for-woocommerce' ) . '</em>';
		$save_changes = '<em>' . esc_html__( 'Save Changes', 'subaccounts-for-woocommerce' ) . '</em>';
		
		
		printf(
			esc_html__( '%1$s in case the %2$s menu item is not shown on the %3$s page, please update the WordPress permalinks structure by going to: %4$s and clicking %5$s.', 'subaccounts-for-woocommerce' ), 
			$important_strong,
			$subaccounts_menu_item,
			$my_account_translation,
			$permalink_path,
			$save_changes
		);
	?>

	</p>
	<?php
}

function sfwc_option_selected_roles_html() {

	global $wp_roles;

	if ( ! isset( $wp_roles ) ) {
		$wp_roles = new WP_Roles();
	}
	
	$roles = $wp_roles->get_names();

	// 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');

	echo '<div style="max-width:28rem;">';
	echo '<select id="sfwc_option_selected_roles" name="sfwc_options[sfwc_option_selected_roles][]" multiple>';

	if ( ! empty( $roles ) ) {

		foreach ( $roles as $role => $value ) {

			$selected = in_array( $role, $sfwc_option_selected_roles ) ? ' selected="selected" ' : '';			
			
			if ( in_array( $role, sfwc_get_valid_roles() ) ) {
				
				printf(
					'<option value="%1$s"' . $selected . '>%2$s</option>', 
					esc_attr( $role ), 
					esc_html( translate_user_role( $value ) )
				);						
			}
		}	
	}	

	echo '</select>';
	echo '<p>' . esc_html__( "Only roles eligible for the subaccount system are available for selection.", 'subaccounts-for-woocommerce' ) .'<p>';
	echo '</div>';
}

function sfwc_option_subaccount_default_role_html() {
	
	global $wp_roles;

	// 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' );
	
	// Get 'Keep user roles in sync' value
	$sfwc_options_keep_roles_synced = ( isset( $sfwc_options['sfwc_options_keep_roles_synced'] ) ) ? $sfwc_options['sfwc_options_keep_roles_synced'] : 0;
	
	// Toggle new subaccount default role sub-options.
	$display_keep_roles_synced_option = $sfwc_option_subaccount_default_role === 'select_role' ? 'display:none;' : '';
	$display_new_subacount_role_option = $sfwc_option_subaccount_default_role === 'inherit_role' ? 'display:none;' : '';
    ?>


    <input style="float:left;clear:left;position:relative;top:5px;" type="radio" name="sfwc_options[sfwc_option_subaccount_default_role]" value="select_role" id="select_role" <?php checked('select_role', $sfwc_option_subaccount_default_role, true); ?> >
    <label style="float:left;clear:right;margin-bottom:15px;" for="select_role"><?php esc_html_e( 'Select role(s)', 'subaccounts-for-woocommerce' ); ?><br>
        <span style="color:#74808c;"><?php esc_html_e( 'Each subaccount can be assigned multiple roles.', 'subaccounts-for-woocommerce' ); ?></span>
	</label><br><br>
	
	<?php
	echo '<div style="max-width:28rem; margin:0 0 15px 20px; float:left; clear:both;' .  $display_new_subacount_role_option . '" id="sfwc_option_subaccount_default_role_select_role_wrap">';
	echo '<select id="sfwc_option_subaccount_default_role_select_role" name="sfwc_options[sfwc_option_subaccount_default_role_select_role][]" multiple>';

	if ( ! empty( $sfwc_option_selected_roles ) ) {

		foreach ( $sfwc_option_selected_roles as $role ) {
			
			$role_object = get_role( $role );

			$selected = in_array( $role, $sfwc_option_subaccount_default_role_select_role ) ? ' selected="selected" ' : '';
			
			if ( in_array( $role, sfwc_get_valid_roles() ) ) {
				
				printf(
					'<option value="%1$s"' . $selected . '>%2$s</option>', 
					esc_attr( $role ), 
					esc_html( translate_user_role( $wp_roles->roles[ $role ]['name'] ) )
				);						
			}
		}	
	}	

	echo '</select>';
	echo '<p>' . esc_html__( "Only enabled roles are available for selection.", 'subaccounts-for-woocommerce' ) .'<p>';
	echo '</div>';
	?>

    <input style="float:left;clear:left;position:relative;top:5px;" type="radio" name="sfwc_options[sfwc_option_subaccount_default_role]" value="inherit_role" id="inherit_role" <?php checked('inherit_role', $sfwc_option_subaccount_default_role, true); ?> >
    <label style="float:left;clear:right;margin-bottom:15px;" for="inherit_role"><?php esc_html_e( 'Subaccounts inherit the same role(s) as the parent account', 'subaccounts-for-woocommerce' ); ?><br>
        <span style="color:#74808c;"><?php esc_html_e( 'When a parent account adds new subaccounts, assign the subaccounts the same roles as the parent account.', 'subaccounts-for-woocommerce' ); ?></span><br>
    </label><br><br>
	
	
	<label style="float:left;clear:right;margin:0 0 15px 20px; <?php echo $display_keep_roles_synced_option;?>" id="keep_roles_synced_label" for="sfwc_options_keep_roles_synced"><span style="display:block;margin-bottom:5px;font-weight:600;"><?php esc_html_e( 'Keep user roles in sync', 'subaccounts-for-woocommerce' ); ?></span>
		<input type="checkbox" id="sfwc_options_keep_roles_synced" name="sfwc_options[sfwc_options_keep_roles_synced]" value="1" <?php checked(1, $sfwc_options_keep_roles_synced, true) ?> />
        <span style="color:#74808c;"><?php esc_html_e( 'Whenever parent account roles are changed in the user profile edit screen, also change the subaccount roles accordingly.', 'subaccounts-for-woocommerce' ); ?></span><br>
    </label>
    <?php
}

function sfwc_option_subaccount_default_role_select_role_html()  {/* See sfwc_option_subaccount_default_role_html */}
function sfwc_option_subaccount_default_role_inherit_role_html() {/* See sfwc_option_subaccount_default_role_html */}

function sfwc_option_subaccounts_number_limit_html() {

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

	// Get Subaccounts Number Limit option value.
	$sfwc_option_subaccounts_number_limit = ( isset( $sfwc_options['sfwc_option_subaccounts_number_limit'] ) ) ? $sfwc_options['sfwc_option_subaccounts_number_limit'] : 10;
	?>

	<input type="number" id="sfwc_option_subaccounts_number_limit" name="sfwc_options[sfwc_option_subaccounts_number_limit]" value="<?php echo esc_attr( $sfwc_option_subaccounts_number_limit ); ?>" style="max-width:65px;" <?php echo ( ! is_plugin_active( 'subaccounts-for-woocommerce-pro/subaccounts-for-woocommerce-pro.php' ) ? 'min="1" max="10"' : 'min="0"' ); ?> />
	<?php
	esc_html_e( "Set 0 for unlimited", 'subaccounts-for-woocommerce' );
	
	if ( ! is_plugin_active( 'subaccounts-for-woocommerce-pro/subaccounts-for-woocommerce-pro.php' ) ) {

		/*
		$subaccounts_pro = '<a style="color: #148ff3; font-weight: 600;" href="' . 
							esc_url( admin_url( '/admin.php?checkout=true&page=subaccounts-pricing&plugin_id=10457&plan_id=17669&pricing_id=19941&billing_cycle=annual' ) ) . 
							'">Subaccounts Pro</a>';
		*/
		
		$subaccounts_pro = 'Subaccounts Pro';
		
		printf(
			' (' . esc_html__( '%1$s required', 'subaccounts-for-woocommerce' ) . ')',
			$subaccounts_pro
		);
	}
	echo '.';
}

function sfwc_option_display_name_html() {

	// Get 'Options' settings.
    $sfwc_options = (array) get_option( 'sfwc_options' );
	
	// Get Display Name mode.
	$sfwc_option_display_name = ( isset( $sfwc_options['sfwc_option_display_name'] ) ) ? $sfwc_options['sfwc_option_display_name'] : 'username';
    ?>


    <input style="float:left;clear:left;position:relative;top:5px;" type="radio" name="sfwc_options[sfwc_option_display_name]" value="username" id="username" <?php checked('username', $sfwc_option_display_name, true); ?> >
    <label style="float:left;clear:right;margin-bottom:15px;" for="username"><?php esc_html_e( 'Username + Email', 'subaccounts-for-woocommerce' ); ?><br>
        <span style="color:#74808c;"><strong><?php esc_html_e( 'Example:', 'subaccounts-for-woocommerce' ); ?></strong> John.doe - [ johndoe@email.com ]</span>
	</label><br><br>


    <input style="float:left;clear:left;position:relative;top:5px;" type="radio" name="sfwc_options[sfwc_option_display_name]" value="full_name" id="full_name" <?php checked('full_name', $sfwc_option_display_name, true); ?> >
    <label style="float:left;clear:right;margin-bottom:15px;" for="full_name"><?php esc_html_e( 'Full Name + Email', 'subaccounts-for-woocommerce' ); ?><br>
        <span style="color:#74808c;"><strong><?php esc_html_e( 'Example:', 'subaccounts-for-woocommerce' ); ?></strong> John Doe - [ johndoe@email.com ]</span><br>
        <em><?php esc_html_e( "If neither the First Name nor Last Name have been set, the customer's Username will be shown as a fallback.", "subaccounts-for-woocommerce" ); ?></em>
    </label><br><br>


    <input style="float:left;clear:left;position:relative;top:5px;" type="radio" name="sfwc_options[sfwc_option_display_name]" value="company_name" id="company_name" <?php checked('company_name', $sfwc_option_display_name, true); ?> >
    <label style="float:left;clear:right;margin-bottom:15px;" for="company_name"><?php esc_html_e( 'Company + Email', 'subaccounts-for-woocommerce' ); ?><br>
        <span style="color:#74808c;"><strong><?php esc_html_e( 'Example:', 'subaccounts-for-woocommerce' ); ?></strong> Enterprise Inc - [ johndoe@email.com ]</span><br>
        <em><?php esc_html_e( "If no Company Name has been set, the customer's Username will be shown as a fallback.", "subaccounts-for-woocommerce" ); ?></em>
    </label>

    <?php
}

function sfwc_option_allow_subaccount_deactivation_html_dummy() {
	?>
	<input title="<?php esc_attr_e( 'This feature is only available on Subaccounts Pro', 'subaccounts-for-woocommerce'); ?>" type="checkbox" id="sfwc_options_enable_subaccount_deactivation" name=""  value="" disabled />
	<?php
}

function sfwc_options_enable_user_switcher_html() {

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

	// Get Show Meta Box value
	$sfwc_options_enable_user_switcher = ( isset( $sfwc_options['sfwc_options_enable_user_switcher'] ) ) ? $sfwc_options['sfwc_options_enable_user_switcher'] : 1;
	?>

	<input type="checkbox" id="sfwc_options_enable_user_switcher" name="sfwc_options[sfwc_options_enable_user_switcher]" value="1" <?php checked(1, $sfwc_options_enable_user_switcher, true) ?> />
	<?php
	esc_html_e( "Useful in case you want to allow a parent account to place orders on behalf of subaccounts", 'subaccounts-for-woocommerce' );
}




function sfwc_options_show_order_meta_box_html() {

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

	// Get Show Meta Box value
	$sfwc_options_show_order_meta_box = ( isset( $sfwc_options['sfwc_options_show_order_meta_box'] ) ) ? $sfwc_options['sfwc_options_show_order_meta_box'] : 0;
	?>

	<input type="checkbox" id="sfwc_options_show_order_meta_box" name="sfwc_options[sfwc_options_show_order_meta_box]" value="1" <?php checked(1, $sfwc_options_show_order_meta_box, true) ?> />
	<?php
	esc_html_e( "You may need to enable this under 'Screen Options' too", 'subaccounts-for-woocommerce' );
}




/**
 * Appearance Options Validation.
 */
function sfwc_switcher_appearance_validate( $input ) {

	// Create our array for storing the validated options.
	$output = array();

	// Loop through each of the incoming options.
	foreach ( $input as $key => $value ) {

		// Check if the current option has a value.
		if ( isset( $input[$key] ) ) {

			// if user insert a HEX color with #.
			if ( preg_match( '/^#[0-9a-fA-F]{6}$/i', $input[$key] ) ) {

				// Sanitization should not be required here due to strict preg_match comparison, anyway...
				$output[$key] = sanitize_text_field( $input[$key] );
			} else {

				if ( $input[$key] == $input['sfwc_switcher_pane_bg_color'] ) {

					add_settings_error( 'sfwc_settings_messages', 'sfwc_wrong_hex_color', esc_html__( 'Incorrect value entered for: Background Color.', 'subaccounts-for-woocommerce' ), 'warning' );
				}
				if ( $input[$key] == $input['sfwc_switcher_pane_headline_color'] ) {

					add_settings_error( 'sfwc_settings_messages', 'sfwc_wrong_hex_color', esc_html__( 'Incorrect value entered for: Headline Color.', 'subaccounts-for-woocommerce' ), 'warning' );
				}
				if ( $input[$key] == $input['sfwc_switcher_pane_text_color'] ) {

					add_settings_error( 'sfwc_settings_messages', 'sfwc_wrong_hex_color', esc_html__( 'Incorrect value entered for: Text Color.', 'subaccounts-for-woocommerce' ), 'warning' );
				}
				if ( $input[$key] == $input['sfwc_switcher_pane_select_bg_color'] ) {

					add_settings_error( 'sfwc_settings_messages', 'sfwc_wrong_hex_color', esc_html__( 'Incorrect value entered for: Button Background Color.', 'subaccounts-for-woocommerce' ), 'warning' );
				}
				if ( $input[$key] == $input['sfwc_switcher_pane_select_text_color'] ) {

					add_settings_error( 'sfwc_settings_messages', 'sfwc_wrong_hex_color', esc_html__( 'Incorrect value entered for: Button Text Color.', 'subaccounts-for-woocommerce' ), 'warning' );
				}
			}
		}
	}

	// Return the array processing any additional functions filtered by this action.
	return apply_filters('sfwc_switcher_appearance_validate', $output, $input);
}




/**
 * Settings Options Validation.
 */
function sfwc_options_validate( $input ) {

	// Create our array for storing the validated options.
	$output = array();



	if ( ! is_plugin_active( 'subaccounts-for-woocommerce-pro/subaccounts-for-woocommerce-pro.php' ) ) {
		// Check if the current option has a value.
		if ( isset( $input['sfwc_option_subaccounts_number_limit'] ) ) {

			// Sanitize sfwc_option_subaccounts_number_limit.
			$sanitized_subaccounts_number_limit = preg_replace( '/[^0-9]/', '', $input['sfwc_option_subaccounts_number_limit'] );
			
			
			// Validate sfwc_option_subaccounts_number_limit.
			if ( is_numeric( $sanitized_subaccounts_number_limit ) ) {
				
				if ( $sanitized_subaccounts_number_limit >= 1 && $sanitized_subaccounts_number_limit <= 10 ) {
				
					$output['sfwc_option_subaccounts_number_limit'] = $sanitized_subaccounts_number_limit;
				} 
				else {

					add_settings_error(
						'sfwc_settings_messages',
						'sfwc_wrong_subaccounts_number_limit',
						esc_html__( 'Incorrect value entered for: Maximum number of subaccounts allowed. Please enter a value between 1 and 10.', 'subaccounts-for-woocommerce' ),
						'error'
					);
				}
			}
			else {

				add_settings_error(
					'sfwc_settings_messages',
					'sfwc_wrong_subaccounts_number_limit',
					esc_html__( 'Incorrect value entered for: Maximum number of subaccounts allowed.', 'subaccounts-for-woocommerce' ),
					'error'
				);
			}
		}
	}




    // Check if the current option has a value.
    if ( isset( $input['sfwc_option_selected_roles'] ) ) {
		
		$sanitized_roles = array();
		$valid_roles = array();
		
		// Sanitize posted values.
		foreach ( $input['sfwc_option_selected_roles'] as $single_role ) {
			
			$sanitized_roles[] = sanitize_text_field( $single_role ); 
		}
		
		
		// Validate posted values.
		if ( ! empty( $sanitized_roles ) ) {
			
			foreach ( $sanitized_roles as $sanitized_role ) {
				
				if ( in_array( $sanitized_role, sfwc_get_valid_roles() ) ) {
					
					$valid_roles[] = $sanitized_role;
				}
			}
		}

		if ( ! empty( $valid_roles ) ) {
			
			$output['sfwc_option_selected_roles'] = $valid_roles;
		}
		else {

            add_settings_error( 
				'sfwc_settings_messages',
				'sfwc_wrong_display_name',
				esc_html__( 'Incorrect value entered for: Select the buyer role(s) to enable the subaccount system for', 'subaccounts-for-woocommerce' ),
				'error'
			);
        }
    }




	// Check if the current option has a value.
    if ( isset( $input['sfwc_option_subaccount_mode'] ) ) {

        $valid_radio_subaccount_mode = array( 'sub_user', 'multi_user' );

        if ( in_array( $input['sfwc_option_subaccount_mode'], $valid_radio_subaccount_mode ) ) {
			
			// When "Sub-User" mode is enabled, flush permalinks to prevent My Account > Subaccounts > Subaccount Orders from returning Error 404.
			if ( $input['sfwc_option_subaccount_mode'] == 'sub_user' ) {
				if ( get_transient( 'sfwc_flush_rewrite_rules_required' ) === false ) {
					set_transient('sfwc_flush_rewrite_rules_required', true);
				}
			}

            $output['sfwc_option_subaccount_mode'] = sanitize_text_field( $input['sfwc_option_subaccount_mode'] );

        } else {

            add_settings_error( 
				'sfwc_settings_messages',
				'sfwc_wrong_subaccount_mode',
				esc_html__( 'Incorrect value entered for: Subaccount Mode.', 'subaccounts-for-woocommerce' ),
				'error'
			);
        }
    }




	// Check if the current option has a value.
    if ( isset( $input['sfwc_option_display_name'] ) ) {

        $valid_radio_display_name = array( 'username', 'full_name', 'company_name' );

        if ( in_array( $input['sfwc_option_display_name'], $valid_radio_display_name ) ) {

            $output['sfwc_option_display_name'] = sanitize_text_field( $input['sfwc_option_display_name'] );

        } else {

            add_settings_error( 
				'sfwc_settings_messages',
				'sfwc_wrong_display_name',
				esc_html__( 'Incorrect value entered for: Customer Display Name.', 'subaccounts-for-woocommerce' ),
				'error'
			);
        }
    }
	
	
	
	
	
	// Check if the current option has a value.
    if ( isset( $input['sfwc_option_subaccount_default_role'] ) ) {

        $valid_radio_default_role = array( 'select_role', 'inherit_role' );

        if ( in_array( $input['sfwc_option_subaccount_default_role'], $valid_radio_default_role ) ) {

            $output['sfwc_option_subaccount_default_role'] = sanitize_text_field( $input['sfwc_option_subaccount_default_role'] );

        } else {

            add_settings_error( 
				'sfwc_settings_messages',
				'sfwc_wrong_subaccount_default_role',
				esc_html__( 'Incorrect value entered for: New Subaccount Default Role.', 'subaccounts-for-woocommerce' ),
				'error'
			);
        }
    }




    // Check if the current option has a value.
	if ( isset( $input['sfwc_option_subaccount_default_role'] ) && $input['sfwc_option_subaccount_default_role'] === 'select_role' && isset( $input['sfwc_option_subaccount_default_role_select_role'] ) ) {
		
		$sanitized_default_roles = array();
		$valid_default_roles = array();
		
		// Sanitize posted values.
		foreach ( $input['sfwc_option_subaccount_default_role_select_role'] as $single_role ) {
			
			$sanitized_default_roles[] = sanitize_text_field( $single_role ); 
		}
		
		
		// Validate posted values.
		if ( ! empty( $sanitized_default_roles ) ) {
			
			foreach ( $sanitized_default_roles as $sanitized_role ) {
				
				if ( in_array( $sanitized_role, sfwc_get_valid_roles() ) ) {
					
					$valid_default_roles[] = $sanitized_role;
				}
			}
		}

		if ( ! empty( $valid_default_roles ) ) {
			
			$output['sfwc_option_subaccount_default_role_select_role'] = $valid_default_roles;
		}
		else {
			
            add_settings_error( 
				'sfwc_settings_messages',
				'sfwc_wrong_new_default_role',
				esc_html__( 'Incorrect value entered for: \'Select New Subaccount Default Role(s)\' option', 'subaccounts-for-woocommerce' ),
				'error'
			);
        }
    }





	// Default value if not set.
	$output['sfwc_options_keep_roles_synced'] = '0';
	
	// The 'Keep user role synced' feature can only be enabled if option 'Subaccounts inherit the same role(s) as the parent account' is enabled.
	if ( isset( $input['sfwc_option_subaccount_default_role'] ) && $input['sfwc_option_subaccount_default_role'] === 'inherit_role' && isset( $input['sfwc_options_keep_roles_synced'] ) ) {

		$output['sfwc_options_keep_roles_synced'] = '1';
		
	} elseif (  isset( $input['sfwc_option_subaccount_default_role'] ) && $input['sfwc_option_subaccount_default_role'] !== 'inherit_role' && isset( $input['sfwc_options_keep_roles_synced'] )  ) {
		
		add_settings_error( 
			'sfwc_settings_messages',
			'sfwc_inherit_role_option_required',
			esc_html__( 'In order to enable the \'Keep user role synced\' feature, first make sure that the \'Subaccounts inherit the same role(s) as the parent account\' option is enabled.', 'subaccounts-for-woocommerce' ),
			'error'
		);
	}




	// Default value if not set.
	$output['sfwc_options_enable_user_switcher'] = '0';

	// Check if the current option has a value.
	if ( isset( $input['sfwc_options_enable_user_switcher'] ) ) {

		$output['sfwc_options_enable_user_switcher'] = '1';
	}




	// Default value if not set.
	$output['sfwc_options_show_order_meta_box'] = '0';

	// Check if the current option has a value.
	if ( isset( $input['sfwc_options_show_order_meta_box'] ) ) {

		$output['sfwc_options_show_order_meta_box'] = '1';
	}


	// Validate PRO settings.
	do_action_ref_array('sfwc_options_validate', array(&$output, &$input));

	return $output;
}




/**
 * Flush rewrite rules after updating certain plugin settings.
 * 
 * Update permalink structure after updating below settings:
 *
 *	- Subaccount Mode
 *	- Choose who can create and add new subaccounts
 */
function sfwc_flush_rewrite_rules_after_settings_update() {

	if ( delete_transient( 'sfwc_flush_rewrite_rules_required' ) ) {
		flush_rewrite_rules();
	}
}
add_action('admin_init', 'sfwc_flush_rewrite_rules_after_settings_update');




/**
 * Create Tabbed content for settings page
 */
function sfwc_admin_page_contents() {

	// check user capabilities
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	// add error/update messages
	// check if the user have submitted the settings
	// WordPress will add the "settings-updated" $_GET parameter to the url
	if ( isset( $_GET['settings-updated'] ) ) {

		// add settings saved message with the class of "updated"
		add_settings_error( 'sfwc_settings_messages', 'sfwc_settings_message', esc_html__( 'Settings Saved.', 'subaccounts-for-woocommerce' ), 'updated' );
	}

	// show error/update messages
	settings_errors('sfwc_settings_messages');


	global $sfwc_active_tab;
	$sfwc_active_tab = isset( $_GET['tab'] ) ? sanitize_text_field( $_GET['tab'] ) : 'options';
	?>
	
	<div id="sfwc-header-wrapper">
		<?php		
		if( sfwc_is_plugin_active( 'subaccounts-for-woocommerce-pro.php' ) ) {
			echo '<img src="' . esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce-pro/assets/images/subaccounts-pro.svg" width="365" height="79" alt="Subaccounts Pro" class="sfwc-logo-img">';
		} else {
			echo '<img src="' . esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/images/subaccounts-for-woocommerce.svg" width="313" height="79" alt="Subaccounts for WooCommerce" class="sfwc-logo-img">';
		}
		?>
	</div>
	
	<!--
	<?php if ( $sfwc_active_tab == 'options' ) : ?>

		<h2><?php esc_html_e('Options', 'subaccounts-for-woocommerce'); ?></h2>		
		<p><?php esc_html_e( 'On this page you can configure the Subaccounts plugin settings.', 'subaccounts-for-woocommerce' ); ?></p>

	<?php elseif ( $sfwc_active_tab == 'appearance' ) : ?>
	
		<h2><?php esc_html_e('Appearance', 'subaccounts-for-woocommerce'); ?></h2>		
		<p><?php esc_html_e( 'On this page you can configure the appearance of the User Switcher Pane.', 'subaccounts-for-woocommerce' ); ?></p>
		
	<?php endif; ?>
	-->
	
	<div class="wrap fs-section">
		<nav class="nav-tab-wrapper">
		<?php
		do_action( 'sfwc_settings_tab' );
		?>
		</nav>
	</div>
	<?php
	do_action('sfwc_settings_content');
}




/**
 * Add heading content on Freemius pages.
 *
 * Add custom content when Freemius' 'Account' and 'Add-Ons' tabs are selected.
 */
function sfwc_admin_freemius_page_headings() {
	
	global $pagenow;
	
	if ( ! isset( $_GET['page'] ) ) {
		return;
	} else {
		$page = sanitize_text_field( $_GET['page'] );
	}
	
	if ( ( $pagenow == 'admin.php' ) ) {
		
		if ( ( $page == 'subaccounts-account' ) || ( $page == 'subaccounts-addons' ) ) {
		?>
			<div id="sfwc-header-wrapper">
				<?php		
				if( sfwc_is_plugin_active( 'subaccounts-for-woocommerce-pro.php' ) ) {
					echo '<img src="' . esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce-pro/assets/images/subaccounts-pro.svg" width="365" height="79" alt="Subaccounts Pro" class="sfwc-logo-img">';
				} else {
					echo '<img src="' . esc_url( WP_PLUGIN_URL ) . '/subaccounts-for-woocommerce/assets/images/subaccounts-for-woocommerce.svg" width="313" height="79" alt="Subaccounts for WooCommerce" class="sfwc-logo-img">';
				}
				?>
			</div>
		<?php
		}
	}
}
add_action('all_admin_notices', 'sfwc_admin_freemius_page_headings' );




/**
 * Tab 1: Options.
 */
function sfwc_options_tab() {
	global $sfwc_active_tab;
	?>
	<a class="nav-tab fs-tab options <?php echo $sfwc_active_tab == 'options' || '' ? 'nav-tab-active' : ''; ?>" href="<?php echo esc_url( admin_url( 'admin.php?page=subaccounts&tab=options' ) ); ?>"><?php esc_html_e( 'Options', 'subaccounts-for-woocommerce' ); ?> </a>
	<?php
}
add_action('sfwc_settings_tab', 'sfwc_options_tab', 1);



function sfwc_options_tab_content() {

	global $sfwc_active_tab;

	if ( 'options' != $sfwc_active_tab )
		return;
	?>

	<div id="sub_accounts_settings_options_tab">

		<h3><?php esc_html_e( 'General settings', 'subaccounts-for-woocommerce' ); ?></h3>


		<!-- Appearance content here -->
		<form method="POST" action="options.php">

		<?php		
		// Real options
		settings_fields('sfwc_options_group');
		do_settings_sections('subaccounts&tab=options');

		// Fake options (only available in Pro version)
		do_action('sfwc_dummy_html_markup_after_enabled_options');

		submit_button();
		?>

		</form>
	</div>
	<?php
}
add_action('sfwc_settings_content', 'sfwc_options_tab_content');




/**
 * Tab 2: Appearance.
 */
function sfwc_appearance_tab() {
	global $sfwc_active_tab;
	?>
	<a class="nav-tab fs-tab appearance <?php echo $sfwc_active_tab == 'appearance' ? 'nav-tab-active' : ''; ?>" href="<?php echo esc_url( admin_url('admin.php?page=subaccounts&tab=appearance') ); ?>"><?php esc_html_e('Appearance', 'subaccounts-for-woocommerce'); ?> </a>
	<?php
}
add_action('sfwc_settings_tab', 'sfwc_appearance_tab', 2);




function sfwc_appearance_tab_content() {
	global $sfwc_active_tab;
	if ( '' || 'appearance' != $sfwc_active_tab )
		return;
	?>

	<div id="sub_accounts_settings_appearance_tab">
		<div id="sub_accounts_settings_appearance_tab_left">
		<!-- <h3><?php esc_html_e( 'Frontend User Switcher Pane Appearance', 'subaccounts-for-woocommerce' ); ?></h3> -->

			<!-- Appearance content here -->
			<form method="POST" action="options.php">
			<?php
			settings_fields('sfwc_switcher_appearance_group');
			do_settings_sections('subaccounts');
			submit_button();
			?>
			</form>

		</div>


		<div id="sub_accounts_settings_appearance_tab_right">

			<h3><?php esc_html_e( 'User Switcher Pane Preview', 'subaccounts-for-woocommerce' ); ?></h3>

			<p>
				<?php
					$user_switcher_pane_translation = '<em>' . esc_html__( 'User Switcher Pane', 'subaccounts-for-woocommerce' ) . '</em>';
					$my_account_translation = '<strong>' . esc_html__( 'My Account', 'subaccounts-for-woocommerce' ) . '</strong>';
					$supervisor_add_on_translation = '<em>' . esc_html__( 'Supervisor Add-on', 'subaccounts-for-woocommerce' ) . '</em>';
					
					printf(
						esc_html__( 'This is the preview of the %1$s, which is visible in the %2$s area only for Manager account types. In case the %3$s is installed, the User Switcher Pane is also visible for Supervisor account types.', 'subaccounts-for-woocommerce' ), 
						$user_switcher_pane_translation,
						$my_account_translation,
						$supervisor_add_on_translation
					);
				?>
			</p>

			<div id="sfwc-user-switcher-pane">

				<h3><?php esc_html_e( 'You are currently logged in as:', 'subaccounts-for-woocommerce' ); ?></h3>
				<p style="color:' . $sfwc_switcher_pane_text_color . ';"><strong><?php esc_html_e( 'User:', 'subaccounts-for-woocommerce' ); ?></strong> John Doe - [ johndoe@email.com ]</p>

				<form method="post">
					<select>

						<option selected="selected" disabled><?php esc_html_e( 'Select Account', 'subaccounts-for-woocommerce' ); ?>&nbsp; &#8644;</option>
						<option>James Miller - [ jamesmiller@email.com ]</option>
						<option>Robert Williams - [ robertwilliams@email.com ]</option>
						<option>Rebecca Smith - [ rebeccasmith@email.com ]</option>

					</select>
				</form>
			</div>

			<p id="sfwc-user-switcher-pane-default-values"><?php esc_html_e( '[Restore default color scheme]', 'subaccounts-for-woocommerce' ); ?></p>
		</div>
	</div>
	<?php
}
add_action('sfwc_settings_content', 'sfwc_appearance_tab_content');




/**
 * Dummy content for Option tab in plugin's Settings admin page.
 *
 * Add dummy content for Option tab in case Subaccounts Pro is not installed.
 */
function sfwc_add_dummy_html_markup_after_enabled_options() {
	?>

	<table class="form-table" role="presentation">
		<tbody>
			<tr>
				<th scope="row" style="padding: 15px 10px 20px 0;">
					<?php echo esc_html__('Show subaccounts information on WooCommerce orders list page', 'subaccounts-for-woocommerce') . '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__("Add the 'Order placed by' column to the WooCommerce orders list page in WordPress admin area. In case Sub-User mode is active, 'Account Type' and 'Parent Accounts' columns will also show up.", 'subaccounts-for-woocommerce') . '"></span>'; ?>
					<br>
					<a style="color:#148ff3;" href="<?php echo esc_url( admin_url( '/admin.php?checkout=true&page=subaccounts-pricing&plugin_id=10457&plan_id=17669&pricing_id=19941&billing_cycle=annual' ) ); ?>">
					<?php echo esc_html__( 'Get Subaccounts Pro', 'subaccounts-for-woocommerce' ); ?></a>

					<span style="font-weight:400;">
						<?php echo esc_html__( 'and unlock this feature!', 'subaccounts-for-woocommerce' ); ?>
					</span>
				</th>
				<td>
					<input title="<?php esc_attr_e( 'This feature is only available on Subaccounts Pro', 'subaccounts-for-woocommerce'); ?>" type="checkbox" name="sfwc_columns_order" value="" disabled>
					<span style="vertical-align: middle;"><?php esc_html_e( "You may need to enable this under 'Screen Options' too", "subaccounts-for-woocommerce" ); ?></span>
				</td>
			</tr>
			<tr>
				<th scope="row" style="padding: 15px 10px 20px 0;">
					<?php echo esc_html__( 'Show subaccounts information on WordPress users list page', 'subaccounts-for-woocommerce' ) . '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( "Add 'Account Type', 'Subaccounts' and 'Parent Accounts' columns to the users list page in WordPress admin area.", "subaccounts-for-woocommerce" ) . '"></span>'; ?>
					<br>
					<a style="color:#148ff3;" href="<?php echo esc_url( admin_url( '/admin.php?checkout=true&page=subaccounts-pricing&plugin_id=10457&plan_id=17669&pricing_id=19941&billing_cycle=annual' ) ); ?>">
					<?php echo esc_html__( 'Get Subaccounts Pro', 'subaccounts-for-woocommerce' ); ?></a>

					<span style="font-weight:400;">
						<?php echo esc_html__( 'and unlock this feature!', 'subaccounts-for-woocommerce' ); ?>
					</span>
				</th>
				<td>
					<input title="<?php esc_attr_e( 'This feature is only available on Subaccounts Pro', 'subaccounts-for-woocommerce'); ?>" type="checkbox" name="sfwc_columns_users" value="" disabled>
					<span style="vertical-align: middle;"><?php esc_html_e( "You may need to enable this under 'Screen Options' too", "subaccounts-for-woocommerce" ); ?></span>
				</td>
			</tr>
			<tr>
				<th scope="row" style="padding: 15px 10px 20px 0;">
					<?php echo esc_html__('Add subaccounts information to new order emails', 'subaccounts-for-woocommerce') . '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( 'Show customer\'s Manager and Supervisor information in new order emails.', "subaccounts-for-woocommerce" ) . '"></span>'; ?>
					<br>
					<a style="color:#148ff3;" href="<?php echo esc_url( admin_url( '/admin.php?checkout=true&page=subaccounts-pricing&plugin_id=10457&plan_id=17669&pricing_id=19941&billing_cycle=annual' ) ); ?>">
					<?php echo esc_html__( 'Get Subaccounts Pro', 'subaccounts-for-woocommerce' ); ?></a>

					<span style="font-weight:400;">
						<?php echo esc_html__( 'and unlock this feature!', 'subaccounts-for-woocommerce' ); ?>
					</span>
				</th>
				<td>
					<input title="<?php esc_attr_e( 'This feature is only available on Subaccounts Pro', 'subaccounts-for-woocommerce'); ?>" type="radio" name="sfwc_email_option" value="" disabled checked>
					<label for=""><?php esc_html_e('No', 'subaccounts-for-woocommerce'); ?></label><br>

					<input title="<?php esc_attr_e( 'This feature is only available on Subaccounts Pro', 'subaccounts-for-woocommerce'); ?>" type="radio" name="sfwc_email_option" value="" disabled>
					<label for=""><?php esc_html_e('For Admin Only', 'subaccounts-for-woocommerce'); ?></label><br>

					<input title="<?php esc_attr_e( 'This feature is only available on Subaccounts Pro', 'subaccounts-for-woocommerce'); ?>" type="radio" name="sfwc_email_option" value="" disabled>
					<label for=""><?php esc_html_e('For Customer Only', 'subaccounts-for-woocommerce'); ?></label><br>

					<input title="<?php esc_attr_e( 'This feature is only available on Subaccounts Pro', 'subaccounts-for-woocommerce'); ?>" type="radio" name="sfwc_email_option" value="" disabled>
					<label for=""><?php esc_html_e('For both Admin and Customer', 'subaccounts-for-woocommerce'); ?></label>
					
					<p style="margin-top:8px;">
					
						<?php
							$important_strong = '<strong>' . esc_html__( 'Important:', 'subaccounts-for-woocommerce' ) . '</strong>';
							$email_settings_path =	'<em>' . esc_html__( 'WooCommerce', 'subaccounts-for-woocommerce' ) . '</em> ➝ ' . 
													'<em>' . esc_html__( 'Settings', 'subaccounts-for-woocommerce' ) . '</em> ➝ ' . 
													'<em>' . esc_html__( 'Emails', 'subaccounts-for-woocommerce' ) . '</em>';
							
							
							printf(
								esc_html__( '%1$s make sure email notifications are properly set and enabled in: %2$s.', 'subaccounts-for-woocommerce' ), 
								$important_strong,
								$email_settings_path
							);
						?>

					</p>
				</td>
			</tr>
			<tr>
				<th scope="row" style="padding: 15px 10px 20px 0;">
					<?php echo esc_html__( 'Subaccount billing address', 'subaccounts-for-woocommerce' ) . '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( "With this option enabled whenever a Manager billing address is updated, the changes are reflected to subaccounts as well.", "subaccounts-for-woocommerce" ) . '"></span>'; ?>
					<br>
					<a style="color:#148ff3;" href="<?php echo esc_url( admin_url( '/admin.php?checkout=true&page=subaccounts-pricing&plugin_id=10457&plan_id=17669&pricing_id=19941&billing_cycle=annual' ) ); ?>">
					<?php echo esc_html__( 'Get Subaccounts Pro', 'subaccounts-for-woocommerce' ); ?></a>

					<span style="font-weight:400;">
						<?php echo esc_html__( 'and unlock this feature!', 'subaccounts-for-woocommerce' ); ?>
					</span>
				</th>
				<td>
					<input title="<?php esc_attr_e( 'This feature is only available on Subaccounts Pro', 'subaccounts-for-woocommerce'); ?>" type="checkbox" name="sfwc_columns_users" value="" disabled>
					<span style="vertical-align: middle;"><?php esc_html_e( "Force subaccounts to inherit the billing address from their Manager", "subaccounts-for-woocommerce" ); ?></span>
					
					<p style="margin-top:8px;">
					
						<?php
							$important_strong = '<strong>' . esc_html__( 'Important:', 'subaccounts-for-woocommerce' ) . '</strong>';
							$my_account_edit_address_path =	'<em>' . esc_html__( 'My Account', 'subaccounts-for-woocommerce' ) . '</em> ➝ ' . 
															'<em>' . esc_html__( 'Addresses', 'subaccounts-for-woocommerce' ) . '</em>';
							
							
							printf(
								esc_html__( '%1$s with this option enabled, subaccount billing address fields in: %2$s will become uneditable.', 'subaccounts-for-woocommerce' ), 
								$important_strong,
								$my_account_edit_address_path
							);
						?>

					</p>
				</td>
			</tr>
			<tr>
				<th scope="row" style="padding: 15px 10px 20px 0;">
					<?php echo esc_html__( 'Subaccount shipping address', 'subaccounts-for-woocommerce' ) . '<span class="tips woocommerce-help-tip" data-tip="' . esc_attr__( "With this option enabled whenever a Manager's shipping address is updated, the changes are reflected to subaccounts as well.", "subaccounts-for-woocommerce" ) . '"></span>'; ?>
					<br>
					<a style="color:#148ff3;" href="<?php echo esc_url( admin_url( '/admin.php?checkout=true&page=subaccounts-pricing&plugin_id=10457&plan_id=17669&pricing_id=19941&billing_cycle=annual' ) ); ?>">
					<?php echo esc_html__( 'Get Subaccounts Pro', 'subaccounts-for-woocommerce' ); ?></a>

					<span style="font-weight:400;">
						<?php echo esc_html__( 'and unlock this feature!', 'subaccounts-for-woocommerce' ); ?>
					</span>
				</th>
				<td>
					<input title="<?php esc_attr_e( 'This feature is only available on Subaccounts Pro', 'subaccounts-for-woocommerce'); ?>" type="checkbox" name="sfwc_columns_users" value="" disabled>
					<span style="vertical-align: middle;"><?php esc_html_e( "Force subaccounts to inherit the shipping address from their Manager", "subaccounts-for-woocommerce" ); ?></span>
					
					<p style="margin-top:8px;">
					
						<?php
							$important_strong = '<strong>' . esc_html__( 'Important:', 'subaccounts-for-woocommerce' ) . '</strong>';
							$my_account_edit_address_path =	'<em>' . esc_html__( 'My Account', 'subaccounts-for-woocommerce' ) . '</em> ➝ ' . 
															'<em>' . esc_html__( 'Addresses', 'subaccounts-for-woocommerce' ) . '</em>';
							
							
							printf(
								esc_html__( '%1$s with this option enabled, subaccount shipping address fields in: %2$s will become uneditable.', 'subaccounts-for-woocommerce' ), 
								$important_strong,
								$my_account_edit_address_path
							);
						?>

					</p>
				</td>
			</tr>
		<tbody>
	</table>
	<?php
}
add_action('sfwc_dummy_html_markup_after_enabled_options', 'sfwc_add_dummy_html_markup_after_enabled_options');




/**
 * Provide possibility to edit the 'subaccounts' account endpoint.
 * 
 * Allow admin to customize the My Account 'subaccounts' endpoint slug, in: WooCommerce > Settings > Advanced > Page setup > Account endpoints.
 */
function sfwc_add_edit_subaccounts_endpoint_setting( $settings ) {
	
		$new_settings = array();

		foreach ( $settings as $setting ) {

			$new_settings[] = $setting;
			
			// Add the 'Subaccounts' account endpoint setting after the 'Payment methods' endpoint.
			if ( isset( $setting['id'] ) && 'woocommerce_myaccount_payment_methods_endpoint' === $setting['id'] ) {

				$new_settings[] = array(
					'title'    => __( 'Subaccounts', 'woocommerce' ),
					'desc'     => __( 'Endpoint for the "My account &rarr; Subaccounts" page.', 'woocommerce' ),
					'id'       => 'woocommerce_myaccount_subaccounts_endpoint',
					'type'     => 'text',
					'default'  => 'subaccounts',
					'desc_tip' => true,
				);
			}
		}

		return $new_settings;
}
add_filter( 'woocommerce_settings_pages', 'sfwc_add_edit_subaccounts_endpoint_setting' );




/**
 * Keep subaccount roles in sync with parent account roles.
 *
 * When the Manager's role is updated from the backend edit user profile page, change subaccount roles accordingly.
 */ 
function sfwc_keep_subaccount_roles_synced_with_parent_roles_when_updating_users_on_backend( $user_id, $old_user_data, $userdata ) {
	
	// Get Options settings.
	$sfwc_options = (array) get_option('sfwc_options');
	
	// 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 'Keep user roles in sync' value
	$sfwc_options_keep_roles_synced = ( isset( $sfwc_options['sfwc_options_keep_roles_synced'] ) ) ? $sfwc_options['sfwc_options_keep_roles_synced'] : 0;
	
	// Get the user object.
	$parent = new WP_User( $user_id );

	// Get account type of the user whose role has been chenged.
	$account_level_type = get_user_meta( $user_id, 'sfwc_account_level_type', true );
	
	// Get parent account roles.
	$parent_roles = sfwc_is_user_role_valid( $user_id );
	
	// Get children (array) of currently logged in user.                                                                                                                                                                                                                                                                                      
	$children_ids = get_user_meta( $user_id, 'sfwc_children', true );
	
	// Check if 'Keep user roles in sync' feature is enabled.
	if ( $sfwc_option_subaccount_default_role === 'inherit_role' && $sfwc_options_keep_roles_synced == 1 ) {
	
		// Check if the user whose role has been chenged is a manager.
		if ( $account_level_type == 'manager' ) {
			
			/**
			 * 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.
			 */
			$valid_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 ) {
								  
						// 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'
							)
						{
							$valid_children_ids[] = $single_id;
						}
					}
				}
			}
				
			// Change subaccount roles.
			if ( ! empty ( $valid_children_ids ) && ! empty( $parent_roles ) ) {
						  
				foreach ( $valid_children_ids as $subaccount_id ) {
					
					$subaccount = new WP_User( $subaccount_id );
					
					// Remove old subaccount role(s).
					$subaccount->set_role('');
					
					// Add new subaccount role(s).
					foreach( $parent_roles as $parent_role ) {
						$subaccount->add_role( $parent_role );
					}
				}
			}
		}
	}
}
add_action( 'profile_update', 'sfwc_keep_subaccount_roles_synced_with_parent_roles_when_updating_users_on_backend', 10, 3 );




/**
 * Register new endpoint "Add Subaccount" to use for My Account page.
 * 
 *		-------------------------------------------------
 * 		Remember to update Permalinks to avoid 404 error.
 *		-------------------------------------------------
 *
 * Do NOT move this piece of code to: subaccounts-for-woocommerce > public > my-account.php
 * Other code in: subaccounts-for-woocommerce > public > my-account.php
 * See: "Add Subaccount" menu item to My Acount page.
 *
 * DO NOT REMOVE!
 * Removed on version 1.1.3 and restored on version 1.1.4 to prevent endpoint returning 'Not Found Error'.
 *
 * Keep this function here, in addition to function: sfwc_subaccounts_endpoint_query_vars
 * in: subaccounts-for-woocommerce > public > my-account.php
 */
function sfwc_register_subaccounts_endpoint() {
	add_rewrite_endpoint( sanitize_text_field( get_option( 'woocommerce_myaccount_subaccounts_endpoint', 'subaccounts' ) ), EP_ROOT | EP_PAGES );
}
add_action( 'init', 'sfwc_register_subaccounts_endpoint' );