<?php


namespace Elex\MultiVendor\Controller;

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

use Elex\MultiVendor\Model\SiteSettings;

class AdminSettings {
	public static $settings = null;

	public static function init() {
		$self = new self();
		
		add_action( 'elex_mv_settings_tab_general', array( self::class, 'load_general_settings' ) );
		add_action( 'elex_mv_settings_tab_commission', array( self::class, 'load_commission_settings' ) );
		add_action( 'elex_mv_settings_tab_vendor_capability', array( self::class, 'load_vendor_capability_settings' ) );
		add_action( 'elex_mv_settings_tab_settlement', array( self::class, 'load_settlement_settings' ) );

		add_filter( 'elex_mv_settings_saving_general', array( self::class, 'save_general_settings' ) );
		add_filter( 'elex_mv_settings_saving_commission', array( self::class, 'save_commission_settings' ) );
		add_filter( 'elex_mv_settings_saving_vendor_capability', array( self::class, 'save_vendor_capability_settings' ) );
		add_filter( 'elex_mv_settings_saving_settlement', array( self::class, 'save_settlement_settings' ) );
	}
	
	public static function save_vendor_capability_settings( SiteSettings $settings ) {
		check_admin_referer( 'elex_mv_save_settings', 'elex_mv_settings_nonce' );
		$new_settings = array();
		$new_settings['can_vendor_sell_products_without_approval'] = isset( $_POST['can_vendor_sell_products_without_approval'] ) ? sanitize_text_field( wp_unslash( $_POST['can_vendor_sell_products_without_approval'] ) ) : '';
		$new_settings['allow_vendor_shipping']                     = isset( $_POST['allow_vendor_shipping'] ) ? sanitize_text_field( wp_unslash( $_POST['allow_vendor_shipping'] ) ) : '';
		$new_settings['allow_vendor_to_initiate_refund']           = isset( $_POST['allow_vendor_to_initiate_refund'] ) ? sanitize_text_field( wp_unslash( $_POST['allow_vendor_to_initiate_refund'] ) ) : '';

		$new_settings['allow_vendor_override_credentials']   = isset( $_POST['allow_vendor_override_credentials'] ) ? sanitize_text_field( wp_unslash( $_POST['allow_vendor_override_credentials'] ) ) : '';
		$new_settings['can_vendor_choose_shipping_services'] = isset( $_POST['can_vendor_choose_shipping_services'] ) ? sanitize_text_field( wp_unslash( $_POST['can_vendor_choose_shipping_services'] ) ) : '';
		$new_settings['can_vendor_create_product_category']  = isset( $_POST['can_vendor_create_product_category'] ) ? sanitize_text_field( wp_unslash( $_POST['can_vendor_create_product_category'] ) ) : '';
		$new_settings['allow_vendor_flat_rate']              = isset( $_POST['allow_vendor_flat_rate'] ) ? sanitize_text_field( wp_unslash( $_POST['allow_vendor_flat_rate'] ) ) : '';
		$new_settings['can_vendor_change_order_status']      = isset( $_POST['can_vendor_change_order_status'] ) ? sanitize_text_field( wp_unslash( $_POST['can_vendor_change_order_status'] ) ) : '';
		$new_settings['allow_vendor_coupon']                 = isset( $_POST['allow_vendor_coupon'] ) ? sanitize_text_field( wp_unslash( $_POST['allow_vendor_coupon'] ) ) : '';

	

		return $settings->merge( $new_settings );
	}
	public static function save_general_settings( SiteSettings $settings ) {
		check_admin_referer( 'elex_mv_save_settings', 'elex_mv_settings_nonce' );
		$new_settings                                     = array();
		$new_settings['vendor_onboarding_wizard']         = isset( $_POST['vendor_onboarding_wizard'] ) ? sanitize_text_field( wp_unslash( $_POST['vendor_onboarding_wizard'] ) ) : '';
		$new_settings['approve_vendor_onboard']           = isset( $_POST['approve_vendor_onboard'] ) ? sanitize_text_field( wp_unslash( $_POST['approve_vendor_onboard'] ) ) : '';
		$new_settings['allow_admin_dashboard']            = isset( $_POST['allow_admin_dashboard'] ) ? sanitize_text_field( wp_unslash( $_POST['allow_admin_dashboard'] ) ) : '';
		$new_settings['show_vendor_details_store_page']   = isset( $_POST['show_vendor_details_store_page'] ) ? sanitize_text_field( wp_unslash( $_POST['show_vendor_details_store_page'] ) ) : '';
		$new_settings['show_vendor_details_product_page'] = isset( $_POST['show_vendor_details_product_page'] ) ? sanitize_text_field( wp_unslash( $_POST['show_vendor_details_product_page'] ) ) : '';
		$new_settings['elex_mv_store_slug']               = isset( $_POST['elex_mv_store_slug'] ) && ! empty( $_POST['elex_mv_store_slug'] ) ? sanitize_text_field( wp_unslash( $_POST['elex_mv_store_slug'] ) ) : 'elex-store';
		$new_settings['elex_mv_store_slug_pre']           = isset( $_POST['elex_mv_store_slug_pre'] ) ? sanitize_text_field( wp_unslash( $_POST['elex_mv_store_slug_pre'] ) ) : '';
		$new_settings['elex_mv_header_text']              = isset( $_POST['elex_mv_header_text'] ) ? sanitize_text_field( wp_unslash( $_POST['elex_mv_header_text'] ) ) : 'Please Enter & Verify Your Details';

		if ( ! empty( $new_settings['elex_mv_store_slug'] ) && ! empty( $new_settings['elex_mv_store_slug_pre'] ) && $new_settings['elex_mv_store_slug'] !== $new_settings['elex_mv_store_slug_pre'] ) {


			$posts = get_posts(
				array(
					'name'                   => $new_settings['elex_mv_store_slug_pre'],
					'post_type'              => 'page',
					'post_status'            => 'all',
					'numberposts'            => 1,
					'update_post_term_cache' => false,
					'update_post_meta_cache' => false,           
		
				)
			);
				 
		
			if ( ! empty( $posts ) ) {

				wp_update_post(
					array(
						'ID'        => $posts[0]->ID,
						'post_name' => $new_settings['elex_mv_store_slug'],
					) 
				);
				
			}       
		}
		return $settings->merge( $new_settings );
	}

	public static function save_commission_settings( SiteSettings $settings ) {
		check_admin_referer( 'elex_mv_save_settings', 'elex_mv_settings_nonce' );
		$old_commission = $settings->get( 'commission_for_each_sale' );
		$new_settings                             = array();
		$new_settings['commission_for_each_sale'] = isset( $_POST['commission_for_each_sale'] ) ? sanitize_text_field( wp_unslash( $_POST['commission_for_each_sale'] ) ) : '';
		$new_settings['commission_type_of_sale']  = isset( $_POST['discount_type'] ) ? sanitize_text_field( wp_unslash( $_POST['discount_type'] ) ) : 'percent';
		$new_settings['ship_fee']                 = isset( $_POST['ship_fee'] ) ? sanitize_text_field( wp_unslash( $_POST['ship_fee'] ) ) : 'vendor';
		$new_settings['tax_fee']                  = isset( $_POST['tax_fee'] ) ? sanitize_text_field( wp_unslash( $_POST['tax_fee'] ) ) : 'vendor';

		$new_commission = $new_settings['commission_for_each_sale'];
		
		// Trigger the product commission metadata update only if the rate has actually changed.
		if ( (float) $old_commission !== (float) $new_commission ) {
			self::update_vendors_global_commission( $new_commission );
		}

		return $settings->merge( $new_settings );
	}

	/**
	 * Scans for all vendors utilizing the global commission setting and
	 * updates their associated products' commission meta values to the new rate.
	 *
	 * @param float|string $new_commission The new global commission percentage rate.
	 */
	public static function update_vendors_global_commission( $new_commission ) {
		// Query all vendors where the custom vendor commission switch is turned off.
		$args = array(
			'post_type'      => 'elex_vendor',
			'post_status'    => 'any',
			'posts_per_page' => -1,
			'meta_query'  => array(
				'relation' => 'OR',
				array(
					'key'     => 'elex_mv_apply_vendor_commission_switch',
					'compare' => 'NOT EXISTS', // Not set defaults to global settings.
				),
				array(
					'key'     => 'elex_mv_apply_vendor_commission_switch',
					'value'   => '1',
					'compare' => '!=', // Explicitly set to disabled.
				),
			),
			'fields' => 'ids',
		);
		$vendor_ids = get_posts( $args );

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

		$per_page = 100;
		$page     = 1;

		// Fetch and update products in batches of IDs to optimize performance and memory usage.
		do {
			$products = get_posts(
				array(
					'post_type'      => 'product',
					'post_status'    => 'any', // Ensure draft/pending products are updated too.
					'posts_per_page'         => $per_page,
					'paged'                  => $page,
					'fields'                 => 'ids', // Performance optimization: fetch IDs only.
					'update_post_term_cache' => false, // Term cache is not needed since we don't handle taxonomies here.
					'meta_key'               => 'elex_mv_store_id',
					'meta_value'             => $vendor_ids,
					'meta_compare'           => 'IN',
				)
			);

			// Break loop if no products are returned in the current batch.
			if ( empty( $products ) ) {
				break;
			}

			// Iterate through matching product IDs and update the commission meta value.
			foreach ( $products as $product_id ) {
				update_post_meta( $product_id, 'elex_mv_commission', $new_commission );
			}
			$page++;
		} while ( true );
	}

	public static function save_settlement_settings( SiteSettings $settings ) {
		check_admin_referer( 'elex_mv_save_settings', 'elex_mv_settings_nonce' );
		$new_settings                                     = array();
		$new_settings['elex_mv_date_of_month_pay_settle'] = isset( $_POST['elex_mv_date_of_month_pay_settle'] ) && ! empty( $_POST['elex_mv_date_of_month_pay_settle'] ) ? sanitize_text_field( wp_unslash( $_POST['elex_mv_date_of_month_pay_settle'] ) ) : 0;
		$new_settings['buffer_time']                      = isset( $_POST['buffer_time'] ) && ! empty( $_POST['buffer_time'] ) ? sanitize_text_field( wp_unslash( $_POST['buffer_time'] ) ) : 0;
		$new_settings['elex_mv_order_status_radios']      = isset( $_POST['elex_mv_order_status_radios'] ) ? map_deep( wp_unslash( $_POST['elex_mv_order_status_radios'] ), 'sanitize_text_field' ) : array();
		return $settings->merge( $new_settings );
	}

	public static function load_general_settings() {
		$data['elex_mv_options'] = self::get_widget_settings();
		SiteSettings::include_file( 'templates/admin-settings/general-settings.php', $data );
	}
	public static function load_commission_settings() {
		$data['elex_mv_options'] = self::get_widget_settings();
		SiteSettings::include_file( 'templates/admin-settings/commission-charges.php', $data );
	}
	public static function load_vendor_capability_settings() {
		$data['elex_mv_options'] = self::get_widget_settings();
		SiteSettings::include_file( 'templates/admin-settings/vendor-capability.php', $data );
	}
	public static function load_settlement_settings() {
		$data['elex_mv_options'] = self::get_widget_settings();
		SiteSettings::include_file( 'templates/admin-settings/settlement.php', $data );
	}

	public static function get_current_tab() {
		$tab = SiteSettings::get_param( 'tab' );
		return ! empty( $tab ) ? $tab : self::get_default_tab();
	}

	public static function get_default_tab() {
		/** 
		 * Fire a filter hook for default settings tab
		 *
		 * @since 2.0.0
		 */
		return apply_filters( 'elex_mv_admin_settings', 'general' );
	}

	public static function get_widget_settings( $reload = false ) {
		if ( self::$settings && false === $reload ) {
			return self::$settings;
		}

		$settings = SiteSettings::load();

		/** 
		 * Fire a filter hook for settings
		 *
		 * @since 2.0.0
		 * @param $settings
		 */
		self::$settings = apply_filters( 'elex_mv_get_settings', $settings );

		return self::$settings;
	}
}
