<?php


namespace Elex\MultiVendor\Controller;

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

use Elex\MultiVendor\Model\WoocommerceReportAdmin;

use Elex\MultiVendor\Model\SiteSettings;
use Elex\MultiVendor\Model\WoocommerceReport;
use Elex\MultiVendor\Model\Store;

class AdminDashboard {
	public static function init() {
		$self = new self();
		add_action( 'wp_ajax_elex_mv_admin_product_data_last_thirty_days', array( $self, 'elex_mv_admin_product_data_last_thirty_days' ) );
		add_action( 'wp_ajax_elex_mv_admin_country_data', array( $self, 'elex_mv_admin_country_data' ) );
		add_action( 'admin_menu', array( $self, 'elex_mv_dashboard_menu' ) );
		add_action( 'wp_ajax_elex_mv_admin_dashboard_page', array( $self, 'elex_mv_admin_dashboard_page' ) );
	}
	public static function elex_mv_dashboard_menu() {
		$self          = new self();
		$site_settings = SiteSettings::load();

		if ( $site_settings->is_setup_finished( 'is_setup_finished' ) ) {
			add_submenu_page( 'elex-multi-vendor-for-woocommerce-dashboard', 'ELEX Multi Vendor', 'Dashboard', 'admin_vendor_access', 'elex-multi-vendor-for-woocommerce-dashboard', array( $self, 'admin_dashboard_page' ), 0 ); // phpcs:ignore WordPress.WP.Capabilities.Unknown
		}
	}

	
	public function elex_mv_admin_dashboard_page() {
		global $wpdb;
		$admin_dashboard_page_details = array();

		if ( ! isset( $_POST['_ajax_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_ajax_nonce'] ) ), 'elex_mv_admin_dashboard' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Unauthorized', 403 );
		}

		$current_from_date = $this->get_current_from_date();

		// Ensure $current_from_date is valid or set a default value
		$current_from_date = $current_from_date ? $current_from_date : wp_date( 'Y-m-d H:i:s' );

		// Get 'from' and 'to' date values from the form or use default values
		$from_date = isset( $_POST['from'] ) ? sanitize_text_field( wp_unslash( $_POST['from'] ) ) : $current_from_date;
		$to_date   = isset( $_POST['to'] ) ? sanitize_text_field( wp_unslash( $_POST['to'] ) ) : wp_date( 'Y-m-d H:i:s' );

		// Ensure from_date and to_date are formatted correctly
		$from_date = gmdate( 'Y-m-d H:i:s', strtotime( $from_date ) );
		$to_date   = gmdate( 'Y-m-d 23:59:59', strtotime( $to_date ) );


		$status = array(
			'on-hold'    => 0, 
			'processing' => 0, 
			'cancelled'  => 0, 
			'completed'  => 0, 
			'pending'    => 0, 
			'refunded'   => 0,
		);
		


		$args = array(
			'post_type'      => 'shop_order',
			'post_status'    => array_keys( wc_get_order_statuses() ),
			'posts_per_page' => -1,
			'date_query'     => array(
				array(
					'after'     => $from_date,
					'before'    => $to_date,
					'inclusive' => true,
				),
			),
			'meta_query'     => array( // phpcs:ignore WordPress.DB.SlowDBQuery
				array(
					'key'     => 'elex_mv_has_sub_order',
					'compare' => 'NOT EXISTS',
				),
			),
		);

		$query = new \WP_Query( $args );

		// Fetch order IDs
		$current_orders = wp_list_pluck( $query->posts, 'ID' );

	
		$last_30days_order             = count( $current_orders );
		$last_30_days_net_sales        = 0;
		$last_30days_commission        = 0; 
		$last_30days_commission_refund = 0;
		foreach ( $current_orders as $order_id ) {
			$order = wc_get_order( $order_id );
			if ( $order ) {
				$status = self::elex_mv_order_status_count( $status, $order->get_status() );
				if ( 'processing' === $order->get_status() || 'completed' === $order->get_status() ) { 
					$last_30days_commission        += ! empty( $order->get_meta( 'elex_mv_admin_commission_from_product' ) ) ? $order->get_meta( 'elex_mv_admin_commission_from_product' ) : 0 ;
					$last_30days_commission_refund += ! empty( $order->get_meta( 'elex_mv_admin_commission_refund_amount_products' ) ) ? $order->get_meta( 'elex_mv_admin_commission_refund_amount_products' ) : 0 ;
					$last_30_days_net_sales        += $order->get_total();
				}           
			}
		}

		$last_30days_commission = (float) $last_30days_commission - (float) $last_30days_commission_refund ;

 
		$current_time     = current_time( 'timestamp' ); // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested
		$last_30_days     = gmdate( 'Y-m-d H:i:s', strtotime( '-29 days', $current_time ) );
		$previous_30_days = gmdate( 'Y-m-d H:i:s', strtotime( '-59 days', $current_time ) );
		 
		$previous_orders            = wc_get_orders(
			array(
				'limit'          => -1,
				'date_completed' => $previous_30_days . '...' . $last_30_days,
				'meta_key'       => 'elex_mv_has_sub_order', // phpcs:ignore WordPress.DB.SlowDBQuery
				'meta_compare'   => 'NOT EXISTS',
				'return'         => 'ids',
			)
		);
		$previous_30days_order      = count( $previous_orders );
		$previous_30days_commission = 0;
		 
	


		$admin_dashboard_page_details['last_30_days_net_sales'] = wc_price( $last_30_days_net_sales );
		$admin_dashboard_page_details['last_30days_order']      = $last_30days_order;
		$admin_dashboard_page_details['last_30days_commission'] = wc_price( $last_30days_commission );
		$admin_dashboard_page_details['status']                 = $status;

	

		$vendor_count                                 = self::elex_mv_vendor_count( $from_date, $to_date );
		$admin_dashboard_page_details['vendor_count'] = $vendor_count;
	
		$product_count                                        = self::elex_mv_total_product_count( $from_date, $to_date );
		$admin_dashboard_page_details['product_count']        = $product_count;
		$admin_dashboard_page_details['product_status_count'] = self::elex_mv_product_status_count($from_date, $to_date);

		$admin_dashboard_page_details['total_refund_amount'] = self::total_refund_amount( $from_date, $to_date );

		$admin_dashboard_page_details['most_sold_product'] = self::elex_mv_most_sold_product( $from_date, $to_date );

		$admin_dashboard_page_details['top_vendor'] = self::elex_mv_top_vendor( $from_date, $to_date );
		
		wp_send_json_success( $admin_dashboard_page_details );
	}

	public function admin_dashboard_page() {

	
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . '/templates/admin-dashboard/admin-dash-ui.php';
	}
 
	public function total_refund_amount( $from_date, $to_date ) {

		$current_orders = wc_get_orders(
			array(
				'limit'        => -1,
				'date_created' => $from_date . '...' . $to_date,
				'return'       => 'ids',
			)
		); 

		$total_refund = 0;

	
		if ( ! empty( $current_orders ) ) {

			foreach ( $current_orders as $order_id ) {
				$order         = wc_get_order( $order_id );
				$total_refund += (int) $order->get_meta( 'elex_mv_full_refund_amount' );
			}
		}
		return wc_price( $total_refund );
	}

	public function get_current_from_date() {
		$installation_date = get_option( 'elex_mv_installation_date' );
		// Get the current date minus 29 days
		$current_minus_29 = wp_date( 'Y-m-d', strtotime( '-29 days' ) );
		// Compare the dates
		if ( strtotime( $installation_date ) >= strtotime( $current_minus_29 ) ) {
			// If the installation date is within the last 29 days, use the installation date
			$current_from_date = esc_html( $installation_date );
		} else {
			// Otherwise, use the current date minus 29 days
			$current_from_date = esc_attr( $current_minus_29 );
		}
		return $current_from_date;
	}

	public function elex_mv_admin_product_data_last_thirty_days() {

		include_once WP_PLUGIN_DIR . '/woocommerce/includes/admin/reports/class-wc-admin-report.php' ;
		include_once WP_PLUGIN_DIR . '/woocommerce/includes/admin/reports/class-wc-report-sales-by-date.php' ;
		$WC_Admin_Report = new \WC_Admin_Report();
		$spark_line_data = array();
		global $wpdb;
		if ( ! isset( $_POST['_ajax_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_ajax_nonce'] ) ), 'elex_mv_admin_dashboard' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Unauthorized', 403 );
		}

		$current_from_date = $this->get_current_from_date();
		$default_day       = $current_from_date;
		$from_date         = isset( $_POST['from'] ) ? sanitize_text_field( wp_unslash( $_POST['from'] ) ) : $default_day ;
		$from_date_obj     = date_create( $from_date );
		$to_date           = isset( $_POST['to'] ) ? sanitize_text_field( wp_unslash( $_POST['to'] ) ) : gmdate( 'Y-m-d', strtotime( 'today' ) );
		$to_date_obj       = date_create( $to_date );

		$interval = date_diff( $from_date_obj, $to_date_obj );
		$days     = (int) $interval->format( '%a' );
		
		$order_statuses = array( 'wc-processing', 'wc-completed' );

		
		$WC_Admin_Report_Data  = new WoocommerceReportAdmin();
		$admin_dashboard_chart = $WC_Admin_Report_Data->get_order_report_on_sales( $from_date, $to_date );

		
		return wp_send_json_success( wp_json_encode( $admin_dashboard_chart ) );
	}

	public static function elex_mv_most_sold_product( $from_date, $to_date ) {

		$admin_as_vendor_date = get_option( 'elex_mv_admin_detail_set_as_vendor_date' );
	

		if ( strtotime( $from_date ) < strtotime( $admin_as_vendor_date ) ) {

			$from_date = $admin_as_vendor_date;

		}
		$product_data   = array();
		$current_orders = wc_get_orders(
			array(
				'limit'        => -1,
				'date_created' => $from_date . '...' . $to_date,
				'return'       => 'ids',
			)
		);
  
		$unit_sold = 0;
		if ( ! empty( $current_orders ) ) {
			foreach ( $current_orders as $order_id ) {
				$order = wc_get_order( $order_id );
				if ( $order ) {
					$items = $order->get_items();
					
					

					foreach ( $items as $item ) {
						$product_id = $item->get_product_id();
				
						$product = wc_get_product( $product_id );
						$qty     = $item->get_quantity();
						if ( 'processing' === $order->get_status() || 'completed' === $order->get_status() ) { 
							if ( isset( $vendor_product[ $product_id ] ) ) {
								$vendor_product[ $product_id ] += $item->get_total();   
							} else {
								$vendor_product[ $product_id ] = $item->get_total();
							}
							if ( is_object( $product ) && $product->get_meta( 'elex_mv_store_id', true ) ) {
								if ( isset( $commission[ $product_id ] ) ) {
									$commission[ $product_id ] += self::elex_mv_calculate_commission( $product_id, $item->get_total() );

								} else {
									$commission[ $product_id ] = self::elex_mv_calculate_commission( $product_id, $item->get_total() );
								}
							} else {
								$commission[ $product_id ] = 0;
							}
							if ( isset( $products[ $product_id ] ) ) {
								$products[ $product_id ] += $qty;
							} else {
								$products[ $product_id ] = $qty;
							}
						}               
					}
				}
			}

			if ( ! empty( $vendor_product ) && ! empty( $products ) ) {
				arsort( $vendor_product );
				arsort( $products );
				$most_sold_product_id = key( $products );
				$quantity             = $products[ $most_sold_product_id ];
				$product              = wc_get_product( $most_sold_product_id );
				if ( ! empty( $product ) ) {
					$product_name = $product->get_name();
				}
		
				$store_id = is_object( $product ) && ! empty( $product->get_meta( 'elex_mv_store_id', true ) ) ? $product->get_meta( 'elex_mv_store_id', true ) : '';
				if ( empty( $store_id ) ) {
					$user_id = get_post_field( 'post_author', $most_sold_product_id );
				} else {
					$user_id = get_post_field( 'post_author', $store_id );
				}
				$product_author_name = get_the_author_meta( 'display_name' , $user_id );
			 
				$product_data['unit_sold']    = ! empty( $quantity ) ? $quantity : 0;
				$product_data['product_name'] = ! empty( $product_name ) ? $product_name : 0;
				$product_data['author_name']  = ! empty( $product_author_name ) ? $product_author_name : 0;
				$product_data['image']        = is_object( $product ) && ! empty( $product->get_image() ) ? wp_kses_post( $product->get_image() ) : '';

			}
		}
		return $product_data;
	}

	public function elex_mv_admin_country_data() {
		if ( ! isset( $_POST['_ajax_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_ajax_nonce'] ) ), 'elex_mv_admin_dashboard' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Unauthorized', 403 );
		}
		
		// Get the start and end dates for the last 30 days
		$current_from_date = $this->get_current_from_date();

		$from_date = isset( $_POST['from'] ) ? sanitize_text_field( wp_unslash( $_POST['from'] ) ) : $current_from_date;

		$to_date = isset( $_POST['to'] ) ? sanitize_text_field( wp_unslash( $_POST['to'] ) ) : time();


		// Query the WooCommerce database for all orders placed in the last 30 days
		$args = array(
			
			'post_type'    => 'shop_order',
			'limit'        => -1, // retrieve all orders
			'status'       => array( 'processing', 'completed' ),
		
			'date_created' => $from_date . '...' . $to_date,
		   
		   
		);

		$orders     = wc_get_orders( $args );
		$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 );
	}

	public static function elex_mv_top_vendor( $from, $to ) {

		global $wpdb;

		new \WpFluent\Connection( $wpdb, array(), 'DB' );

		$vendor_details = array();
		$top_vendor     = array();
		$vendor_stores  = Store::get_stores();

		foreach ( $vendor_stores  as $store ) {

			$store_id = $store->ID;
	
			$results_com = $wpdb->get_results(
				$wpdb->prepare(
					"
				SELECT SUM(vendor_earning.meta_value) as total_vendor_earning, SUM(admin_commission.meta_value) as total_admin_commission
				FROM {$wpdb->prefix}wc_orders as orders
				INNER JOIN {$wpdb->prefix}wc_orders_meta as vendor_id ON orders.id = vendor_id.order_id AND vendor_id.meta_key = 'elex_mv_store_id' AND vendor_id.meta_value = %s
				INNER JOIN {$wpdb->prefix}wc_orders_meta as vendor_earning ON orders.id = vendor_earning.order_id AND vendor_earning.meta_key = 'elex_mv_vendor_earning'
				INNER JOIN {$wpdb->prefix}wc_orders_meta as admin_commission ON orders.id = admin_commission.order_id AND admin_commission.meta_key = 'elex_mv_admin_earning'

				WHERE orders.status IN ('wc-processing', 'wc-completed') 
				AND DATE(orders.date_created_gmt) BETWEEN %s AND %s
				",
					$store_id,
					$from,
					$to
				)
			);
			$results_com = json_decode( wp_json_encode( $results_com[0] ), true );

		
			if ( empty( $top_vendor ) ) {

				$top_vendor = $results_com;
				if ( isset( $results_com['total_vendor_earning'] ) && isset( $results_com['total_admin_commission'] ) && ! empty( $results_com['total_vendor_earning'] ) && ! empty( $results_com['total_admin_commission'] ) ) {
					$top_vendor['total_vendor_earning'] = $results_com['total_vendor_earning'] + $results_com['total_admin_commission'] ;

				}

				$top_vendor['store_id'] = $store_id;

				$user_id = get_post_field( 'post_author', $store_id );
					
				$user_meta = get_userdata( $user_id );
				if ( isset( $user_meta ) ) {

					$top_vendor['display_name'] = $user_meta->display_name;
					$top_vendor['email']        = $user_meta->user_email;
	
					$top_vendor['image'] = has_post_thumbnail( $store_id ) ? esc_url( get_the_post_thumbnail_url( $store_id ) ) : esc_url( ELEX_MULTI_VENDOR_MAIN_URL_PATH . 'assets/images/default-store-icon.svg' );
				
				}           
			} elseif ( ! empty( $top_vendor ) ) {
 
				$tota_vendor_earn = isset( $top_vendor['total_vendor_earning'] ) ? $top_vendor['total_vendor_earning'] : 0;
				$query_total      = isset( $results_com['total_vendor_earning'] ) ? $results_com['total_vendor_earning'] : 0;

				if ( $tota_vendor_earn < $query_total ) {
					$top_vendor                         = $results_com;
					$top_vendor['total_vendor_earning'] = $results_com['total_vendor_earning'] + $results_com['total_admin_commission'] ;

					$top_vendor['store_id'] = $store_id;
					$user_id                = get_post_field( 'post_author', $store_id );
					
					$user_meta                  = get_userdata( $user_id );
					$top_vendor['display_name'] = $user_meta->display_name;
					$top_vendor['email']        = $user_meta->user_email;

					$top_vendor['image'] = has_post_thumbnail( $store_id ) ? esc_url( get_the_post_thumbnail_url( $store_id ) ) : esc_url( ELEX_MULTI_VENDOR_MAIN_URL_PATH . 'assets/images/default-store-icon.svg' );
				
				}           
			}       
		}


		return $top_vendor;
	}

	public static function elex_mv_calculate_commission( $product_id, $sales ) {
		$site_settings     = SiteSettings::load();
		$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 ) : $site_settings->get( 'commission_type_of_sale' );
		$commission_amount = ! empty( $product->get_meta( 'elex_mv_commission', true ) ) ? $product->get_meta( 'elex_mv_commission', true ) : $site_settings->get( 'commission_for_each_sale' );
		$commission_amount = (float) $commission_amount;
		$sales             = (float) $sales;
		$commission        = 0;

		if ( ! empty( $sales ) ) {

			if ( 'percent' === $commission_type ) {
				$commission = $sales * ( $commission_amount / 100 );
			} else {
				$commission = $sales - $commission_amount;
			}
		}
	  
		return $commission;
	}
	
	public static function elex_mv_product_status_count( $from, $to ) {
		$status = array(
			'publish'  => 0, 
			'pending'  => 0, 
			'reject' => 0,
		);
		$args   = array(
			'post_type'      => 'product',
			'posts_per_page' => -1,
			'post_status'    => array( 'pending', 'publish', 'reject' ),
			'meta_key' => 'elex_mv_store_id',
			'date_query'     => array(
				array(
					'after'     => $from,
					'before'    => $to,
					'inclusive' => true,
				),
			),
		);
		
		$product_data = get_posts( $args );
		foreach ( $product_data as $key => $val ) {
			$status = self::elex_mv_product_status( $status, $val->post_status );
		}
		return $status;
	}
	public static function elex_mv_product_status( $product_status, $status ) {
		switch ( $status ) {
			case 'publish':
				$product_status['publish'] += 1;
				break;
			case 'pending':
				$product_status['pending'] += 1;
				break;
			case 'reject':
				$product_status['reject'] += 1;
				break;
			default:
				break;
		}
		return $product_status;
	}
	public static function elex_mv_total_product_count( $from, $to ) {
		$product_count = array();
		$args          = array(
			'post_type'      => 'product',
			'posts_per_page' => -1,
			'post_status'    => array( 'pending', 'publish' ),
			'meta_key' => 'elex_mv_store_id',
			'date_query'     => array(
				array(
					'after'     => $from,
					'before'    => $to,
					'inclusive' => true,
				),

			),
			'fields'         => 'ids',
		);
		
		$current_product_count = count( get_posts( $args ) );
	
		$product_count['30_days'] = ! empty( $current_product_count ) ? $current_product_count : 0;
		return $product_count;
	}


	public static function elex_mv_order_status_count( $order_status, $status ) {
		
		switch ( $status ) {
			case 'on-hold':
				$order_status['on-hold'] += 1;
				break;
			case 'processing':
				$order_status['processing'] += 1;
				break;
			case 'cancelled':
				$order_status['cancelled'] += 1;
				break;
			case 'completed':
				$order_status['completed'] += 1;
				break;
			case 'pending':
				$order_status['pending'] += 1;
				break;
			case 'refunded':
				$order_status['refunded'] += 1;
				break;
			default:
				break;

		}
		return $order_status;
	}

	public static function elex_mv_vendor_count( $from, $to ) {
		$vendor_count = array();
		$args         = array(
			'date_query'     => array(
				array(
					'after'     => $from,
					'before'    => $to,
					'inclusive' => true,
				),
			),
			'fields'         => 'ID',
			'post_type'      => 'elex_vendor',
			'status'         => array( 'publish', 'private', 'pending' ),
			'posts_per_page' => -1,
		);
	
		$last_30_days_vendor = count( get_posts( $args ) );

		$vendor_count['last_30_days'] = ! empty( $last_30_days_vendor ) ? $last_30_days_vendor : 0; 
		return $vendor_count;
	}
}
