<?php

namespace Elex\MultiVendor\Model;

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

use Elex\MultiVendor\Model\SiteSettings;

class OrderModel {

	


	public function maybe_split_orders( $parent_order ) {

		if ( ! is_a( $parent_order, \WC_Order::class ) ) {
			return;
		}
	$order_id = $parent_order->get_id();

	$this->elex_mv_log(
		sprintf( 'Processing order #%d for sub-order creation.', $order_id )
	);


		if (
		metadata_exists( 'post', $order_id, 'elex_mv_has_sub_order' ) &&
		'1' === $parent_order->get_meta( 'elex_mv_has_sub_order', true )
	) {
			$child_orders = wc_get_orders(
				array(
					'parent' => $order_id,
					'type'   => 'shop_order',
					'limit'  => -1,
					'status' => 'any',
					'return' => 'objects',
				)
			);

			foreach ( $child_orders as $child_order ) {
				$child_order->delete( true );
			}
		}

	$vendors = $this->elex_mv_get_sellers_by( $parent_order );

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

		if ( 1 === count( $vendors ) ) {

			$store_id = array_key_first( $vendors );

			/**
			 * Action to create parent order.
			 *
			 * @since 1.0.0
			 */
			do_action(
				'elex_mv_create_parent_order',
				$parent_order,
				$store_id
			);

			$this->elex_mv_update_admin_commission( $parent_order );
			$this->elex_mv_update_vendor_amount( $parent_order, $store_id );

			$parent_order->update_meta_data( 'elex_mv_store_id', $store_id );
			$parent_order->update_meta_data( 'elex_mv_settlement_status', 'false' );
			$parent_order->delete_meta_data( 'elex_mv_has_sub_order' );
			$parent_order->save();

			$this->send_vendor_order_email( $parent_order, $store_id );

			return;
		}


	$parent_order->update_meta_data( 'elex_mv_has_sub_order', '1' );
	$parent_order->save();

		foreach ( $vendors as $store_id => $seller_products ) {

			$this->create_sub_order(
				$parent_order,
				$store_id,
				$seller_products
			);
		}
	}

	private function send_vendor_order_email( $order, $store_id ) {

		$store_email = get_post_meta( $store_id, 'elex_mv_email', true );
		$store_name  = get_post_meta( $store_id, 'elex_mv_title', true );

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

		$billing       = $order->get_address( 'billing' );
		$customer_name = trim(
			( $billing['first_name'] ?? '' ) . ' ' . ( $billing['last_name'] ?? '' )
		);

		$subject = sprintf(
			'New Order #%d Received - %s',
			$order->get_id(),
			get_bloginfo( 'name' )
		);

		$body  = '<p>Dear ' . esc_html( $store_name ) . ',</p>';
		$body .= '<p>You have received a new order.</p>';
		$body .= '<p><strong>Order ID:</strong> ' . esc_html( $order->get_id() ) . '</p>';
		$body .= '<p><strong>Customer:</strong> ' . esc_html( $customer_name ) . '</p>';
		$body .= '<p><strong>Total:</strong> ' . wp_kses_post( $order->get_formatted_order_total() ) . '</p>';
		$body .= '<p>Please log in to process the order.</p>';

		wp_mail(
			$store_email,
			$subject,
			$body,
			array(
				'Content-Type: text/html; charset=UTF-8',
				'From: ' . get_bloginfo( 'name' ) . ' <' . get_bloginfo( 'admin_email' ) . '>',
			)
		);
	}





	public function elex_mv_get_sellers_by( $order ) {

		if ( ! is_a( $order, \WC_Order::class ) ) {
			return array();
		}

	$sellers = array();

		foreach ( $order->get_items() as $item ) {

			$product = $item->get_product();
			if ( ! $product ) {
				continue;
			}

			if ( $product->is_type( 'variation' ) ) {
				$parent_id = $product->get_parent_id();
				$product   = wc_get_product( $parent_id );
			}

			if ( ! $product ) {
				continue;
			}

			$store_id = $product->get_meta( 'elex_mv_store_id', true );





			if ( empty( $store_id ) ) {
				$store_id = 'admin';
			}

			/**
			 * Filter to get卖家 (sellers) by order item.
			 *
			 * @since 1.0.0
			 */
			$store_id = apply_filters(
				'elex_mv_get_sellers_by',
				$store_id,
				$item,
				$order
			);

			if ( ! isset( $sellers[ $store_id ] ) ) {
				$sellers[ $store_id ] = array();
			}

			$sellers[ $store_id ][] = $item;
		}

	return $sellers;
	}

	public static function elex_mv_get_seller_id_by_order( $order_id, $id = '' ) {
	
		// if seller is not found, try to retrieve it via line items
			$order     = wc_get_order( $order_id );
			$items     = $order->get_items( 'line_item' );
			$seller_id = '';
		if ( ! $items ) {
		/**
		* Fire an filter hook to get seller id by order
		*
		* @since 2.0.0
		* @param $seller_id
		* @param $items
		*/
			return apply_filters( 'elex_mv_get_seller_id_by_order', $seller_id, $items );
		}

	

		$product_id = current( $items )->get_product_id();
		$product    = wc_get_product( $product_id );
	
		if ( 'elex_mv_store_id' === $id ) {
			$seller_id = current( $items )->get_meta( 'elex_mv_store_id', true );

		
				
			$seller_id = current( $items )->get_meta( 'elex_mv_store_id', true ) ? current( $items )->get_meta( 'elex_mv_store_id', true ) : $product->get_meta( 'elex_mv_store_id', true );
			
	
			
			if ( ! $seller_id ) {
				$seller_id = get_post_field( 'post_author', $product_id );

			}       
		} elseif ( is_object( $product ) && ! empty( $product->get_meta( 'elex_mv_store_id', true ) ) ) {

			$store_id  = $product->get_meta( 'elex_mv_store_id', true );
			$seller_id = get_post_field( 'post_author', $store_id );
		} else {

			$seller_id = get_post_field( 'post_author', $product_id );
		}
		
	
			$seller_id = $seller_id ? absint( $seller_id ) : 0;
			
	

		/**
		* Fire an filter hook to get seller id by order
		*
		* @since 2.0.0
		* @param $seller_id
		* @param $items
		*/
			return apply_filters( 'elex_mv_get_seller_id_by_order', $seller_id, $items );
	}

	public function create_sub_order( $parent_order, $store_id, $seller_products ) {

		$this->elex_mv_log( 'Creating sub order for vendor: #' . $store_id );

		$bill_ship = array(
			'billing_country',
			'billing_first_name',
			'billing_last_name',
			'billing_company',
			'billing_address_1',
			'billing_address_2',
			'billing_city',
			'billing_state',
			'billing_postcode',
			'billing_email',
			'billing_phone',
			'shipping_country',
			'shipping_first_name',
			'shipping_last_name',
			'shipping_company',
			'shipping_address_1',
			'shipping_address_2',
			'shipping_city',
			'shipping_state',
			'shipping_postcode',
		);

		try {
			$order = new \WC_Order();

			// save billing and shipping address
			foreach ( $bill_ship as $key ) {
				if ( is_callable( array( $order, "set_{$key}" ) ) ) {
					$order->{"set_{$key}"}( $parent_order->{"get_{$key}"}() );
				}
			}
		   
			// now insert line items
			$this->create_line_items( $order, $seller_products );

			// do shipping
			$this->create_shipping( $order, $parent_order );

			// do tax
			$this->create_taxes( $order, $parent_order, $seller_products );

			// add coupons if any
			$this->create_coupons( $order, $parent_order, $seller_products );
			
	

			// save other details
			$order->set_created_via( 'elex_mv' );
			$order->set_cart_hash( $parent_order->get_cart_hash() );
			$order->set_customer_id( $parent_order->get_customer_id() );
			$order->set_currency( $parent_order->get_currency() );
			$order->set_prices_include_tax( $parent_order->get_prices_include_tax() );
			$order->set_customer_ip_address( $parent_order->get_customer_ip_address() );
			$order->set_customer_user_agent( $parent_order->get_customer_user_agent() );
			$order->set_customer_note( $parent_order->get_customer_note() );
			$order->set_payment_method( $parent_order->get_payment_method() );
			$order->set_payment_method_title( $parent_order->get_payment_method_title() );
			$order->update_meta_data( 'elex_mv_store_id', $store_id );
			$order->update_meta_data( 'elex_mv_suborder', true );
			$order->update_meta_data( 'elex_sub_parent_order_id', $parent_order->get_id() );
			$order->update_meta_data( 'elex_mv_settlement_status', 'false' );
			$order->update_meta_data( 'elex_mv_refund_settlement_status', 'false' );
			
		/**
		* Fire an action hook before calculate totals
		*
		* @since 2.0.0
		* @param $order
		* @param $parent_order
		* @param $seller_products
		*/
			do_action( 'elex_mv_create_sub_order_before_calculate_totals', $order, $parent_order, $seller_products );

			// finally, let the order re-calculate itself and save
	 
			$order->calculate_totals();

			$order->set_status( 'wc-processing' );
			$order->set_parent_id( $parent_order->get_id() );
			
		
			$this->elex_mv_update_admin_commission( $order );
			$this->elex_mv_update_vendor_amount( $order, $store_id );
			$order_id = $order->save();

			$order    = wc_get_order( $order_id );
			$ord_data = $order->get_data();
			foreach ( $order->get_items() as  $item_key => $item_values ) {
			$item_data = $item_values->get_data();

		
			$product_id  = $item_data['product_id'];
			$product     = wc_get_product( $product_id );
			$store_id    = $product->get_meta( 'elex_mv_store_id', true );
			$store_name  = get_post_meta( $store_id, 'elex_mv_title', true );
			$store_email = get_post_meta( $store_id, 'elex_mv_email', true );

			$product_name  = $item_data['name'];
			$quantity      = $item_data['quantity'];
			$line_total    = $item_data['total'];
			$customer_name = $ord_data['billing']['first_name'] . ' ' . $ord_data['billing']['last_name'];
			$customer_addr = implode( ', ', $ord_data['billing'] );


			$to        = $store_email;
			$subject   = 'New Order Received for Your Product on ' . $store_name;
			$body      = ' Dear ' . $store_name . "<br>
			
			We hope this message finds you well.<br>

			Congratulations! You've received a new order for your product on " . get_bloginfo( 'name' ) . '. Here are the details:<br>
			
			- **Order ID:**' . $order_id . '<br>
			- **Product Name:** ' . $product_name . '<br>
			- **Quantity:** ' . $quantity . '<br>
			- **Total Amount:** ' . $line_total . "<br>
			- **Customer's Name:** " . $customer_name . '<br>
			- **Shipping Address:** ' . $customer_addr . '<br>
			
			Please ensure you fulfill the order promptly and provide excellent service to our valued customers. If you have any questions or need assistance, feel free to reach out to us.<br>
			
			Thank you for your commitment to excellence on [Your Multi-Vendor Site]. We wish you continued success!<br>
			
			Best regards,<br>
			';
			$headers   = array();
			$headers[] = 'Content-type: text/html; charset=utf-8';
			$headers[] = 'From:' . get_bloginfo( 'admin_email' );
			// Send email using wp_mail() function



			$result = wp_mail( $to, $subject, $body, $headers );
			}
			// update total_sales count for sub-order
			wc_update_total_sales_counts( $order_id );

			$this->elex_mv_log( 'Created sub order : #' . $order_id );
		/**
		* Fire an action hook after updating order meta
		*
		* @since 2.0.0
		* @param $order_id
		* @param $store_id
		*/
			do_action( 'elex_mv_checkout_update_order_meta', $order_id, $store_id );
		} catch ( Exception $e ) {
			return new WP_Error( 'elex-multi-vendor-for-woocommerce-suborder-error', $e->getMessage() );
		}
	}

	public function elex_mv_update_vendor_amount( $order, $store_id ) {
		$adminearning         = get_post_meta( $store_id, 'elex_mv_admin_earning', true ); // stores the value of logged in user's meta data for 'test'.
		$vendorearning        = get_post_meta( $store_id, 'elex_mv_vendor_earning', true ); 
		$vendor_total_sales   = get_post_meta( $store_id, 'elex_mv_vendor_total_sales', true );
		$vendor_total_earning = get_post_meta( $store_id, 'elex_mv_vendor_total_earning', true );
		$vendor_amount        = (float) $vendorearning + (float) $order->get_meta( 'elex_mv_vendor_earning', true );
		$vendor_earning       = (float) $vendor_total_earning + (float) $order->get_meta( 'elex_mv_vendor_earning', true );
		$vendor_sales         = (float) $vendor_total_sales + (float) $order->get_meta( 'elex_mv_vendor_sales', true );
		$admin_earning_amount = (float) $adminearning + (float) $order->get_meta( 'elex_mv_admin_commission_from_product', true );
		update_post_meta( $store_id, 'elex_mv_vendor_total_sales', $vendor_sales );
		update_post_meta( $store_id, 'elex_mv_vendor_earning', $vendor_amount );
		update_post_meta( $store_id, 'elex_mv_vendor_total_earning', $vendor_earning );
		update_post_meta( $store_id, 'elex_mv_admin_earning', $admin_earning_amount );
	}
	

	public function elex_mv_update_admin_commission( $order ) {
		$site_settings = SiteSettings::load();

		$ship_fee_beared_by = $site_settings->get( 'ship_fee' );
		$order->update_meta_data( 'elex_mv_ship_fee_beared_by', $ship_fee_beared_by );
		$total_ship  = 0;
		$total_sales = 0;

		$items_shipping = $order->get_items( 'shipping' );

		foreach ( $items_shipping as $item_ship ) {
			$total_ship += $item_ship->get_total();
		}
		
		if ( $order ) {
			$commission  = 0;
			$items       = $order->get_items();
			$total_sales = 0;

			foreach ( $items as $item ) {
				$product_id = $item->get_product_id();
				$product    = wc_get_product( $product_id );

				if ( $product->get_meta( 'elex_mv_store_id', true ) ) {             
					$sales        = (float) $item->get_total();
					$commission  += $this->elex_mv_order_calculate_commission( $order, $product_id, $sales , $item->get_quantity() );
					$total_sales += $sales; 
				}
			}

			$vendor_sales   = $total_sales;
			$vendor_earning = $total_sales - $commission;
			if ( 'vendor' === $ship_fee_beared_by ) {
				$vendor_earning = $vendor_earning + $total_ship;
				$vendor_sales   = $total_sales + $total_ship;
			}
			

			$order->update_meta_data( 'elex_mv_vendor_earning', $vendor_earning );
			$order->update_meta_data( 'elex_mv_vendor_sales', $vendor_sales );
			$order->update_meta_data( 'elex_mv_admin_commission_from_product', $commission );

			if ( 'admin' === $ship_fee_beared_by ) {

			$commission = $commission + $total_ship;
			}
			$total_tax_order = $order->get_total_tax();

			$commission = $commission + $total_tax_order;
			
			$order->update_meta_data( 'elex_mv_admin_earning', $commission );

			$order->update_meta_data( 'elex_mv_total_shipping', $total_ship );

		}
		$order->save();
	}
	/**
	 * Calculates the total original admin commission earnings for a parent order
	 * by summing up the original admin earnings meta from all its suborders.
	 *
	 * @param WC_Order $order Parent order object.
	 * @return float Total original admin earnings.
	 */
	public static function get_main_order_admin_earning( $order ) {
		$suborder_ids = wc_get_orders(
			array(
				'parent'      => $order->get_id(),
				'post_type'   => 'shop_order',
				'post_status' => 'any', 
				'numberposts' => -1,
				'return'      => 'ids',
			) 
		);

		$admin_earnings_by_store = 0;
		foreach ( $suborder_ids as $sub_id ) {
			$sub_order                = wc_get_order( $sub_id );
			$admin_earnings_by_store += (float) $sub_order->get_meta( 'elex_mv_admin_earning', true );
		}
		return $admin_earnings_by_store;
	}

	/**
	 * Calculates the total refunded admin commission amount for a parent order
	 * by summing up the admin commission refund meta from all its suborders.
	 *
	 * @param WC_Order $order Parent order object.
	 * @return float Total refunded admin commission.
	 */
	public static function get_main_order_admin_commission_refund( $order ) {
		$suborder_ids = wc_get_orders(
			array(
				'parent'      => $order->get_id(),
				'post_type'   => 'shop_order',
				'post_status' => 'any',
				'numberposts' => -1,
				'return'      => 'ids',
			) 
		);

		$total_refund = 0;
		foreach ( $suborder_ids as $sub_id ) {
			$sub_order    = wc_get_order( $sub_id );
			$total_refund += (float) $sub_order->get_meta( 'elex_mv_admin_commission_refund_amount_products', true );
		}
		return $total_refund;
	}

	public function elex_mv_order_calculate_commission( $order, $product_id, $sales, $qty ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed       
		$product           = wc_get_product( $product_id );
		$commission_type   = ! empty( $product->get_meta( 'elex_mv_commission_type', true ) ) ? $product->get_meta( 'elex_mv_commission_type', true ) : '';
		$commission_amount = ! empty( $product->get_meta( 'elex_mv_commission', true ) ) ? (float) $product->get_meta( 'elex_mv_commission', true ) : 0;
		$commission        = 0;

		
		if ( ! empty( $sales ) ) {
			if ( ! $commission_amount ) {
				$commission = 0;
			}
				$commission = $sales * ( $commission_amount / 100 );
		}
		$sales = $sales - $commission;
		$order->update_meta_data( 'elex_mv_vendor_earned_for_product_id_' . $product_id , $sales );
		$order->update_meta_data( 'elex_mv_commission_cut_for_product_id_' . $product_id , $commission );
		$order->update_meta_data( 'elex_mv_commission_cut_after_refund_for_product_id_' . $product_id , $commission );

		$order->save();
		return $commission;
	}


	
	public function create_line_items( $order, $products ) {
		foreach ( $products as $item ) {
			$product_item = new \WC_Order_Item_Product();

			$product_item->set_name( $item->get_name() );
			$product_item->set_product_id( $item->get_product_id() );
			$product_item->set_variation_id( $item->get_variation_id() );
			$product_item->set_quantity( $item->get_quantity() );
			$product_item->set_tax_class( $item->get_tax_class() );
			$product_item->set_subtotal( $item->get_subtotal() );
			$product_item->set_subtotal_tax( $item->get_subtotal_tax() );
			$product_item->set_total_tax( $item->get_total_tax() );
			$product_item->set_total( $item->get_total() );
			$product_item->set_taxes( $item->get_taxes() );

			$metadata = $item->get_meta_data();
			if ( $metadata ) {
				foreach ( $metadata as $meta ) {
					$product_item->add_meta_data( $meta->key, $meta->value );
				}
			}

			$order->add_item( $product_item );
		}

		$order->save();
		/**
		* Fire an action hook after creating line_items
		*
		* @since 2.0.0
		* @param $order
		*/
		do_action( 'elex_mv_after_create_line_items', $order );
	}

	public function create_shipping( $order, $parent_order ) {

		$this->elex_mv_log( sprintf( '#%d - Creating Shipping.', $order->get_id() ) );

		// Get all shipping methods for parent order

		$shipping_methods = $parent_order->get_shipping_methods();


		$order_seller_id         = $this->elex_mv_get_seller_id_by_order( $order->get_id(), 'elex_mv_store_id' );
		$applied_shipping_method = '';
		if ( $shipping_methods ) {
			foreach ( $shipping_methods as $method_item_id => $shipping_object ) {
				$shipping_seller_id = wc_get_order_item_meta( $method_item_id, 'Vendor_Id', true );


				if ( (int) $order_seller_id === (int) $shipping_seller_id ) {
					$applied_shipping_method = $shipping_object;
					break;
				}
				if ( user_can( $order_seller_id, 'manage_options' ) ) {
					$applied_shipping_method = $shipping_object;
					break;
				}
			}
		}

		/**
		* Fire an filter hook to set shipping method
		*
		* @since 2.0.0
		* @param $applied_shipping_method
		* @param $order_id
		* @param $parent_order
		*/
		$shipping_method = apply_filters( 'elex_mv_shipping_method', $applied_shipping_method, $order->get_id(), $parent_order );
		// bail out if no shipping methods found
		if ( ! $shipping_method ) {
		$this->elex_mv_log( sprintf( '#%d - No shipping method found. Aborting.', $order->get_id() ) );
			return;
		}
		if ( is_a( $shipping_method, 'WC_Order_Item_Shipping' ) ) {
			$item = new \WC_Order_Item_Shipping();

			$this->elex_mv_log( sprintf( '#%d - Adding shipping item.', $order->get_id() ) );

			$item->set_props(
				array(
					'method_title' => $shipping_method->get_name(),
					'method_id'    => $shipping_method->get_method_id(),
					'total'        => $shipping_method->get_total(),
					'taxes'        => $shipping_method->get_taxes(),
				)
			);

			$metadata = $shipping_method->get_meta_data();

			if ( $metadata ) {
				foreach ( $metadata as $meta ) {
					$item->add_meta_data( $meta->key, $meta->value );
				}
			} 
	   
		

			$order->add_item( $item );
			$order->set_shipping_total( $shipping_method->get_total() );
			$order->save();
		}
	}

	public function create_coupons( $order, $parent_order, $products ) {

		$used_coupons = $parent_order->get_items( 'coupon' );
		$product_ids  = array_map(
			function ( $item ) {
				return $item->get_product_id();
			},
			$products
		);

		if ( ! $used_coupons ) {
			return;
		}

		foreach ( $used_coupons as $item ) {
			$coupon = new \WC_Coupon( $item->get_code() );

			if ( $coupon && ! is_wp_error( $coupon ) && array_intersect( $product_ids, $coupon->get_product_ids() ) ) {
				$new_item = new \WC_Order_Item_Coupon();
				$new_item->set_props(
					array(
						'code'         => $item->get_code(),
						'discount'     => $item->get_discount(),
						'discount_tax' => $item->get_discount_tax(),
					)
				);

				$new_item->add_meta_data( 'elex_mv_coupon_data', $coupon->get_data() );

				$order->add_item( $new_item );
			}
		}

		$order->save();
	}

	public function create_taxes( $order, $parent_order, $products ) {

		$shipping  = $order->get_items( 'shipping' );
		$tax_total = 0;

		foreach ( $products as $item ) {
			$tax_total += $item->get_total_tax();
		}

		foreach ( $parent_order->get_taxes() as $tax ) {
			$seller_shipping = reset( $shipping );

			$item = new \WC_Order_Item_Tax();
			$item->set_props(
				array(
					'rate_id'            => $tax->get_rate_id(),
					'label'              => $tax->get_label(),
					'compound'           => $tax->get_compound(),
					'rate_code'          => \WC_Tax::get_rate_code( $tax->get_rate_id() ),
					'tax_total'          => $tax_total,
					'shipping_tax_total' => is_bool( $seller_shipping ) ? '' : $seller_shipping->get_total_tax(),
				)
			);

			$order->add_item( $item );
		}

		$order->save();
	}
	public function elex_mv_log( $message, $level = 'debug' ) {
		$logger  = wc_get_logger();
		$context = array( 'source' => 'elex_mv' );
		return $logger->log( $level, $message, $context );
	}

	public static function order_lists( $store_id = '', $args = array(), $search_key = '' ) {
		$default = array(
			'orderby'    => 'date',
			'order'      => 'DESC',
			'meta_key'   => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
			'meta_value' => $store_id, // phpcs:ignore WordPress.DB.SlowDBQuery
		); 
		
		if ( $search_key ) {
			$orders           = self::mv_search_orders( $search_key , $store_id );
			$args['post__in'] = $orders;
		}

		$filters = array_merge( $default , $args );
		$query   = wc_get_orders( $filters );
		
		return $query;
	}
	public static function mv_search_orders( $term, $store_id ) {
		global $wpdb;

		/**
		 * Searches on meta data can be slow - this lets you choose what fields to search.
		 * 3.0.0 added _billing_address and _shipping_address meta which contains all address data to make this faster.
		 * This however won't work on older orders unless updated, so search a few others (expand this using the filter if needed).
		 *
		 * @var array
		*/
		
		
		$result         = $wpdb->get_results(
			$wpdb->prepare(
				"
			SELECT p.ID as order_id
			FROM {$wpdb->posts} p 
			JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
			JOIN {$wpdb->prefix}woocommerce_order_items oi ON p.ID = oi.order_id
			WHERE 
				(pm.meta_key = '_billing_first_name' AND pm.meta_value LIKE %s) OR
				(pm.meta_key = '_billing_last_name' AND pm.meta_value LIKE %s) OR
				(pm.meta_key = '_shipping_first_name' AND pm.meta_value LIKE %s) OR
				(pm.meta_key = '_shipping_last_name' AND pm.meta_value LIKE %s) OR
				(p.ID LIKE %s)
			GROUP BY p.ID
			",
				'%' . $wpdb->esc_like( $term ) . '%', // for _billing_first_name
				'%' . $wpdb->esc_like( $term ) . '%', // for _billing_last_name
				'%' . $wpdb->esc_like( $term ) . '%', // for _shipping_first_name
				'%' . $wpdb->esc_like( $term ) . '%', // for _shipping_last_name
				'%' . $wpdb->esc_like( $term ) . '%' // for order_id
			),
			ARRAY_A 
		);
		$query_order_id = wp_list_pluck( $result, 'order_id' );
		$query_orders   = implode( ',' , $query_order_id );
	
			
		$result_2 = $wpdb->get_results(
			$wpdb->prepare(
				"
			SELECT
				p.ID as order_id
			FROM
				{$wpdb->posts} p 
				JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
				JOIN {$wpdb->prefix}woocommerce_order_items oi ON p.ID = oi.order_id
			WHERE
				pm.meta_key = 'elex_mv_store_id' AND pm.meta_value = %d AND oi.order_id IN ( %d )
			GROUP BY
				p.ID
			",
				$store_id,
				$query_orders
			),
			ARRAY_A 
		);
		
		return wp_list_pluck( $result_2, 'order_id' );
	}

	public static function order_total_count( $store_id, $filters = array() ) {
		$query = wpFluent()->table( 'posts' );
		$query->join( 'postmeta', 'postmeta.post_id', '=' , 'posts.ID' );
		$query->where( 'postmeta.meta_key' , 'elex_mv_store_id' );
		if ( isset( $store_id ) && ! empty( $store_id ) ) {
			$query->where( 'postmeta.meta_value' , $store_id );
		}
		$query->where( 'posts.post_type' , 'shop_order' );

		if ( isset( $filters['s'] ) && ! empty( $filters['s'] ) ) {
			$query->where( 'post_title', 'like', '%' . $filters['s'] . '%' );
		}

		$query->orderBy( 'posts.ID', 'DESC' );
		update_post_meta( $store_id, 'elex_mv_total_vendor_order' , $query->count() );
		return $query->count();
	}
	
	public static function update_order_status_count( $store_id ) {
		$status = array(
			'completed'  => 'wc-completed',
			'processing' => 'wc-processing',
			'onhold'     => 'wc-on-hold',
			'pending'    => 'wc-pending',
			'cancelled'  => 'wc-cancelled',
			'refunded'   => 'wc-refunded',
		);
		foreach ( $status as $key => $val ) {
			$customer_orders = get_posts(
				array(
					'numberposts' => -1,
					'meta_key'    => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
					'meta_value'  => $store_id, // phpcs:ignore WordPress.DB.SlowDBQuery
					'post_type'   => 'shop_order',
					'post_status' => array( $val ),
				) 
			);
			update_post_meta( $store_id, 'elex_mv_order_status_' . $key, count( $customer_orders ) );
		}
	}
}
