<?php
namespace Elex\MultiVendor\Controller;

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

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

use function PHPSTORM_META\override;

class ShippingController {

	public static $nonce_error_msg = 'Wrong Nonce';

	public static function init() {
		$self = new self();
		add_action( 'elex_mv_shipping_page', array( $self, 'shipping_page' ) );
		
		add_action( 'wp_ajax_elex_mv_shipping_save_vendor_credentials', array( self::class, 'validate_and_save_credentials' ) );

		add_action( 'wp_ajax_elex_mv_override_vendor_credential', array( self::class, 'override_vendor_credential' ) );

		add_action( 'wp_ajax_elex_mv_enabling_shipping_method_plugin', array( self::class, 'enabling_shipping_method_plugins' ) );

		add_action( 'wp_ajax_elex_mv_enabling_woocommerce_shipping_method_plugin', array( self::class, 'enabling_woocommerce_shipping_method_plugins' ) );

		add_filter( 'woocommerce_cart_shipping_packages', array( self::class, 'split_packages_acc_to_vendor' ), 9999, 4 );

		// phpcs:ignore

		add_filter( 'elex_vendor_formate_origin_address', array( self::class, 'formate_origin_address' ), 10, 2 );

		add_filter( 'woocommerce_shipping_package_name', array( self::class, 'New_shipping_title' ), 10, 2 );

		add_filter( 'woocommerce_package_rates' , array( self::class, 'elex_mv_update_shipping_meta' ), 9999, 2 );

		add_filter( 'elex_mv_vendor_splitted_packages_for_diff_service', array( self::class, 'elex_mv_vendor_label_packages' ), 10, 4 );
	}


	public static function New_shipping_title( $name, $vendor_id ) {
		$self = new self();

		$vendor_name = $self->get_vendor_name_from_product( $vendor_id );
		return $vendor_name;
	}


	public static function elex_mv_vendor_label_packages( $packages, $ship_from_address, $ship_from_address_context = 'vendor_address' ) {
		$self     = new self();
		$packages = $packages[0];
			//if origin preference is not vendor address, Do nothing.
		if ( 'vendor_address' !== $ship_from_address_context ) {
			return $packages;
		}
		
			$vendor_packages = array();

		foreach ( $packages as $package ) {
			
			foreach ( $package['contents'] as $key => $order_details ) {
			
				$vendor_id = $self->get_vendor_id_from_product( $order_details );
				$vendor_packages[ $vendor_id ]['contents'][ $key ] = $order_details;
				$vendor_packages[ $vendor_id ]['destination']      = $package['destination'];
				/**
				 * TO change address in vendor.
				 *
				 * @since 1.0.0
				 */
				$vendor_packages[ $vendor_id ]['origin']              = apply_filters( 'elex_vendor_formate_origin_address', $vendor_id );
				$vendor_packages[ $vendor_id ]['origin']['vendor_id'] = $vendor_id;
				if ( isset( $package['orderId'] ) ) {
					$vendor_packages[ $vendor_id ]['orderId'] = $package['orderId'] ;
					$vendor_packages[ $vendor_id ]['title']   = get_post_meta( $package['orderId'], 'wf_elex_ep_vendor_shipping_service' . $vendor_id, true );  
				}
			}       
		}
		
			// Now the packages array will be indexed by vendor ID.
			return $vendor_packages;
	}

	public static function elex_mv_update_shipping_meta( $rates, $package ) {


		if ( empty( $rates ) ) {
			return $rates;  
		} 
		if ( ! is_array( $rates ) ) {
			return $rates;
		}

	


		if ( is_array( $package ) && isset( $package['vendor_id'] ) && ! empty( $package['vendor_id'] ) ) {
				$seller_id = $package['vendor_id'];
  
			foreach ( $rates as $carrier_id => $rate_obj ) {

				$rates[ $carrier_id ]->add_meta_data( 'Vendor_Id', $seller_id );

				if ( $rate_obj instanceof \WC_Shipping_Rate ) {

	
					$ship_settings = get_option(
						'woocommerce_' . $rate_obj->get_method_id() . '_' . $rate_obj->get_instance_id() . '_settings'
					);

					if ( ! empty( $ship_settings['elex_extra_field_assigned_vendor'] ) 
						&& is_array( $ship_settings['elex_extra_field_assigned_vendor'] ) ) {

						if ( in_array( $seller_id, $ship_settings['elex_extra_field_assigned_vendor'], true ) ) {
							$rate_obj->add_meta_data( 'Vendor_Id', $seller_id );
						} else {
							unset( $rates[ $carrier_id ] );
						}                   
					} else {
						unset( $rates[ $carrier_id ] );
					}            
				}           
			}
			
			if ( empty( $rates ) ) {
					$rate_obj->add_meta_data( 'Vendor_Id', $seller_id );

					$has_free_shipping = false;
				foreach ( $rates as $r ) {
					if ( $r instanceof \WC_Shipping_Rate && $r->get_method_id() === 'free_shipping' ) {
						$has_free_shipping = true;
						break;
					}
				}

				if ( ! $has_free_shipping ) {
						
					$free_rate = new \WC_Shipping_Rate(
						'free_shipping:1',
						'Free Shipping',
						0,
						array(),
						'free_shipping'
					);
					$free_rate->add_meta_data( 'Vendor_Id', $seller_id );
					$rates['free_shipping:1'] = $free_rate;
				}
			} 
		}

		return $rates;
	}






		
	public static function formate_origin_address( $store_id ) {
	
		
		$s = array(
			'country'    => get_post_meta( $store_id, 'elex_mv_country', true ),
			'first_name' => get_post_meta( $store_id, 'elex_mv_user_name', true ),
			'last_name'  => get_post_meta( $store_id, 'elex_mv_user_name', true ),
			'company'    => 'xyz',
			'address_1'  => get_post_meta( $store_id, 'elex_mv_address', true ),
			'address_2'  => 'asa',
			'city'       => get_post_meta( $store_id, 'elex_mv_city', true ),
			'state'      => get_post_meta( $store_id, 'elex_mv_state', true ),
			'postcode'   => get_post_meta( $store_id, 'elex_mv_postal_code', true ),
			'phone'      => get_post_meta( $store_id, 'elex_mv_phone_number', true ),
			'email'      => get_post_meta( $store_id, 'elex_mv_email', true ),
	
		);
		if ( empty( $s['country'] ) ) {
			return array();
		}
	
		return $s;
	}


	public static function enabling_woocommerce_shipping_method_plugins() {
	
		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
				wp_send_json_error( self::$nonce_error_msg, 403 );
				die();      
		}

	

		$store_id           = isset( $_POST['store_id'] ) ? sanitize_text_field( wp_unslash( $_POST['store_id'] ) ) : '';
		$shipping_method    = isset( $_POST['shipping_method'] ) ? sanitize_text_field( wp_unslash( $_POST['shipping_method'] ) ) : '';
		$enable             = isset( $_POST['enable'] ) && 'true' === $_POST['enable'] ? 1 : 0;
		$shipping_method_id = isset( $_POST['shipping_method_id'] ) ? sanitize_text_field( wp_unslash( $_POST['shipping_method_id'] ) ) : '';

		update_post_meta( $store_id, $shipping_method . $shipping_method_id , $enable );


		wp_send_json_success(
			array(
				'message' => __( 'Saved successfully' , 'elex-multi-vendor-for-woocommerce' ),
			)
		);
	}
	
	public static function enabling_shipping_method_plugins() {

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

		$carrier_slug = isset( $_POST['carrier_slug'] ) ? sanitize_text_field( wp_unslash( $_POST['carrier_slug'] ) ) : '';
		$enable       = isset( $_POST['enable'] ) ? sanitize_text_field( wp_unslash( $_POST['enable'] ) ) : false;
		$store_id     = isset( $_POST['store_id'] ) ? sanitize_text_field( wp_unslash( $_POST['store_id'] ) ) : '';

		$carriers_enable_list[ $carrier_slug ] = $enable;
		
		if ( get_post_meta( $store_id, 'elex_mv_enabling_shipping_method_plugins', true ) ) {

			$carriers_enable_list = get_post_meta( $store_id, 'elex_mv_enabling_shipping_method_plugins', true );

			$carriers_enable_list[ $carrier_slug ] = $enable;

		}

		update_post_meta( $store_id, 'elex_mv_enabling_shipping_method_plugins', $carriers_enable_list ); 
		wp_send_json_success(
			array(
				'message' => __( 'Saved successfully' , 'elex-multi-vendor-for-woocommerce' ),
			)
		);
	}

	/**
	 * For override the services saved for the particular vendor in the shop order page of multivendor
	 *
	 * @param [array] $services
	 * @param [array] $package
	 * @param [order object] $order
	 * @param [string] $plugin
	 * @return services
	 */
	public static function override_services_for_request( $services, $package, $order, $plugin ) {

		$vendor_services = array();
	
		$store_id = isset( $package['vendor_id'] ) ? $package['vendor_id'] : '';

		if ( isset( $order ) ) {

			$store_id = $order->get_meta( 'elex_mv_store_id' );
		}

		$carriers_enable_list = get_post_meta( $store_id, 'elex_mv_enabling_shipping_method_plugins', true );

		
		if ( ! $store_id || ( ! isset( $carriers_enable_list[ $plugin ] ) || ! $carriers_enable_list[ $plugin ] ) ) {
			return $services;
		}
		$vendor_services = get_post_meta( $store_id, 'woocommerce_wf_' . $plugin . '_shipping_settings', true );

	

		$services = ! empty( $vendor_services ) ? $vendor_services : $services ;
		

		return $services ;
	}

	public static function change_account_number_accc_vendor( $cred_info, $package, $plugin ) {
		$vendor_creds = array();
		
		

		foreach ( $package['contents'] as $pack ) {
			$prod_id  = $pack['data']->get_id();
			$store_id = $pack['data']->get_meta( 'elex_mv_store_id', true );

			if ( ! $store_id ) {
				return $cred_info;
			}
			$permission_override_creds = get_post_meta( $store_id, 'elex_mv_override_credentials', true );
			if ( 'false' === $permission_override_creds || empty( $permission_override_creds ) ) {
				return $cred_info;
			}


			$vendor_creds = get_post_meta( $store_id, 'woocommerce_wf_' . $plugin . '_credentials_settings', false );


		}
			

		$cred_info['site_id']                = $vendor_creds[0]['site_id'];
		$cred_info['site_password']          = $vendor_creds[0]['site_password'];
		$cred_info['payment_account_number'] = $vendor_creds[0]['account_number'];
		$cred_info['base_country']           = $vendor_creds[0]['base_country'];
		$cred_info['payment_country_code']   = $vendor_creds[0]['base_country'];


		return $cred_info;
	}

	public static function split_packages_acc_to_vendor( $packages ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed

		$self = new self();

		$package_temp = $packages;

		$new_packages = array();      
		//Init splitted package
		$splitted_packages = array();
		$vendor_id         = '';

		foreach ( WC()->cart->get_cart() as $item_key => $item ) {
			if ( $item['data']->needs_shipping() ) {
				
				$vendor_id = $self->get_vendor_id_from_product( $item );
				$vendor_id = $self->get_vendor_id_from_product( $item );

				$splitted_packages[ $vendor_id ][ $item_key ] = $item;
			}
		}


		if ( is_array( $splitted_packages ) ) {
			
			foreach ( $splitted_packages as $vendor_id => $splitted_package_items ) {

				$new_packages[ $vendor_id ] = array(
					'contents'      => $splitted_package_items,
					'contents_cost' => array_sum( wp_list_pluck( $splitted_package_items, 'line_total' ) ),
					'user'          => array(
						'ID' => $vendor_id, 
					),
					'vendor_id'     => $vendor_id,
					'Veller_Id'     => $vendor_id,
					/**
					 * TO change address in vendor.
					 *
					 * @since 1.0.0
					 */
					'origin'        => apply_filters( 'elex_vendor_formate_origin_address', $vendor_id ),
					'destination'   => array(
						'country'   => WC()->customer->get_shipping_country(),
						'state'     => WC()->customer->get_shipping_state(),
						'postcode'  => WC()->customer->get_shipping_postcode(),
						'city'      => WC()->customer->get_shipping_city(),
						'address'   => WC()->customer->get_shipping_address(),
						'address_2' => WC()->customer->get_shipping_address_2(),
					),
				);
				if ( ! isset( $new_packages[ $vendor_id ]['origin'] ) || empty( $new_packages[ $vendor_id ]['origin'] ) ) {
					unset( $new_packages[ $vendor_id ]['origin'] );
				}

				if ( is_array( $package_temp ) && isset( $package_temp[ $vendor_id ] ) ) {
					$vendor_package_data = $package_temp[ $vendor_id ];
					if ( is_array( $vendor_package_data ) ) {
						if ( isset( $vendor_package_data['vendor_id'] ) ) {
							$new_packages[ $vendor_id ]['vendor_id'] = $vendor_package_data['vendor_id'] ;
						}
						if ( isset( $vendor_package_data['pickup_address'] ) ) {
							$new_packages[ $vendor_id ]['pickup_address'] = $vendor_package_data['pickup_address'];
						}                   
					}
				}
			}       
		}

	

		update_option( 'elex_mv_splitted_packages', $new_packages );
		return $new_packages;
	}

	public function get_vendor_id_from_product( $order_details ) {
		
		$product_id = ! empty( $order_details['data']->get_parent_id() ) ? $order_details['data']->get_parent_id() : $order_details['data']->get_id();
		$prdct      = wc_get_product( $product_id );
		
		$prod_vendor = $prdct->get_meta( 'elex_mv_store_id', true );
	
		if ( ! $prod_vendor ) {
			return 0;
		}

		return $prod_vendor;
	}
	public function get_vendor_name_from_product( $store_id ) {
		if ( ! $store_id ) {
			return 'Admin :';
		}

		return get_post_meta( $store_id, 'elex_mv_user_name', true ) ? get_post_meta( $store_id, 'elex_mv_user_name', true ) . ' :' : '' ;
	}

	public function shipping_page() {

		$woocommerce_shipping_methods = array();
		$vendor_info                  = Vendor::load( wp_get_current_user() );
		$store                        = new Store();
		if ( $vendor_info->has_store() ) {
			$store = $vendor_info->get_store();
		}

		$zones = \WC_Shipping_Zones::get_zones();

		$shipping_methodds = WC()->shipping()->load_shipping_methods();
		
		

		foreach ( $zones as $zone ) { 
			$zone_id = $zone['zone_id'];

			$zone_name = $zone['zone_name'];
			foreach ( $zone['shipping_methods'] as $shipping_method ) {
		
				$shipping_method->instance_settings = array_merge(
					$shipping_method->instance_settings,
					array(
						'zone_region' => $zone['formatted_zone_location'],
						'zone_name'   => $zone_name,
					) 
				);
			}
			$woocommerce_shipping_methods = array_merge( $woocommerce_shipping_methods, $zone['shipping_methods'] );
			
			
		}
		

		
			$vendor_all_permissions = $store->get_checkbox_list();
			$all_admin_permissions  = get_option( 'elex_mv_admin_installation_params' );

			$override_credentials_for_shipping_method = get_post_meta( $store->get_id(), 'elex_mv_override_credentials', true );

			$carriers_enable_list = get_post_meta( $store->get_id(), 'elex_mv_enabling_shipping_method_plugins', true );

			/**
			 * TO change vendor.
			 *
			 * @since 1.0.0
			 */
			$shipping_values_from_dhl = apply_filters( 'elex_mv_shipping_info_shipping_method' , array(), $store );
			$shipping_values_from_dhl = array();

			/**
			 * TO change vendor.
			 *
			 * @since 1.0.0
			 */
			$woocommerce_shipping_methods = apply_filters( 'elex_mv_shipping_woocommerce_shipping_method' , $woocommerce_shipping_methods, $store );


			include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/shipping/shipping.php';
	}
	public static function override_vendor_credential() {
		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
				wp_send_json_error( self::$nonce_error_msg, 403 );
				die();      
		}
		// phpcs:ignore
		$credential_array['enable']          = isset( $_POST['enable'] ) ? sanitize_text_field( wp_unslash( $_POST['enable'] ) ) : '';
		$credential_array['shipping_method'] = isset( $_POST['shipping_method'] ) ? sanitize_text_field( wp_unslash( $_POST['shipping_method'] ) ) : '';


		$data_array = array();

	
		$vendor_info = Vendor::load( wp_get_current_user() );
		$store       = new Store();
  
		if ( $vendor_info->has_store() ) {
			$store = $vendor_info->get_store();
		}
			$override_credentials_for_shipping_method = get_post_meta( $store->get_id(), 'elex_mv_override_credentials', true );

		if ( $override_credentials_for_shipping_method ) {

			$override_credentials_for_shipping_method[ $credential_array['shipping_method'] ] = $credential_array['enable'];
				
		

			update_post_meta( $store->get_id(), 'elex_mv_override_credentials' , $override_credentials_for_shipping_method );

		} else {
			$data_array[ $credential_array['shipping_method'] ] = $credential_array['enable'];

					
			

			update_post_meta( $store->get_id(), 'elex_mv_override_credentials' , $data_array );

		}

		wp_send_json_success(
			array(
				'message' => __( 'Saved successfully' , 'elex-multi-vendor-for-woocommerce' ),
			)
		);
	}

	public static function validate_and_save_credentials() {
		// phpcs:ignore
		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
				wp_send_json_error( self::$nonce_error_msg, 403 );
				die();      
		}

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

		$vendor_info = Vendor::load( wp_get_current_user() );
		$store       = new Store();
  
		if ( $vendor_info->has_store() ) {
			$store = $vendor_info->get_store();
		}


		$credentials = array();

		$credentials['site_id']         = isset( $_POST['_custom_site_id_field'] ) ? sanitize_text_field( wp_unslash( $_POST['_custom_site_id_field'] ) ) : '';
		$credentials['site_password']   = isset( $_POST['_custom_site_password_field'] ) ? sanitize_text_field( wp_unslash( $_POST['_custom_site_password_field'] ) ) : '';
		$credentials['account_number']  = isset( $_POST['_custom_account_number_field'] ) ? sanitize_text_field( wp_unslash( $_POST['_custom_account_number_field'] ) ) : '';
		$credentials['base_country']    = isset( $_POST['_custom_base_country_field'] ) ? sanitize_text_field( wp_unslash( $_POST['_custom_base_country_field'] ) ) : '';
		$credentials['production']      = isset( $_POST['_custom_test_mode_field'] ) ? sanitize_text_field( wp_unslash( $_POST['_custom_test_mode_field'] ) ) : '';
		$credentials['shipping_plugin'] = isset( $_POST['shipping_plugin'] ) ? sanitize_text_field( wp_unslash( $_POST['shipping_plugin'] ) ) : '';
		$shipping_plugin                = $credentials['shipping_plugin'] ;

			/**
			 * Vendor credentaisl to ovverride admin credential.
			 *
			 * @since 1.0.0
			 */
		$shipping_post_data = array(
			'store_id'                     => $store_id,
			'_custom_site_id_field'        => $credentials['site_id'],
			'_custom_site_password_field'  => $credentials['site_password'],
			'_custom_account_number_field' => $credentials['account_number'],
			'_custom_base_country_field'   => $credentials['base_country'],
			'_custom_test_mode_field'      => $credentials['production'],
			'shipping_plugin'              => $credentials['shipping_plugin'],
		);
		/**
		 * Filters the vendor shipping credentials used to override admin settings for a given shipping plugin.
		 *
		 * @since 1.0.0
		 * @param array  $credentials       The vendor shipping credentials array.
		 * @param array  $shipping_post_data The posted shipping form data.
		 */
		$credentials = apply_filters( 'elex_mv_vendor_credentials_to_override_admin_' . $shipping_plugin, $credentials, $shipping_post_data );
		$data        = array(
			'errors' => array(),
		);

		/**
		 *While validating vendor credential.
		 *
		 * @since 1.0.0
		 */
		$validation_errors = apply_filters( 'elex_mv_shipping_validate_vendor_credentials', array(), $shipping_plugin, $store_id );
		

		/**
		 * Main Filter To change vendor credential as you want for shipping.
		 *
		 * @since 1.0.0
		 */
		$validation_errors = apply_filters( 'elex_mv_shipping_validate_vendor_credentials_' . $shipping_plugin, $data, $store_id, $credentials );

	

		if ( count( $validation_errors['errors'] ) ) {
			wp_send_json_error( $validation_errors );
			die;
		}
 
			/**
			 * While saving vendor credentials save your data.
			 *
			 * @since 1.0.0
			 */
		do_action( 'elex_mv_shipping_save_vendor_credentials_' . $shipping_plugin, $store, $credentials );

		wp_send_json_success(
			array(
				'message' => __( 'Saved successfully' , 'elex-multi-vendor-for-woocommerce' ),
			)
		);
	}
}
