<?php


namespace Elex\MultiVendor\Controller;

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

use Elex\MultiVendor\Model\OrderModel;
use Elex\MultiVendor\Model\Vendor;
use Elex\MultiVendor\Model\SiteSettings;

class OrderController {
	public static function init() {
		$self = new self();
		add_filter( 'manage_woocommerce_page_wc-orders_columns', array( $self, 'elex_mv_admin_shop_order_edit_columns' ), 10, 1 );
		add_action( 'manage_woocommerce_page_wc-orders_custom_column', array( $self, 'elex_mv_shop_order_custom_columns' ), 10, 2 );  

		add_action( 'admin_head', array( $self, 'remove_refund_button' ) );


		add_action( 'elex_mv_orders_page', array( $self, 'mv_order_tab_content' ) );
		add_action( 'wp_ajax_elex_mv_vendor_order_export', array( $self, 'elex_mv_vendor_order_export' ) );
		add_action( 'wp_ajax_elex_mv_change_status', array( $self, 'elex_mv_change_status' ) );
		add_action( 'elex_mv_order_detail_page', array( $self, 'elex_mv_order_page_detail' ) );
		// on order status change
		add_action( 'woocommerce_order_status_changed', array( $self, 'elex_mv_order_status_change' ), 10, 4 );
		add_action( 'woocommerce_order_status_changed', array( $self, 'elex_mv_suborder_status_change' ), 99, 1 );

		add_action( 'woocommerce_order_status_completed', array( $self, 'send_order_completed_email' ), 10, 1 );

		add_action( 'admin_enqueue_scripts', array( $self, 'elex_mv_admin_shop_order_scripts' ) );
	   
		add_filter( 'woocommerce_shop_order_list_table_order_css_classes', array( $self, 'elex_mv_admin_shop_order_row_classes' ), 99, 2 );

		// create sub-orders
		add_action( 'woocommerce_checkout_order_created', array( $self, 'elex_mv_split_vendor_orders' ) );
		add_action( 'woocommerce_store_api_checkout_order_processed', array( $self, 'elex_mv_split_vendor_orders' ) );


		add_action( 'woocommerce_order_refunded', array( $self, 'elex_mv_woocommerce_order_refunded' ), 10, 2 ); 

		add_action( 'wp_ajax_elex_mv_refund_line_items', array( $self, 'elex_mv_refund_line_items' ), 10, 2 ); 

		add_action( 'woocommerce_order_status_changed', array( $self, 'elex_custom_order_status_changed' ) , 10, 4 );
	}
	public function elex_custom_order_status_changed( $order_id, $old_status, $new_status, $order ) {
		// Check if the new status is 'refunded' update old status of order
		if ( 'refunded' === $new_status ) {
			$order->update_meta_data( 'elex_mv_order_old_status', 'wc-' . $old_status );
			$order->save();
		}
	}

	public function remove_refund_button() {

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- only reading URL context to apply UI styles with no state changes
		$post_id  = isset( $_GET['post'] ) ? absint( wp_unslash( $_GET['post'] ) ) : 0;
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- only reading URL context to apply UI styles with no state changes
		$page     = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- only reading URL context to apply UI styles with no state changes
		$order_id = isset( $_GET['id'] )   ? absint( wp_unslash( $_GET['id'] ) ) : 0;


		$order = null;

		if ( $post_id ) {
			$order = wc_get_order( $post_id );
		} elseif ( 'wc-orders' === $page ) {
			$order = wc_get_order( $order_id );
		}

		if ( is_object( $order ) && $order->get_meta( 'elex_mv_has_sub_order' ) ) {

			wp_add_inline_style(
				'elex-mv-order-controller',
				'.refund-items { display: none !important; }'
			);
		}
	}

	public function send_order_completed_email( $order_id ) {

		$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 trust this message finds you well.</br>

			We're pleased to inform you that the order for your product on" . get_bloginfo( 'name' ) . ' has been completed. 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 ' . $store_name . ' . 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 );
		}
	}

	public function elex_mv_refund_line_items() {

		if ( ! current_user_can( 'elex_mv_vendor' ) && ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Forbidden', 403 );
		}

		if ( ! isset( $_POST['elex_mv_refund_line_items_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['elex_mv_refund_line_items_nonce'] ) ), 'elex_mv_refund_line_items_action' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
		


		$order_id               = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
		$refund_amount          = isset( $_POST['total_refund_amount'] ) ? wc_format_decimal( sanitize_text_field( wp_unslash( $_POST['total_refund_amount'] ) ), wc_get_price_decimals() ) : 0;
		$refund_reason          = isset( $_POST['reason_to_refund'] ) ? sanitize_text_field( wp_unslash( $_POST['reason_to_refund'] ) ) : '';
		$line_item_qtys         = isset( $_POST['refund_line_item_quantity'] ) ? map_deep( wp_unslash( $_POST['refund_line_item_quantity'] ), 'sanitize_text_field' ) : array();
		$line_item_totals       = isset( $_POST['refund_line_item_price'] ) ? map_deep( wp_unslash( $_POST['refund_line_item_price'] ), 'sanitize_text_field' ) : array();
		$line_item_tax_totals   = isset( $_POST['refund_line_item_tax'] ) ? map_deep( wp_unslash( $_POST['refund_line_item_tax'] ), 'sanitize_text_field' ) : array();
		$api_refund             = isset( $_POST['api_refund'] ) && 'true' === $_POST['api_refund'];
		$restock_refunded_items = isset( $_POST['restock_items'] ) && 'true' === $_POST['restock_items'];

		try {
			$order      = wc_get_order( $order_id );
			
			// Security Check: Ensure vendors can only refund line items on orders belonging to their own store
			if ( ! current_user_can( 'manage_woocommerce' ) ) {
				$vendor   = Vendor::load( wp_get_current_user() );
				$store    = $vendor ? $vendor->get_store() : null;
				$store_id = $store ? $store->get_id() : 0;
				if ( (int) $order->get_meta( 'elex_mv_store_id', true ) !== (int) $store_id ) {
					throw new \Exception( __( 'You are not authorized to perform this action on this order', 'elex-multi-vendor-for-woocommerce' ) );
				}
			}

			$max_refund = wc_format_decimal( $order->get_total() - $order->get_total_refunded(), wc_get_price_decimals() );

			if ( ( ! $refund_amount && ( wc_format_decimal( 0, wc_get_price_decimals() ) !== $refund_amount ) ) || $max_refund < $refund_amount || 0 > $refund_amount ) {
				throw new \Exception( __( 'Invalid refund amount', 'elex-multi-vendor-for-woocommerce' ) );
			}

			// Prepare line items which we are refunding.
			$line_items = array();
			$item_ids   = array_unique( array_merge( array_keys( $line_item_qtys ), array_keys( $line_item_totals ) ) );

			foreach ( $item_ids as $item_id ) {
				$line_items[ $item_id ] = array(
					'qty'          => 0,
					'refund_total' => 0,
					'refund_tax'   => array(),
				);
			}

			foreach ( $line_item_qtys as $item_id => $qty ) {
				$line_items[ $item_id ]['qty'] = max( $qty, 0 );
			}
			foreach ( $line_item_totals as $item_id => $total ) {
				$line_items[ $item_id ]['refund_total'] = wc_format_decimal( $total );
			}
			foreach ( $line_item_tax_totals as $item_id => $tax_totals ) {
				$line_items[ $item_id ]['refund_tax'] = array_filter( array_map( 'wc_format_decimal', $tax_totals ) );
			}

			// Create the refund object.
			$refund = wc_create_refund(
				array(
					'amount'         => $refund_amount,
					'reason'         => $refund_reason,
					'order_id'       => $order_id,
					'line_items'     => $line_items,
					'refund_payment' => $api_refund,
					'restock_items'  => $restock_refunded_items,
				)
			);

			if ( is_wp_error( $refund ) ) {
				throw new \Exception( $refund->get_error_message() );
			}

			if ( did_action( 'woocommerce_order_fully_refunded' ) ) {
				$response['status'] = 'fully_refunded';
			}
		} 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 );
	}


	public function elex_mv_admin_shop_order_row_classes( $classes, $order ) {   
		$post_re = get_post( $order->get_id() );

		$parent_id = $post_re->post_parent ? $post_re->post_parent : $order->get_parent_id();
		if ( is_search() || ! current_user_can( 'manage_woocommerce' ) ) { // phpcs:ignore WordPress.WP.Capabilities.Unknown
			return $classes;
		}
		$vendor_id = ! empty( get_query_var( 'vendor_id' ) ) ? sanitize_text_field( wp_unslash( get_query_var( 'vendor_id' ) ) ) : '';
	
		if ( $vendor_id ) {
			return $classes;
		}
	
		if ( 0 !== $parent_id ) {
			$classes[] = 'sub-order parent-' . $parent_id;
		}   
		return $classes;
	}

	public function elex_mv_admin_shop_order_scripts( $hook ) {

	// HPOS orders page: woocommerce_page_wc-orders
	// Legacy CPT orders page: edit.php?post_type=shop_order
	$is_hpos   = 'woocommerce_page_wc-orders' === $hook;

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only GET request on protected admin screen to identify the custom post type context.
	$is_legacy = 'edit.php' === $hook
					&& isset( $_GET['post_type'] )
					&& 'shop_order' === sanitize_key( $_GET['post_type'] );

		if ( ! $is_hpos && ! $is_legacy ) {
			return;
		}


	$user_id   = get_current_user_id();
	$user_data = get_userdata( $user_id );

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

	$user_roles = (array) $user_data->roles;
	$is_admin   = in_array( 'administrator', $user_roles, true );

   
	wp_register_script( 'elex-admin-orders', false, array( 'jquery' ), '1.0', true );
	wp_enqueue_script( 'elex-admin-orders' );

	wp_register_style( 'elex-admin-orders-style', false, array(), '1.0' );
	wp_enqueue_style( 'elex-admin-orders-style' );

	$js = '
    jQuery(function($) {

        ' . ( $is_admin ? "$('tr.sub-order').hide();" : "$('tr.sub-order').show();" ) . "

        $('a.show-sub-orders').on('click', function(e) {
            e.preventDefault();

            var \$self = $(this),
                el = $('tr.' + \$self.data('class') );

            if ( el.is(':hidden') ) {
                el.show();
                \$self.text( \$self.data('hide') );
            } else {
                el.hide();
                \$self.text( \$self.data('show') );
            }
        });

        $('button.toggle-sub-orders').on('click', function(e) {
            e.preventDefault();
            $('tr.sub-order').toggle();
        });

    });
    ";

	wp_add_inline_script( 'elex-admin-orders', $js );

	$css = '
    tr.sub-order { background: #ECFFF2; }
    th#order_number { width: 21ch; }
    th#order_date { width: 9ch; }
    th#order_status { width: 12ch; }
    th#shipping_address { width: 18ch; }
    th#wc_actions { width: 9ch; }
    th#seller { width: 6ch; }
    th#suborder { width: 9ch; }
    ';

	wp_add_inline_style( 'elex-admin-orders-style', $css );
	}
	



	public function elex_mv_admin_shop_order_edit_columns( $existing_columns ) {

		if ( WC_VERSION > '3.2.6' ) {
			unset( $existing_columns['wc_actions'] );
	
			$columns = array_slice( $existing_columns, 0, count( $existing_columns ), true ) +
				array(
					'seller'                => __( 'ELEX Vendor', 'elex-multi-vendor-for-woocommerce' ),
					'suborder'              => __( 'Sub Order', 'elex-multi-vendor-for-woocommerce' ),
					'elex_mv_admin_earning' => __( 'Admin Earning', 'elex-multi-vendor-for-woocommerce' ),
				)
				+ array_slice( $existing_columns, count( $existing_columns ), count( $existing_columns ) - 1, true );
		} else {
			$existing_columns['seller'] = __( 'ELEX Vendor', 'elex-multi-vendor-for-woocommerce' );
			if ( is_admin() ) {
				$existing_columns['suborder']              = __( 'Sub Order', 'elex-multi-vendor-for-woocommerce' );
				$existing_columns['elex_mv_admin_earning'] = __( 'Admin Earning', 'elex-multi-vendor-for-woocommerce' );

			}
		}
	
		if ( WC_VERSION > '3.2.6' ) {
			// Remove seller, suborder column if seller is viewing his own product
			if ( ! current_user_can( 'manage_woocommerce' ) || ( ! empty( get_query_var( 'author' ) ) ) ) { // phpcs:ignore WordPress.WP.Capabilities.Unknown
				unset( $columns['suborder'] );
				unset( $columns['seller'] );
			}
		/**
		 * Fires hook to edit shop order coloumn
		 * 
		 * @since 1.0.0
		 * @param $existing_columns
		 */
			return apply_filters( 'elex_edit_shop_order_columns', $columns );
		}
	
		// Remove seller, suborder column if seller is viewing his own product
		if ( ! current_user_can( 'manage_woocommerce' ) || ( ! empty( get_query_var( 'author' ) ) ) ) { // phpcs:ignore WordPress.WP.Capabilities.Unknown
			unset( $existing_columns['suborder'] );
			unset( $existing_columns['seller'] );
		}
		/**
		* Fires hook to edit shop order coloumn
		* 
		* @since 1.0.0
		* @param $existing_columns
		*/
		return apply_filters( 'elex_mv_edit_shop_order_columns', $existing_columns );
	}

	public function elex_mv_shop_order_custom_columns( $col, $obj ) {

		// global $post, $the_order;

		$post_re = get_post( $obj->get_id() );

		$order = wc_get_order( $obj->get_id() );

	
		$parent = $post_re->post_parent ? $post_re->post_parent : $order->get_parent_id();

		if ( ! current_user_can( 'manage_woocommerce' ) ) { // phpcs:ignore WordPress.WP.Capabilities.Unknown
			return $col;
		}

		switch ( $col ) {

			case 'order_number':
				if ( 0 !== $parent ) {
					echo '<strong>';
					echo esc_html__( '&nbsp;Sub Order of', 'elex-multi-vendor-for-woocommerce' );
					printf( ' <a href="%s">#%s</a>', esc_url( admin_url( 'post.php?action=edit&post=' . $parent ) ), esc_html( $parent ) );
					echo '</strong>';
				}
				break;
	
			case 'suborder':
				$has_sub = $order->get_meta( 'elex_mv_has_sub_order', true );

				if ( '1' === $has_sub ) {
					printf( '<a href="#" class="show-sub-orders" data-class="parent-%1$d" data-show="%2$s" data-hide="%3$s">%2$s</a>', esc_attr( $obj->get_id() ), esc_attr__( 'Show Sub-Orders', 'elex-multi-vendor-for-woocommerce' ), esc_attr__( 'Hide Sub-Orders', 'elex-multi-vendor-for-woocommerce' ) );
				}
				break;
	
			case 'seller':
				$has_sub = $order->get_meta( 'elex_mv_has_sub_order', true );
			
				if ( '1' !== $has_sub ) {
					$user_data = OrderModel::elex_mv_get_seller_id_by_order( $post_re );
					$seller    = get_user_by( 'id', $user_data );
					
					printf( '<p>%s</p>', esc_html( isset( $seller->display_name ) ? $seller->display_name : '--' ) );
				}
				break;

			case 'elex_mv_admin_earning':
				// Fetch original admin earning and refunded amounts from metadata
				$admin_earned  = $order->get_meta( 'elex_mv_admin_earning', true );
				$refund_amount = $order->get_meta( 'elex_mv_admin_commission_refund_amount_products', true );
				$has_sub       = $order->get_meta( 'elex_mv_has_sub_order', true );

				// If this is a parent order, sum up the earnings and refunds from all its suborders
				if ( $has_sub ) {
					$admin_earned  = OrderModel::get_main_order_admin_earning( $order );
					$refund_amount = OrderModel::get_main_order_admin_commission_refund( $order );
				}
				
				// Render refunded style if there is a refunded amount, otherwise render normally
				if ( $refund_amount ) {
					printf( '<del>%s</del> ', wp_kses_post( wc_price( $admin_earned ) ) );

					echo ' <span class="tips" data-tip="' . esc_attr( sprintf( /* translators: %s: refunded amount */__( 'Refunded Amount %s', 'elex-multi-vendor-for-woocommerce' ), wp_kses_post( wc_price( $refund_amount ) ) ) ) . '"><ins>' . wp_kses_post( wc_price( (float) $admin_earned - (float) $refund_amount ) ) . '</ins></span>';

				} else {
					printf( '<p>%s</p>', wp_kses_post( wc_price( $admin_earned ) ) );
				}
				break;
		}
	}


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

		$vendor         = Vendor::load( wp_get_current_user() );
		$store          = $vendor->get_store();
		$store_id       = $store->get_id();
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only pagination parameter for UI state.
		$current_page   = ! empty( filter_input( INPUT_GET, 'page_order' , FILTER_SANITIZE_NUMBER_INT ) ) ? absint( filter_input( INPUT_GET, 'page_order' , FILTER_SANITIZE_NUMBER_INT ) ) : 1;
		$order_per_page = 6; // Number of orders per page
		$search_key     = '';
		$GET_status     = '';

		$args = array(
			'limit' => $order_per_page, // How many per page
			'paged' => $current_page, // What page to get, starting from 1.

		);
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only search parameter for filtering UI lists.
		if ( ! empty( filter_input( INPUT_GET, 'search_term' , FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ) ) {
			$search_key       = sanitize_text_field( filter_input( INPUT_GET, 'search_term' , FILTER_SANITIZE_FULL_SPECIAL_CHARS ) );
			$args['order_id'] = $search_key;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only status parameter for filtering UI lists.
		if ( ! empty( get_query_var( 'status' ) ) && 'all' !== get_query_var( 'status' ) ) {
			$GET_status = sanitize_text_field( wp_unslash( get_query_var( 'status' ) ) );
			$args['status'] = array( $GET_status );
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only date range parameters for filtering UI lists.
		if ( ! empty( get_query_var( 'from_date' ) ) && ! empty( get_query_var( 'to_date' ) ) ) {
			$args['date_created'] = get_query_var( 'from_date' ) . '...' . get_query_var( 'to_date' );
		}
		$query                = OrderModel::order_lists( $store_id, $args, $search_key );
		$orders               = $query;
		$total_count          = OrderModel::order_total_count( $store_id , $args );
		$total_order_per_page = ceil( $total_count / $order_per_page );
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/orders/orders.php';
	}

	public function elex_mv_order_page_detail() {
		$site_settings = SiteSettings::load();
		$order_id      = ! empty( get_query_var( 'order_id' ) ) ? sanitize_text_field( get_query_var( 'order_id' ) ) : ''; 
		$order         = wc_get_order( $order_id );
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/orders/order-detail.php';
	}

	/**
	 * AJAX handler to change order status.
	 * Simply updates the order status in WooCommerce.
	 */
	public function elex_mv_change_status() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'mv_nonce' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
		if ( ! current_user_can( 'elex_mv_vendor' ) && ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'You are not authorized to perform this action', 403 );
		}
		if ( isset( $_POST['order_id'] ) && ! empty( $_POST['order_id'] ) ) {
			
			$ids = wp_parse_id_list( wp_unslash( $_POST['order_id'] ) );
			$status = isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '';
			
			foreach ( $ids as $id ) {
				$order = wc_get_order( $id );
				if ( ! $order ) {
					continue;
				}
				
				// Security Check: Ensure vendors can only modify orders/suborders belonging to their own store
				if ( ! current_user_can( 'manage_woocommerce' ) ) {
					$vendor   = Vendor::load( wp_get_current_user() );
					$store    = $vendor ? $vendor->get_store() : null;
					$store_id = $store ? $store->get_id() : 0;
					if ( (int) $order->get_meta( 'elex_mv_store_id', true ) !== (int) $store_id ) {
						wp_send_json_error( 'You are not authorized to perform this action on this order', 403 );
					}
				}
				
				$order->set_status( $status );
				$order->save();
			}
		}   
		wp_send_json_success();
	}

	public function elex_mv_split_vendor_orders( $parent_order ) {

		$is_order_splitted = $parent_order->get_meta( 'elex_mv_order_splitted_' . $parent_order->get_id(), true );

		if ( empty( $is_order_splitted ) || ! $is_order_splitted ) {
			$order = new OrderModel();

			$neworder = $order->maybe_split_orders( $parent_order );

			$parent_order->update_meta_data( 'elex_mv_order_splitted_' . $parent_order->get_id(), true );
			$parent_order->save();
		}
	}

	public function elex_mv_order_status_change( $order_id, $old_status, $new_status, $order ) {
		// Split order if the order doesn't have parent and sub orders,
		// and the order is created from dashboard.
		if ( empty( $order->post_parent ) && empty( $order->get_meta( 'elex_mv_has_sub_order' ) ) && is_admin() ) {
			// Remove the hook to prevent recursive callas.
			remove_action( 'woocommerce_order_status_changed', array( $this, 'elex_mv_order_status_change' ), 10 );
			// Split the order.
			$splitorder = new OrderModel();

			// $splitorder->maybe_split_orders( $order_id );

			// Add the hook back.
			add_action( 'woocommerce_order_status_changed', array( $this, 'elex_mv_order_status_change' ), 10, 4 );
		}

		// make sure order status contains "wc-" prefix
		if ( stripos( $new_status, 'wc-' ) === false ) {
			$new_status = 'wc-' . $new_status;
		}
		// if any child orders found, change the orders as well
		$sub_orders = get_children(
			array(
				'post_parent' => $order_id,
				'post_type'   => 'shop_order',
			)
		);

		if ( $sub_orders ) {
			foreach ( $sub_orders as $order_post ) {
				$order = wc_get_order( $order_post->ID );
				$order->update_status( $new_status );
			}
		}
	}

	public function elex_mv_suborder_status_change( $order_id ) {
		$order_post = get_post( $order_id );
		// we are monitoring only child orders
		if ( 0 === $order_post->post_parent ) {
			return;
		}
		// get all the child orders and monitor the status
		$parent_order_id = $order_post->post_parent;
		$sub_orders      = get_children(
			array(
				'post_parent' => $parent_order_id,
				'post_type'   => 'shop_order',
			)
		);

		// return if any child order is not completed
		$all_complete   = true;
		$all_processing = true;
		$all_onhold     = true;
		$all_refunded   = true;
		if ( $sub_orders ) {
			foreach ( $sub_orders as $sub ) {
				$order = wc_get_order( $sub->ID );

				if ( 'completed' !== $order->get_status() ) {
					$all_complete = false;
				}
				if ( 'processing' !== $order->get_status() ) {
					$all_processing = false;
				}
				if ( 'on-hold' !== $order->get_status() ) {
					$all_onhold = false;
				}
				if ( 'refunded' !== $order->get_status() ) {
					$all_refunded = false;
				}
			}
		}
		if ( $all_complete ) {
			$parent_order = wc_get_order( $parent_order_id );
			$parent_order->update_status( 'wc-completed', __( 'Mark parent order completed when all child orders are completed.', 'elex-multi-vendor-for-woocommerce' ) );
		}
		if ( $all_processing ) {
			$parent_order = wc_get_order( $parent_order_id );
			$parent_order->update_status( 'wc-processing', __( 'Mark parent order processing when all child orders are processing.', 'elex-multi-vendor-for-woocommerce' ) );
		}
		if ( $all_onhold ) {
			$parent_order = wc_get_order( $parent_order_id );
			$parent_order->update_status( 'wc-on-hold', __( 'Mark parent order on-hold when all child orders are on-hold.', 'elex-multi-vendor-for-woocommerce' ) );
		}
		if ( $all_refunded ) {
			$parent_order = wc_get_order( $parent_order_id );
			$parent_order->update_status( 'wc-refunded', __( 'Mark parent order refunded when all child orders are refunded.', 'elex-multi-vendor-for-woocommerce' ) );
		}
	}


	public function elex_mv_woocommerce_order_refunded( $order_id, $refund_id ) {

		$order    = wc_get_order( $order_id );
		$ord_data = $order->get_data();
		
		$order_store_id  = $order->get_meta( 'elex_mv_store_id', true );
		$refunds         = new \WC_Order_Refund( $refund_id );
		$shipping_refund = $refunds->get_shipping_total();
	
		self::elex_refund_on_parent_order( $order, $refunds );
	
	
		foreach ( $refunds->get_items() as $item_id => $item ) {

			
				// ## --- Using WC_Order_Item_Product methods --- ##
				$product_id = $item->get_product_id(); // Quantity: zero or negative integer
			if ( ! $product_id ) {
				continue;
			}
				$product                          = wc_get_product( $product_id );
				$item_commission_cut              = $order->get_meta( 'elex_mv_commission_cut_for_product_id_' . $product_id, true );
				$item_commission_cut_after_refund = $order->get_meta( 'elex_mv_commission_cut_after_refund_for_product_id_' . $product_id, true ) ? $order->get_meta( 'elex_mv_commission_cut_after_refund_for_product_id_' . $product_id, true ) : $order->get_meta( 'elex_mv_commission_cut_for_product_id_' . $product_id, true );

				$store_id      = $product->get_meta( 'elex_mv_store_id', true );
				$seller_id     = get_post_field( 'post_author', $store_id );
				$AuthorData    = get_userdata( $seller_id );
				$AuthorRoles   = array();
				$AuthorRoles   = (array) $AuthorData->roles;
				$product_total = $product->get_price();
			if ( in_array( 'elex_mv_vendor', $AuthorRoles ) ) {
				
				$refunded_line_subtotal = ( $item->get_subtotal() < 0 ) ? $item->get_subtotal() * -1 : $item->get_subtotal();

				$order_line_item_subtotal = 1;

				// Get all items in the order
				$order_items = $order->get_items();

				// Loop through order items to find the corresponding order line item
				foreach ( $order_items as $order_item ) {

					if ( (string) $item->get_meta( '_refunded_item_id', true ) === (string) $order_item->get_id() ) {
							
						$order_line_item_subtotal = $order_item->get_subtotal();

						break;
					}
				}

					$ratio_refund = $refunded_line_subtotal / $order_line_item_subtotal;
				
					$earning_amount = get_post_meta( $order_store_id, 'elex_mv_vendor_earning', true );
					$admin_earning  = get_post_meta( $order_store_id, 'elex_mv_admin_earning', true );

					$earning_amount = $earning_amount ? $earning_amount : 0;
				

					$order_line_item_cost_earned_vendor = (float) $order_line_item_subtotal - (float) $item_commission_cut;

					$refunded_line_subtotal_ratio_vendor = (float) $order_line_item_cost_earned_vendor * (float) $ratio_refund ;

					$refunded_item_commission_cut_ratio_vendor = (float) $item_commission_cut * (float) $ratio_refund ;

					$earning_amount = $earning_amount - $refunded_line_subtotal_ratio_vendor ;
			
					$admin_earning = $admin_earning - $refunded_item_commission_cut_ratio_vendor;
				   
				 
					update_post_meta( $order_store_id, 'elex_mv_vendor_earning', $earning_amount );

					update_post_meta( $order_store_id, 'elex_mv_admin_earning', $admin_earning );

					//update refund amount
					$vendor_refund                 = get_post_meta( $order_store_id, 'elex_mv_vendor_refund_amount', true );
					$vendor_refund                 = ( float ) $vendor_refund + (float) $refunded_line_subtotal_ratio_vendor;
					$vendor_last_settlement_refund = get_post_meta( $order_store_id, 'elex_mv_vendor_last_settlement_refund', true );
					$vendor_last_settlement_amount = ( float ) $vendor_last_settlement_refund + ( float ) $refunded_line_subtotal_ratio_vendor;
					update_post_meta( $order_store_id, 'elex_mv_vendor_refund_amount', $vendor_refund );
					update_post_meta( $order_store_id, 'elex_mv_vendor_last_settlement_refund', $vendor_last_settlement_amount );
					$order_refund                   = $order->get_meta( 'elex_mv_admin_commission_refund_amount_products' );
					$order_refund_product_to_vendor = ! empty( $order->get_meta( 'elex_mv_refund_amount_product_to_vendor' ) ) ? $order->get_meta( 'elex_mv_refund_amount_product_to_vendor' ) : 0 ;
					$order_full_refunded_product    = $order->get_meta( 'elex_mv_refunded_amount_product' );

					$order_refund                     = ( float ) $refunded_item_commission_cut_ratio_vendor + ( float ) $order_refund;
					$order_refund_product_to_vendor   = ( float ) $order_refund_product_to_vendor + ( float ) $refunded_line_subtotal_ratio_vendor ;
					$order_full_refunded_product      = ( float ) $order_full_refunded_product + ( float ) $refunded_line_subtotal;
					$item_commission_cut_after_refund = (float) $item_commission_cut_after_refund - (float) $order_refund;
					$order_status                     = $order->get_status(); // Get the order status (see the conditional method has_status() below)

				if ( 'refunded' === $order_status ) {
					$order->update_meta_data( 'elex_mv_item_full_refund' , 'true' );
					if ( $order->get_meta( 'elex_mv_refund_settlement_status' ) === 'false' ) {
					$partial_refund = ! empty( $order->get_meta( 'elex_mv_item_partial_refund_amount' ) ) ? $order->get_meta( 'elex_mv_item_partial_refund_amount' ) : 0;
					} else {
					$partial_refund = 0;
					}
					$full_refund = ! empty( $order->get_meta( 'elex_mv_item_full_refund_amount' ) ) ? $order->get_meta( 'elex_mv_item_full_refund_amount' ) : 0;
					$full_refund = $full_refund + (float) $partial_refund + ( float ) $refunded_line_subtotal_ratio_vendor;
					$order->update_meta_data( 'elex_mv_item_full_refund_amount' , $full_refund );
					$order->update_meta_data( 'elex_mv_item_partial_refund_amount' , 0 );
					$order->update_meta_data( 'elex_mv_item_partial_refund' , 'false' );
				} else {
					$order->update_meta_data( 'elex_mv_item_partial_refund' , 'true' );
					$partial_refund = $order->get_meta( 'elex_mv_item_partial_refund_amount' );
					if ( $partial_refund ) {
						$partial_refund = $partial_refund + ( float ) $refunded_line_subtotal_ratio_vendor;
						$order->update_meta_data( 'elex_mv_item_partial_refund_amount' , $partial_refund );
					} else {
						$order->update_meta_data( 'elex_mv_item_partial_refund_amount' , $order_refund_product_to_vendor );
					}
					$order->update_meta_data( 'elex_mv_item_full_refund' , 'false' );
				}
		
					$order->update_meta_data( 'elex_mv_commission_cut_after_refund_for_product_id_' . $product_id, $item_commission_cut_after_refund );
					$order->update_meta_data( 'elex_mv_admin_commission_refund_amount_products', $order_refund );
					$order->update_meta_data( 'elex_mv_refund_amount_product_to_vendor', $order_refund_product_to_vendor );
					$order->update_meta_data( 'elex_mv_refunded_amount_product', $order_full_refunded_product );

				if ( $order->get_meta( 'elex_mv_refund_settlement_status' ) !== 'false' ) {
					
					$partial_refund_amount = $order->get_meta( 'elex_mv_item_partial_refund_amount' );
					if ( $partial_refund_amount ) {
						$order->update_meta_data( 'elex_mv_item_partial_refund_amount' , $refunded_line_subtotal_ratio_vendor );
					}
						
					$order->update_meta_data( 'elex_mv_order_shipping_refund_amount_vendor', 0 );
					$order->update_meta_data( 'elex_mv_refund_settlement_status' , 'false' );
				}           
			}  
			
			$item_data = $item->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       = 'Order Refunded for Your Product on ' . $store_name;
			$body          = ' Dear ' . $store_name . '<br>

			
			We hope this message finds you well.<br>

			We regret to inform you that the order for your product on ' . $store_name . ' has been refunded. Here are the details:<br>


			- **Order ID:**' . $order_id . '
			- **Product Name:** ' . $product_name . '
			- **Refunded Quantity:** ' . -1 * $quantity . '
			- **Refunded Amount:** ' . -1 * $line_total . "
			- **Customer's Name:** " . $customer_name . '
			- **Shipping Address:** ' . $customer_addr . '<br>
			
			If you have any questions or concerns regarding the refund, please contact us. We appreciate your understanding and cooperation in providing the best service to our customers.<br>

			Thank you for your ongoing commitment to ' . get_bloginfo( 'name' ) . '.<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 );
		}
		if ( $shipping_refund ) {
			self::elex_mv_shipping_refund( $shipping_refund, $order );
		}
	
		$order->update_meta_data( 'elex_mv_full_refund_amount', $refunds->get_amount() );

		$order->save();
	}
	public static function elex_refund_on_parent_order( $order, $refunds ) {
		// Identify if this is a suborder by checking for the parent order ID meta
		$parent_order_id = $order->get_meta( 'elex_sub_parent_order_id', true );
		$parent_order    = wc_get_order( $parent_order_id );
		$vendor_id       = $order->get_meta( 'elex_mv_store_id', true );
	
		if ( $parent_order_id ) {
			// Get refunded item details
			$product_refund_total  = 0;
			$shipping_refund_total = 0;
			$item_to_refund        = array();

			// 1. Process Shipping Refunds:
			// Map suborder shipping items to corresponding parent order shipping items
			$shippings_refund = $refunds->get_items( 'shipping' );
			foreach ( $shippings_refund as $shipping_item ) {
				$shipping_id                = $shipping_item->get_method_id();
				$per_shipping_refund        = $shipping_item->get_total();

				$ship_line_item = null;
				foreach ( $parent_order->get_items( 'shipping' ) as $ship_item ) {
					$ship_id_parent = $ship_item->get_method_id();
					if ( $shipping_id === $ship_id_parent && $vendor_id === $ship_item->get_meta( 'Vendor_Id', true ) ) {
						$ship_line_item = $ship_item;
						break;
					}
				}
			
				if ( ! $ship_line_item ) {
					continue;
				}

				// Validate shipping refund amount against the parent order's remaining shipping balance
				$parent_shipping_refunded = $parent_order->get_total_shipping_refunded( $ship_line_item->get_id() );
				$parent_shipping_remaining = $ship_line_item->get_total() - $parent_shipping_refunded;

				if ( abs( $per_shipping_refund ) > $parent_shipping_remaining ) {
					throw new \Exception( esc_html__( 'Invalid refund amount.', 'elex-multi-vendor-for-woocommerce' ) );
				}
				
				// Map shipping tax to WooCommerce-expected associative array format [ tax_rate_id => tax_amount ]
				$shipping_taxes = array();
				$ship_item_taxes = $shipping_item->get_taxes();
				if ( ! empty( $ship_item_taxes['total'] ) ) {
					foreach ( $ship_item_taxes['total'] as $tax_rate_id => $tax_amount ) {
						$shipping_taxes[ $tax_rate_id ] = abs( wc_format_decimal( $tax_amount ) );
					}
				}
	
				$item_to_refund[ $ship_line_item->get_id() ] = array(
					'qty'          => 0,
					'refund_total' => abs( wc_format_decimal( $per_shipping_refund ) ), 
					'refund_tax'   => $shipping_taxes, 
				);
				$shipping_refund_total                      += abs( wc_format_decimal( $per_shipping_refund ) );
			}
			
		
			// 2. Process Product Line Item Refunds:
			// Map suborder product line items to parent order's product line items
			$items = $refunds->get_items();
			foreach ( $items as $item_id => $item ) {
				$product_id        = $item->get_product_id();
				$refund_amount     = $item->get_total();
				// Use the absolute value of current refund item quantity
				$item_qty          = abs( $item->get_quantity() );
		
				// Find the corresponding product line item in parent order
				$line_item = null;
				foreach ( $parent_order->get_items() as $order_item ) {
					if ( $order_item->get_product_id() === $product_id ) {
						$line_item = $order_item;
						break;
					}
				}

				if ( ! $line_item ) {
					continue;
				}

				// Validate the product refund amount against parent order item's remaining balance
				$parent_item_refunded = $parent_order->get_total_refunded_for_item( $line_item->get_id() );
				$parent_item_remaining = $line_item->get_total() - $parent_item_refunded;

				if ( abs( $refund_amount ) > $parent_item_remaining ) {
					throw new \Exception( esc_html__( 'Invalid refund amount.', 'elex-multi-vendor-for-woocommerce' ) );
				}
				
				// Map product tax to WooCommerce-expected associative array format [ tax_rate_id => tax_amount ]
				$taxes = array();
				$item_taxes = $item->get_taxes();
				if ( ! empty( $item_taxes['total'] ) ) {
					foreach ( $item_taxes['total'] as $tax_rate_id => $tax_amount ) {
						$taxes[ $tax_rate_id ] = abs( wc_format_decimal( $tax_amount ) );
					}
				}
			
				$item_to_refund[ $line_item->get_id() ] = array(
					'qty'          => $item_qty, 
					'refund_total' => abs( wc_format_decimal( $refund_amount ) ), 
					'refund_tax'   => $taxes,
				);

				$product_refund_total += abs( wc_format_decimal( $refund_amount ) );        
			}

			// 3. Replicate the refund to parent order:
			$refund_total = $product_refund_total + $shipping_refund_total;
			// Validate final refund total against parent order's remaining refund limit
			$remaining_refund_amount = $parent_order->get_total() - $parent_order->get_total_refunded();
			if ( $refund_total > $remaining_refund_amount ) {
				throw new \Exception( esc_html__( 'Invalid refund amount.', 'elex-multi-vendor-for-woocommerce' ) );
			} else {
				// Create refund record on the parent order
				$refund = wc_create_refund(
					array(
						'amount'     => abs( $refund_total ),
						'reason'     => 'Customer requested refund',
						'order_id'   => $parent_order_id,
						'line_items' => $item_to_refund,
					) 
				);
			
				$parent_order->calculate_totals();

				// Add refund note only after the refund has been successfully created
				$parent_order->add_order_note(
					// translators: Placeholder %s is the refunded amount for the suborder.
					sprintf( __( 'Refunded %1$s for suborder %2$s', 'elex-multi-vendor-for-woocommerce' ), wc_price( $refund_total ), $order->get_id() )
				);

				$parent_order->save();
			}
		}
	}
	public static function elex_mv_shipping_refund( $shipping_refund, $order ) { 
		$order_store_id = $order->get_meta( 'elex_mv_store_id', true );

		if ( $order->get_meta( 'elex_mv_ship_fee_beared_by' ) === 'vendor' ) {
			$earning_amount                  = get_post_meta( $order_store_id, 'elex_mv_vendor_earning', true );
			$earning_amount                  = $earning_amount + $shipping_refund; // this shipping refund is in negative.
			$vendor_last_settlement_refund   = get_post_meta( $order_store_id, 'elex_mv_vendor_last_settlement_refund', true );
			$shipping_last_settlement_refund = $vendor_last_settlement_refund + abs( $shipping_refund );
			$shipping_refund                 = 0 - $shipping_refund;
			$shippig_refund_amt              = ! empty( $order->get_meta( 'elex_mv_order_shipping_refund_amount_vendor' ) ) ? $order->get_meta( 'elex_mv_order_shipping_refund_amount_vendor' ) : 0;
			if ( $shippig_refund_amt ) {
			$shippig_refund_amt = $shippig_refund_amt + $shipping_refund;
			$order->update_meta_data( 'elex_mv_order_shipping_refund_amount_vendor', $shippig_refund_amt );
			} else {
			$order->update_meta_data( 'elex_mv_order_shipping_refund_amount_vendor', $shipping_refund );
			}
			update_post_meta( $order_store_id, 'elex_mv_vendor_earning', $earning_amount );
			$earning_amounts = get_post_meta( $order_store_id, 'elex_mv_vendor_earning', true );
			update_post_meta( $order_store_id, 'elex_mv_vendor_last_settlement_refund', $shipping_last_settlement_refund );

		} else {
			$refunded_ship = get_post_meta( $order_store_id, 'elex_mv_vendor_refund_amount', true ) - $shipping_refund;
			update_post_meta( $order_store_id, 'elex_mv_vendor_refund_amount', $refunded_ship );
			$order_refund = $order->get_meta( 'elex_mv_refund_amount' );
			$order_refund = (float) $order_refund - (float) $shipping_refund;
			$order->update_meta_data( 'elex_mv_refund_amount', $order_refund );
		}

		$order_status = $order->get_status();
		if ( 'vendor' === $order->get_meta( 'elex_mv_ship_fee_beared_by' ) && 'refunded' === $order_status ) {
			$order->update_meta_data( 'elex_mv_item_full_refund' , 'true' );
			$full_refund         = ! empty( $order->get_meta( 'elex_mv_item_full_refund_amount' ) ) ? $order->get_meta( 'elex_mv_item_full_refund_amount' ) : 0 ;
			$shippig_refund_amt  = $order->get_meta( 'elex_mv_order_shipping_refund_amount_vendor' );
			$shipping_refund_val = (float) $full_refund + (float) $shipping_refund;
			$order->update_meta_data( 'elex_mv_item_full_refund_amount' , $shipping_refund_val );
			$order->update_meta_data( 'elex_mv_item_partial_refund' , 'false' );
		} elseif ( $order->get_meta( 'elex_mv_ship_fee_beared_by' ) === 'vendor' ) {
			$order->update_meta_data( 'elex_mv_item_partial_refund' , 'true' );
			$partial_refund     = ! empty( $order->get_meta( 'elex_mv_item_partial_refund_amount' ) ) ? $order->get_meta( 'elex_mv_item_partial_refund_amount' ) : 0;
			$shippig_refund_amt = $order->get_meta( 'elex_mv_order_shipping_refund_amount_vendor' );
			if ( $partial_refund ) {
				$partial_refund = (float) $partial_refund + ( float ) $shipping_refund;
				$order->update_meta_data( 'elex_mv_item_partial_refund_amount' , $partial_refund );
			} else {
				$order->update_meta_data( 'elex_mv_item_partial_refund_amount' , $shippig_refund );
			}
			$order->update_meta_data( 'elex_mv_item_full_refund' , 'false' );
		}
 
		if ( $order->get_meta( 'elex_mv_ship_fee_beared_by' ) === 'vendor' && $order->get_meta( 'elex_mv_refund_settlement_status' ) !== 'false' ) {
				$partial_refund_amount = $order->get_meta( 'elex_mv_item_partial_refund_amount' );
				$shippig_refund_amt    = $order->get_meta( 'elex_mv_order_shipping_refund_amount_vendor' );
			if ( $partial_refund_amount && $shippig_refund_amt ) {
				$order->update_meta_data( 'elex_mv_item_partial_refund_amount' , $shipping_refund );
			}
				$order->update_meta_data( 'elex_mv_refund_settlement_status' , 'false' );
		}
	}   


	public function elex_mv_vendor_order_export() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'mv_nonce' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}

		$export_data = array(
			'vendor_id'        => isset( $_POST['vendor_id'] ) ? sanitize_text_field( wp_unslash( $_POST['vendor_id'] ) ) : '',
			'file_format'      => isset( $_POST['file_format'] ) ? sanitize_text_field( wp_unslash( $_POST['file_format'] ) ) : '',
			'export_from_date' => isset( $_POST['from_date'] ) ? sanitize_text_field( wp_unslash( $_POST['from_date'] ) ) : '',
			'export_to_date'   => isset( $_POST['to_date'] ) ? sanitize_text_field( wp_unslash( $_POST['to_date'] ) ) : '',
			'status'           => isset( $_POST['elex_mv_order_status'] ) ? sanitize_text_field( wp_unslash( $_POST['elex_mv_order_status'] ) ) : '',
			'length'           => 10,
		);
		if ( isset( $export_data['status'] ) && 'all' !== $export_data['status'] ) {
			$args['status'] = $export_data['status'];
		}
		if ( isset( $export_data['export_from_date'] ) && isset( $export_data['export_to_date'] ) ) {
			$args['date_created'] = $export_data['export_from_date'] . '...' . $export_data['export_to_date'] ;
		}
		$store_id = $export_data['vendor_id'];
		$order    = new OrderModel();
		header( 'Content-Type: text/csv; charset=utf-8' ); //For .csv
		header( 'Content-Disposition: attachment; filename=settlement_history.csv' );
		$output            = fopen( 'php://output', 'w' );
		$array_for_headers = array( 'order_id', 'order_status', 'created_at', 'order_by', 'order_total', 'order_items' );
		/**
		* Fires hook for csv export
		* 
		* @since 1.0.0
		* @param $csv
		*/
		$array_for_headers = apply_filters( 'elex_mv_csv_header_vendor_orders_for_export', $array_for_headers );
		fputcsv( $output, $array_for_headers );
		$page_no = 1;
		
		$orders = $order->order_lists( $store_id, $args );
		while ( count( ( is_countable( $orders ) ? $orders : array() ) ) > 0 ) {

			foreach ( $orders as $order_data ) {
				$csv = array( 

					$order_data->get_id(),
					$order_data->get_status(),
					$order_data->get_date_created()->date( 'd-m-Y' ),
					$order_data->get_billing_first_name(), 
					$order_data->get_total(),
					$order_data->get_item_count(),
					
				);
				/**
				 * Fires hook for csv export
				 *
				 * @since 1.0.0 
				 * @param $csv
				 */
				$csv = apply_filters( 'elex_mv_csv_header_vendor_orders_for_export', $csv );
				fputcsv( $output, $csv );
			}

			++$page_no;
			$args['limit']  = $export_data['length'];
			$args['offset'] = ( $page_no - 1 ) * $export_data['length'];
			$orders         = $order->order_lists( $store_id, $args );
		}

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