<?php
namespace Elex\MultiVendor\Controller;

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

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



class ProductController {

	public static $nonce_error_msg = 'Wrong Nonce';


	public static function init() {
		$self = new self();



		add_action( 'woocommerce_after_single_product', array( $self, 'elex_mv_add_views_count' ) );
		add_action( 'wp_ajax_elex_mv_edit_product_display', array( $self, 'ajax_elex_mv_edit_product_display' ) );
		add_action( 'wp_ajax_elex_mv_edit_product', array( $self, 'elex_mv_add_product_details' ) );
		add_action( 'wp_ajax_elex_mv_toggle_page_link', array( $self, 'elex_mv_toggle_page_link' ) );
		add_action( 'wp_ajax_elex_mv_export', array( $self, 'elex_mv_export' ) );
		add_action( 'wp_ajax_elex_mv_cat_search_with_entered_val', array( $self, 'elex_mv_cat_search_with_entered_val' ) );


		add_action( 'wp_ajax_elex_mv_json_search_taxonomy_terms', array( $self, 'json_search_taxonomy_terms' ) );

		add_action( 'wp_ajax_elex_mv_add_new_attributes', array( $self, 'add_new_attributes' ) );

		add_action( 'wp_ajax_elex_mv_save_image_wordpress', array( $self, 'elex_mv_save_image_wordpress' ) );

		add_action( 'wp_ajax_elex_mv_save_attributes', array( $self, 'save_attributes' ) );

		add_action( 'wp_ajax_elex_mv_link_all_variations', array( $self, 'elex_mv_link_all_variations' ) );

		add_action( 'wp_ajax_elex_mv_load_variations', array( $self, 'elex_mv_load_variations' ) );

		add_action( 'wp_ajax_elex_mv_load_data_manual_variations', array( $self, 'elex_mv_load_data_manual_variations' ) );

		add_action( 'wp_ajax_elex_mv_save_variations', array( $self, 'elex_mv_save_variations' ) );

		add_action( 'wp_ajax_elex_mv_delete_variations', array( $self, 'elex_mv_delete_variations' ) );

		add_action( 'woocommerce_admin_process_variation_object', array( $self, 'elex_mv_save_variation_image' ), 2, 10 ); 

		add_action( 'wp_ajax_elex_mv_add_product_details', array( $self, 'elex_mv_add_product_details' ) );

	
		add_action( 'wp_ajax_elex_mv_delete_product', array( $self, 'elex_mv_delete_product' ) );
		
		
		add_action( 'elex_mv_product_page', array( $self, 'elex_mv_product_page' ) );
		add_action( 'elex_mv_product_page_tab_product', array( $self, 'elex_mv_product_page_tab_product' ) );

		add_action( 'wp_ajax_elex_mv_api_endpoint_for_products', array( $self, 'api_endpoint_for_products' ) );

		add_action( 'wp_ajax_elex_mv_api_endpoint_for_categories', array( $self, 'api_endpoint_for_categories' ) );

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

		add_action( 'elex_mv_add_product_tab_content_product_details', array( $self, 'elex_add_product_content_tab_product_details' ) );
		add_action( 'elex_mv_add_product_tab_content_inventory', array( $self, 'elex_add_product_content_tab_inventory' ) );
		add_action( 'elex_mv_add_product_tab_content_attributes', array( $self, 'elex_add_product_content_tab_attributes' ) );
		add_action( 'elex_mv_add_product_tab_content_variations', array( $self, 'elex_add_product_content_tab_variations' ) );
		add_action( 'elex_mv_add_product_tab_content_shipping', array( $self, 'elex_add_product_content_tab_shipping' ) );
		add_action( 'elex_mv_add_product_tab_content_carriers', array( $self, 'elex_add_product_content_tab_carriers' ) );

		add_action( 'elex_mv_edit_attributes_product_tab_content', array( $self, 'elex_mv_edit_attributes_product_tab_content' ) );
		add_action( 'elex_mv_edit_variations_product_tab_content', array( $self, 'elex_mv_edit_variations_product_tab_content' ) );

		add_action( 'elex_mv_add_advanced_filter_page', array( $self, 'elex_mv_advanced_filter_page' ) );
		
		add_filter( 'elex_mv_form_add_product_validation', array( $self, 'elex_mv_form_validation' ) );
		add_filter( 'elex_mv_form_edit_product_validation', array( $self, 'elex_mv_form_edit_validation' ) );

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

	public static function elex_mv_save_image_wordpress() {


		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			return;
		}

		if ( ! current_user_can( 'elex_mv_vendor' ) && ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		$upload_dir = wp_upload_dir();

		$image_name = isset( $_FILES['file']['name'] ) ? sanitize_text_field( $_FILES['file']['name'] ) : ''; // images url array of product
		$image_path = isset( $_FILES['file']['tmp_name'] ) ? sanitize_text_field( $_FILES['file']['tmp_name'] ) : '';
		$image_type = isset( $_FILES['file']['type'] ) ? sanitize_text_field( $_FILES['file']['type'] ) : '';

		$ext_file = explode( '.', $image_name )[1];
		

		$hashed_filename = md5( $image_name . microtime( true ) ) . '.' . $ext_file   ;
	
		$upload_path = $upload_dir['basedir'] . '/' . $hashed_filename;
		global $wp_filesystem;
		if ( empty( $wp_filesystem ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
			WP_Filesystem();
		}
		$wp_filesystem->move( $image_path, $upload_path ); 
		// Save the image in the uploads directory.
	

		$attachment = array(
			'post_mime_type' => $image_type,
			'post_title'     => $hashed_filename,
			'post_content'   => '',
			'post_status'    => 'inherit',
			'guid'           => $upload_dir['url'] . '/' . basename( $hashed_filename ), 
		);
	
		$attach_id = wp_insert_attachment( $attachment, $upload_path );


		wp_send_json_success( wp_get_attachment_url( $attach_id ) );

		// return $attach_id;
	}

	public static function elex_mv_delete_variations() {

		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			return;
		}

		if ( isset( $_POST['variation_ids'] ) ) {
			$variation_ids = array_map( 'absint', (array) wp_unslash( $_POST['variation_ids'] ) );

			foreach ( $variation_ids as $variation_id ) {
				if ( 'product_variation' === get_post_type( $variation_id ) ) {
					$variation = wc_get_product( $variation_id );
					$variation->delete( true );
				}
			}
		}

		wp_die( -1 );
	}
	public static function elex_mv_save_variation_image( $variation, $index ) {

		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			return;
		}


		$add_product_var = new Product();

		$image_name = isset( $_FILES['upload_image_id']['name'][ $index ] ) ? sanitize_text_field( $_FILES['upload_image_id']['name'][ $index ] ) : ''; // images url array of product
		$image_path = isset( $_FILES['upload_image_id']['tmp_name'][ $index ] ) ? sanitize_text_field( $_FILES['upload_image_id']['tmp_name'][ $index ] ) : '';
		$image_type = isset( $_FILES['upload_image_id']['type'][ $index ] ) ? sanitize_text_field( $_FILES['upload_image_id']['type'][ $index ] ) : '';

		$file_names  = isset( $_POST['_wc_files_names'][ $index ] ) ? map_deep( wp_unslash( $_POST['_wc_files_names'][ $index ] ), 'sanitize_text_field' ) : ''; // images url array of product
		$file_urls   = isset( $_POST['_wc_files_urls'][ $index ] ) ? map_deep( wp_unslash( $_POST['_wc_files_urls'][ $index ] ), 'sanitize_text_field' ) : '';
		$file_hashes = isset( $_POST['_wc_files_hashes'][ $index ] ) ? map_deep( wp_unslash( $_POST['_wc_files_hashes'][ $index ] ), 'sanitize_text_field' ) : '';

	
		$downloadable_files = array();

	


		foreach ( $file_urls as $key => $fileUrl ) {
			$downloadable_files[] = array(
				'name' => isset( $file_names[ $key ] ) ? $file_names[ $key ] : basename( $fileUrl ),
				'file' => $fileUrl ? $fileUrl : '',
				'id'   => isset( $file_hashes[ $key ] ) ? $file_hashes[ $key ] : '',   

			);
		}

		if ( ! empty( $image_path ) ) {

			$mediaID = $add_product_var->save_image( $image_name, $image_path, $image_type ); // calling the uploadMedia function and passing image url to get the uploaded media id
			if ( $mediaID ) {
				$variation->set_props(
					array(
						'image_id' => $mediaID,

					) 
				); // set the first image as primary image of the product
			} 
		} else {
			$variation->set_props(
				array(
					'image_id' => '',

				) 
			); 
		}

		$downloads = array();
		foreach ( $downloadable_files as $file ) {

			$file_name   = $file['name'];
			$file_url    = $file['file'];
			$download_id = md5( $file['file'] );

			if ( isset( $file['id'] ) && ! empty( $file['id'] ) ) {
				$download_id = $file['id'] ;
			}
			$download_id = md5( $file['file'] ); // Or use wp_generate_uuid4()

			$pd_object = new \WC_Product_Download();

			$pd_object->set_id( $download_id );
			$pd_object->set_name( $file_name );
			$pd_object->set_file( $file_url );
			$downloads[ $download_id ] = $pd_object;

		}
		$variation->set_downloads( $downloads );
	}


	public static function elex_mv_save_variations() {
		ob_start();

		// Check permissions again and make sure we have what we need.

		if ( ! isset( $_POST['nonce'] ) ||
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' )
		) {
			ob_end_clean();
			return;
		}

		if ( empty( $_POST ) || empty( $_POST['product_id'] ) ) {
			ob_end_clean();
			wp_die( -1 );
		}

		$product_id = absint( $_POST['product_id'] );

		\WC_Admin_Meta_Boxes::$meta_box_errors = array();
		\WC_Meta_Box_Product_Data::save_variations( $product_id, get_post( $product_id ) );

		$errors = \WC_Admin_Meta_Boxes::$meta_box_errors;

		if ( $errors ) {
			echo '<div class="error notice is-dismissible">';

			foreach ( $errors as $error ) {
				echo '<p>' . wp_kses_post( $error ) . '</p>';
			}

			echo '<button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__( 'Dismiss this notice.', 'elex-multi-vendor-for-woocommerce' ) . '</span></button>';
			echo '</div>';

			delete_option( \WC_Admin_Meta_Boxes::ERROR_STORE );
		}

		ob_end_clean();
		wp_send_json_success( 'success' );

		wp_die();
	}


	public static function elex_mv_load_variations() {

		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			return;
		}
	
		$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;

		if ( ! $post_id ) {
			wp_die();
		}

		$post           = get_post( $post_id ); // phpcs:ignore
		$product_object = wc_get_product( $post_id );
		
		$variations = wc_get_products(
			array(
				'status'  => array( 'private', 'publish' ),
				'type'    => 'variation',
				'parent'  => $post_id,
			
				'orderby' => array(
					'menu_order' => 'ASC',
					'ID'         => 'DESC',
				),
				'return'  => 'objects',
			)
		);



		$shipping_classes = get_terms(
			array(
				'taxonomy'   => 'product_shipping_class',
				'hide_empty' => false,
			) 
		);
		$ship_class       = wp_json_encode( $shipping_classes );

		$default_attribute = array();
		
		if ( $product_object->get_default_attributes() ) {
			$default_attribute = $product_object->get_default_attributes(); 
		}

		$simplified_data = array();
		$attributes      = array();
		foreach ( $variations as $key => $variation_object ) {
			$simplified_data[ $key ] = $variation_object->get_data();

			

			if ( isset( $simplified_data[ $key ]['image_id'] ) ) {
				$image_src = wp_get_attachment_thumb_url( sanitize_text_field( $simplified_data[ $key ]['image_id'] ) );
				
		
				$simplified_data[ $key ]['image_id'] = $image_src;
			}

			foreach ( $simplified_data[ $key ]['downloads'] as $hash => $hash_val ) {

				$simplified_data[ $key ]['downloads'][ $hash ] = $hash_val->get_data();
			}       
		}
		if ( 'variable' === $product_object->get_type() ) {

			$attributes = $product_object->get_variation_attributes();

			$attributes = array_change_key_case( $attributes, CASE_LOWER );
		}
	

		$data_req = array(
			'shipping_class'     => $ship_class,
			'default_attribute'  => wp_json_encode( $default_attribute ),
			'variation_data'     => wp_json_encode( $simplified_data ),
			'product_attributes' => wp_json_encode( $attributes, JSON_FORCE_OBJECT ),
		);

		
	

		wp_send_json_success( wp_json_encode( $data_req ) , '200' );
		wp_die();
	}

	public static function elex_mv_load_data_manual_variations() {

		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			return;
		}

		$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;

		if ( ! $post_id ) {
			wp_die();
		}

		// if ( ! isset( $_POST['post_id'], $_POST['loop'] ) ) {
		//  wp_die( -1 );
		// }


		$product_id       = intval( $_POST['post_id'] );
		$product_object   = wc_get_product_object( 'variable', $product_id ); // Forces type to variable in case product is unsaved.
		$variation_object = wc_get_product_object( 'variation' );
		$variation_object->set_parent_id( $product_id );
		$variation_object->set_attributes( array_fill_keys( array_map( 'sanitize_title', array_keys( $product_object->get_variation_attributes() ) ), '' ) );
		$variation_id   = $variation_object->save();
		$variation      = get_post( $variation_id );
		$variation_data = array_merge( get_post_custom( $variation_id ), wc_get_product_variation_attributes( $variation_id ) ); // kept for BW compatibility.
		
		
		$default_attribute = array();

		$product_object = wc_get_product_object( 'variable', $product_id ); // Forces type to variable in case product is unsaved.
		
		if ( $product_object->get_default_attributes() ) {
			$default_attribute = $product_object->get_default_attributes(); 
		}

		if ( 'variable' === $product_object->get_type() ) {

			$attributes = $product_object->get_variation_attributes();
			$attributes = array_change_key_case( $attributes, CASE_LOWER );

			
		}
		$shipping_classes = get_terms(
			array(
				'taxonomy'   => 'product_shipping_class',
				'hide_empty' => false,
			) 
		);
		$ship_class       = wp_json_encode( $shipping_classes );

			$data_req = array(
				'shipping_class'     => $ship_class,
				'variation_id'       => $variation_id,
				'default_attribute'  => wp_json_encode( $default_attribute ),
				'product_attributes' => wp_json_encode( $attributes, JSON_FORCE_OBJECT ),
			);



		wp_send_json_success( wp_json_encode( $data_req ) , '200' );
	}

	public static function elex_mv_link_all_variations() {

		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			return;
		}

		wc_maybe_define_constant( 'WC_MAX_LINKED_VARIATIONS', 50 );
		wc_set_time_limit( 0 );

		$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;

		if ( ! $post_id ) {
			wp_die();
		}

		$product        = wc_get_product( $post_id );
		$number_created = self::create_all_product_variations( $product );

		echo esc_html( $number_created );
		// wp_send_json_success($number_created);

		wp_die();
	}

	private static function create_all_product_variations( $product ) {
		$data_store = $product->get_data_store();
		if ( ! is_callable( array( $data_store, 'create_all_product_variations' ) ) ) {
			wp_die();
		}
		$number = $data_store->create_all_product_variations( $product, 50 );
		$data_store->sort_all_product_variations( $product->get_id() );
		return $number;
	}


	public static function save_attributes() {

		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			return;
		}

		if ( ! isset( $_POST['data'], $_POST['post_id'] ) ) {
			// wp_send_json_error( array( 'error' => 'Attributes not saved' ) );

			wp_die( -1 );
		}

		$response = array();

		try {
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			parse_str( wp_unslash( $_POST['data'] ), $data );
			$data = wc_clean( $data );
		
			$product = self::create_product_with_attributes( $data );

			

		} catch ( Exception $e ) {
			wp_send_json_error( array( 'error' => $e->getMessage() ) );
		}

		// wp_send_json_success must be outside the try block not to break phpunit tests.
		wp_send_json_success( $response );
	}



	private static function create_product_with_attributes( $data ) {
		// phpcs:disable WordPress.Security.NonceVerification.Missing
		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			return;
		}

		if ( ! isset( $_POST['post_id'] ) ) {
			wp_die( -1 );
		}

		if ( isset( $data['attribute_names'] ) && is_array( $data['attribute_names'] ) ) {
			$data['attribute_position'] = array_keys( $data['attribute_names'] );
		} else {
			$data['attribute_position'] = array( 0 );
		}
	
		$attributes   = \WC_Meta_Box_Product_Data::prepare_attributes( $data );
		$product_id   = absint( wp_unslash( $_POST['post_id'] ) );
		$product_type = ! empty( $_POST['product_type'] ) ? wc_clean( sanitize_text_field( wp_unslash( $_POST['product_type'] ) ) ) : 'simple';
		$classname    = \WC_Product_Factory::get_product_classname( $product_id, $product_type );
		$product      = new $classname( $product_id );

		$product->set_attributes( $attributes );
		$product->save();
		return $product;
	}

	public static function add_new_attributes() {


		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			return;
		}

		if ( isset( $_POST['taxonomy'], $_POST['term'] ) ) {
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			$taxonomy = sanitize_text_field( wp_unslash( $_POST['taxonomy'] ) );
			$term     = wc_clean( sanitize_text_field( wp_unslash( $_POST['term'] ) ) );

			

			if ( taxonomy_exists( $taxonomy ) ) {

				$result = wp_insert_term( $term, $taxonomy );


				if ( is_wp_error( $result ) ) {
					wp_send_json(
						array(
							'error' => $result->get_error_message(),
						)
					);
				} else {
					$term = get_term_by( 'id', $result['term_id'], $taxonomy );

				

					wp_send_json(
						array(
							'term_id' => $term->term_id,
							'name'    => $term->name,
							'slug'    => $term->slug,
						)
					);

				}
			}
		}

		wp_die( -1 );
	}


	public static function json_search_taxonomy_terms() {
		ob_start();

		if ( ! isset( $_GET['nonce'] ) ||
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['nonce'] ) ), 'elex_mv_prod_page_nonce' )
		) {
			ob_end_clean();
			return;
		}

		$search_text = isset( $_GET['term'] ) ? wc_clean( sanitize_text_field( wp_unslash( $_GET['term'] ) ) ) : '';
		$limit       = isset( $_GET['limit'] ) ? absint( wp_unslash( $_GET['limit'] ) ) : null;
		$taxonomy    = isset( $_GET['taxonomy'] ) ? wc_clean( sanitize_text_field( wp_unslash( $_GET['taxonomy'] ) ) ) : '';
		$orderby     = isset( $_GET['orderby'] ) ? wc_clean( sanitize_text_field( wp_unslash( $_GET['orderby'] ) ) ) : 'name';
		$order       = isset( $_GET['order'] ) ? wc_clean( sanitize_text_field( wp_unslash( $_GET['order'] ) ) ) : 'ASC';

		$args = array(
			'taxonomy'        => $taxonomy,
			'orderby'         => $orderby,
			'order'           => $order,
			'hide_empty'      => false,
			'fields'          => 'all',
			'number'          => $limit,
			'name__like'      => $search_text,
			'suppress_filter' => true,
		);

		/**
		 * Filter the product attribute term arguments used for search.
		 *
		 * @since 3.4.0
		 * @param array $args The search arguments.
		 */
		$terms = get_terms( $args );

		/**
		 * Filter the product attribute terms search results.
		 *
		 * @since 7.0.0
		 * @param array  $terms    The list of matched terms.
		 * @param string $taxonomy The terms taxonomy.
		 */
		ob_end_clean();
		wp_send_json( $terms );
	}
	
	public function elex_mv_toggle_page_link() {

		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, 200 );
		}

	

		if ( isset( $_POST['visibility'] ) && isset( $_POST['id'] ) ) {

			$id         = sanitize_text_field( wp_unslash( $_POST['id'] ) );
			$visibility = sanitize_text_field( wp_unslash( $_POST['visibility'] ) );

			$product = wc_get_product( $id );
			
			

			if ( 'yes' === $visibility ) {

				$product->set_catalog_visibility( 'visible' );
			} else {

				$product->set_catalog_visibility( 'hidden' );
			}
			$product->save();


			wp_send_json_success( 'succesful', 200 );
			die();

		}
	}

	public function elex_mv_cat_search_with_entered_val() {


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

		$category_search_term          = isset( $_POST['search_val'] ) ? sanitize_text_field( wp_unslash( $_POST['search_val'] ) ) : '';
		$category_args                 = array();           
		$category_args['taxonomy']     = 'product_cat' ;
		$category_args['orderby']      = 'name' ;
		$category_args['show_count']   = 0 ;
		$category_args['pad_counts']   = 0 ;
		$category_args['hierarchical'] = 1 ;
		$category_args['title-li']     = '' ;
		$category_args['hide_empty']   = 0 ;


		$category_args['search'] = $category_search_term ;
	
		$searched_categories = get_categories( $category_args );


		wp_send_json_success( $searched_categories, '200' );
		die;
	}

	public function elex_mv_add_views_count() {
		global $product;
		$view_count = $product->get_meta( 'elex_mv_views_count', true );
			
		$view_count = $view_count ? $view_count : 0;
		++$view_count;
		$product->update_meta_data( 'elex_mv_views_count', $view_count );
		$product->save();
	}

	public function elex_mv_export() {

		global $current_user;                     

	

		global $wp_query;

		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, 200 );
		}
		$vendor   = Vendor::load( wp_get_current_user() );
		$store    = $vendor->get_store();
			$args = array(
				'limit'      => -1,
				'order'      => 'DESC',
				'orderby'    => 'date',
				'meta_key'   => 'elex_mv_store_id',
				'meta_value' => $store->get_id(),
			);
			
			
			$from_date = isset( $_GET['from_date'] ) ? sanitize_text_field( wp_unslash( $_GET['from_date'] ) ) : '' ; 
			$to_date   = isset( $_GET['to_date'] ) ? sanitize_text_field( wp_unslash( $_GET['to_date'] ) ) : '' ; 
		
			if ( isset( $_GET['status'] ) && ! empty( $_GET['status'] ) ) {
				$args['post_status'] = sanitize_text_field( wp_unslash( $_GET['status'] ) );

			}

			if ( isset( $_GET['enabled'] ) && ! empty( $_GET['enabled'] ) ) {
				$args['visibility'] = sanitize_text_field( wp_unslash( $_GET['enabled'] ) );

			}


			
			if ( isset( $_GET['stock'] ) && 'low' === sanitize_text_field( wp_unslash( $_GET['stock'] ) ) ) {
				$args['low_in_stock'] = true; 
			} elseif ( isset( $_GET['stock'] ) && 'out' === sanitize_text_field( wp_unslash( $_GET['stock'] ) ) ) {
				$args['stock_status'] = 'outofstock'; 
			} elseif ( isset( $_GET['stock'] ) && 'in' === sanitize_text_field( wp_unslash( $_GET['stock'] ) ) ) {
				$args['stock_status'] = 'instock'; 
			} elseif ( isset( $_GET['stock'] ) && 'onbackorder' === sanitize_text_field( wp_unslash( $_GET['stock'] ) ) ) {
				$args['stock_status'] = 'onbackorder'; 
			}

			if ( isset( $_GET['from_date'] ) && ! empty( $_GET['from_date'] ) ) {
				$date_query         = array(
					array(
						'after'     => $from_date,
						'before'    => $to_date,
						'inclusive' => true,
					),
				);
				$args['date_query'] = $date_query;
			} else {
				$args['date_query'] = '';
			}

			if ( isset( $_GET['sort_by'] ) && 'sold' === sanitize_text_field( wp_unslash( $_GET['sort_by'] ) ) ) {
				$args['orderby'] = 'total_sales';
			} elseif ( isset( $_GET['sort_by'] ) && 'view' === sanitize_text_field( wp_unslash( $_GET['sort_by'] ) ) ) {
				$args['orderby']  = 'meta_value_num';
				$args['meta_key'] = 'elex_mv_views_count';
			}

			$this->filter_on_low_stock_db_operation();

			if ( isset( $_GET['order_by'] ) && 'asc' === sanitize_text_field( wp_unslash( $_GET['order_by'] ) ) ) {
				$args['order'] = 'ASC';
			} elseif ( isset( $_GET['order_by'] ) && 'desc' === sanitize_text_field( wp_unslash( $_GET['order_by'] ) ) ) {
				$args['order'] = 'DESC';
			}

		
		 
	

		// $products_query = new \WC_Product_Query( $args);
		

		// $products_elex_mv = $products_query->get_products();
	

		header( 'Content-Type: text/csv; charset=utf-8' ); //For .csv
		header( 'Content-Disposition: attachment; filename=store-products.csv' );

		$output            = fopen( 'php://output', 'w' );
		$array_for_headers = array( 'product_id', 'product_name', 'product_description', 'product_regular_price', 'product_sale_price', 'product_stock_value', 'product_weight', 'product_length', 'product_width', 'product_height', 'product_status' );
		
		/**
		 * If someone wants to add extra parameters in export of csv.
		 *
		 * @since 1.0.0
		 */
		$array_for_headers = apply_filters( 'elex_mv_csv_header_for_export', $array_for_headers );

		fputcsv( $output, $array_for_headers );

		$products_elex_mv = wc_get_products( $args );

			foreach ( $products_elex_mv as $product ) {
				$csv = array( 
					$product->get_id(), 
					$product->get_name(), 
					$product->get_description(), 
					$product->get_regular_price(), 
					$product->get_sale_price(), 
					$product->get_stock_quantity(), 
					$product->get_weight(), 
					$product->get_length(), 
					$product->get_width(), 
					$product->get_height(), 
					$product->get_status(),    

				);
				/**
				 * If someone wants to add extra parameters in the export of csv.
				 *
				 * @since 1.0.0
				 */
				$csv = apply_filters( 'elex_mv_csv_row_for_export', $csv );

				fputcsv( $output, $csv );
			}

		// Since we are streaming data directly to the browser for file download, we used core PHP functions.
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
		fclose( $output );

		die;
	}


	public function filter_on_low_stock_db_operation() {
		
		
		add_filter(
			'posts_join',
			function ( $join ) {
			global $wpdb;
				if ( 'low' === get_query_var( 'stock' ) || 'onbackorder' === get_query_var( 'stock' ) || ( isset( $_GET['stock'] ) && 'low' === $_GET['stock'] ) || ( isset( $_GET['stock'] ) && 'onbackorder' === $_GET['stock'] ) ) {
					check_ajax_referer( 'elex_mv_prod_page_nonce', 'nonce' );
					$join .= "LEFT JOIN $wpdb->postmeta as stock ON $wpdb->posts.ID = stock.post_id ";
					$join .= "LEFT JOIN $wpdb->postmeta as threshold ON $wpdb->posts.ID = threshold.post_id ";
					$join .= "LEFT JOIN $wpdb->postmeta as backorder ON $wpdb->posts.ID = backorder.post_id ";

				}
		
			return $join;
			}
		);
		
		add_filter(
			'posts_where',
			function ( $where ) {
				if ( 'onbackorder' === get_query_var( 'stock' ) || ( isset( $_GET['stock'] ) && 'onbackorder' === $_GET['stock'] ) ) {
					check_ajax_referer( 'elex_mv_prod_page_nonce', 'nonce' );
					$where .= " AND ( stock.meta_key='_stock' OR  ( backorder.meta_key = '_backorders' AND backorder.meta_value = 'yes' ) )";
					$where .= " AND ( threshold.meta_key ='_low_stock_amount' OR (  backorder.meta_key = '_backorders' AND backorder.meta_value = 'yes')  )";
					$where .= " AND ( CAST(threshold.meta_value AS SIGNED) >= CAST(stock.meta_value AS SIGNED) OR backorder.meta_value = 'yes' )";
				} elseif ( 'low' === get_query_var( 'stock' ) || ( isset( $_GET['stock'] ) && 'low' === $_GET['stock'] ) ) {
					check_ajax_referer( 'elex_mv_prod_page_nonce', 'nonce' );
					$where .= " AND  ( stock.meta_key='_stock' )";
					$where .= " AND  ( threshold.meta_key ='_low_stock_amount' )";
					$where .= ' AND  ( CAST( threshold.meta_value AS SIGNED) >= CAST(stock.meta_value AS SIGNED) ) ';
				}
				
			return $where;
			} 
		);
	}

	public function elex_mv_delete_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, 200 );
		}
		if ( isset( $_POST['id'] ) ) {
			wp_delete_post( sanitize_text_field( wp_unslash( $_POST['id'] ) ) );
		}
	}



	
	public function elex_mv_add_product_details() {

		if ( ! isset( $_POST['elex-nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['elex-nonce'] ) ), 'elex_mv_add_prod' ) 
		) {
			return;
		}

		$all_fields_data   = array();
		$new_product_array = array();

	

		$new_product_array['product_type'] = isset( $_POST['product_type'] ) ? sanitize_text_field( wp_unslash( $_POST['product_type'] ) ) : '';

		$new_product_array['elex_prod_id']        = isset( $_POST['elex_prod_id'] ) ? sanitize_text_field( wp_unslash( $_POST['elex_prod_id'] ) ) : '';
		$new_product_array['product_id']          = isset( $_POST['product_id'] ) ? sanitize_text_field( wp_unslash( $_POST['product_id'] ) ) : '';
		$new_product_array['edit_page']           = isset( $_POST['edit_page'] ) ? sanitize_text_field( wp_unslash( $_POST['edit_page'] ) ) : '';
		$new_product_array['product_name']        = isset( $_POST['product_name'] ) ? sanitize_text_field( wp_unslash( $_POST['product_name'] ) ) : '';
		$new_product_array['product_description'] = isset( $_POST['product_description'] ) ? sanitize_text_field( wp_unslash( $_POST['product_description'] ) ) : '';
		$new_product_array['product_category']    = isset( $_POST['product_category'] ) ? map_deep( wp_unslash( $_POST['product_category'] ), 'sanitize_text_field' ) : '';
		

		if ( isset( $_POST['commission'] ) ) {
			$new_product_array['commission'] = sanitize_text_field( wp_unslash( $_POST['commission'] ) ); 
		}
		$new_product_array['downloadable_product'] = isset( $_POST['downloadable_product'] ) ? sanitize_text_field( wp_unslash( $_POST['downloadable_product'] ) ) : '';
		$new_product_array['virtual_product']      = isset( $_POST['virtual_product'] ) ? sanitize_text_field( wp_unslash( $_POST['virtual_product'] ) ) : '';
		$new_product_array['download_expiry']      = isset( $_POST['download_expiry'] ) ? sanitize_text_field( wp_unslash( $_POST['download_expiry'] ) ) : '';
		$new_product_array['download_limit']       = isset( $_POST['download_limit'] ) ? sanitize_text_field( wp_unslash( $_POST['download_limit'] ) ) : '';

		$new_product_array['_wc_file_urls']   = isset( $_POST['_wc_file_urls'] ) ? map_deep( wp_unslash( $_POST['_wc_file_urls'] ), 'sanitize_text_field' ) : '';
		$new_product_array['_wc_file_hashes'] = isset( $_POST['_wc_file_hashes'] ) ? map_deep( wp_unslash( $_POST['_wc_file_hashes'] ), 'sanitize_text_field' ) : '';
		$new_product_array['_wc_file_names']  = isset( $_POST['_wc_file_names'] ) ? map_deep( wp_unslash( $_POST['_wc_file_names'] ), 'sanitize_text_field' ) : '';

		

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

		// check product image is allowed format
		if ( ! empty( $new_product_array['image_name'] ) ) {
			if ( ! elex_mv_is_valid_image_file( $new_product_array['image_name'], $new_product_array['image_path'] ) ) {
				wp_send_json_error( array( 'product_image' => array( __( 'Unsupported image format.', 'elex-multi-vendor-for-woocommerce' ) ) ), 422 );
			}
		}
		
		$new_product_array['regular_price']      = isset( $_POST['regular_price'] ) ? sanitize_text_field( wp_unslash( $_POST['regular_price'] ) ) : '';
		$new_product_array['sale_price']         = isset( $_POST['sale_price'] ) ? sanitize_text_field( wp_unslash( $_POST['sale_price'] ) ) : '';
		$new_product_array['sale_start_date']    = isset( $_POST['sale_start_date'] ) ? sanitize_text_field( wp_unslash( $_POST['sale_start_date'] ) ) : '';
		$new_product_array['sale_end_date']      = isset( $_POST['sale_end_date'] ) ? sanitize_text_field( wp_unslash( $_POST['sale_end_date'] ) ) : '';
		$new_product_array['manage_stock_level'] = isset( $_POST['manage_stock_level'] ) ? sanitize_text_field( wp_unslash( $_POST['manage_stock_level'] ) ) : '';
		$new_product_array['stock_status']       = isset( $_POST['stock_status'] ) ? sanitize_text_field( wp_unslash( $_POST['stock_status'] ) ) : '';

		$new_product_array['sku'] = isset( $_POST['sku'] ) ? sanitize_text_field( wp_unslash( $_POST['sku'] ) ) : '';
		
		$new_product_array['stock_value']            = isset( $_POST['stock_value'] ) ? sanitize_text_field( wp_unslash( $_POST['stock_value'] ) ) : '';
		$new_product_array['lower_threshold']        = isset( $_POST['lower_threshold'] ) ? sanitize_text_field( wp_unslash( $_POST['lower_threshold'] ) ) : '';
		$new_product_array['allow_back_orders']      = isset( $_POST['allow_back_orders'] ) ? sanitize_text_field( wp_unslash( $_POST['allow_back_orders'] ) ) : '';
		$new_product_array['sold_individual_orders'] = isset( $_POST['sold_individual_orders'] ) ? sanitize_text_field( wp_unslash( $_POST['sold_individual_orders'] ) ) : '';

		$new_product_array['product_weight'] = isset( $_POST['product_weight'] ) ? sanitize_text_field( wp_unslash( $_POST['product_weight'] ) ) : '';
		$new_product_array['product_length'] = isset( $_POST['product_length'] ) ? sanitize_text_field( wp_unslash( $_POST['product_length'] ) ) : '';
		$new_product_array['product_width']  = isset( $_POST['product_width'] ) ? sanitize_text_field( wp_unslash( $_POST['product_width'] ) ) : '';
		$new_product_array['product_height'] = isset( $_POST['product_height'] ) ? sanitize_text_field( wp_unslash( $_POST['product_height'] ) ) : '';
		$new_product_array['shipping_class'] = isset( $_POST['shipping_class'] ) ? sanitize_text_field( wp_unslash( $_POST['shipping_class'] ) ) : '';

		$new_product_array['send_for_approval'] = isset( $_POST['send_for_approval'] ) ? sanitize_text_field( wp_unslash( $_POST['send_for_approval'] ) ) : '';

		$new_product_array['publish'] = isset( $_POST['publish'] ) ? sanitize_text_field( wp_unslash( $_POST['publish'] ) ) : '';

		$new_product_array['form-step']     = isset( $_POST['form-step'] ) ? sanitize_text_field( wp_unslash( $_POST['form-step'] ) ) : '';
		$new_product_array['save_as_draft'] = isset( $_POST['save-as-draft'] ) ? sanitize_text_field( wp_unslash( $_POST['save-as-draft'] ) ) : '';

		$all_fields_data = $new_product_array;
	
		$validation_errors = $this->elex_mv_form_product_validation( $new_product_array );
	
	
		if ( isset( $validation_errors['errors'] ) && count( $validation_errors['errors'] ) ) {
			wp_send_json_error( $validation_errors['errors'], 422 );
		}

			/**
				 * If someone wants to add extra fields for product.
				 *
				 * @since 1.0.0
			*/
		$new_product_array = apply_filters( 'elex_mv_form_products_field_to_save', $new_product_array );

		$product_params = array();
			/**
				 * If someone wants to add extra fields for product.
				 *
				 * @since 1.0.0
			*/
		$product_params = apply_filters( 'elex_mv_form_products_field_params_to_save', $product_params );


		$add_product_var = new Product();
	
		$elex_mv_prod_id = $add_product_var->create_product( $new_product_array, $all_fields_data );

		$product       = wc_get_product( $elex_mv_prod_id );
		$prod_store_id = $product->get_meta( 'elex_mv_store_id', true );
		$store_post    = get_post( $prod_store_id );


		$store_obj  = Store::load_by_store( $store_post );
		$date_fomat = get_option( 'date_format' );
		$to         = get_bloginfo( 'admin_email' );
	  
		$subject = ' New Product Added and Auto-Approved';
		$body    = '';
		if ( isset( $new_product_array['publish'] ) && 'yes' === $new_product_array['publish'] ) {
			$body = 'Dear ' . get_bloginfo( 'name' ) . ',<br>

			  
			We hope this message finds you well.<br>

			
			We wanted to inform you that a new product has been added to your site. The exciting news is that this product has been automatically approved and published on the platform due to the "Auto Approval for Newly Added Products" feature being enabled. In Case you want to disable this feature, navigate to your settings<br>

			Vendor: ' . $store_obj->title . '
			Product Name: ' . $product->get_name() . '
			Product ID: ' . $elex_mv_prod_id . '
			Publication Date: ' . gmdate( $date_fomat ) . '<br>

			While you don\'t need to manually approve this particular product, we encourage you to periodically review newly added products to ensure they align with our platform\'s guidelines and quality standards.<br>

			Best regards,<br>

			';
		} elseif ( ! isset( $new_product_array['edit_page'] ) || ! $new_product_array['edit_page'] ) {

			$body = 'Dear ' . get_bloginfo( 'name' ) . ',<br>

			  
			We hope this message finds you well.<br>

			We are writing to inform you that a new product has been submitted for approval by one of your valued vendors on your site. As the site administrator, your action is needed to review and approve or reject this product for publication on the platform.<br>
			
			Vendor: ' . $store_obj->title . '
			Product Name: ' . $product->get_name() . '
			Product ID: ' . $elex_mv_prod_id . '
			Submission Date: ' . $product->get_date_created() . '<br>

			To review and take action on this product, please follow these steps:<br>

			1. Log in to your administrator dashboard on [Your Multi-Vendor Site].
			2. Navigate to the " Vendors Product" tab under “ELEX Multi Vendor”
			3. Locate the product submitted by the vendor mentioned above.
			4. Click on the product to access the details and review the information provided by the vendor.
			5. After careful consideration, select the "Approve" or "Reject" option to finalize your decision.<br>
			
			If you choose to approve the product, it will be published on the platform for customers to view and purchase. If you decide to reject the product, the product will not be published on the site.<br>
			
			
			If you have any questions or encounter any issues during the approval process, please do not hesitate to contact us.<br>
			

			Best regards,<br>

			';

		}
		$headers   = array();
		$headers[] = 'Content-type: text/html; charset=utf-8';
		$headers[] = 'From:' . get_bloginfo( 'admin_email' );
		$result    = wp_mail( $to, $subject, $body, $headers );
		wp_send_json_success( $elex_mv_prod_id, 200 );
		die;
	} 

	public function elex_mv_form_product_validation( $new_product_array ) {
		$data = array(
			'message' => __( 'Empty Fields' , 'elex-multi-vendor-for-woocommerce' ),
			'errors'  => array(),
		);



		if ( isset( $new_product_array['form-step'] ) && '1' === $new_product_array['form-step'] ) {
			if ( ! isset( $new_product_array['product_name'] ) || empty( $new_product_array['product_name'] ) ) {
				$data['errors']['product_name'][] = __( 'Please enter name', 'elex-multi-vendor-for-woocommerce' );
			}
			if ( isset( $new_product_array['product_name'] ) && ! preg_match( '/^[a-zA-z][ a-zA-z_0-9]*$/', $new_product_array['product_name'] ) ) {
			$data['errors']['product_name'][] = __( 'Only alphabets and whitespace are allowed.', 'elex-multi-vendor-for-woocommerce' );
			}       
			if ( isset( $new_product_array['regular_price'] ) ) {

				if ( ! is_numeric( $new_product_array['regular_price'] ) ) {
					$data['errors']['regular_price'][] = __( 'Enter Only Numbers ', 'elex-multi-vendor-for-woocommerce' );
				} 
			}
			if ( isset( $new_product_array['sale_price'] ) ) {
	
				if ( ! is_numeric( $new_product_array['sale_price'] ) ) {
				$data['errors']['sale_price'][] = __( 'Enter Only Numbers ', 'elex-multi-vendor-for-woocommerce' );
					
				}
				if ( $new_product_array['sale_price'] > $new_product_array['regular_price'] ) {
					$data['errors']['sale_price'][] = __( 'Should not be greater than regular price ', 'elex-multi-vendor-for-woocommerce' );

				}
			} 
		}
	
		if ( isset( $new_product_array['form-step'] ) && ( '2' === $new_product_array['form-step'] ) ) {
			
			if ( isset( $new_product_array['stock_value'] ) ) {
	
				if ( ! empty( $new_product_array['stock_value'] ) && ! is_numeric( $new_product_array['stock_value'] ) ) {
					$data['errors']['stock_value'][] = __( 'Enter Only Numbers ', 'elex-multi-vendor-for-woocommerce' );
				}
			}
			if ( isset( $new_product_array['lower_threshold'] ) ) {
	 
				if ( ! empty( $new_product_array['lower_threshold'] ) && ! is_numeric( $new_product_array['lower_threshold'] ) ) {
					$data['errors']['lower_threshold'][] = __( 'Enter Only Numbers ', 'elex-multi-vendor-for-woocommerce' );
				}
			}
		}
	

		if ( isset( $new_product_array['form-step'] ) && '3' === $new_product_array['form-step'] ) {

			if ( isset( $new_product_array['product_weight'] ) ) {

				if ( ! empty( $new_product_array['product_weight'] ) && ! is_numeric( $new_product_array['product_weight'] ) ) {
					$data['errors']['product_weight'][] = __( 'Enter Only Numbers ', 'elex-multi-vendor-for-woocommerce' );
				}
			}
			if ( isset( $new_product_array['product_length'] ) ) {
  
				if ( ! empty( $new_product_array['product_length'] ) && ! is_numeric( $new_product_array['product_length'] ) ) {
					$data['errors']['product_length'][] = __( 'Enter Only Numbers ', 'elex-multi-vendor-for-woocommerce' );
				}
			} 
			if ( isset( $new_product_array['product_width'] ) ) {
 
				if ( ! empty( $new_product_array['product_width'] ) && ! is_numeric( $new_product_array['product_width'] ) ) {
					$data['errors']['product_width'][] = __( 'Enter Only Numbers ', 'elex-multi-vendor-for-woocommerce' );
				}  
			}
			if ( isset( $new_product_array['product_height'] ) ) {

				if ( ! empty( $new_product_array['product_height'] ) && ! is_numeric( $new_product_array['product_height'] ) ) {
					$data['errors']['product_height'][] = __( 'Enter Only Numbers ', 'elex-multi-vendor-for-woocommerce' );
				}  
			}
		}
		/**
		 * Hook for validation of products.
		 *
		 * @since 1.0.0
		 */
		$data = apply_filters( 'elex_mv_form_product_validation', $data );
		return $data;
	}




	public function ajax_elex_mv_edit_product_display() {

		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, 200 );
		}
		if ( isset( $_POST['id'] ) ) {
			$product_details           = wc_get_product( sanitize_text_field( wp_unslash( $_POST['id'] ) ) );
			$data_edit                 = array();
			$data_edit['prod_id']      = sanitize_text_field( wp_unslash( $_POST['id'] ) );
			$data_edit['product_name'] = $product_details->get_name();
			// $data_edit['product_description'] =  $product_details->get_description();
			$data_edit['product_description'] = $product_details->get_description();
			$data_edit['product_downloads']   = $product_details->get_downloads();

			$data_edit['rejected_message'] = ! empty( $product_details->get_meta( 'elex_mv_rejection_message' ) ) ? $product_details->get_meta( 'elex_mv_rejection_message' ) : '';

		

			$dwn_object_ar = $product_details->get_downloads();

			$dwn_product_obj = array();
	
			foreach ( $dwn_object_ar as $key => $dwn_object ) {
				$dwn_product_obj[ $key ] = $dwn_object->get_data();   
			}

			$data_edit['product_downloads'] = $dwn_product_obj ;

			$cate_arr = array() ;
			$cate_ids = $product_details->get_category_ids(); 
			foreach ( $cate_ids as $cate_id ) {
				$cate_name  = get_the_category_by_ID( $cate_id );
				$cate_arr[] = array(
					'cat_id'   => $cate_id,
					'cat_name' => $cate_name,
				);
			}



			// Output the variations
		
			$variations = wc_get_products(
				array(
					'status'  => array( 'private', 'publish' ),
					'type'    => 'variation',
					'parent'  => sanitize_text_field( wp_unslash( $_POST['id'] ) ),
				
					'orderby' => array(
						'menu_order' => 'ASC',
						'ID'         => 'DESC',
					),
					'return'  => 'objects',
				)
			);
	
			
	
			$variation_product = array();
	
			foreach ( $variations as $key => $variation_object ) {
				$variation_product[ $key ] = $variation_object->get_data();

	
			}

			$data_req  = array();
			$prod_attr = array();


		

		
					$attributes = $product_details->get_attributes();

					$attributes_s = array();

					



			foreach ( $attributes as $key => $atri_object ) {

				$attribute_value = wc_get_product_terms( $data_edit['prod_id'], $atri_object->get_name(), array( 'fields' => 'names' ) );
						
				$attributes_s[ $key ] = $attribute_value;
						

			}
					

					$attributes_s = array_change_key_case( $attributes_s, CASE_LOWER );

					

					$prod_attr = $product_details->get_attributes( 'edit' );

					$prod_attr_arr = array();
			foreach ( $prod_attr as $key => $atr_object ) {
				$prod_attr[ $key ] = $atr_object->get_data();
			}

			if ( 'variable' === $product_details->get_type() && ! empty( $product_details->get_variation_attributes() ) ) {

				$attributes = $product_details->get_variation_attributes();
				$attributes = array_change_key_case( $attributes, CASE_LOWER );

		
			
				$data_req = array(
					'variations'         => wp_json_encode( $variation_product ),
					'product_attributes' => wp_json_encode( $attributes, JSON_FORCE_OBJECT ),
				);
				

				$prod_attr = $product_details->get_attributes( 'edit' );

				$prod_attr_arr = array();
				foreach ( $prod_attr as $key => $atr_object ) {
					$prod_attr[ $key ] = $atr_object->get_data();
				}                   
			} elseif ( 'simple' === $product_details->get_type() && ! empty( $attributes ) ) {
				$final = array();

				foreach ( $attributes as $attribute_obj ) {

					// Get dynamic name (e.g., "boo")
					$name = $attribute_obj->get_name();

					// Get options array (e.g., ["K", "P", "O", "L"])
					$options = $attribute_obj->get_options();

					// Reverse if you want reversed output
					$final[ $name ] = $options;
				}
										$attributes = array_change_key_case( $final, CASE_LOWER );

				$data_edit['product_attribute'] = wp_json_encode( $attributes, JSON_FORCE_OBJECT );
			}
			

		

			$data_edit['product_category'] = $cate_arr;

			$data_edit['product_image'] = wp_get_attachment_image_src( get_post_thumbnail_id( sanitize_text_field( wp_unslash( $_POST['id'] ) ) ), 'single-post-thumbnail' );

			$data_edit['product_regular_price'] = $product_details->get_regular_price();
			$data_edit['product_sale_price']    = $product_details->get_sale_price();
			$data_edit['allow_back_orders']     = $product_details->get_backorders();
			$data_edit['product_weight']        = $product_details->get_weight();
			$data_edit['product_length']        = $product_details->get_length();
			$data_edit['product_width']         = $product_details->get_width();
			$data_edit['product_height']        = $product_details->get_height();
			$data_edit['shipping_class']        = $product_details->get_shipping_class_id();

			$data_edit['status'] = $product_details->get_status();
			$data_edit['type']   = $product_details->get_type();

			$data_edit['sku']               = $product_details->get_sku();
			$data_edit['manage_stock']      = $product_details->get_manage_stock();
			$data_edit['stock_status']      = $product_details->get_stock_status();
			$data_edit['lower_threshold']   = $product_details->get_low_stock_amount();
			$data_edit['allow_back_orders'] = $product_details->get_backorders();
			$data_edit['stock_value']       = $product_details->get_stock_quantity();

			$data_edit['sold_individually'] = $product_details->get_sold_individually();

			$data_edit['is_virtual'] = $product_details->get_virtual();

			$data_edit['is_downloadable'] = $product_details->get_downloadable();
			$data_edit['download_expiry'] = $product_details->get_download_expiry();
			$data_edit['download_limit']  = $product_details->get_download_limit();

			$data_edit['sale_start_date'] = wp_json_encode( $product_details->get_date_on_sale_from() );
			$data_edit['sale_end_date']   = wp_json_encode( $product_details->get_date_on_sale_to() );

			$data_edit['attributes']     = wp_json_encode( $prod_attr, JSON_FORCE_OBJECT );
			$data_edit['variation_data'] = $data_req;



			// $variations_id = wp_list_pluck( $variations, 'variation_id' );
		/**
		 * Hook for showing the fields in edit page from specific plugin.
		 *
		 * @since 1.0.0
		 */
			$data_edit = apply_filters( 'elex_mv_products_specific_plugin_fields_to_show', $data_edit );


		}
		wp_send_json_success( $data_edit );
	}

	public function elex_mv_product_page() {


		$add_product_tabs = array(
			array(
				'title' => __( 'Product Details' , 'elex-multi-vendor-for-woocommerce' ),
				'slug'  => 'product_details',
			),
			array(
				'title' => __( 'Inventory' , 'elex-multi-vendor-for-woocommerce' ),
				'slug'  => 'inventory',
			),
			array(
				'title' => __( 'Shipping' , 'elex-multi-vendor-for-woocommerce' ),
				'slug'  => 'shipping',
			),
			array(
				'title' => __( 'Attributes' , 'elex-multi-vendor-for-woocommerce' ),
				'slug'  => 'attributes',
			),
			array(
				'title' => __( 'Variations' , 'elex-multi-vendor-for-woocommerce' ),
				'slug'  => 'variations',
			),
			array(
				'title' => __( 'Publish' , 'elex-multi-vendor-for-woocommerce' ),
				'slug'  => 'carriers',
			),
		);

		include_once ELEX_MULTI_VENDOR_PLUGIN_PATH . '/templates/products/product-topbar.php';
	}

	public static function args_for_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 );
		}

		$args = array(
			'post_status' => array( 'publish', 'reject', 'pending', 'draft' ),
		);
		if ( ! empty( $_POST['store_id'] ) ) {
			$args['store_id'] = sanitize_text_field( wp_unslash( $_POST['store_id'] ) );
		}

		$from_date = isset( $_POST['from_date'] ) ? sanitize_text_field( wp_unslash( $_POST['from_date'] ) ) : ''; 
		$to_date   = isset( $_POST['to_date'] ) ? sanitize_text_field( wp_unslash( $_POST['to_date'] ) ) : '';
	
		$args['limit'] = isset( $_POST['limit'] ) ? sanitize_text_field( wp_unslash( $_POST['limit'] ) ) : '';  

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

		$args['visibility'] = isset( $_POST['visibility'] ) ? sanitize_text_field( wp_unslash( $_POST['visibility'] ) ) : '';  

		$args['s'] = isset( $_POST['search_term'] ) ? sanitize_text_field( wp_unslash( $_POST['search_term'] ) ) : '';  
		
		$args['stock_status'] = isset( $_POST['stock_status'] ) ? sanitize_text_field( wp_unslash( $_POST['stock_status'] ) ) : '';

	
		if ( get_query_var( 'from_date' ) ) {
			$date_query         = array(
				array(
					'after'     => $from_date,
					'before'    => $to_date,
					'inclusive' => true,
				),
			);
			$args['date_query'] = $date_query;
		} else {
			$args['date_query'] = '';
		}

		/**
		 * Hook for extra products arguments.
		 *
		 * @since 1.0.0
		 */
		return apply_filters( 'elex_mv_product_args', $args );
	}


	public static function elex_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, 'store_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 static function api_endpoint_for_products() {


		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 );
		}

		
		$products_array = array();

	
		$args                 = self::args_for_product();
		$products_query       = new \WC_Product_Query( $args );
		$products_elex_mv_all = $products_query->get_products();

	

		foreach ( $products_elex_mv_all as $prod_key => $prod_value ) {
			array_push(
				$products_array,
				array(
					'name' => $prod_value->get_name(),
					'id'   => $prod_value->get_id(),
				) 
			);
		}
		// $products_elex_mv = array_map( self::map_products_name_id(), $products_elex_mv_all );

		wp_send_json_success( $products_array , 200 );
	}


	public static function api_endpoint_for_categories() {
		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 );
		}

		$user = wp_get_current_user();
 
		$roles = ( array ) $user->roles;
	 
	

		if ( Vendor::is_vendor() || in_array( 'administrator', $roles ) ) {
			$category_search_term = isset( $_POST['search_val'] ) ? sanitize_text_field( wp_unslash( $_POST['search_val'] ) ) : '';
			$args                 = array(
				'taxonomy'     => isset( $_POST['taxonomy'] ) ? sanitize_text_field( wp_unslash( $_POST['taxonomy'] ) ) : 'product_cat',
				'orderby'      => isset( $_POST['orderby'] ) ? sanitize_text_field( wp_unslash( $_POST['orderby'] ) ) : 'name',
				'show_count'   => isset( $_POST['show_count'] ) ? sanitize_text_field( wp_unslash( $_POST['show_count'] ) ) : 0,
				'pad_counts'   => isset( $_POST['pad_counts'] ) ? sanitize_text_field( wp_unslash( $_POST['pad_counts'] ) ) : 0,
				'hierarchical' => isset( $_POST['hierarchical'] ) ? sanitize_text_field( wp_unslash( $_POST['hierarchical'] ) ) : 1,
				'title_li'     => isset( $_POST['title_li'] ) ? sanitize_text_field( wp_unslash( $_POST['title_li'] ) ) : '',
				'hide_empty'   => isset( $_POST['hide_empty'] ) ? sanitize_text_field( wp_unslash( $_POST['hide_empty'] ) ) : 0, 
			);
	
			$args['search'] = $category_search_term ;

			if ( isset( $_POST['store_id'] ) ) {
				$args['meta_query'] = array(
					'relation' => 'OR',
					array(
						'key'   => 'created_by_vendor',     // Adjust to your needs!
						'value' => sanitize_text_field( wp_unslash( $_POST['store_id'] ) ),   // Adjust to your needs!
					),
					
				);
			}
	
		/**
		 * Hook for extra category arguments.
		 *
		 * @since 1.0.0
		 */
			$args = apply_filters( 'elex_mv_category_args', $args );
	
	
			$categories = get_categories( $args );
	
			wp_send_json_success( $categories , 200 );
	
		} else {
			wp_send_json_error( 'You are not allowed', 403 );
			die();
		}
	}
	public function elex_mv_product_page_tab_product() {

		if ( ! isset( $_GET['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			return;
		}

		$vendor   = Vendor::load( wp_get_current_user() );
		$store    = $vendor->get_store();
			$args = array(
				'limit'      => 10,
				'order'      => 'DESC',
				'orderby'    => 'date',
				'meta_key'   => 'elex_mv_store_id',
				'meta_value' => $store->get_id(),
			);
			
			
			$from_date = isset( $_GET['from_date'] ) ? sanitize_text_field( wp_unslash( $_GET['from_date'] ) ) : '' ; 
			$to_date   = isset( $_GET['to_date'] ) ? sanitize_text_field( wp_unslash( $_GET['to_date'] ) ) : '' ; 
		
			$status = get_query_var( 'status' );
			if ( $status ) {
				$args['post_status'] = get_query_var( 'status' );

			} else {
				$args['post_status'] = 'any';

			}

			$args['visibility'] = get_query_var( 'enabled' );

			$args['s'] = get_query_var( 'search_term' );
			
			if ( isset( $_GET['stock'] ) && 'low' === sanitize_text_field( wp_unslash( $_GET['stock'] ) ) ) {
				$args['low_in_stock'] = true; 
			} elseif ( isset( $_GET['stock'] ) && 'out' === sanitize_text_field( wp_unslash( $_GET['stock'] ) ) ) {
				$args['stock_status'] = 'outofstock'; 
			} elseif ( isset( $_GET['stock'] ) && 'in' === sanitize_text_field( wp_unslash( $_GET['stock'] ) ) ) {
				$args['stock_status'] = 'instock'; 
			} elseif ( isset( $_GET['stock'] ) && 'onbackorder' === sanitize_text_field( wp_unslash( $_GET['stock'] ) ) ) {
				$args['stock_status'] = 'onbackorder'; 
			}

			if ( isset( $_GET['from_date'] ) && ! empty( $_GET['from_date'] ) ) {
				$date_query         = array(
					array(
						'after'     => $from_date,
						'before'    => $to_date,
						'inclusive' => true,
					),
				);
				$args['date_query'] = $date_query;
			} else {
				$args['date_query'] = '';
			}
		
			if ( 'sold' === get_query_var( 'sort_by' ) ) {
				$args['orderby'] = 'total_sales';
			}
			
			if ( 'view' === get_query_var( 'sort_by' ) ) {
				$args['orderby']  = 'meta_value_num';
				$args['meta_key'] = 'elex_mv_views_count';
			}

			if ( 'asc' === get_query_var( 'order_by' ) ) {
				$args['order'] = 'ASC';
			} elseif ( 'desc' === get_query_var( 'order_by' ) ) {
				$args['order'] = 'DESC';
			}
			
			

			$page_number = 1;
			if ( 'prev' === get_query_var( 'page_c' ) ) {
				if ( get_query_var( 'page_num' ) ) {
					$page_number = get_query_var( 'page_num' );
					--$page_number;
				}
			}
			if ( 'next' === get_query_var( 'page_c' ) ) {
				if ( get_query_var( 'page_num' ) ) {
					$page_number = get_query_var( 'page_num' );
					++$page_number;
				}
			}

			if ( get_query_var( 'page_num' ) ) {
				$args['offset'] = ( $page_number - 1 ) * $args['limit'] ;
			}

			$this->filter_on_low_stock_db_operation();

			if ( 'yes' === get_query_var( 'elex-advance-filter' ) ) {
				$args['offset']   = 0;
				$_GET['page_num'] = 0;
			}
			//$products_query = new \WC_Product_Query( $args );
			$vendor            = Vendor::load( wp_get_current_user() );
			$store             = $vendor->get_store();
			$vendor_store_id   = $store->get_id();
			$vendor_capability = $store->get_checkbox_list();
			//$products_elex_mv_new   = $products_query->get_products();
			$products_elex_mv    = wc_get_products( $args );
			$count_of_mv_product = count( $products_elex_mv );
			$num_of_products     = count( $products_elex_mv );
			update_post_meta( $vendor_store_id , 'elex_mv_total_product_count' , $num_of_products );
			$limit_of_products = $args['limit'];
			$admin_params      = get_option( 'elex_mv_admin_installation_params', false );     

		include_once ELEX_MULTI_VENDOR_PLUGIN_PATH . '/templates/products/products.php';
	}

	
	public function elex_mv_product_page_tab_categories() {

		if ( ! isset( $_GET['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			return;
		}

		$vendor              = Vendor::load( wp_get_current_user() );
		$store           = $vendor->get_store();
		$vendor_store_id = $store->get_id();

		$category_search = isset( $_GET['category_search'] ) ? sanitize_text_field( wp_unslash( $_GET['category_search'] ) ) : '';
		include_once ELEX_MULTI_VENDOR_PLUGIN_PATH . '/templates/products/categories.php';
	}

	public function elex_mv_edit_attributes_product_tab_content() {
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/products/edit-product/edit-attributes.php';
	}

	public function elex_mv_edit_variations_product_tab_content() {
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/products/edit-product/edit_variations.php';
	}

	public function elex_add_product_content_tab_product_details() {
		$site_settings   = get_option( 'elex_mv_admin_installation_params', false );
		$vendor          = Vendor::load( wp_get_current_user() );
		$store           = $vendor->get_store();
		$vendor_store_id = $store->get_id();

		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/products/product-details-form.php';
	}

	public function elex_add_product_content_tab_inventory() {
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/products/product-inventory.php';
	}

	public function elex_add_product_content_tab_attributes() {
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/products/product-attributes.php';
	}

	public function elex_add_product_content_tab_variations() {
	

		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/products/product-variations.php';
	}

	public function elex_add_product_content_tab_shipping() {
	

		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/products/product-shipping.php';
	}
	public function elex_add_product_content_tab_carriers() {

		$vendor            = Vendor::load( wp_get_current_user() );
		$store             = $vendor->get_store();
		$vendor_store_id   = $store->get_id();
		$vendor_capability = $store->get_checkbox_list();

		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/products/product-carriers.php';
	}

	public function elex_mv_advanced_filter_page() {
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/products/product-advanced-filters.php';
	}
}
