<?php

class B2bking_Activator {

	public static function activate() {

		// clear b2bking transients
		if (function_exists('b2bking')){
			b2bking()->clear_caches_transients();
		}

		// prevent option update issues due to caching
		wp_cache_delete ( 'alloptions', 'options' );
		

		// Trigger post types and endpoints functions
		require_once ( B2BKING_DIR . 'admin/class-b2bking-admin.php' );
		require_once ( B2BKING_DIR . 'public/class-b2bking-public.php' );
		$adminobj = new B2bking_Admin;
		$publicobj = new B2bking_Public;
		$adminobj->b2bking_register_post_type_customer_groups();
		$adminobj->b2bking_register_post_type_conversation();
		$adminobj->b2bking_register_post_type_offer();
		$adminobj->b2bking_register_post_type_dynamic_rules();
		$adminobj->b2bking_register_post_type_custom_role();
		$adminobj->b2bking_register_post_type_custom_field();
		$publicobj->b2bking_custom_endpoints();

		
		// Flush rewrite rules
		if (apply_filters('b2bking_flush_permalinks', true)){
			// Flush rewrite rules
			flush_rewrite_rules();
		}

		$permalinks = get_option('b2bking_force_permalinks_flushing_setting');
			if (empty($permalinks)){
				update_option('b2bking_force_permalinks_flushing_setting', 1);
			}

			add_option('b2bking_first_activation_time', time(), '', false);

			// if it doesn't exist, then this is the first activation, and we shouldn't show reviews immediately
			if (empty(get_user_meta(get_current_user_id(),'b2bking_dismiss_activate_woocommerce_notice', true))){
			// give users 48 hours first
			update_user_meta( get_current_user_id(), 'b2bking_dismiss_review_notice_time', time());
			update_user_meta( get_current_user_id(), 'b2bking_dismiss_review_notice', 1 );
		}

		// Set admin notice state to enabled ('activate woocommerce' notice)
		update_user_meta(get_current_user_id(), 'b2bking_dismiss_activate_woocommerce_notice', 0);

		// If license is not active yet, show the welcome page after activation.
		self::b2bking_set_welcome_redirect_state();

		// Update from sort_number to menu_order only once
		if (get_option('b2bking_update_sort_number_menu_order', 'no') === 'no'){
			// do update
			$custom_fields = get_posts([
	    		'post_type' => 'b2bking_custom_field',
	    	  	'numberposts' => -1,
	    	  	'fields'	=> 'ids'
	    	]);

	    	foreach ($custom_fields as $field_id){
	    		$field_order = get_post_meta($field_id, 'b2bking_custom_field_sort_number', true);
	    		if (function_exists('b2bking')){
	    			b2bking()->update_sort_order($field_order, $field_id);
	    		}
	    	}

			$custom_roles = get_posts([
	    		'post_type' => 'b2bking_custom_role',
	    	  	'numberposts' => -1,
	    	  	'fields'	=> 'ids'
	    	]);

	    	foreach ($custom_roles as $field_id){
	    		$field_order = get_post_meta($field_id, 'b2bking_custom_role_sort_number', true);
	    		if (function_exists('b2bking')){
	    			b2bking()->update_sort_order($field_order, $field_id);
	    		}
	    	}

			update_option('b2bking_update_sort_number_menu_order', 'yes');
		}

			// update conversations if necessary
		if (get_option('b2bking_update_conversations_time_new', 'no') === 'no'){

    		$conversations = get_posts([
        		'post_type' => 'b2bking_conversation',
        	  	'numberposts' => 1000,
        	  	'fields'	=> 'ids',
        	  	'skip_sort_reply_time' => 'yes'
        	]);

	        foreach ($conversations as $post_id) {
	            // Get the last message number
	            $lastmessagenumber = get_post_meta($post_id, 'b2bking_conversation_messages_number', true);
	            
	            if (!empty($lastmessagenumber)) {
	                // Get the time of the last message
	                $time_last_message = get_post_meta($post_id, 'b2bking_conversation_message_' . $lastmessagenumber . '_time', true);
	                
	                if (!empty($time_last_message)) {
	                    // Update the last reply time meta
	                    update_post_meta($post_id, 'b2bking_conversation_last_reply_time', $time_last_message);
	                }
	            }
	        }

		    update_option('b2bking_update_conversations_time_new', 'yes');

		}

		// Create B2B offer product if it doesn't exist
		if (apply_filters('b2bking_use_offer_and_credit_products', true)){
			$offer_id = intval(get_option('b2bking_offer_product_id_setting', 0));
			$offer_status = $offer_id ? get_post_status( $offer_id ) : false;
			if ( $offer_status === 'trash' ) {
				wp_untrash_post( $offer_id );
			} elseif ( !$offer_status ) {
				$offer = array(
				    'post_title' => 'Offer',
				    'post_status' => 'publish',
				    'post_type' => 'product',
				    'post_author' => 1,
				);
				$product_id = wp_insert_post($offer);
				//Set product hidden: 
				$terms = array( 'exclude-from-catalog', 'exclude-from-search' );
				wp_set_object_terms( $product_id, $terms, 'product_visibility' );
				wp_set_object_terms( $product_id, 'simple', 'product_type' );
				update_post_meta( $product_id, '_visibility', 'hidden' );
				update_post_meta( $product_id, '_stock_status', 'instock');
				update_post_meta( $product_id, '_regular_price', '' );
				update_post_meta( $product_id, '_sale_price', '' );
				update_post_meta( $product_id, '_purchase_note', '' );
				update_post_meta( $product_id, '_product_attributes', array() );
				update_post_meta( $product_id, '_sale_price_dates_from', '' );
				update_post_meta( $product_id, '_sale_price_dates_to', '' );
				update_post_meta( $product_id, '_price', '1' );
				update_post_meta( $product_id, '_sold_individually', '' );
				update_post_meta( $product_id, '_b2bking_system_product', '1' );

				// set option to product id
				update_option( 'b2bking_offer_product_id_setting', intval($product_id) );
			}

			// Create B2B credit product if it doesn't exist
			$credit_id = intval(get_option('b2bking_credit_product_id_setting', 0));
			$credit_status = $credit_id ? get_post_status( $credit_id ) : false;
			if ( $credit_status === 'trash' ) {
				wp_untrash_post( $credit_id );
			} elseif ( !$credit_status ) {
				$credit_id = array(
				    'post_title' => 'Credit',
				    'post_status' => 'publish',
				    'post_type' => 'product',
				    'post_author' => 1,
				);
				$product_id = wp_insert_post($credit_id);
				//Set product hidden: 
				$terms = array( 'exclude-from-catalog', 'exclude-from-search' );
				wp_set_object_terms( $product_id, $terms, 'product_visibility' );
				wp_set_object_terms( $product_id, 'simple', 'product_type' );
				update_post_meta( $product_id, '_visibility', 'hidden' );
				update_post_meta( $product_id, '_stock_status', 'instock');
				update_post_meta( $product_id, '_regular_price', '' );
				update_post_meta( $product_id, '_sale_price', '' );
				update_post_meta( $product_id, '_purchase_note', '' );
				update_post_meta( $product_id, '_product_attributes', array() );
				update_post_meta( $product_id, '_sale_price_dates_from', '' );
				update_post_meta( $product_id, '_sale_price_dates_to', '' );
				update_post_meta( $product_id, '_price', '1' );
				update_post_meta( $product_id, '_sold_individually', '' );
				update_post_meta( $product_id, '_tax_status', 'none' );
				update_post_meta( $product_id, '_tax_class', 'zero-rate' );
				update_post_meta( $product_id, '_virtual', 'yes' );
				update_post_meta( $product_id, '_b2bking_system_product', '1' );

				// set option to product id
				update_option( 'b2bking_credit_product_id_setting', intval($product_id) );
			}
		}

		
		
		// Create 2 default user roles if they don't exist: Individual Customer and B2B

		// also create please select opion
		$please_select_role_id = intval(get_option('b2bking_please_select_role_id_setting', 0));
		// if role does not exist, = 0

		// do not add to existing websites, websites that already have individual customer for example
		$individual_role_id = intval(get_option('b2bking_individual_role_id_setting', 0));
		// if role does not exist, = 0
		if (intval($individual_role_id) === 0){
			if (intval($please_select_role_id) === 0){
				$role = array(
				    'post_title' => sanitize_text_field(esc_html__('– – – Select User Role – – –','b2bking')),
				    'post_status' => 'publish',
				    'post_type' => 'b2bking_custom_role',
				    'post_author' => 1,
				);
				$role_id = wp_insert_post($role);
				// set role status as enabled
				update_post_meta($role_id, 'b2bking_custom_role_status', 1);
				update_post_meta($role_id, 'b2bking_non_selectable', 1);
				// set role approval as automatic
				update_post_meta( $role_id, 'b2bking_custom_role_approval', 'automatic');

				if (function_exists('b2bking')){
					b2bking()->update_sort_order(0, $role_id);
				}

				// set option 
				update_option( 'b2bking_please_select_role_id_setting', intval($role_id) );
			}
		}


		$individual_role_id = intval(get_option('b2bking_individual_role_id_setting', 0));
		// if role does not exist, = 0
		if (intval($individual_role_id) === 0){
			$role = array(
			    'post_title' => sanitize_text_field(esc_html__('Individual Customer','b2bking')),
			    'post_status' => 'publish',
			    'post_type' => 'b2bking_custom_role',
			    'post_author' => 1,
			);
			$role_id = wp_insert_post($role);
			// set role status as enabled
			update_post_meta($role_id, 'b2bking_custom_role_status', 1);
			// set role approval as automatic
			update_post_meta( $role_id, 'b2bking_custom_role_approval', 'automatic');

			if (function_exists('b2bking')){
				b2bking()->update_sort_order(1, $role_id);
			}


			// set option 
			update_option( 'b2bking_individual_role_id_setting', intval($role_id) );
		}

		
		$b2b_role_id = intval(get_option('b2bking_b2b_role_id_setting', 0));

		// if role does not exist, = 0
		if (intval($b2b_role_id) === 0){
			$role = array(
			    'post_title' => sanitize_text_field(esc_html__('B2B (requires approval)','b2bking')),
			    'post_status' => 'publish',
			    'post_type' => 'b2bking_custom_role',
			    'post_author' => 1,
			);
			$role_id = wp_insert_post($role);
			// set role status as enabled
			update_post_meta($role_id, 'b2bking_custom_role_status', 1);
			// set role approval as manual
			update_post_meta($role_id, 'b2bking_custom_role_approval', 'manual');

			if (function_exists('b2bking')){
				b2bking()->update_sort_order(2, $role_id);
			}

			// set option 
			update_option( 'b2bking_b2b_role_id_setting', intval($role_id) );

			$b2b_role_id = intval($role_id);
		}
	

		// Create 11 default B2B fields
		$first_name_initial_field_id = intval(get_option('b2bking_first_name_initial_field_id_setting', 0));
		// if field does not exist, = 0
		if (intval($first_name_initial_field_id) === 0){
			$field = array(
			    'post_title' => sanitize_text_field(esc_html__('First Name','b2bking')),
			    'post_status' => 'publish',
			    'post_type' => 'b2bking_custom_field',
			    'post_author' => 1,
			);
			$field_id = wp_insert_post($field);
			
			// set field meta
			update_post_meta($field_id, 'b2bking_custom_field_status', 1);
			update_post_meta($field_id, 'b2bking_custom_field_required', 1);

			if (function_exists('b2bking')){
				b2bking()->update_sort_order(1, $field_id);
			}

			update_post_meta($field_id, 'b2bking_custom_field_registration_role', 'role_'.$b2b_role_id);
			update_post_meta($field_id, 'b2bking_custom_field_editable', 1);
			update_post_meta($field_id, 'b2bking_custom_field_field_type', 'text');
			update_post_meta($field_id, 'b2bking_custom_field_field_label', sanitize_text_field(esc_html__('First Name','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_field_placeholder', sanitize_text_field(esc_html__('Enter your first name here...','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_billing_connection', 'billing_first_name');

			// set option 
			update_option( 'b2bking_first_name_initial_field_id_setting', intval($field_id) );
		}
		

		$last_name_initial_field_id = intval(get_option('b2bking_last_name_initial_field_id_setting', 0));
		// if field does not exist, = 0
		if (intval($last_name_initial_field_id) === 0){

			$field = array(
			    'post_title' => sanitize_text_field(esc_html__('Last Name','b2bking')),
			    'post_status' => 'publish',
			    'post_type' => 'b2bking_custom_field',
			    'post_author' => 1,
			);
			$field_id = wp_insert_post($field);
			
			// set field meta
			update_post_meta($field_id, 'b2bking_custom_field_status', 1);
			update_post_meta($field_id, 'b2bking_custom_field_required', 1);

			if (function_exists('b2bking')){
				b2bking()->update_sort_order(2, $field_id);
			}

			update_post_meta($field_id, 'b2bking_custom_field_registration_role', 'role_'.$b2b_role_id);
			update_post_meta($field_id, 'b2bking_custom_field_editable', 1);
			update_post_meta($field_id, 'b2bking_custom_field_field_type', 'text');
			update_post_meta($field_id, 'b2bking_custom_field_field_label', sanitize_text_field(esc_html__('Last Name','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_field_placeholder', sanitize_text_field(esc_html__('Enter your last name here...','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_billing_connection', 'billing_last_name');

			// set option 
			update_option( 'b2bking_last_name_initial_field_id_setting', intval($field_id) );
		}
	


		$company_name_initial_field_id = intval(get_option('b2bking_company_name_initial_field_id_setting', 0));
		// if field does not exist, = 0
		if (intval($company_name_initial_field_id) === 0){

			$field = array(
			    'post_title' => sanitize_text_field(esc_html__('Company Name','b2bking')),
			    'post_status' => 'publish',
			    'post_type' => 'b2bking_custom_field',
			    'post_author' => 1,
			);
			$field_id = wp_insert_post($field);
			
			// set field meta
			update_post_meta($field_id, 'b2bking_custom_field_status', 1);
			update_post_meta($field_id, 'b2bking_custom_field_required', 0);

			if (function_exists('b2bking')){
				b2bking()->update_sort_order(3, $field_id);
			}

			update_post_meta($field_id, 'b2bking_custom_field_registration_role', 'role_'.$b2b_role_id);
			update_post_meta($field_id, 'b2bking_custom_field_editable', 1);
			update_post_meta($field_id, 'b2bking_custom_field_field_type', 'text');
			update_post_meta($field_id, 'b2bking_custom_field_field_label', sanitize_text_field(esc_html__('Company Name','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_field_placeholder', sanitize_text_field(esc_html__('Enter your company name here...','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_billing_connection', 'billing_company');

			// set option 
			update_option( 'b2bking_company_name_initial_field_id_setting', intval($field_id) );
		}
		
		$street_address_initial_field_id = intval(get_option('b2bking_street_address_initial_field_id_setting', 0));
		// if field does not exist, = 0
		if (intval($street_address_initial_field_id) === 0){

			$field = array(
			    'post_title' => sanitize_text_field(esc_html__('Street Address','b2bking')),
			    'post_status' => 'publish',
			    'post_type' => 'b2bking_custom_field',
			    'post_author' => 1,
			);
			$field_id = wp_insert_post($field);

			// set field meta
			update_post_meta($field_id, 'b2bking_custom_field_status', 1);
			update_post_meta($field_id, 'b2bking_custom_field_required', 1);

			if (function_exists('b2bking')){
				b2bking()->update_sort_order(4, $field_id);
			}

			update_post_meta($field_id, 'b2bking_custom_field_registration_role', 'role_'.$b2b_role_id);
			update_post_meta($field_id, 'b2bking_custom_field_editable', 1);
			update_post_meta($field_id, 'b2bking_custom_field_field_type', 'text');
			update_post_meta($field_id, 'b2bking_custom_field_field_label', sanitize_text_field(esc_html__('Street Address','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_field_placeholder', sanitize_text_field(esc_html__('Enter your address here...','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_billing_connection', 'billing_address_1');

			// set option 
			update_option( 'b2bking_street_address_initial_field_id_setting', intval($field_id) );
		}
		

		$street_address_second_initial_field_id = intval(get_option('b2bking_street_address_second_initial_field_id_setting', 0));
		// if field does not exist, = 0
		if (intval($street_address_second_initial_field_id) === 0){

			$field = array(
			    'post_title' => sanitize_text_field(esc_html__('Address Line 2','b2bking')),
			    'post_status' => 'publish',
			    'post_type' => 'b2bking_custom_field',
			    'post_author' => 1,
			);
			$field_id = wp_insert_post($field);

			// set field meta
			update_post_meta($field_id, 'b2bking_custom_field_status', 1);
			update_post_meta($field_id, 'b2bking_custom_field_required', 0);

			if (function_exists('b2bking')){
				b2bking()->update_sort_order(5, $field_id);
			}

			update_post_meta($field_id, 'b2bking_custom_field_registration_role', 'role_'.$b2b_role_id);
			update_post_meta($field_id, 'b2bking_custom_field_editable', 1);
			update_post_meta($field_id, 'b2bking_custom_field_field_type', 'text');
			update_post_meta($field_id, 'b2bking_custom_field_field_label', sanitize_text_field(esc_html__('Address Line 2','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_field_placeholder', sanitize_text_field(esc_html__('Address line 2...','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_billing_connection', 'billing_address_2');

			// set option 
			update_option( 'b2bking_street_address_second_initial_field_id_setting', intval($field_id) );
		}

		$town_city_initial_field_id = intval(get_option('b2bking_town_city_initial_field_id_setting', 0));
		// if field does not exist, = 0
		if (intval($town_city_initial_field_id) === 0){

			$field = array(
			    'post_title' => sanitize_text_field(esc_html__('Town / City','b2bking')),
			    'post_status' => 'publish',
			    'post_type' => 'b2bking_custom_field',
			    'post_author' => 1,
			);
			$field_id = wp_insert_post($field);

			// set field meta
			update_post_meta($field_id, 'b2bking_custom_field_status', 1);
			update_post_meta($field_id, 'b2bking_custom_field_required', 1);

			if (function_exists('b2bking')){
				b2bking()->update_sort_order(8, $field_id);
			}

			update_post_meta($field_id, 'b2bking_custom_field_registration_role', 'role_'.$b2b_role_id);
			update_post_meta($field_id, 'b2bking_custom_field_editable', 1);
			update_post_meta($field_id, 'b2bking_custom_field_field_type', 'text');
			update_post_meta($field_id, 'b2bking_custom_field_field_label', sanitize_text_field(esc_html__('Town / City','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_field_placeholder', sanitize_text_field(esc_html__('Enter your town / city here...','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_billing_connection', 'billing_city');

			// set option 
			update_option( 'b2bking_town_city_initial_field_id_setting', intval($field_id) );
		}

		$postcode_zip_initial_field_id = intval(get_option('b2bking_postcode_zip_initial_field_id_setting', 0));
		// if field does not exist, = 0
		if (intval($postcode_zip_initial_field_id) === 0){

			$field = array(
			    'post_title' => sanitize_text_field(esc_html__('Postcode / ZIP','b2bking')),
			    'post_status' => 'publish',
			    'post_type' => 'b2bking_custom_field',
			    'post_author' => 1,
			);
			$field_id = wp_insert_post($field);

			// set field meta
			update_post_meta($field_id, 'b2bking_custom_field_status', 1);
			update_post_meta($field_id, 'b2bking_custom_field_required', 1);

			if (function_exists('b2bking')){
				b2bking()->update_sort_order(9, $field_id);
			}

			update_post_meta($field_id, 'b2bking_custom_field_registration_role', 'role_'.$b2b_role_id);
			update_post_meta($field_id, 'b2bking_custom_field_editable', 1);
			update_post_meta($field_id, 'b2bking_custom_field_field_type', 'text');
			update_post_meta($field_id, 'b2bking_custom_field_field_label', sanitize_text_field(esc_html__('Postcode / ZIP','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_field_placeholder', sanitize_text_field(esc_html__('Enter your postcode / ZIP here...','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_billing_connection', 'billing_postcode');

			// set option 
			update_option( 'b2bking_postcode_zip_initial_field_id_setting', intval($field_id) );
		}

		$phone_initial_field_id = intval(get_option('b2bking_phone_initial_field_id_setting', 0));
		// if field does not exist, = 0
		if (intval($phone_initial_field_id) === 0){

			$field = array(
			    'post_title' => sanitize_text_field(esc_html__('Phone Number','b2bking')),
			    'post_status' => 'publish',
			    'post_type' => 'b2bking_custom_field',
			    'post_author' => 1,
			);
			$field_id = wp_insert_post($field);

			// set field meta
			update_post_meta($field_id, 'b2bking_custom_field_status', 1);
			update_post_meta($field_id, 'b2bking_custom_field_required', 1);

			if (function_exists('b2bking')){
				b2bking()->update_sort_order(10, $field_id);
			}

			update_post_meta($field_id, 'b2bking_custom_field_registration_role', 'role_'.$b2b_role_id);
			update_post_meta($field_id, 'b2bking_custom_field_editable', 1);
			update_post_meta($field_id, 'b2bking_custom_field_field_type', 'tel');
			update_post_meta($field_id, 'b2bking_custom_field_field_label', sanitize_text_field(esc_html__('Phone Number','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_field_placeholder', sanitize_text_field(esc_html__('Enter your phone here...','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_billing_connection', 'billing_phone');

			// set option 
			update_option( 'b2bking_phone_initial_field_id_setting', intval($field_id) );
		}

		$country_state_initial_field_id = intval(get_option('b2bking_country_state_initial_field_id_setting', 0));
		// if field does not exist, = 0
		if (intval($country_state_initial_field_id) === 0){

			$field = array(
			    'post_title' => sanitize_text_field(esc_html__('Country + State','b2bking')),
			    'post_status' => 'publish',
			    'post_type' => 'b2bking_custom_field',
			    'post_author' => 1,
			);
			$field_id = wp_insert_post($field);

			// set field meta
			update_post_meta($field_id, 'b2bking_custom_field_status', 1);
			update_post_meta($field_id, 'b2bking_custom_field_required', 1);

			if (function_exists('b2bking')){
				b2bking()->update_sort_order(7, $field_id);
			}

			update_post_meta($field_id, 'b2bking_custom_field_registration_role', 'role_'.$b2b_role_id);
			update_post_meta($field_id, 'b2bking_custom_field_editable', 1);
			update_post_meta($field_id, 'b2bking_custom_field_field_type', 'text');
			update_post_meta($field_id, 'b2bking_custom_field_field_label', sanitize_text_field(esc_html__('Country and State','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_field_placeholder', sanitize_text_field(esc_html__('Enter your country and state here...','b2bking')));
			update_post_meta($field_id, 'b2bking_custom_field_billing_connection', 'billing_countrystate');

			// set option 
			update_option( 'b2bking_country_state_initial_field_id_setting', intval($field_id) );
		}

		// Set up a VAT field by default
		$vat_initial_field_id = intval(get_option('b2bking_vat_initial_field_id_setting', 0));
		// if field does not exist, = 0
		if (intval($vat_initial_field_id) === 0){

			// if the B2B role exists // may be deleted already for older setups
			if (get_post_status(intval(get_option('b2bking_b2b_role_id_setting', 0))) === 'publish' && get_post_type(intval(get_option('b2bking_b2b_role_id_setting', 0))) === 'b2bking_custom_role' ){
				$field = array(
				    'post_title' => sanitize_text_field(esc_html__('VAT','b2bking')),
				    'post_status' => 'publish',
				    'post_type' => 'b2bking_custom_field',
				    'post_author' => 1,
				);
				$field_id = wp_insert_post($field);

				// set field meta
				update_post_meta($field_id, 'b2bking_custom_field_status', 0);
				update_post_meta($field_id, 'b2bking_custom_field_required', 0);

				if (function_exists('b2bking')){
					b2bking()->update_sort_order(11, $field_id);
				}

				update_post_meta($field_id, 'b2bking_custom_field_registration_role', 'role_'.$b2b_role_id);
				update_post_meta($field_id, 'b2bking_custom_field_editable', 1);
				update_post_meta($field_id, 'b2bking_custom_field_field_type', 'text');
				update_post_meta($field_id, 'b2bking_custom_field_field_label', sanitize_text_field(esc_html__('VAT','b2bking')));
				update_post_meta($field_id, 'b2bking_custom_field_field_placeholder', sanitize_text_field(esc_html__('Enter your VAT number here...','b2bking')));
				update_post_meta($field_id, 'b2bking_custom_field_billing_connection', 'billing_vat');

				// set EU countries as default
				update_post_meta($field_id, 'b2bking_custom_field_VAT_countries', 'AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE');

				

				// set option 
				update_option( 'b2bking_vat_initial_field_id_setting', intval($field_id) );
			}

			
		}


		// Check Product Number and User Number. Deactivate products / users selector in dynamic rules if too many
		$users = count_users();
		if (isset($users['avail_roles']['customer'])){
			if (intval($users['avail_roles']['customer']) > 1000){
				// hide users
				update_option('b2bking_customers_panel_ajax_setting', 1);
			}
		}
		

		$products_over_number = get_posts( array(
							'post_type' => array( 'product', 'product_variation'),
							'post_status'=>'publish', 
							'numberposts' => 2000,
							'fields' => 'ids',
						));

		if (count($products_over_number) > 1999){
			// over 500 products and variations
			update_option('b2bking_replace_product_selector_setting', 1);
		} else {
			// do nothing
		}

		$groups = get_posts([
		  'post_type' => 'b2bking_group',
		  'post_status' => 'publish',
		  'numberposts' => -1,
		  'fields' => 'ids',
		]);

		if (apply_filters('b2bking_use_wp_roles', false)){
			// add b2c user WP Role
			add_role(apply_filters('b2bking_b2c_role_name', 'b2bking_role_b2cuser'), esc_html__('B2BKing B2C User','b2bking'), array( 'read' => true));
			// for an existing user, create all groups as roles
			
			foreach ($groups as $group){
				add_role('b2bking_role_'.$group, get_the_title($group), array( 'read' => true));
			}
		}

		if (intval(count($groups)) === 0){
			// there are no groups, let's create a B2B group
			$groupp = array(
				'post_title'  => sanitize_text_field( esc_html__( 'B2B Users', 'b2bking' ) ),
				'post_status' => 'publish',
				'post_type'   => 'b2bking_group',
				'post_author' => 1,
			);
			$group_id = wp_insert_post( $groupp );
		}



		// Upgrade Status
		// for all offers, if they have no status, set to enabled by default
		$offers = get_posts([
		  'post_type' => 'b2bking_offer',
		  'post_status' => 'publish',
		  'numberposts' => -1,
		  'fields' => 'ids',
		]);
		foreach ($offers as $offer){
			$offer_status = get_post_meta($offer,'b2bking_post_status_enabled', true);
			if ($offer_status !== '0' && $offer_status !== '1'){
				update_post_meta($offer,'b2bking_post_status_enabled', 1);
			}
		}
		// group rules same
		$offers = get_posts([
		  'post_type' => 'b2bking_grule',
		  'post_status' => 'publish',
		  'numberposts' => -1,
		  'fields' => 'ids',
		]);
		foreach ($offers as $offer){
			$offer_status = get_post_meta($offer,'b2bking_post_status_enabled', true);
			if ($offer_status !== '0' && $offer_status !== '1'){
				update_post_meta($offer,'b2bking_post_status_enabled', 1);
			}
		}
	}

	private static function b2bking_set_welcome_redirect_state() {
		$user_id = get_current_user_id();

		if ( empty( $user_id ) ) {
			return;
		}

		// Default to showing the welcome page unless we can confirm an active license.
		$show_welcome_page = true;

		$license = get_option( 'b2bking_license_key_setting', '' );
		$email   = get_option( 'b2bking_license_email_setting', '' );
		$welcome_shown_count = intval( get_user_meta( $user_id, 'b2bking_pro_welcome_page_shown_count', true ) );

		// The welcome page is only available when Core is active.
		if ( ! defined( 'B2BKINGCORE_DIR' ) ) {
			$show_welcome_page = false;
		}

		// Existing license details indicate this is not a first-time setup.
		if ( ! empty( $license ) || ! empty( $email ) ) {
			$show_welcome_page = false;
		}

		if ( $welcome_shown_count >= 2 ) {
			$show_welcome_page = false;
		}

		if ( $show_welcome_page ) {
			update_user_meta( $user_id, 'b2bking_redirect_to_welcome_page', 1 );
		} else {
			delete_user_meta( $user_id, 'b2bking_redirect_to_welcome_page' );
		}
	}

}
