<?php


namespace Elex\MultiVendor\Controller;

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

use Elex\MultiVendor\Model\AdminPayment;
use Elex\MultiVendor\Model\WoocommerceReport;

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

class VendorDashboardController {
	public static $settings = null;
	const VERSION           = '2.0.0';


	public static function init() {
		$self = new self();
		add_action( 'elex_mv_dashboard_page', array( $self, 'elex_mv_dashboard_page' ) );
		add_action( 'wp_ajax_elex_mv_vendor_dashboard_page', array( $self, 'elex_mv_vendor_dashboard_page' ) );

		add_action( 'wp_ajax_elex_mv_product_data_last_seven_days', array( $self, 'elex_mv_product_data_last_seven_days' ) );
		add_action( 'wp_ajax_elex_mv_country_data', array( $self, 'elex_mv_country_data' ) );
	}

	public function elex_mv_vendor_dashboard_page() {

		if ( ! isset( $_POST['_ajax_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_ajax_nonce'] ) ), 'elex_mv_vendor_dashboard' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
		if ( ! current_user_can( 'read' ) ) {
			wp_send_json_error( 'Unauthorized', 403 );
		}
	
		if ( ! empty( $_POST['from'] ) ) {
			$from_date = sanitize_text_field( wp_unslash( $_POST['from'] ) ) . ' 00:00:00';
		} else {
			$from_date = wp_date( 'Y-m-d 00:00:00', strtotime( '-29 days' ) );
		}

		if ( ! empty( $_POST['to'] ) ) {
			$to_date = sanitize_text_field( wp_unslash( $_POST['to'] ) ) . ' 23:59:59';
		} else {
			$to_date = wp_date( 'Y-m-d 23:59:59', strtotime( 'now' ) );
		}

		$vendor   = Vendor::load( wp_get_current_user() );
		$store    = $vendor->get_store();
		$store_id = ! empty( $store ) ? $store->get_id() : 0 ;
		OrderModel::update_order_status_count( $store_id );

		OrderModel::order_total_count( $store_id );
		Product::product_status_count( $store_id );
		$total_vendor_sales           = 0;
		$commission_amount            = 0;
		$refund_amount                = 0;
		$refunded_commission_amount   = 0;
		$refund_of_product_from_admin = 0;
		$products                     = wc_get_products(
			array(
				'meta_key'     => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value'   => $store_id, // phpcs:ignore WordPress.DB.SlowDBQuery
				'status'       => 'any',
				'date_created' => $from_date . '...' . $to_date,

			)
		);

		$products = count( $products );

		$published_products = wc_get_products(
			array(
				'meta_key'     => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value'   => $store_id, // phpcs:ignore WordPress.DB.SlowDBQuery
				'status'       => 'publish',
				'date_created' => $from_date . '...' . $to_date,

			)
		);
		$count_published_product = count( $published_products );

		$pending_products = wc_get_products(
			array(
				'meta_key'     => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value'   => $store_id, // phpcs:ignore WordPress.DB.SlowDBQuery
				'status'       => 'pending',
				'date_created' => $from_date . '...' . $to_date,

			)
		);
		$count_pending_product = count( $pending_products );

		$rejected_products = wc_get_products(
			array(
				'meta_key'     => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value'   => $store_id, // phpcs:ignore WordPress.DB.SlowDBQuery
				'status'       => 'reject',
				'date_created' => $from_date . '...' . $to_date,

			)
		);
		$count_rejected_product = count( $rejected_products );

		// total product count doesn't includes rejected products so we are subtracting rejected products count from total products count
		$products = $products - $count_rejected_product;


		$current_orders = wc_get_orders(
			array(
				'limit'        => -1, // retrieve all orders
				'meta_key'     => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value'   => ! empty( $store_id ) ? sanitize_text_field( $store_id ) : '', // phpcs:ignore WordPress.DB.SlowDBQuery
				'status'       => 'any',
				'return'       => 'ids',
				'date_created' => $from_date . '...' . $to_date,

			) 
		);
		$total_orders = count( $current_orders );

		$on_hold_orders = wc_get_orders(
			array(
				'limit'        => -1, // retrieve all orders
				'meta_key'     => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value'   => ! empty( $store_id ) ? sanitize_text_field( $store_id ) : '', // phpcs:ignore WordPress.DB.SlowDBQuery
				'status'       => array( 'on-hold' ),
				'return'       => 'ids',
				'date_created' => $from_date . '...' . $to_date,

			) 
		);
		$total_on_hold_orders = count( $on_hold_orders );

		$completed_orders = wc_get_orders(
			array(
				'limit'        => -1, // retrieve all orders
				'meta_key'     => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value'   => ! empty( $store_id ) ? sanitize_text_field( $store_id ) : '', // phpcs:ignore WordPress.DB.SlowDBQuery
				'status'       => array( 'completed' ),
				'return'       => 'ids',
				'date_created' => $from_date . '...' . $to_date,

			) 
		);
		$total_completed_orders = count( $completed_orders );

		$processing_orders = wc_get_orders(
			array(
				'limit'        => -1, // retrieve all orders
				'meta_key'     => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value'   => ! empty( $store_id ) ? sanitize_text_field( $store_id ) : '', // phpcs:ignore WordPress.DB.SlowDBQuery
				'status'       => array( 'processing' ),
				'return'       => 'ids',
				'date_created' => $from_date . '...' . $to_date,

			) 
		);
		$total_processing_orders = count( $processing_orders );

		$pending_orders = wc_get_orders(
			array(
				'limit'        => -1, // retrieve all orders
				'meta_key'     => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value'   => ! empty( $store_id ) ? sanitize_text_field( $store_id ) : '', // phpcs:ignore WordPress.DB.SlowDBQuery
				'status'       => array( 'pending' ),
				'return'       => 'ids',
				'date_created' => $from_date . '...' . $to_date,

			) 
		);
		$total_pending_orders = count( $pending_orders );

		$refunded_orders = wc_get_orders(
			array(
				'limit'        => -1, // retrieve all orders
				'meta_key'     => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value'   => ! empty( $store_id ) ? sanitize_text_field( $store_id ) : '', // phpcs:ignore WordPress.DB.SlowDBQuery
				'status'       => array( 'refunded' ),
				'return'       => 'ids',
				'date_created' => $from_date . '...' . $to_date,

			) 
		);
		$total_refunded_orders = count( $refunded_orders );

		$cancelled_orders = wc_get_orders(
			array(
				'limit'        => -1, // retrieve all orders
				'meta_key'     => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value'   => ! empty( $store_id ) ? sanitize_text_field( $store_id ) : '', // phpcs:ignore WordPress.DB.SlowDBQuery
				'status'       => array( 'cancelled' ),
				'return'       => 'ids',
				'date_created' => $from_date . '...' . $to_date,

			) 
		);
		$total_cancelled_orders = count( $cancelled_orders );


		foreach ( $current_orders as $order_id ) {
			$order = wc_get_order( $order_id );
			if ( $order ) {
					$commission_amount          += ! empty( $order->get_meta( 'elex_mv_admin_commission_from_product' ) ) ? $order->get_meta( 'elex_mv_admin_commission_from_product' ) : 0 ;
					$refunded_commission_amount += ! empty( $order->get_meta( 'elex_mv_admin_commission_refund_amount_products' ) ) ? $order->get_meta( 'elex_mv_admin_commission_refund_amount_products' ) : 0 ;
					$vendor_item_total               = 0;
					foreach ( $order->get_items() as $item_id => $item ) {
						$item_product_men = $item->get_product();
						if ( ! $item_product_men || ! $item_product_men->meta_exists( 'elex_mv_store_id' ) ) {
							continue;
						}
						$vendor_item_total += (float) $item->get_total();
					}
					$total_vendor_sales           += $vendor_item_total;  
					$refund_amount                += ! empty( $order->get_meta( 'elex_mv_refunded_amount_product' ) ) ? $order->get_meta( 'elex_mv_refunded_amount_product' ) : 0 ;
					$refund_of_product_from_admin += ! empty( $order->get_meta( 'elex_mv_refund_amount_product_to_vendor' ) ) ? $order->get_meta( 'elex_mv_refund_amount_product_to_vendor' ) : 0 ;


			}
		}

	 
		$total_shipping_vendor = self::total_shipping_refund( $store_id, $from_date, $to_date );


		$vendor_dashboard_details['commission_amount']            = wc_price( $commission_amount - $refunded_commission_amount );
		$vendor_dashboard_details['total_vendor_sales']           = wc_price( $total_vendor_sales );
		$vendor_dashboard_details['elex_mv_refund_amount']        = wc_price( $refund_amount );
		$vendor_dashboard_details['total_vendor_earnings']        = wc_price( $total_vendor_sales - $commission_amount - $refund_of_product_from_admin );
		$vendor_dashboard_details['total_shipping_amount']        = wc_price( $total_shipping_vendor['shipping_total'] );
		$vendor_dashboard_details['total_shipping_refund_amount'] = wc_price( $total_shipping_vendor['shipping_refund_total'] );

		$vendor_dashboard_details['total_cancelled_orders']  = $total_cancelled_orders;
		$vendor_dashboard_details['total_refunded_orders']   = $total_refunded_orders;
		$vendor_dashboard_details['total_pending_orders']    = $total_pending_orders;
		$vendor_dashboard_details['total_processing_orders'] = $total_processing_orders;
		$vendor_dashboard_details['total_completed_orders']  = $total_completed_orders;
		$vendor_dashboard_details['total_on_hold_orders']    = $total_on_hold_orders;
		$vendor_dashboard_details['total_orders']            = $total_orders;
		
		$vendor_dashboard_details['count_rejected_product']  = $count_rejected_product;
		$vendor_dashboard_details['count_pending_product']   = $count_pending_product;
		$vendor_dashboard_details['count_published_product'] = $count_published_product;
		$vendor_dashboard_details['products']                = $products;

		wp_send_json_success( $vendor_dashboard_details );
	} 

	public static function total_shipping_refund( $store_id, $from_date, $to_date ) {

	
		$shipping_total        = 0 ;
		$shipping_refund_total = 0;
		$orders                = wc_get_orders(   
			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( 'wc-processing', 'wc-completed', 'wc-refunded' ),
				'date_created' => $from_date . '...' . $to_date,

			) 
		);
		foreach ( $orders as $order_ship ) {
			
			if ( $order_ship->get_meta( 'elex_mv_ship_fee_beared_by' ) === 'vendor' ) {
				$shipping_total += $order_ship->get_shipping_total();
				$order_refunds   = $order_ship->get_refunds();


				foreach ( $order_refunds as $refund ) {
					// Loop through the order refund line items
					foreach ( $refund->get_items( 'shipping' ) as $item_id => $item ) {
				
						## --- Using WC_Order_Item_Product methods --- ##
				
						$shipping_refund_total += -1 * $item->get_total(); // line subtotal: zero or negative number
	
					}
				}           
			}       
		}
		
		$shipping_data = array(
			'shipping_total'        => $shipping_total,
			'shipping_refund_total' => $shipping_refund_total,
		);
		return $shipping_data;
	}

	public function elex_mv_dashboard_page() {
		// Guarantee vendor-dashboard.js and its params are loaded whenever the dashboard
		// renders — even when menu_tab is absent (the default landing URL).
		// WordPress deduplicates by handle, so these are no-ops if already enqueued.
		wp_enqueue_script(
			'elex-mv-vendor-dashboard-main',
			ELEX_MULTI_VENDOR_MAIN_URL_PATH . 'assets/js/vendor-dashboard.js',
			array( 'jquery', 'chart-js', 'leaflet-js', 'elex-mv-country-centroids', 'elex_mv_select_2_js' ),
			ELEX_MULTI_VENDOR_PLUGIN_VERSION,
			true
		);

		// Inject the nonce as an inline script immediately BEFORE vendor-dashboard.js
		// so it is defined when the script runs in the footer.
		// NOTE: do NOT use wp_add_inline_script('jquery', ...) here — jQuery is a head
		// script and wp_head has already fired during content rendering, so any 'after'
		// inline code attached to the jquery handle would never be output.
		wp_add_inline_script(
			'elex-mv-vendor-dashboard-main',
			'var elex_mv_vendor_dashboard_params = ' . wp_json_encode(
				array(
					'ajax_url' => admin_url( 'admin-ajax.php' ),
					'nonce'    => wp_create_nonce( 'elex_mv_vendor_dashboard' ),
				)
			) . ';',
			'before'
		);

		$vendor   = Vendor::load( wp_get_current_user() );
		$store    = $vendor->get_store();
		$store_id = $store->get_id();
		OrderModel::update_order_status_count( $store_id );
		OrderModel::order_total_count( $store_id );
		Product::product_status_count( $store_id );
		$total_vendor_earning = 0;
		$commission_amount    = 0;
		$refund_amount        = 0;
		$products             = get_posts(
			array(
				'post_type'  => 'product',
				'meta_key'   => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value' => $store_id, // phpcs:ignore WordPress.DB.SlowDBQuery
			)
		);
		$current_orders       = wc_get_orders(
			array(
				'limit'      => -1, // retrieve all orders
				'meta_key'   => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_value' => ! empty( $store_id ) ? sanitize_text_field( $store_id ) : '', // phpcs:ignore WordPress.DB.SlowDBQuery
				'status'     => array( 'processing', 'completed' ),
				'return'     => 'ids',
			) 
		);
		foreach ( $current_orders as $order_id ) {
			$order = wc_get_order( $order_id );
			if ( $order ) {
					$commission_amount    += ! empty( $order->get_meta( 'elex_mv_admin_commission_from_product' ) ) ? $order->get_meta( 'elex_mv_admin_commission_from_product' ) : 0 ;
					$total_vendor_earning += $order->get_total();  
					$refund_amount        += ! empty( $order->get_meta( 'elex_mv_vendor_refund_amount' ) ) ? $order->get_meta( 'elex_mv_vendor_refund_amount' ) : 0 ;
			}
		}

		require ELEX_MULTI_VENDOR_PLUGIN_PATH . '/templates/vendor-dashboard/vendor-dashboard-html.php';
	}

	
	public static function elex_mv_product_data_last_seven_days() {
	
	
		$WC_Admin_Report_Data = new WoocommerceReport();

		$spark_line_data = array();
		$order_statuses  = array( 'wc-processing', 'wc-completed' );
		if ( ! isset( $_POST['_ajax_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_ajax_nonce'] ) ), 'elex_mv_vendor_dashboard' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
		if ( ! current_user_can( 'read' ) ) {
			wp_send_json_error( 'Unauthorized', 403 );
		}

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

		$from_date = gmdate( 'Y-m-d', strtotime( 'midnight -' . ( $days - 1 ) . ' days', current_time( 'timestamp' ) ) ); // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested
		$to_date   = gmdate( 'Y-m-d' );


		if ( isset( $_POST['product_id'] ) && ! empty( $_POST['product_id'] ) ) {

			$vendor_dashboard_chart = $WC_Admin_Report_Data->get_order_report_on_sales( $store_id, $from_date, $to_date, sanitize_text_field( wp_unslash( $_POST['product_id'] ) ) );

		} else {
			$vendor_dashboard_chart = $WC_Admin_Report_Data->get_order_report_on_sales( $store_id, $from_date, $to_date, '' );

		}
	
	
		return wp_send_json_success( wp_json_encode( $vendor_dashboard_chart ) );
	}
	
	public static function elex_mv_country_data() {

		// Get the start and end dates for the last 7 days
		if ( ! isset( $_POST['_ajax_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_ajax_nonce'] ) ), 'elex_mv_vendor_dashboard' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
		if ( ! current_user_can( 'read' ) ) {
			wp_send_json_error( 'Unauthorized', 403 );
		}
		$start_date = strtotime( isset( $_POST['days'] ) ? sanitize_text_field( wp_unslash( $_POST['days'] ) ) : 7 );
		$end_date   = time();
	
		// Query the WooCommerce database for all orders placed in the last 7 days
		$args = array(
			'limit'        => -1, // retrieve all orders
			'meta_key'     => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
			'meta_value'   => ! empty( $_POST['store_id'] ) ? sanitize_text_field( wp_unslash( $_POST['store_id'] ) ) : '', // phpcs:ignore WordPress.DB.SlowDBQuery
			'status'       => array( 'processing', 'completed' ),
			'date_created' => '>=' . $start_date,
		);
		
		$orders = wc_get_orders( $args );
	
		// Initialize an empty array to store the order data
		$order_data = array();
		
		// Loop through the orders and extract the order data
		
		foreach ( $orders as $order ) {
			$billing_country = $order->get_billing_country();
			$order_total     = 1;

			// Store the order data in an array indexed by the billing country
			if ( isset( $order_data[ $billing_country ] ) ) {
				$order_data[ $billing_country ] += $order_total;
			} else {
				$order_data[ $billing_country ] = $order_total;
			}
		}
		$country_data      = array();
		$country_data_temp = array();
		$countries         = new \WC_Countries();
		// Loop through the array and calculate the total sales for each country
		
		foreach ( $order_data as $country => $total_sales ) {
			$country_name          = $countries->countries[ $country ];
			$country_data['id']    = $country;
			$country_data['name']  = $country_name;
			$country_data['value'] = $total_sales;
			$country_data_temp[]   = $country_data;
		}
	
		wp_send_json_success( $country_data_temp );
	}
}
