<?php
namespace Elex\MultiVendor\Controller;

if ( ! defined( 'ABSPATH' ) ) {
exit;
}

use Elex\MultiVendor\Model\Vendor;
use Elex\MultiVendor\Model\Store;
use WP_User;

class ManageVendors {

	public static $nonce_error_msg = 'Wrong Nonce';


	public static function init() {
		$self = new self();
		add_action( 'elex_mv_manage_vendor_page', array( self::class, 'manage_vendor_page' ) );
		add_action( 'wp_ajax_elex_mv_api_endpoint_for_vendors', array( self::class, 'api_endpoint_for_vendors' ) );
		add_action( 'wp_ajax_elex_mv_update_product_commission', array( self::class, 'elex_mv_update_product_commission' ) );
		add_action( 'wp_ajax_elex_mv_assign_vendor_name_product', array( self::class, 'elex_mv_assign_vendor_name_product' ) );

		add_action( 'wp_ajax_elex_mv_update_vendor_status', array( self::class, 'elex_mv_update_vendor_status' ) );
		add_action( 'wp_ajax_elex_mv_add_vendor_details', array( $self, 'elex_mv_add_vendor_details' ) );
		add_action( 'wp_ajax_elex_mv_enable_disable_vendor', array( $self, 'elex_mv_enable_disable_vendor' ) );
		add_action( 'wp_ajax_elex_mv_edit_vendor_display', array( $self, 'elex_mv_edit_vendor_display' ) );
		add_action( 'wp_ajax_elex_mv_edit_vendor_details', array( $self, 'elex_mv_add_vendor_details' ) );
		add_action( 'wp_ajax_elex_mv_bulk_action_for_manage_vendor', array( $self, 'bulk_action_for_manage_vendor' ) );

		add_action( 'elex_mv_add_commission_to_products_selected', array( $self, 'elex_mv_add_commission_to_products_selected' ) );

		add_action( 'wp_ajax_elex_mv_load_states', array( $self, 'load_states_callback' ) );
		add_action( 'wp_ajax_nopriv_elex_mv_load_states', array( $self, 'load_states_callback' ) );

		add_filter( 'woocommerce_product_data_store_cpt_get_products_query', array( $self, 'handle_custom_query_for_product_commission' ), 10, 2 );
	}


	public static function handle_custom_query_for_product_commission( $query, $query_vars ) {
		
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Internal WooCommerce query filter for data retrieval only.
		if ( ! empty( filter_input( INPUT_POST, 'vendor_id' , FILTER_SANITIZE_NUMBER_INT ) ) ) {
			$query['meta_query'][] = array(
				'key'   => 'elex_mv_store_id',
				'value' => sanitize_text_field( $query_vars['store_id'] ),
			);
		}
	
		return $query;
	}
	
	public function elex_mv_add_commission_to_products_selected( $post_value ) {

		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_manage_vendors_nonce' ) 
		) {
			wp_send_json_error( self::$nonce_error_msg, 403 );
			die();      
		}
  

		$store_id = isset( $post_value['vendor_id'] ) ? sanitize_text_field( $post_value['vendor_id'] ) : '';

		$apply_vendor_commission_switch = !empty( $post_value['apply_vendor_commission_switch'] ) ? true : false; 

		$commission_req = isset( $post_value['commission_amount'] ) ? $post_value['commission_amount'] : ''; 



			$page = 1;


		do {

			$args = array(
				'post_type' => 'product',
				'limit'     => 100,
				'page'      => $page, 
				'store_id'  => $store_id,
						  
			);

				$products_query = new \WC_Product_Query( $args );
				$page_products  = $products_query->get_products();
				
			

			foreach ( $page_products as $product ) {

				$cat_ids = $product->get_category_ids(); 

				
				if ( isset( $post_value['category_commission_switch_vendor_edit'] ) && $post_value['category_commission_switch_vendor_edit'] ) {
	
						$categories_com_selected = isset( $post_value['categories_selected_forCommission'] ) ? $post_value['categories_selected_forCommission'] : array() ;

						$categories_com = isset( $post_value['category_commission_vendor'] ) ? $post_value['category_commission_vendor'] : array() ;
			
						$arr_cat = array();
	
				

					foreach ( $cat_ids as $cate ) {
						
						foreach ( $categories_com_selected as $key_cat => $cate_sel ) {

							
							$falg = 0;
							foreach ( $cate_sel  as $catval ) {
	
								$catval = explode( ':', $catval );
								if ( (int) $catval[0] === (int) $cate ) {
	
										$arr_cat[] = $key_cat;
										$falg      = 1;
	
										break;
								}                           
							}
							if ( 1 === $falg ) {
								break;
							}
						}                   
					}
					if ( ! empty( $arr_cat ) ) {

						$min_index = min( $arr_cat );
	
						$commission_req = $categories_com[ $min_index ];

						

					
					}               
				}
	
				if ( isset( $post_value['product_commission_switch_vendor_edit'] ) && $post_value['product_commission_switch_vendor_edit'] ) {
			
					$products_com_selected = isset( $post_value['products_selected_forCommission'] ) ? $post_value['products_selected_forCommission'] : array() ;

					$products_com = isset( $post_value['product_commission_vendor'] ) ? $post_value['product_commission_vendor'] : array() ;
			
					$arr_cat = array();
	
	
					foreach ( $products_com_selected as $key_cat => $cate_sel ) {
							
						$falg = 0;
						foreach ( $cate_sel  as $catval ) {
	
						
							$catval = explode( ':', $catval );
							if ( (int) $catval[0] === (int) $product->get_id() ) {
	
								
								$commission_req = $products_com[ $key_cat ];

								$falg = 1;
								break;
								

							}                       
						}
						if ( 1 === $falg ) {
							break;
						}                       
					}                 
				}
				if ( empty( $commission_req ) || 0 === $commission_req ) {
					$commission_req = isset( $post_value['commission_amount'] ) ? $post_value['commission_amount'] : ''; 

				}
				if ( ! $apply_vendor_commission_switch ) {
					$admin_params   = get_option( 'elex_mv_admin_installation_params', false );
					$commission_req = $admin_params['commission_for_each_sale'];
				}
				$product->update_meta_data( 'elex_mv_commission', $commission_req );
				$product->save();
				$commission_req = '';
			}
			++$page;
			  


		} while ( ! empty( $page_products ) );
	}

	public function load_states_callback() {
		
		$nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
		if ( ! wp_verify_nonce($nonce, 'elex_mv_load_states_nonce') ) {
			wp_send_json_error(self::$nonce_error_msg, 403);
		}

		if ( is_user_logged_in() ){
			if ( !( current_user_can('manage_woocommerce') || current_user_can('vendor_settings_manage') ) ) {
				wp_send_json_error("You are not allowed to perform this action", 403);
			}
		}

		$country_code = isset($_POST['country']) ? sanitize_text_field(wp_unslash($_POST['country'])) : '';
		if ( empty($country_code) ) {
			wp_send_json_error('Missing country code', 400);
		}

		$states = WC()->countries->get_states($country_code);
		$string_arr = '';

		if ( ! empty( $states ) ) {
			foreach ( $states as $code => $name ) {
				$string_arr .= '<option value="' . esc_attr($code) . '">' . esc_html($name) . '</option>';
			}
		}
		wp_send_json_success($string_arr);
	}

	public static function args_for_vendor( $status = '', $vendor_search = '', $posts_per_page = 7 ) {

		
		$vendor_statuses = self::get_vendor_statuses();
		$numberofposts   = ! empty( $posts_per_page ) ? absint( $posts_per_page ) : 7;


		$args = array(
			'post_type'   => 'elex_vendor',
			'numberposts' => $numberofposts,
		);

		$args['post_status'] = $vendor_statuses;

		if ( ! empty( $status ) ) {
			$args['post_status'] = sanitize_text_field( $status );
		}

		if ( ! empty( $vendor_search ) ) {
			$args['s'] = sanitize_text_field( $vendor_search );
		}

		/**
		 * Include arguments for getting vendors throught the hook below.
		 *
		 * @since 1.0.0
		 */
		return apply_filters( 'elex_mv_api_vendor_args', $args );
	}

	// fetch vendor's commission to display in the woocommerce product page for admin.
	public static function elex_mv_update_product_commission() {
		if ( ! isset( $_GET['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			wp_send_json_error( self::$nonce_error_msg, 403 );
			die();      
		}
		if (  ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'You are not allowed', 403 );
			die();      
		}
		$store_id   = isset( $_GET['vendor_id'] ) ? sanitize_text_field( wp_unslash( $_GET['vendor_id'] ) ) : 0;
		$commission = get_post_meta( $store_id, 'elex_mv_store_commission', true );
	
		wp_send_json_success( $commission, 200 );
	}

	public static function api_endpoint_for_vendors() {
		$nonce = isset( $_GET['nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['nonce'] ) ) : '';
		if ( ! $nonce ) {
			// Return error if the nonce parameter is missing or empty
			wp_send_json_error( self::$nonce_error_msg, 403 );
			wp_die();
		}

		// This function can be called from either the product page or the vendor page, so we check both nonces.
		// The request is blocked only if BOTH verification checks fail.
		if ( ! wp_verify_nonce( $nonce, 'elex_mv_prod_page_nonce' ) 
			&& ! wp_verify_nonce( $nonce, 'elex_mv_manage_vendors_nonce' ) 
		) {
			wp_send_json_error( self::$nonce_error_msg, 403 );
			wp_die();      
		}

		if ( ! is_admin() ) {
			wp_send_json_error( 'You are not allowed', 403 );
			wp_die();      
		}

		$posts_per_page = isset( $_GET['posts_per_page'] ) ? absint( $_GET['posts_per_page'] ) : 7;
		// Fallback if absint results in 0
		if ( 0 === $posts_per_page ) { 
			$posts_per_page = 7; 
		} 

		$status        = isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '';
		$vendor_search = isset( $_GET['vendor_search'] ) ? sanitize_text_field( wp_unslash( $_GET['vendor_search'] ) ) : '';

		$args = self::args_for_vendor( $status, $vendor_search, $posts_per_page );

		
		$vendor_stores = Store::get_stores( $args );
		wp_send_json_success( $vendor_stores, 200 );
	}

	public static function elex_mv_assign_vendor_name_product() {
		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			wp_send_json_error( self::$nonce_error_msg, 403 );
			die();      
		}
		if (  ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'You are not allowed', 403 );
			die();      
		}
		$vendor_name = isset( $_POST['vendor_name'] ) ? sanitize_text_field( wp_unslash( $_POST['vendor_name'] ) ) : '';
		$product_id  = isset( $_POST['product_id'] ) ? sanitize_text_field( wp_unslash( $_POST['product_id'] ) ) : '';

		$product = wc_get_product( $product_id );

		if ( ! empty( $vendor_name ) ) {
			$product->update_meta_data( 'elex_mv_store_id', $vendor_name );
			$product->save();
			wp_send_json_success( 'Success', 200 );
		}
	} 
	
	public function bulk_action_for_manage_vendor() {

		if ( ! isset( $_POST['nonce'] ) ||
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_manage_vendors_nonce' )
		) {
			wp_send_json_error( self::$nonce_error_msg, 403 );
			die();
		}

		$new_status             = isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '';
		$vendors                = isset( $_POST['vendor_ids'] ) ? map_deep( wp_unslash( $_POST['vendor_ids'] ), 'sanitize_text_field' ) : '';
		$message                = isset( $_POST['message'] ) ? sanitize_text_field( wp_unslash( $_POST['message'] ) ) : '';
		$status_array           = array( 'publish', 'private' );
		$status_array_with_pend = array( 'publish', 'private', 'pending' );

		foreach ( $vendors as $vendor_id ) {

			$vendor_obj = get_post( $vendor_id );

			if ( in_array( $vendor_obj->post_status, $status_array, true ) && ( 'reject' === $new_status || 'pending' === $new_status ) ) {
				continue;
			}
		
			if ( in_array( $new_status, $status_array_with_pend, true ) && ( 'reject' === $vendor_obj->post_status ) ) {
				continue;
			}
		
			if ( 'reject' === $new_status ) {

				update_post_meta( $vendor_obj->ID, 'elex_mv_rejection_message', $message );
				$headers   = array();
				$headers[] = 'Content-type: text/html; charset=utf-8';
				$headers[] = 'From:' . get_bloginfo( 'admin_email' );
				$email     = get_post_meta( $store_post->ID, 'elex_mv_email', true );
				$receiver  = $email;
				$subject   = 'Rejection of Vendor Application';
				$body      = 'We are sorry to inform you that your application for being vendor with us is not approved.
				         Reason : ' . $message;
				wp_mail( $receiver, $subject, $body, $headers );
			}

			if ( 'publish' === $new_status ) {

				$ven_user = get_user_by( 'ID', $user_id );

				$display_name = $ven_user->display_name;
				$email        = $ven_user->user_email;
			
	
				$subject = ' Welcome to ' . get_bloginfo( 'name' ) . ' - Your Journey Starts Here!';
				$body    = 'Dear ' . $display_name . ',<br>
	
				We are delighted to welcome you to ' . $store_obj->get_title() . ", where your journey as a seller begins! 🚀 <br>

				Congratulations on successfully onboarding as a vendor with us. We are thrilled to have you as part of our vibrant and growing community of sellers. With your dedication and unique products, we believe you will add tremendous value to our platform.<br><br>
				
				We have equipped you with a powerful Vendor Dashboard, where you can effortlessly manage every aspect of your business. Your dashboard includes the following essential features:<br><br>
				
				1. **Order Management:** Keep track of incoming orders, process them efficiently and ensure timely deliveries to your customers.<br>
				
				2. **Product & Inventory Management:** Easily list your products, update product details, and manage your inventory levels to prevent overselling.<br>
				
				3. **Product Reviews:** Monitor and respond to customer reviews for your products, fostering trust and improving your products based on feedback.<br>
				
				4. **Shipping Options:** Explore various shipping methods and set your preferences to offer flexible shipping solutions to your customers.<br>
				
				5. **Settlement History:** Access historical settlement data to keep tabs on your earnings and financial transactions.<br><br>
				
				This is just the beginning of an exciting journey, and we are confident that your dedication and passion will drive your success on Admin Site. We can't wait to see your business thrive and grow.<br>
				
				Thank you once again for choosing us as your partner. We are here to support you in achieving your goals and reaching new heights.<br>
				
				Welcome aboard, and here's to a prosperous journey ahead!
				
				Best regards,<br>";
	
					
			  
	
				$headers   = array();
				$headers[] = 'Content-type: text/html; charset=utf-8';
				$headers[] = 'From:' . get_bloginfo( 'admin_email' );
				wp_mail( $email, $subject, $body, $headers );

			}
			
			$update = array(
				'ID'          => $vendor_id,
				'post_status' => $new_status,
			);

			if ( in_array( $new_status, $status_array, true ) ) {

				$page     = 1;
				$per_page = 10;
				do {
					$products = wc_get_products(
						array(
							'limit'      => $per_page,
							'page'       => $page,
							'meta_key'   => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
							'meta_value' => $vendor_id, // phpcs:ignore WordPress.DB.SlowDBQuery
						)
					);
				
					if ( $products ) {
						foreach ( $products as $product ) {
							
							if ( 'publish' === $new_status ) {
								$product->set_catalog_visibility( 'visible' );
							} else {
								$product->set_catalog_visibility( 'hidden' );
							}                       
							$product->save();
						}
				
						++$page;
					} else {
						break;
					}               
				} while ( true );
			}
			

			wp_update_post( $update );
		}

		

		wp_send_json_success( array( 'message' => __( 'Updated successfully', 'elex-multi-vendor-for-woocommerce' ) ), 200 );
	}


	public function elex_mv_edit_vendor_display() {

		if ( ! isset( $_POST['nonce'] ) ||
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_manage_vendors_nonce' )
		) {
			wp_send_json_error( self::$nonce_error_msg, 403 );
			die();
		}

		$store_id = isset( $_POST['id'] ) ? sanitize_text_field( wp_unslash( $_POST['id'] ) ) : '';

		$store = get_post( $store_id );
		
		$req_store = Store::load_by_store( $store );

		$admin_params = get_option( 'elex_mv_admin_installation_params', false );

		

		$vendor_info = array(
			'store_image'                            => $req_store->get_image(),
			'store_name'                             => $req_store->get_title(),
			'store_user_name'                        => $req_store->get_user_name(),
			'store_address1'                         => $req_store->get_address1(),
			'store_address2'                         => $req_store->get_address2(),
			'store_email'                            => $req_store->get_email(),
			'store_city'                             => $req_store->get_city(),
			'store_state'                            => $req_store->get_state(),
			'store_country'                          => $req_store->get_country(),
			'store_postal_code'                      => $req_store->get_postal_code(),
			'store_paypal_email'                     => $req_store->get_paypal_email(),
			'store_commission'                       => $req_store->get_commission(),
			'store_phone_number'                     => $req_store->get_phone_number(),
			'store_dial_code'                        => $req_store->get_dial_code(),
			'store_country_iso'                      => $req_store->get_country_iso(),
			'global_capabilities'                    => $req_store->get_global_capabilities_toggle(),
			'apply_vendor_commission_switch'         => $req_store->get_apply_vendor_commission_switch(),

			'category_commission_switch_vendor'      => $req_store->get_category_commission_switch_vendor(),
			'product_commission_switch_vendor'       => $req_store->get_product_commission_switch_vendor(),

			'all_categories_selected_for_commission' => $req_store->get_categories_selected_for_commission(),
			'all_products_selected_for_commission'   => $req_store->get_products_selected_for_commission(),

			'category_commission_vendor'             => $req_store->get_category_commission_vendor(),
			'product_commission_vendor'              => $req_store->get_product_commission_vendor(),

			'global_commission_for_each_sale'        => $admin_params['commission_for_each_sale'],
		);
	
		
		$vendor_info_checkbox = $req_store->get_checkbox_list();

		$vendor_info = array_merge( $vendor_info, $vendor_info_checkbox );
		
	
		wp_send_json_success( $vendor_info );
	}

	public static function get_all_stores( $status = '', $vendor_search = '', $posts_per_page = 7, $page_num = 1 ) {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		$args            = self::args_for_vendor( $status, $vendor_search, $posts_per_page );
		$vendor_statuses = self::get_vendor_statuses();

		$page_number = $args['paged'] = absint( $page_num );
		$vendor_count_by_status = wpFluent()->table( 'posts' )->where( 'post_type', 'elex_vendor' )->whereIn( 'post_status', $vendor_statuses )->groupBy( 'post_status' )->select( wpFluent()->raw( 'count(ID) as count, post_status' ) )->get();

		$vendor_count_by_status = wp_list_pluck( $vendor_count_by_status, 'count', 'post_status' );
  
		$total_stores = array_sum( $vendor_count_by_status );
  
		if ( ! is_array( $args['post_status'] ) ) {
			$total_stores = isset( $vendor_count_by_status[ $args['post_status'] ] ) ? $vendor_count_by_status[ $args['post_status'] ] : 0;
		}

		$total_pages = ceil( $total_stores / $args['numberposts'] );


		$next = null;

		if ( $total_pages > $page_number ) {
			$next = $page_number + 1;
		}

		$prev = null;

		if ( $page_number > 1 ) {
			$prev = $page_number - 1;
		}

		$vendor_stores = Store::get_stores( $args );

		return array(
			'vendor_stores'          => $vendor_stores,
			'prev'                   => $prev,
			'next'                   => $next,
			'page_number'            => $page_number,
			'total_pages'            => $total_pages,
			'total_stores'           => $total_stores,
			'vendor_count_by_status' => $vendor_count_by_status,
		) ;
	}

	private static function fetch_manage_vendor_page_data() {
		$nonce = isset( $_GET['admin_vendor_page_nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['admin_vendor_page_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'admin_vendor_page_nonce' ) ) {
			return array();
		}

		return array(
			'posts_per_page' => isset( $_GET['posts_per_page'] ) ? absint( $_GET['posts_per_page'] ) : 7,
			'status'         => isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '',
			'vendor_search'  => isset( $_GET['vendor_search'] ) ? sanitize_text_field( wp_unslash( $_GET['vendor_search'] ) ) : '',
			'page_num'       => isset( $_GET['page_num'] ) ? absint( $_GET['page_num'] ) : 1,
		);
	}

	public static function manage_vendor_page() {

		$filters = self::fetch_manage_vendor_page_data();

		$posts_per_page = ! empty( $filters['posts_per_page'] ) ? $filters['posts_per_page'] : 7;
		$status         = ! empty( $filters['status'] ) ? $filters['status'] : '';
		$vendor_search  = ! empty( $filters['vendor_search'] ) ? $filters['vendor_search'] : '';
		$page_num       = ! empty( $filters['page_num'] ) ? $filters['page_num'] : 1;

		$vendor_statuses = self::get_vendor_statuses();

		$values_of_stores = self::get_all_stores( $status, $vendor_search, $posts_per_page, $page_num );

		$vendor_stores          = $values_of_stores['vendor_stores'];
		$prev                   = $values_of_stores['prev'];
		$next                   = $values_of_stores['next'];
		$page_number            = $values_of_stores['page_number'];
		$total_pages            = $values_of_stores['total_pages'];
		$total_stores           = $values_of_stores['total_stores'];
		$vendor_count_by_status = $values_of_stores['vendor_count_by_status'];

		global $wp_post_statuses;



		$all_user_ids        = wp_list_pluck( $vendor_stores, 'ID' );
		$all_user_author_ids = wp_list_pluck( $vendor_stores, 'post_author' );

		$all_user_ids = array_unique( $all_user_ids );


		$store_products_count = array();

		$admin_params = get_option( 'elex_mv_admin_installation_params', false );




		if ( ! empty( $all_user_ids ) ) {
			$query_args = array(
				'post_type'      => 'product',
				'post_status'    => 'publish',
				'meta_query'     => array( // phpcs:ignore WordPress.DB.SlowDBQuery
					array(
						'key'     => 'elex_mv_store_id',
						'value'   => $all_user_ids,
						'compare' => 'IN',
					),
				),
				'fields'         => 'ids',
				'posts_per_page' => -1, // This disables the LIMIT clause
			);
			
			
			$query = new \WP_Query( $query_args );
			// Get counts
			$store_products_count = array_count_values(
				array_map(
					function ( $post_id ) {
					return get_post_meta( $post_id, 'elex_mv_store_id', true );
					},
					$query->posts
				)
			); 
		}

		$args = array(
			'include' => $all_user_author_ids, // ID's of users you want to get
			'fields'  => array( 'ID', 'user_email', 'display_name', 'user_url' ),
		);

		$vendor_users = get_users( $args );

		$vendor_users = json_decode( wp_json_encode( $vendor_users ), true );

		$vendors = array();
		foreach ( $vendor_users  as $vendor ) {
				$vendors[ $vendor['ID'] ] = $vendor;
		}

		unset( $vendor_users );


		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/manage-vendors-dashboard/manage-vendors-dashboard.php';
	}

	public static function get_vendor_statuses() {
		$statuses = array(
			'draft',
			'pending',
			'reject',
			'publish',
			'private',
		);

		/**
		 * To include extra  Vendor statuses.  
		 *
		 * @since 1.0.0
		 */
		return apply_filters( 'elex_mv_vendor_statuses', $statuses );
	}

	public static function elex_mv_update_vendor_status() {
		// TODO: validations
		//  is user logged in
		//  has admin caps
		//  isset of status
		//  isset of vendor_ids
		//  is vendor_ids array?

		// nonce check
		if ( ! isset( $_POST['nonce'] ) ||
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_manage_vendors_nonce' )
		) {
			wp_send_json_error( self::$nonce_error_msg, 403 );
			wp_die();
		}
		// admin capability check
		if (  ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'You are not allowed', 403 );
			wp_die();     
		}

		if ( empty( $_POST['status'] ) || empty( $_POST['vendor_ids'] ) || ! is_array( $_POST['vendor_ids'] ) ) {
			wp_send_json_error( 'Invalid request', 403 );
			wp_die();
		}
		$new_status = isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '';
		$vendors    = isset( $_POST['vendor_ids'] ) ? map_deep( wp_unslash( $_POST['vendor_ids'] ) , 'sanitize_text_field' ) : '';
		$message    = isset( $_POST['message'] ) ? sanitize_text_field( wp_unslash( $_POST['message'] ) ) : '';
		
		foreach ( $vendors as $vendor_id ) {

			$store_post = get_post( $vendor_id );
			$store_obj  = Store::load_by_store( $store_post );

			if ( 'reject' === $new_status ) {
			
				update_post_meta( $store_post->ID , 'elex_mv_rejection_message', $message );
				$headers   = array();
				$headers[] = 'Content-type: text/html; charset=utf-8';
				$headers[] = 'From:' . get_bloginfo( 'admin_email' );
				$email     = get_post_meta( $store_post->ID, 'elex_mv_email', true );
				$receiver  = $email;
				$subject   = 'Rejection of Vendor Application';
				$body      = 'We are sorry to inform you that your application for being vendor with us is not approved.
				         Reason : ' . $message;
				wp_mail( $receiver, $subject, $body, $headers );

			} else {
				$user_id  = $store_post->post_author; 
				$ven_user = get_user_by( 'ID', $user_id );
				$ven_user->add_role( 'elex_mv_vendor' );
			}

			if ( 'publish' === $new_status ) {

				$ven_user = get_user_by( 'ID', $user_id );

				$display_name = $ven_user->display_name;
				$email        = $ven_user->user_email;
			
	
				$subject = ' Welcome to ' . get_bloginfo( 'name' ) . ' - Your Journey Starts Here!';
				$body    = 'Dear ' . $display_name . ',<br>
	
				We are delighted to welcome you to ' . $store_obj->get_title() . ", where your journey as a seller begins! 🚀 <br>

				Congratulations on successfully onboarding as a vendor with us. We are thrilled to have you as part of our vibrant and growing community of sellers. With your dedication and unique products, we believe you will add tremendous value to our platform.<br><br>
				
				We have equipped you with a powerful Vendor Dashboard, where you can effortlessly manage every aspect of your business. Your dashboard includes the following essential features:<br><br>
				
				1. **Order Management:** Keep track of incoming orders, process them efficiently and ensure timely deliveries to your customers.<br>
				
				2. **Product & Inventory Management:** Easily list your products, update product details, and manage your inventory levels to prevent overselling.<br>
				
				3. **Product Reviews:** Monitor and respond to customer reviews for your products, fostering trust and improving your products based on feedback.<br>
				
				4. **Shipping Options:** Explore various shipping methods and set your preferences to offer flexible shipping solutions to your customers.<br>
				
				5. **Settlement History:** Access historical settlement data to keep tabs on your earnings and financial transactions.<br><br>
				
				This is just the beginning of an exciting journey, and we are confident that your dedication and passion will drive your success on Admin Site. We can't wait to see your business thrive and grow.<br>
				
				Thank you once again for choosing us as your partner. We are here to support you in achieving your goals and reaching new heights.<br>
				
				Welcome aboard, and here's to a prosperous journey ahead!
				
				Best regards,<br>";
	
					
			  
	
				$headers   = array();
				$headers[] = 'Content-type: text/html; charset=utf-8';
				$headers[] = 'From:' . get_bloginfo( 'admin_email' );
				wp_mail( $email, $subject, $body, $headers );

			}
			$update = array(
				'ID'          => $vendor_id,
				'post_status' => $new_status,
			);
			wp_update_post( $update );

		}


		wp_send_json_success( array( 'message' => __( 'Updated successfully', 'elex-multi-vendor-for-woocommerce' ) ), 200 );
	}

	public function elex_mv_enable_disable_vendor() {

		if ( ! isset( $_POST['nonce'] ) ||
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_manage_vendors_nonce' )
		) {
			wp_send_json_error( self::$nonce_error_msg, 403 );
			die();
		}


		$new_status = isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '';
		$vendors    = isset( $_POST['vendor_ids'] ) ? map_deep( wp_unslash( $_POST['vendor_ids'] ), 'sanitize_text_field' ) : '';


		foreach ( $vendors as $vendor_id ) {
			$update = array(
				'ID'          => $vendor_id,
				'post_status' => $new_status,
			);
			$args   = array(
				'post_type'  => 'product',
				'meta_key'   => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value' => $vendor_id, // phpcs:ignore WordPress.DB.SlowDBQuery            
			);
			$posts  = get_posts( $args );


			foreach ( $posts as $post ) {
				$product = wc_get_product( $post->ID );

				if ( 'private' === $new_status ) {
					$product->set_catalog_visibility( 'hidden' );
				} else {
					$product->set_catalog_visibility( 'visible' );
				}
				$product->save();
				
			}

			wp_update_post( $update );
		}

	

		wp_send_json_success( array( 'message' => __( 'Updated successfully', 'elex-multi-vendor-for-woocommerce' ) ), 200 );
	}


	public function manage_categories_function( $vendor_info, $store ) {
	
		if ( isset( $vendor_info['category_commission_switch_vendor_edit'] ) && $vendor_info['category_commission_switch_vendor_edit'] ) {
			$store->set_category_commission_switch_vendor( true );
		} else {
			$store->set_category_commission_switch_vendor( false );

		}

		if ( isset( $vendor_info['product_commission_switch_vendor_edit'] ) && $vendor_info['product_commission_switch_vendor_edit'] ) {
			$store->set_product_commission_switch_vendor( true );
		} else {
			$store->set_product_commission_switch_vendor( false );

		}
	}

	public function elex_mv_add_vendor_details() {
		$self = new self();
		if ( ! isset( $_POST['nonce'] ) ||
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_manage_vendors_nonce' )
		) {
			wp_send_json_error( self::$nonce_error_msg, 403 );
			die();
		}

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Insufficient permissions.', 403 );
			die();
		}


		$new_vendor_array       = array();
		$new_vendor_array_check = array();

		$vendor_info_post = array(
			'vendor_id'                              => isset( $_POST['vendor_id'] ) ? absint( $_POST['vendor_id'] ) : 0,
			'apply_vendor_commission_switch'         => isset( $_POST['apply_vendor_commission_switch'] ),
			'commission_amount'                      => isset( $_POST['commission_amount'] ) ? sanitize_text_field( wp_unslash( $_POST['commission_amount'] ) ) : '',
			'category_commission_switch_vendor_edit' => isset( $_POST['category_commission_switch_vendor_edit'] ),
			'product_commission_switch_vendor_edit'  => isset( $_POST['product_commission_switch_vendor_edit'] ),
			'categories_selected_forCommission'      => isset( $_POST['categories_selected_forCommission'] ) ? map_deep( wp_unslash( $_POST['categories_selected_forCommission'] ), 'sanitize_text_field' ) : array(),
			'category_commission_vendor'             => isset( $_POST['category_commission_vendor'] ) ? map_deep( wp_unslash( $_POST['category_commission_vendor'] ), 'sanitize_text_field' ) : array(),
			'products_selected_forCommission'        => isset( $_POST['products_selected_forCommission'] ) ? map_deep( wp_unslash( $_POST['products_selected_forCommission'] ), 'sanitize_text_field' ) : array(),
			'product_commission_vendor'              => isset( $_POST['product_commission_vendor'] ) ? map_deep( wp_unslash( $_POST['product_commission_vendor'] ), 'sanitize_text_field' ) : array(),
		);

		/**
		 * For applying vendor commission.
		 *
		 * @since 1.0.0
		 */
		do_action( 'elex_mv_add_commission_to_products_selected', $vendor_info_post );


		$new_vendor_array['user_name']      = isset( $_POST['user_name'] ) ? sanitize_text_field( wp_unslash( $_POST['user_name'] ) ) : '';
		$new_vendor_array['prev_user_name'] = isset( $_POST['prev_user_name'] ) ? sanitize_text_field( wp_unslash( $_POST['prev_user_name'] ) ) : '';

		$new_vendor_array['add_vendor']      = isset( $_POST['add_vendor'] ) ? sanitize_text_field( wp_unslash( $_POST['add_vendor'] ) ) : '';
		$new_vendor_array['add_vendor_page'] = isset( $_POST['add_vendor_page'] ) ? sanitize_text_field( wp_unslash( $_POST['add_vendor_page'] ) ) : '';
		$new_vendor_array['edit_page']       = isset( $_POST['edit_page'] ) ? sanitize_text_field( wp_unslash( $_POST['edit_page'] ) ) : '';

		$new_vendor_array['store_name']      = isset( $_POST['store_name'] ) ? sanitize_text_field( wp_unslash( $_POST['store_name'] ) ) : '';
		$new_vendor_array['prev_store_name'] = isset( $_POST['prev_store_name'] ) ? sanitize_text_field( wp_unslash( $_POST['prev_store_name'] ) ) : '';

		$new_vendor_array['first_page'] = isset( $_POST['first_page'] ) ? sanitize_text_field( wp_unslash( $_POST['first_page'] ) ) : '';

		$new_vendor_array['categories_selected_forCommission'] = isset( $_POST['categories_selected_forCommission'] ) ? map_deep( wp_unslash( $_POST['categories_selected_forCommission'] ), 'sanitize_text_field' ) : array();
		$new_vendor_array['products_selected_forCommission']   = isset( $_POST['products_selected_forCommission'] ) ? map_deep( wp_unslash( $_POST['products_selected_forCommission'] ), 'sanitize_text_field' ) : array();

		$new_vendor_array['category_commission_vendor'] = isset( $_POST['category_commission_vendor'] ) ? map_deep( wp_unslash( $_POST['category_commission_vendor'] ), 'sanitize_text_field' ) : array();
		$new_vendor_array['product_commission_vendor']  = isset( $_POST['product_commission_vendor'] ) ? map_deep( wp_unslash( $_POST['product_commission_vendor'] ), 'sanitize_text_field' ) : array();


		$user_already = get_user_by( 'login', $new_vendor_array['user_name'] );

	// phpcs:ignore

		if ( $new_vendor_array['edit_page'] && 'yes' === $new_vendor_array['first_page'] ) {

			if ( $new_vendor_array['store_name'] && $new_vendor_array['store_name'] !== $new_vendor_array['prev_store_name'] ) {


				$posts = get_posts(
					array( 
						'title'       => $new_vendor_array['store_name'], 
						'post_type'   => 'elex_vendor',
						'post_status' => 'any',

					) 
				);

				if ( ! empty( $posts ) ) {

						wp_die( 'Store name already present.' );
				}         
			}

			if ( $new_vendor_array['user_name'] !== $new_vendor_array['prev_user_name'] && $user_already ) {
				wp_die( 'User already a registered user.' );
			}     
		}

		if ( $new_vendor_array['add_vendor_page'] && 'yes' === $new_vendor_array['first_page'] ) {

			if ( $new_vendor_array['store_name'] ) {


				$posts = get_posts(
					array( 
						'title'       => $new_vendor_array['store_name'], 
						'post_type'   => 'elex_vendor',
						'post_status' => 'any',

					) 
				);

				if ( ! empty( $posts ) ) {

						wp_die( 'Store name already present.' );
				}         
			}

			if ( $user_already ) {
				wp_die( 'User already a registered user.' );
			}     
		}

		if ( $new_vendor_array['add_vendor_page'] && 'yes' === $new_vendor_array['first_page'] ) {

			if ( $new_vendor_array['store_name'] ) {


				$posts = get_posts(
					array( 
						'name'      => $new_vendor_array['store_name'], 
						'post_type' => 'elex_vendor',
					) 
				);

				if ( ! empty( $posts ) ) {

						wp_die( 'Store name already present.' );
				}         
			}

			if ( $user_already ) {
				wp_die( 'User already a registered user.' );
			}     
		}
	 

		$new_vendor_array['store_name']   = isset( $_POST['store_name'] ) ? sanitize_text_field( wp_unslash( $_POST['store_name'] ) ) : '';
		$new_vendor_array['email_id']     = isset( $_POST['email_id'] ) ? sanitize_text_field( wp_unslash( $_POST['email_id'] ) ) : '';
		$new_vendor_array['phone_number'] = isset( $_POST['phone_number'] ) ? sanitize_text_field( wp_unslash( $_POST['phone_number'] ) ) : '';

		$new_vendor_array['dial_code']   = isset( $_POST['dial_code'] ) ? sanitize_text_field( wp_unslash( $_POST['dial_code'] ) ) : '';
		$new_vendor_array['country_iso'] = isset( $_POST['country_iso'] ) ? sanitize_text_field( wp_unslash( $_POST['country_iso'] ) ) : '';

		$new_vendor_array['user_id']   = isset( $_POST['user_id'] ) ? sanitize_text_field( wp_unslash( $_POST['user_id'] ) ) : '';
		$new_vendor_array['vendor_id'] = isset( $_POST['vendor_id'] ) ? sanitize_text_field( wp_unslash( $_POST['vendor_id'] ) ) : '';

		$new_vendor_array['status'] = isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '';

	  
		$new_vendor_array['store_full_addr1'] = isset( $_POST['store_full_addr1'] ) ? sanitize_text_field( wp_unslash( $_POST['store_full_addr1'] ) ) : '';
		$new_vendor_array['store_full_addr2'] = isset( $_POST['store_full_addr2'] ) ? sanitize_text_field( wp_unslash( $_POST['store_full_addr2'] ) ) : '';

		$new_vendor_array['city']              = isset( $_POST['city'] ) ? sanitize_text_field( wp_unslash( $_POST['city'] ) ) : '';
		$new_vendor_array['postal_code']       = isset( $_POST['postal_code'] ) ? sanitize_text_field( wp_unslash( $_POST['postal_code'] ) ) : '';
		$new_vendor_array['state']             = isset( $_POST['state'] ) ? sanitize_text_field( wp_unslash( $_POST['state'] ) ) : '';
		$new_vendor_array['country']           = isset( $_POST['country'] ) ? sanitize_text_field( wp_unslash( $_POST['country'] ) ) : '';
		$new_vendor_array['paypal_email']      = isset( $_POST['paypal_email'] ) ? sanitize_text_field( wp_unslash( $_POST['paypal_email'] ) ) : '';
		$new_vendor_array['commission_amount'] = isset( $_POST['commission_amount'] ) ? sanitize_text_field( wp_unslash( $_POST['commission_amount'] ) ) : 0;
		$new_vendor_array['bypass_validation'] = isset( $_POST['bypass_validation'] ) ? sanitize_text_field( wp_unslash( $_POST['bypass_validation'] ) ) : '';
		$new_vendor_array['is_setup_finished'] = isset( $_POST['is_setup_finished'] ) ? sanitize_text_field( wp_unslash( $_POST['is_setup_finished'] ) ) : '';

		$new_vendor_array['image_name'] = isset( $_FILES['elex-multi-vendor-for-woocommerce-vendor-filetag']['name'] ) ? sanitize_text_field( $_FILES['elex-multi-vendor-for-woocommerce-vendor-filetag']['name'] ) : '';
		$new_vendor_array['image_path'] = isset( $_FILES['elex-multi-vendor-for-woocommerce-vendor-filetag']['tmp_name'] ) ? sanitize_text_field( $_FILES['elex-multi-vendor-for-woocommerce-vendor-filetag']['tmp_name'] ) : '';
		$new_vendor_array['image_type'] = isset( $_FILES['elex-multi-vendor-for-woocommerce-vendor-filetag']['type'] ) ? sanitize_text_field( $_FILES['elex-multi-vendor-for-woocommerce-vendor-filetag']['type'] ) : '';

		// check vendor image allowed format
		if ( ! empty( $new_vendor_array['image_name'] ) ) {
			if ( ! elex_mv_is_valid_image_file( $new_vendor_array['image_name'], $new_vendor_array['image_path'] ) ) {
				wp_send_json_error( array( 'vendor_image' => array( __( 'Unsupported image format.', 'elex-multi-vendor-for-woocommerce' ) ) ), 422 );
			}
		}
	  
		$new_vendor_array['deleted_image'] = isset( $_POST['deleted_image'] ) && sanitize_text_field( wp_unslash( $_POST['deleted_image'] ) ) ? 1 : 0;

		$new_vendor_array['apply_vendor_commission_switch'] = isset( $_POST['apply_vendor_commission_switch'] ) ? true : false;


		$new_vendor_array['for_checkBox'] = isset( $_POST['for_checkBox'] ) ? true : false;

		$new_vendor_array_check['global_capabilities'] = isset( $_POST['global_capabilities'] ) ? true : false;

		$new_vendor_array_check['vendor_to_sell_without_approval'] = isset( $_POST['vendor_to_sell_without_approval'] ) ? true : false;
		$new_vendor_array_check['vendor_to_allow_vendor_shipping'] = isset( $_POST['vendor_to_allow_vendor_shipping'] ) ? true : false;

	// phpcs:ignore
	  
		$new_vendor_array_check['vendor_to_override_creds'] = isset( $_POST['vendor_to_override_creds'] ) ? true : false;

		$new_vendor_array_check['vendor_to_choose_ship_services']               = isset( $_POST['vendor_to_choose_ship_services'] ) ? true : false;
		$new_vendor_array_check['vendor_to_use_flat_rate_service_set_by_admin'] = isset( $_POST['vendor_to_use_flat_rate_service_set_by_admin'] ) ? true : false;
		$new_vendor_array_check['vendor_to_change_order_status']                = isset( $_POST['vendor_to_change_order_status'] ) ? true : false;
		$new_vendor_array_check['vendor_to_generate_coupons']                   = isset( $_POST['vendor_to_generate_coupons'] ) ? true : false;
		$new_vendor_array_check['vendor_to_create_category']                    = isset( $_POST['vendor_to_create_category'] ) ? true : false;

		$new_vendor_array_check['show_vendor_detail_on_woocom_store_page']   = isset( $_POST['show_vendor_detail_on_woocom_store_page'] ) ? true : false;
		$new_vendor_array_check['show_vendor_detail_on_woocom_product_page'] = isset( $_POST['show_vendor_detail_on_woocom_product_page'] ) ? true : false;
		

		$validation_errors = $self->elex_mv_form_vendor_validation( $new_vendor_array );
  
		if ( isset( $validation_errors['errors'] ) && count( $validation_errors['errors'] ) ) {
			wp_send_json_error( $validation_errors['errors'], 422 );
		}
  
		$new_user_id = $new_vendor_array['user_id'] ; 
		if ( ! $new_user_id ) {

			if ( isset( $new_vendor_array['vendor_id'] ) && ! empty( $new_vendor_array['vendor_id'] ) ) {
				$new_user_post = get_post( $new_vendor_array['vendor_id'] );

	
				$new_user_id = $new_user_post->post_author;
	
				$new_user = get_user_by( 'id', $new_user_id );


			} else {
				$password    = wp_generate_password();
				$userdata    = array(
					'user_login' => $new_vendor_array['user_name'],
					'user_pass'  => $password,
					'user_email' => $new_vendor_array['email_id'],
					'role'       => 'elex_mv_vendor',
				);
				// This is a multi-vendor plugin, so wp_insert_user function call is necessary.
				// It is used here to register new vendor accounts on the site.
				// Security is handled via strict nonce and capability checks.
				$new_user_id = wp_insert_user( $userdata );
				if ( is_wp_error( $new_user_id ) ) {
					wp_send_json_error( $new_user_id->get_error_message(), 422 );
					die;
				}
	  
				$new_user = new WP_User( $new_user_id );

			}
		} elseif ( $new_user_id ) {
			$new_user = get_user_by( 'id', $new_user_id );
			
		}   
		$vendor_info = Vendor::load( $new_user ); 
		$store       = new Store();

		if ( $vendor_info->has_store() || $vendor_info->had_store() ) {
			$store = $vendor_info->get_store();
		} else {
			$new_vendor_array_check = $store->get_checkbox_list();
		}
		

		$store->set_vendor( $vendor_info );
  
		self::manage_categories_function( $vendor_info_post, $store );

		if ( isset( $new_vendor_array['store_name'] ) ) {
			$store->set_title( sanitize_text_field( $new_vendor_array['store_name'] ) );
		}
		if ( isset( $new_vendor_array_check['global_capabilities'] ) && $new_vendor_array_check['global_capabilities'] ) {
		

			$store->set_global_capabilities_toggle( true );
		} else {
		
			$store->set_global_capabilities_toggle( false );

		}
		if ( $new_vendor_array['apply_vendor_commission_switch'] ) {
			$store->set_apply_vendor_commission_switch( $new_vendor_array['apply_vendor_commission_switch'] );

		} else {
			$store->set_apply_vendor_commission_switch( false );

		}
			
		if ( isset( $new_vendor_array['status'] ) ) {       
			$store->set_status( $new_vendor_array['status'] );
		}

		

		if ( isset( $new_vendor_array['categories_selected_forCommission'] ) ) {       
			$store->set_categories_selected_for_commission( $new_vendor_array['categories_selected_forCommission'] );
		}
		if ( isset( $new_vendor_array['products_selected_forCommission'] ) ) {       
			$store->set_products_selected_for_commission( $new_vendor_array['products_selected_forCommission'] );
		}

		if ( isset( $new_vendor_array['category_commission_vendor'] ) ) {       
			$store->set_category_commission_vendor( $new_vendor_array['category_commission_vendor'] );
		}
		if ( isset( $new_vendor_array['product_commission_vendor'] ) ) {       
			$store->set_product_commission_vendor( $new_vendor_array['product_commission_vendor'] );
		}

		if ( isset( $new_vendor_array['phone_number'] ) ) {
			$store->set_phone_number( sanitize_text_field( $new_vendor_array['phone_number'] ) );
		}
		if ( isset( $new_vendor_array['dial_code'] ) ) {
			$store->set_dial_code( sanitize_text_field( $new_vendor_array['dial_code'] ) );
		}
		if ( isset( $new_vendor_array['country_iso'] ) ) {
			$store->set_country_iso( sanitize_text_field( $new_vendor_array['country_iso'] ) );
		}
		if ( isset( $new_vendor_array['user_name'] ) ) {
			$store->set_user_name( sanitize_text_field( $new_vendor_array['user_name'] ) );
		}
		if ( isset( $new_vendor_array['user_id'] ) ) {
			$store->set_user_id( sanitize_text_field( $new_vendor_array['user_id'] ) );
		}
		if ( isset( $new_vendor_array['email_id'] ) ) {
			$store->set_email( sanitize_text_field( $new_vendor_array['email_id'] ) );
		}
		if ( isset( $new_vendor_array['store_full_addr2'] ) ) {
			$store->set_address1( sanitize_text_field( $new_vendor_array['store_full_addr1'] ) );
		}
		if ( isset( $new_vendor_array['store_full_addr1'] ) ) {
			$store->set_address2( sanitize_text_field( $new_vendor_array['store_full_addr2'] ) );
		}
		if ( isset( $new_vendor_array['city'] ) ) {
			$store->set_city( sanitize_text_field( $new_vendor_array['city'] ) );
		}
		if ( isset( $new_vendor_array['state'] ) ) {
			$store->set_state( sanitize_text_field( $new_vendor_array['state'] ) );
		}
		if ( isset( $new_vendor_array['postal_code'] ) ) {
			$store->set_postal_code( sanitize_text_field( $new_vendor_array['postal_code'] ) );
		}
		if ( isset( $new_vendor_array['country'] ) ) {
			$store->set_country( sanitize_text_field( $new_vendor_array['country'] ) );
		}
		if ( isset( $new_vendor_array['paypal_email'] ) ) {
			$store->set_paypal_email( sanitize_text_field( $new_vendor_array['paypal_email'] ) );
		}       
		if ( isset( $new_vendor_array['commission_amount'] ) ) {
			$store->set_commission( sanitize_text_field( $new_vendor_array['commission_amount'] ) );
		}       
		if ( isset( $new_vendor_array['is_setup_finished'] ) && isset( $new_vendor_array['status'] ) && 'publish' === $new_vendor_array['status'] ) {
			$store->set_is_setup_finished( sanitize_text_field( $new_vendor_array['is_setup_finished'] ) );
		}
		if ( isset( $new_vendor_array['image_name'] ) ) {
			$store->set_image( $new_vendor_array );
		}
		if ( isset( $new_vendor_array['deleted_image'] ) ) {
			$store->set_delete_image( $new_vendor_array['deleted_image'] );
		}
	
		if ( $new_vendor_array['for_checkBox'] ) {
			$store->set_checkbox_list( $new_vendor_array_check );
		}

		$current_timestamp = current_time( 'timestamp' ); // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested
		$formatted_date    = wp_date( 'Y-m-d H:i:s', $current_timestamp );
		$store->set_creation_date( $formatted_date );
	
		$display_name = $new_user->display_name;
		$email        = $new_user->user_email;
		$adt_rp_key   = get_password_reset_key( $new_user );
		$user_login   = $new_user->user_login;

		$rp_link      = '<a href="' . network_site_url( "wp-login.php?action=rp&key=$adt_rp_key&login=" . rawurlencode( $user_login ), 'login' ) . '">Set Password</a>';
		$admin_params = get_option( 'elex_mv_admin_installation_params', false );


		$subject = 'Your Vendor Account has been Created - Set Your Password';
		$body    = 'Dear ' . $display_name . ',<br>

			  We are thrilled to welcome you to ' . get_bloginfo( 'name' ) . "!<br>

			  Your vendor account has been successfully created, and we're excited to have you on board. Below are your account details:<br>
			  - **Username/Email ID:**" . $store->get_email() . '<br>
			  - **Store URL:**' . esc_url( home_url( '/' . $admin_params['elex_mv_store_slug'] . '/' . $new_vendor_array['store_name'] ) ) . ' <br>

			  
			  To get started, you need to set your password. Click on the button below to set your password and access your vendor dashboard:<br>'

				. $rp_link . "<br>

			  If you have any questions or encounter any issues during the password setup process, please don't hesitate to reach out to us. We are here to assist you every step of the way.<br>

			  Thank you for joining " . get_bloginfo( 'name' ) . ' We look forward to seeing your store thrive on our platform!<br>

			  Best regards, <br>'

				. get_bloginfo( 'name' ) . '<br>'
				. get_bloginfo( 'url' ) . '<br>'
				. get_bloginfo( 'admin_email' ) . '<br>';
	

		$headers   = array();
		$headers[] = 'Content-type: text/html; charset=utf-8';
		$headers[] = 'From:' . get_bloginfo( 'admin_email' );
  
		if ( isset( $new_vendor_array['add_vendor'] ) && 'yes' === $new_vendor_array['add_vendor'] ) {
			wp_mail( $email, $subject, $body, $headers );
		}
		$store->create();
		wp_send_json_success( $new_user_id, 200 );
		die;
	}

	public function elex_mv_form_vendor_validation( $new_product_array ) {
	
		global $wpdb;

		$data = array(
			'message' => __( 'Empty Fields' , 'elex-multi-vendor-for-woocommerce' ),
			'errors'  => array(),
		);
  
		if ( ! isset( $new_product_array['store_name'] ) || empty( $new_product_array['store_name'] ) ) {
			$data['errors']['store_name'][] = __( 'Please enter store name', 'elex-multi-vendor-for-woocommerce' );
		}
		if ( ! isset( $new_product_array['user_name'] ) || empty( $new_product_array['user_name'] ) ) {
			$data['errors']['user_name'][] = __( 'Please enter user name', 'elex-multi-vendor-for-woocommerce' );
		} elseif ( ! $new_product_array['bypass_validation'] && username_exists( $new_product_array['user_name'] ) ) {
			$data['errors']['user_name'][] = __( 'Already Exist', 'elex-multi-vendor-for-woocommerce' );

		}
		if ( ! isset( $new_product_array['email_id'] ) || empty( $new_product_array['email_id'] ) ) {

			$data['errors']['email_id'][] = __( 'Please enter email id', 'elex-multi-vendor-for-woocommerce' );

		} elseif ( isset( $new_product_array['email_id'] ) ) {
			$validate = self::isValidEmail( $new_product_array['email_id'] );

			if ( ! $validate ) {
				$data['errors']['email_id'][] = __( 'Please enter valid email address', 'elex-multi-vendor-for-woocommerce' );
			}
		}  
		

		/**
		 * For form validation parameter.  
		 *
		 * @since 1.0.0
		 */
		$data = apply_filters( 'elex_mv_form_vendor_validation', $data );


		return $data;
	}
	public static function isValidEmail( $email ) {
		// Use a regular expression to check if the email format is valid
		$pattern = '/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';
		
		if ( preg_match( $pattern, $email ) ) {
			// Use the filter_var function to further validate the email
			if ( filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
				return true;
			}
		}
	
		return false;
	}
}
