<?php
/**
 * This file handles the Webkul's WC related addons menu registrations.
 *
 * @version 1.3.0
 *
 * @package WKWC Addons
 */

defined( 'ABSPATH' ) || exit(); // Exit if access directly.

use Automattic\WooCommerce\Utilities\OrderUtil;

if ( ! class_exists( 'WKWC_Addons' ) ) {
	/**
	 * WKWC_Addons class.
	 */
	class WKWC_Addons {
		/**
		 * Instance variable.
		 *
		 * @var $instance
		 */
		protected static $instance = null;

		/**
		 * Remove license option specific.
		 *
		 * @var array $validate_license
		 */
		public $validate_license;

		/**
		 * Autoload constructor.
		 */
		public function __construct() {
			defined( 'WKWC_ADDONS_VERSION' ) || define( 'WKWC_ADDONS_VERSION', '1.3.2' );
			defined( 'WKWC_ADDONS_DIR_URL' ) || define( 'WKWC_ADDONS_DIR_URL', plugin_dir_url( __FILE__ ) );
			defined( 'WKLICENSE_PLUGIN_FILE' ) || define( 'WKLICENSE_PLUGIN_FILE', plugin_dir_path( __FILE__ ) );
			defined( 'WKLICENSE_SCRIPT_VERSION' ) || define( 'WKLICENSE_SCRIPT_VERSION', '1.3.2' );

			add_action( 'init', array( $this, 'wkwc_addons_load_textdomain' ) );

			add_action( 'admin_enqueue_scripts', array( $this, 'wkwc_addons_admin_enqueue_scripts' ) );

			add_action( 'admin_menu', array( $this, 'wkwc_add_addon_menu' ) );

			add_action( 'activated_plugin', array( $this, 'wkwc_redirect_to_addons_page_on_activation' ), 9 );

			add_action( 'admin_menu', array( $this, 'wkwc_add_addon_submenu' ), 999 );

			add_filter( 'extra_plugin_headers', array( $this, 'wkwc_addons_extra_headers' ) );

			add_action( 'wp_ajax_wp_pcc_save_purchase_code', array( $this, 'wp_pcc_save' ) );

			add_action( 'wp_ajax_wp_pcc_remove_purchase_code', array( $this, 'wp_pcc_remove' ) );

			add_action( 'wp_footer', array( $this, 'wkwc_addons_front_footer_info' ) );

			$this->validate_license = array( 'wkwc-addons-support-services', 'wkwc-addons-extensions', 'wkwc-addons-license', 'wkwc-addons', 'wkwp-addons-support-services', 'wkwp-addons-extensions', 'wkwp-addons-license', 'wkwp-addons', 'wc-pos-support-and-services', 'wc-pos-extensions', 'wc-pos-licence', 'wk-marketplace-license', 'wk-marketplace-extensions', 'wk-marketplace-support-services' );
		}

		/**
		 * Adding extra plugin headers.
		 *
		 * @param array $headers Plugin headers.
		 *
		 * @hooked 'extra_plugin_headers' filter hook.
		 *
		 * @return array
		 */
		public function wkwc_addons_extra_headers( $headers ) {
			array_push( $headers, 'WKWC_Addons' );

			return $headers;
		}

		/**
		 * Redirect to addons page.
		 *
		 * @return void
		 */
		public function wkwc_redirect_to_addons_page_on_activation() {
			$redirect_to = self::wk_get_request_data( 'redirect_to' );

			if ( 'wkwc-addons' === $redirect_to ) {
				wp_safe_redirect( admin_url( 'admin.php?page=wkwc-addons', 'admin' ) );
				exit();
			}
		}

		/**
		 * Loading WKWC Addons text domain.
		 *
		 * @return void
		 */
		public function wkwc_addons_load_textdomain() {
			load_plugin_textdomain( 'wkwc_addons', false, plugin_basename( __DIR__ ) . '/languages' );
			$this->wkwc_addons_manage_licode();
		}

		/**
		 * Loading WKWC Addons Extensions and Support & Services js.
		 *
		 * @return void
		 */
		public function wkwc_addons_admin_enqueue_scripts() {
			$page_name   = self::wk_get_request_data( 'page' );
			$plugin_data = $this->wp_pcc_get_plugin_data();

			$pages = apply_filters( 'wk_modules_admin_page_slugs', array() );
			wp_enqueue_style( 'wkwc-addons-tabs-style', WKWC_ADDONS_DIR_URL . 'assets/css/wkwc-addons-tabs.css', array(), WKWC_ADDONS_VERSION, 'all' );

			if ( 'wkwc-addons' === $page_name ) {
				wp_enqueue_style( 'wkwc-addons-style', WKWC_ADDONS_DIR_URL . 'assets/css/wkwc-addons.css', array(), WKWC_ADDONS_VERSION, 'all' );
			}
			if ( 'wkwc-addons-support-services' === $page_name ) {
				wp_enqueue_script( 'wkwc-addons-support-services', 'https://webkul.com/common/modules/wksas.bundle.js', array(), WKWC_ADDONS_VERSION, true );
			}
			if ( 'wkwc-addons-extensions' === $page_name ) {
				wp_enqueue_script( 'wkwc-addons-extensions', 'https://wpdemo.webkul.com/wk-extensions/client/wk.ext.js', array(), WKWC_ADDONS_VERSION, true );
				wp_enqueue_script( 'wkwc-addons-select', WKWC_ADDONS_DIR_URL . '/assets/js/wkwc-addons.js', array(), WKWC_ADDONS_VERSION, true );
			}

			$page_exist = false;

			if ( ! empty( $page_name ) ) {
				$slugs         = array();
				$custom_pg_arr = array();

				foreach ( $pages as $parentKey => &$subArray ) {
					foreach ( $subArray as $value ) {
						if ( empty( $value['parent_slug'] ) ) {
							$pages[ $parentKey ] = array_slice( $pages[ $parentKey ], 0, count( $pages[ $parentKey ] ) - 3 );
						}
					}
				}

				foreach ( array_values( $pages ) as $value ) {
					if ( ! empty( $value ) && is_array( $value ) ) {
						foreach ( $value as $data ) {
							$slugs[] = empty( $data['menu_slug'] ) ? '' : $data['menu_slug'];

							if ( ! empty( $data['custom_page'] ) ) {
								$custom_pg_arr[] = \WK_Caching::wk_get_request_data( explode( '=', $data['custom_page'] )[0] );
							}
						}
					}
					if ( in_array( $page_name, $slugs, true ) ) {
						$page_exist = true;
					}

					if ( ! empty( $custom_pg_arr ) && count( $custom_pg_arr ) > 1 && ( $custom_pg_arr[0] === $custom_pg_arr[1] ) ) {
						$page_exist = true;
					}
				}
			}

			$module_name = str_replace( ' ', '_', strtolower( ! empty( $plugin_data['module']['Name'] ) ? $plugin_data['module']['Name'] : '' ) );

			if ( ! empty( $page_name ) && $page_exist && empty( get_option( 'wp_pcc_' . $module_name ) ) && ! empty( $module_name ) ) {
				if ( wp_script_is( 'dc-admin-script', 'enqueued' ) ) {
					return;
				} else {
					wp_enqueue_style( 'dc-admin-style', 'https://wp-tracking.vachak.com/purchase_code_collector/purchasecode.css', array(), WKLICENSE_SCRIPT_VERSION );
					wp_enqueue_script( 'dc-admin-script', 'https://wp-tracking.vachak.com/purchase_code_collector/purchasecode.js', array(), WKLICENSE_SCRIPT_VERSION, false );
					wp_localize_script(
						'dc-admin-script',
						'hposObject',
						array(
							'plugin_name'    => ! empty( $plugin_data ) ? $plugin_data['module']['Name'] : '',
							'plugin_dir'     => ! empty( $plugin_data ) ? explode( '/', $plugin_data['dir'] )[0] : '',
							'plugin_version' => ! empty( $plugin_data ) ? $plugin_data['module']['Version'] : '',
							'pages'          => $pages,
						)
					);
				}
			}
			$this->wp_pcc_enqueue_admin_scripts();
		}

		/**
		 * Adding a common 'Webkul Addons' menu.
		 *
		 * @return void
		 */
		public function wkwc_add_addon_menu() {
			$capability = apply_filters( 'wkmp_dashboard_menu_capability', 'manage_options' );
			$arr        = array(
				array(
					'page_title'    => esc_html__( 'Webkul WC Addons', 'wkwc_addons' ),
					'menu_title'    => esc_html__( 'Webkul WC Addons', 'wkwc_addons' ),
					'capability'    => $capability,
					'menu_slug'     => 'wkwc-addons',
					'parent_slug'   => '',
					'callback'      => 'wkwc_addons_output',
					'icon'          => 'dashicons-editor-paste-word',
					'position'      => 54.978,
					'screen_option' => false,
				),
			);
			wkwc_create_menu( $arr, $this );
		}

		/**
		 * Showing list of all WC Addons by Webkul installed.
		 *
		 * @return void
		 */
		public function wkwc_addons_output() {
			$all_plugins = get_plugins();

			$this->wkwc_show_addon_header();

			foreach ( $all_plugins as $plugin_file => $headers ) {
				if ( ! empty( $headers['WKWC_Addons'] ) ) {
					$plugin_data = get_file_data(
						WP_PLUGIN_DIR . '/' . $plugin_file,
						array(
							'name'          => 'Plugin Name',
							'description'   => 'Description',
							'settings_page' => 'WKWC_Settings',
							'icon_url'      => 'WKWC_Icon_URL',
							'blog_url'      => 'Blog URI',
						),
						'plugin'
					);

					$this->wkwc_show_addon_card( $plugin_file, $plugin_data );
				}
			}

			$this->wkwc_show_addon_footer();
		}

		/**
		 * Show addon header.
		 *
		 * @return void
		 */
		public function wkwc_show_addon_header() {
			?>
			<div class="wkwc-addons-wrap wrap">
				<h2 class="wp-heading-inline"><?php esc_html_e( 'Webkul Addons', 'wkwc_addons' ); ?></h1>
				<p class="wkwc_addon_desc"><?php esc_html_e( 'Showing the list of all installed Webkul WooCommerce Addons.', 'wkwc_addons' ); ?></p>
				<div class="wkwc-addons-list">
			<?php
		}

		/**
		 * Show Addon card
		 *
		 * @param string $plugin_file Plugin file.
		 * @param array  $plugin_data Plugin data.
		 *
		 * @return void
		 */
		public function wkwc_show_addon_card( $plugin_file, $plugin_data ) {
			$setting_page = empty( $plugin_data['settings_page'] ) ? '' : $plugin_data['settings_page'];

			$link         = empty( $setting_page ) ? '#' : admin_url( 'admin.php?page=' . $setting_page );
			$text         = esc_html__( 'Settings', 'wkwc_addons' );
			$text_title   = esc_html__( 'Open Settings', 'wkwc_addons' );
			$card_class   = '';
			$button_class = 'button-primary';

			if ( ! is_plugin_active( $plugin_file ) ) {
				$link         = wp_nonce_url( admin_url( 'plugins.php?action=activate&plugin=' . $plugin_file ), 'activate-plugin_' . $plugin_file );
				$link        .= '&redirect_to=wkwc-addons';
				$text         = esc_html__( 'Activate', 'wkwc_addons' );
				$text_title   = esc_html__( 'Click to activate and use.', 'wkwc_addons' );
				$card_class   = 'disable';
				$button_class = 'button-secondary';
			}

			$plugin_name = empty( $plugin_data['name'] ) ? '' : $plugin_data['name'];
			$icon_url    = empty( $plugin_data['icon_url'] ) ? 'https://webkul.com/wp-content/themes/webkul-2020/images/brand-kit/square-logo/primary-sq.png' : $plugin_data['icon_url'];
			$blog_url    = empty( $plugin_data['blog_url'] ) ? 'https://webkul.com/blog/?s=' . $plugin_name . '&cat=WordPress' : $plugin_data['blog_url'];
			$description = empty( $plugin_data['description'] ) ? '' : wp_trim_words( $plugin_data['description'], 35, '...' );
			?>
			<div class="wkwc-addon-container <?php echo esc_attr( $card_class ); ?>">
				<div class="wkwc-addon-sub-cont">
					<img src="<?php echo esc_url( $icon_url ); ?>" alt="" class="wkwc-addon-img">
					<p class="wkwc-addon-cont-heading"><?php echo esc_html( $plugin_name ); ?></p>
				</div>
				<p class="wkwc-addon-cont-content"><?php echo esc_html( $description ); ?></p>
				<div class="wkwc-addon-btn-container">
					<a title="<?php echo esc_attr( $text_title ); ?>" href="<?php echo esc_url( $link ); ?>" class="wkwc-addons-cta button <?php echo esc_attr( $button_class ); ?>"><?php echo esc_html( $text ); ?></a>
					<a title="<?php esc_attr_e( 'Click to see the Blog', 'wkwc_addons' ); ?>" target="_blank" href="<?php echo esc_url( $blog_url ); ?>"><span class="wkwc-addon-info-btn dashicons dashicons-info-outline"></span></a>
				</div>
			</div>
			<?php
		}


		/**
		 * Manage License code for Webkul plugins.
		 *
		 * @version 1.0.2
		 * @LWDT: 202408121330
		 *
		 * Note: Always copy form wkwc_addons module.
		 */
		public function wkwc_addons_manage_licode() {
			$fields = array(
				'Name'       => 'Plugin Name',
				'Version'    => 'Version',
				'Plugin_Url' => 'Plugin URI',
				'Author'     => 'Author',
			);

			$active_plugins = get_option( 'active_plugins' );

			if ( is_multisite() ) {
				$active_plugins = array_merge( $active_plugins, array_flip( get_site_option( 'active_sitewide_plugins', array() ) ) );
			}

			$existing_plugin = array_filter(
				array_map(
					function ( $data ) use ( $fields ) {
						return get_file_data( WP_PLUGIN_DIR . '/' . $data, $fields );
					},
					array_filter(
						$active_plugins,
						function ( $plugin ) use ( $fields ) {
							$plugin_data = get_file_data( WP_PLUGIN_DIR . '/' . $plugin, $fields );
							$author      = empty( $plugin_data['Author'] ) ? ( empty( $plugin_data['author'] ) ? '' : $plugin_data['author'] ) : $plugin_data['Author'];

							if ( ! empty( $plugin_data['Plugin_Url'] ) && 'webkul' === strtolower( $author ) && ( ! defined( 'WKMP_LITE_PLUGIN_BASENAME' ) || ( defined( 'WKMP_LITE_PLUGIN_BASENAME' ) && WKMP_LITE_PLUGIN_BASENAME !== $plugin ) ) ) {
								return $plugin;
							}
						}
					)
				),
				function ( $plugin_data ) {
					if ( empty( get_option( 'wp_pcc_' . str_replace( ' ', '_', strtolower( $plugin_data['Name'] ) ) ) ) ) {
						return $plugin_data;
					}
				}
			);

			if ( ! empty( $existing_plugin ) ) {
				usort(
					$existing_plugin,
					function ( $a, $b ) {
						if ( ! empty( $a['module'] ) ) {
							if ( (float) $a['module']['Version'] === (float) $b['module']['Version'] ) {
								return 0;
							}
							return (float) $a['module']['Version'] < (float) $b['module']['Version'] ? 1 : -1;
						} else {
							if ( (float) $a['Version'] === (float) $b['Version'] ) {
								return 0;
							}
							return (float) $a['Version'] < (float) $b['Version'] ? 1 : -1;
						}
					}
				);
			}

			$plugin_data = ! empty( array_values( $existing_plugin )[0] ) ? array_values( $existing_plugin )[0] : array();
			$pages       = apply_filters( 'wk_modules_admin_page_slugs', array() );

			if ( ! empty( $plugin_data ) ) {
				add_action(
					'admin_enqueue_scripts',
					function () use ( $pages, $plugin_data ) {
						$page_exist = false;
						$wk_page    = self::wk_get_request_data( 'page' );

						if ( ! empty( $wk_page ) ) {
							$slugs         = array();
							$custom_pg_arr = array();

							foreach ( array_values( $pages ) as $value ) {
								if ( ! empty( $value ) ) {
									foreach ( $value as $data ) {
										$slugs[] = empty( $data['menu_slug'] ) ? '' : $data['menu_slug'];

										if ( ! empty( $data['custom_page'] ) ) {
											$custom_pg_arr[] = \WK_Caching::wk_get_request_data( explode( '=', $data['custom_page'] )[0] );
										}
									}
								}

								if ( in_array( $wk_page, $slugs, true ) ) {
									$page_exist = true;
								}

								if ( ! empty( $custom_pg_arr ) && count( $custom_pg_arr ) > 1 && ( $custom_pg_arr[0] === $custom_pg_arr[1] ) ) {
									$page_exist = true;
								}
							}
						}

						$module_name = str_replace( ' ', '_', strtolower( ! empty( $plugin_data['module']['Name'] ) ? $plugin_data['module']['Name'] : '' ) );

						if ( ! empty( $wk_page ) && $page_exist && empty( get_option( 'wp_pcc_' . $module_name ) ) && ! empty( $module_name ) ) {
							if ( wp_script_is( 'dc-admin-script', 'enqueued' ) ) {
								return;
							} else {
								wp_enqueue_style( 'dc-admin-style', 'https://wp-tracking.vachak.com/purchase_code_collector/purchasecode.css', array(), WKLICENSE_SCRIPT_VERSION );
								wp_enqueue_script( 'dc-admin-script', 'https://wp-tracking.vachak.com/purchase_code_collector/purchasecode.js', array(), WKLICENSE_SCRIPT_VERSION, false );
								wp_localize_script(
									'dc-admin-script',
									'hposObject',
									array(
										'plugin_name'    => ! empty( $plugin_data ) ? $plugin_data['module']['Name'] : '',
										'plugin_dir'     => ! empty( $plugin_data ) ? explode( '/', $plugin_data['dir'] )[0] : '',
										'plugin_version' => ! empty( $plugin_data ) ? $plugin_data['module']['Version'] : '',
										'pages'          => $pages,
									)
								);
							}
						}
					}
				);
			}
		}

		/**
		 * Show addon footer.
		 *
		 * @return void
		 */
		public function wkwc_show_addon_footer() {
			?>
			</div> <!-- wkwc-addons-row -->
			</div> <!-- wkwc-addons-wrap -->
			<?php
		}

		/**
		 * Display All settings tabs.
		 *
		 * @param array  $tabs Setting tabs.
		 * @param string $title Page title.
		 * @param string $icon Module icon.
		 */
		public function create_settings_tabs( $tabs = array(), $title = '', $icon = '' ) {

			$submenu_name = ( is_array( $tabs ) && count( $tabs ) > 0 ) ? array_keys( $tabs )[0] : '';
			$submenu_page = self::wk_get_request_data( 'page' );

			if ( ! empty( $submenu_name ) && ! empty( $submenu_page ) && $submenu_name === $submenu_page ) {
				$tab         = self::wk_get_request_data( 'tab' );
				$current_tab = empty( $tab ) ? $submenu_name : $tab;
				if ( ! empty( $tab ) ) {
					$submenu_page .= '_' . $tab;
				}
				$title = empty( $title ) ? array_values( $tabs )[0] : $title;
				?>
			<div class="wkwc-addons-tabs-wrap">
				<nav class="nav-tab-wrapper wkwc-admin-addon-list-manage-nav">
					<div class="wkwc-addons-page-header">
						<div class="module-icon">
							<?php echo wp_kses_post( $icon ); ?>
						</div>
						<p class="page-title"><?php echo esc_html( $title ); ?></p>
					</div>
					<div class="wkwc-addons-nav-link">
				<?php
				foreach ( $tabs as $name => $label ) {
					$tab_url  = admin_url( 'admin.php?page=' . esc_attr( $submenu_name ) );
					$tab_url .= ( $name === $submenu_name ) ? '' : '&tab=' . $name;
					echo wp_sprintf( '<a href="%s" class="nav-tab %s">%s</a>', esc_url( $tab_url ), ( $current_tab === $name ? 'nav-tab-active' : '' ), esc_html( $label ) );
				}
				?>
					</div>
				</nav>
				<?php
				do_action( $submenu_page . '_content', $submenu_name );
				?>
			</div>
				<?php
			}
		}

		/**
		 * Adding a common 'Webkul Addons' menu.
		 *
		 * @return void
		 */
		public function wkwc_add_addon_submenu() {
			$capability = apply_filters( 'wkmp_dashboard_menu_capability', 'manage_options' );
			$arr        = apply_filters(
				'wk_addon_global_submenus',
				array(
					array(
						'parent_slug'            => 'wkwc-addons',
						'page_title'             => esc_html__( 'License', 'wkwc_addons' ),
						'menu_title'             => esc_html__( 'License', 'wkwc_addons' ),
						'capability'             => $capability,
						'menu_slug'              => 'wkwc-addons-license',
						'callback'               => 'wp_pcc_show_license_listing',
						'screen_option'          => false,
						'screen_option_callback' => '',
					),
					array(
						'parent_slug'            => 'wkwc-addons',
						'page_title'             => esc_html__( 'Extensions', 'wkwc_addons' ),
						'menu_title'             => esc_html__( 'Extensions', 'wkwc_addons' ),
						'capability'             => $capability,
						'menu_slug'              => 'wkwc-addons-extensions',
						'callback'               => 'wkwc_addons_extensions',
						'screen_option'          => false,
						'screen_option_callback' => '',
					),
					array(
						'parent_slug'            => 'wkwc-addons',
						'page_title'             => esc_html__( 'Support & Services', 'wkwc_addons' ),
						'menu_title'             => esc_html__( 'Support & Services', 'wkwc_addons' ),
						'menu_slug'              => 'wkwc-addons-support-services',
						'capability'             => $capability,
						'callback'               => 'wkwc_addons_support_services',
						'screen_option'          => false,
						'screen_option_callback' => '',
					),
				)
			);

			wkwc_create_menu( $arr, $this );
		}

		/**
		 * WKWC Addons extensions callback.
		 *
		 * @return void
		 */
		public function wkwc_addons_extensions() {
			?>
			<webkul-extensions></webkul-extensions>
			<?php
		}

		/**
		 * WKWC Addons support and services menu.
		 *
		 * @return void
		 */
		public function wkwc_addons_support_services() {
			?>
			<wk-area></wk-area>
			<?php
		}

		/**
		 * Get request data.
		 *
		 * @param string $key Key to get the data.
		 * @param array  $args Arguments to get the request data.
		 *
		 * @version 1.1.1
		 * @LWDT: 202406251400.
		 *
		 * Note: Always copy form wk_caching module, if need any change first do it in wk_caching then only copy from wk_caching.
		 *
		 * @return bool|int|string|void|array|object
		 */
		public static function wk_get_request_data( $key, $args = array() ) {
			if ( empty( $key ) ) {
				return '';
			}

			$method  = empty( $args['method'] ) ? 'get' : sanitize_text_field( wp_unslash( $args['method'] ) );
			$filter  = empty( $args['filter'] ) ? 'string' : sanitize_text_field( wp_unslash( $args['filter'] ) );
			$default = empty( $args['default'] ) ? null : sanitize_text_field( wp_unslash( $args['default'] ) );
			$flag    = empty( $args['flag'] ) ? '' : sanitize_text_field( wp_unslash( $args['flag'] ) );

			$method     = ( 'get' === $method ) ? INPUT_GET : INPUT_POST;
			$filter_int = ( 'int' === $filter ) ? FILTER_SANITIZE_NUMBER_INT : FILTER_SANITIZE_FULL_SPECIAL_CHARS;
			$filter_int = ( 'float' === $filter ) ? FILTER_SANITIZE_NUMBER_FLOAT : $filter_int;
			$filter_int = ( 'email' === $filter ) ? FILTER_SANITIZE_EMAIL : $filter_int;

			if ( ! empty( $flag ) && 'array' === $flag ) {
				$flag_value = ( 'array' === $flag ) ? FILTER_REQUIRE_ARRAY : FILTER_REQUIRE_SCALAR;
				$data       = filter_input( $method, $key, $filter_int, $flag_value );

				if ( empty( $data ) ) {
					return array();
				}

				if ( 519 === $filter_int ) { // Int.
					return empty( $data ) ? array() : map_deep(
						wp_unslash( $data ),
						function ( $value ) {
							return empty( $value ) ? $value : intval( $value );
						}
					);
				}
				if ( 520 === $filter_int ) { // Float.
					return empty( $data ) ? array() : map_deep(
						wp_unslash( $data ),
						function ( $value ) {
							return empty( $value ) ? $value : floatval( $value );
						}
					);
				}
				return empty( $data ) ? array() : map_deep( wp_unslash( $data ), 'sanitize_text_field' );
			}
			if ( ! is_array( $key ) ) {
				$data = filter_input( $method, $key, $filter_int );
			} else {
				$data = array_map(
					function ( $key ) use ( $method, $filter_int ) {
						return filter_input( $method, $key, $filter_int );
					},
					$key
				);
			}

			if ( 520 === $filter_int && 'array' !== $flag ) {
				$flag_value = ( 'fraction' === $flag ) ? FILTER_FLAG_ALLOW_FRACTION : FILTER_FLAG_ALLOW_THOUSAND;
				$data       = filter_input( $method, $key, $filter_int, $flag_value );
			}

			if ( empty( $data ) ) {
				return $default;
			}

			if ( 519 === $filter_int ) { // Int.
				return intval( wp_unslash( $data ) );
			}
			if ( 520 === $filter_int ) { // Float.
				return floatval( wp_unslash( $data ) );
			}
			if ( 517 === $filter_int ) { // Email.
				return sanitize_email( wp_unslash( $data ) );
			}

			return sanitize_text_field( wp_unslash( $data ) );
		}

		/**
		 * Declare plugin is compatible with HPOS.
		 *
		 * @param string $file Plugin main file path.
		 * @param bool   $status Compatibility status.
		 */
		public static function wkwc_addon_declare_hpos_compatible( $file = '', $status = false ) {
			add_action(
				'before_woocommerce_init',
				function () use ( $file, $status ) {
					if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
						\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', $file, $status );
					}
				}
			);
		}

		/**
		 * Declare plugin is incompatible with WC Cart and Checkout blocks.
		 *
		 * @param string $file Plugin main file path.
		 * @param bool   $status Compatibility status.
		 *
		 * @return void
		 */
		public static function wkwc_addon_declare_cart_checkout_block_compatibility_status( $file = '', $status = false ) {
			add_action(
				'before_woocommerce_init',
				function () use ( $file, $status ) {
					if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
						\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', $file, $status );
					}
				}
			);
		}

		/**
		 * Check WooCommerce HPOS is enabled.
		 *
		 * @return bool
		 */
		public static function wkwc_is_hpos_enabled() {
			return ( class_exists( '\Automattic\WooCommerce\Utilities\OrderUtil' ) && method_exists( '\Automattic\WooCommerce\Utilities\OrderUtil', 'custom_orders_table_usage_is_enabled' ) && \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() );
		}

		/**
		 * Get Order meta.
		 *
		 * @param object $order Order object.
		 * @param string $key Meta key.
		 * @param int    $order_id Order id.
		 *
		 * @return mixed $meta_data Meta data.
		 */
		public static function get_order_meta( $order = '', $key = '', $order_id = 0 ) {
			if ( empty( $key ) ) {
				return '';
			}
			if ( ! $order instanceof \WC_Abstract_Order && ! empty( $order_id ) ) {
				$order = wc_get_order( $order_id );
			}

			if ( ! $order instanceof \WC_Abstract_Order ) {
				return '';
			}

			$order_id = empty( $order_id ) ? $order->get_id() : $order_id;

			$meta_value = $order->get_meta( $key );

			if ( ! empty( $meta_value ) ) {
				return $meta_value;
			}

			if ( true === self::wkwc_is_hpos_enabled() ) {
				global $wpdb;
				$meta_value = $wpdb->get_var( $wpdb->prepare( "SELECT `meta_value` FROM `{$wpdb->prefix}wc_orders_meta` WHERE `meta_key`=%s AND `order_id`=%d", $key, $order_id ) );

				if ( ! empty( $meta_value ) ) {
					return $meta_value;
				}
			}

			return get_post_meta( $order_id, $key, true );
		}

		/**
		 * Get order edit URL.
		 *
		 * @param int $order_id Order id.
		 *
		 * @return string $order_url Order edit url.
		 */
		public static function get_order_edit_url( $order_id = 0 ) {
			$order_url = OrderUtil::get_order_admin_edit_url( $order_id );
			return esc_url( $order_url );
		}

		/**
		 * Wrapper for admin notice.
		 *
		 * @param string $message The notice message.
		 * @param string $type Notice type like info, error, success.
		 * @param array  $args Additional arguments for wp-6.4.
		 *
		 * @return void
		 */
		public static function wk_show_notice_on_admin( $message = '', $type = 'error', $args = array() ) {
			if ( ! empty( $message ) ) {
				if ( function_exists( 'wp_admin_notice' ) ) {
					$args         = is_array( $args ) ? $args : array();
					$args['type'] = empty( $args['type'] ) ? $type : $args['type'];

					wp_admin_notice( $message, $args );
				} else {
					?>
				<div class="<?php echo esc_attr( $type ); ?>"><p><?php echo wp_kses_post( $message ); ?></p></div>
					<?php
				}
			}
		}

		/**
		 * Show current plugin version and last working date and time on front end.
		 *
		 * @hooked wp_footer Action hook.
		 *
		 * @return void
		 */
		public static function wkwc_addons_front_footer_info() {
			$show_info = self::wk_get_request_data( 'wkmodule_info' );
			$show_info = empty( $show_info ) ? 0 : intval( $show_info );
			if ( 200 === $show_info ) {
				?>
			<input type="hidden" data-lwdt="202409091300" wkwc-addons="<?php echo esc_attr( WKWC_ADDONS_VERSION ); ?>">
				<?php
			}
		}

		/**
		 * Ensures only one instance of this class is loaded or can be loaded.
		 *
		 * @return object
		 */
		public static function get_instance() {
			if ( ! static::$instance ) {
				static::$instance = new self();
			}

			return static::$instance;
		}

		// Lic file start.

		/**
		 * Get Plugins data.
		 *
		 * Note: Always copy form wkwc_addons module.
		 *
		 * @version 1.0.2
		 * @LWDT: 202408121330
		 *
		 * @return array existing plugin array.
		 */
		public function wp_pcc_get_plugin_data() {
			$fields = array(
				'Name'       => 'Plugin Name',
				'Version'    => 'Version',
				'Plugin_Url' => 'Plugin URI',
				'Author'     => 'Author',
			);

			$active_plugins = get_option( 'active_plugins' );

			if ( is_multisite() ) {
				$active_plugins = array_merge( $active_plugins, array_flip( get_site_option( 'active_sitewide_plugins', array() ) ) );
			}

			$existing_plugin = array_filter(
				array_map(
					function ( $data ) use ( $fields ) {
							return array(
								'module' => get_file_data( WP_PLUGIN_DIR . '/' . $data, $fields ),
								'dir'    => $data,
							);
					},
					array_filter(
						$active_plugins,
						function ( $plugin ) use ( $fields ) {
							$plugin_data = get_file_data( WP_PLUGIN_DIR . '/' . $plugin, $fields );
							$author      = empty( $plugin_data['Author'] ) ? ( empty( $plugin_data['author'] ) ? '' : $plugin_data['author'] ) : $plugin_data['Author'];

							if ( ! empty( $plugin_data['Plugin_Url'] ) && 'webkul' === strtolower( $author ) && ( ! defined( 'WKMP_LITE_PLUGIN_BASENAME' ) || ( defined( 'WKMP_LITE_PLUGIN_BASENAME' ) && WKMP_LITE_PLUGIN_BASENAME !== $plugin ) ) ) {
								return $plugin;
							}
						}
					)
				),
				function ( $plugin_data ) {
					if ( empty( get_option( 'wp_pcc_' . str_replace( ' ', '_', strtolower( $plugin_data['module']['Name'] ) ) ) ) ) {
						return $plugin_data;
					}
				}
			);

			if ( ! empty( $existing_plugin ) ) {
				usort(
					$existing_plugin,
					function ( $a, $b ) {
						return floatval( $a['module']['Version'] ) < floatval( $b['module']['Version'] ) ? 1 : 0;
					}
				);
			}

			return ! empty( array_values( $existing_plugin )[0] ) ? array_values( $existing_plugin )[0] : array();
		}

		/**
		 * Enqueue admin scripts.
		 *
		 * Note: Always copy form wkwc_addons module.
		 *
		 * @version 1.0.2
		 * @LWDT: 202408121330
		 *
		 * @return void.
		 */
		public function wp_pcc_enqueue_admin_scripts() {
			$wk_page = self::wk_get_request_data( 'page' );

			if ( 'wkwc-addons-license' === $wk_page ) {
				wp_enqueue_style( 'wp-pcc-admin-style', 'https://wp-tracking.vachak.com/domain-counter/css/licenseList.css', array(), WKLICENSE_SCRIPT_VERSION );
			}
			wp_enqueue_script( 'wp-pcc-admin-script', 'https://wp-tracking.vachak.com/domain-counter/js/license_list.js', array(), WKLICENSE_SCRIPT_VERSION, false );

			$plugin_data = $this->wp_pcc_get_plugin_data();

			wp_localize_script(
				'wp-pcc-admin-script',
				'wpPccObject',
				array(
					'ajaxurl'        => admin_url( 'admin-ajax.php' ),
					'nonce'          => wp_create_nonce( 'wp_pcc_pos_ajax_nonce' ),
					'site_url'       => site_url(),
					'plugin_name'    => ! empty( $plugin_data ) ? $plugin_data['module']['Name'] : '',
					'plugin_dir'     => ! empty( $plugin_data ) ? explode( '/', $plugin_data['dir'] )[0] : '',
					'plugin_version' => ! empty( $plugin_data ) ? $plugin_data['module']['Version'] : '',
				)
			);
		}

		/**
		 * Save Code Data.
		 *
		 * @throws \Exception Contains exception during saving data.
		 *
		 * Note: Always copy from the client records repo.
		 *
		 * @version 1.0.2
		 * @LWDT: 202408121330
		 *
		 * @return void.
		 */
		public function wp_pcc_save() {
			require_once WKLICENSE_PLUGIN_FILE . 'class-wp-pcc-helper.php';
			$helper = \Wp_Pcc_Helper::get_instance();
			try {
				$nonce = self::wk_get_request_data( 'nonce', array( 'method' => 'post' ) );

				// Verify the nonce for security purposes.
				if ( ! empty( $nonce ) && wp_verify_nonce( $nonce, 'wp_pcc_pos_ajax_nonce' ) ) {
					$envato_data = empty( $_POST['envatoData'] ) ? array() : json_decode( stripslashes( $_POST['envatoData'] ) ); //phpcs:ignore.
					$module      = ! empty( $envato_data->data->data ) ? $envato_data->data->data : ( ! empty( $envato_data->data ) ? $envato_data->data : $envato_data );

					$store_type = ! empty( $module->store_type ) ? $module->store_type : 'codecanyon';
					$plugin_dir = ! empty( $module->plugin_dir ) ? $module->plugin_dir : '';

					if ( 'codecanyon' === $store_type ) {
						$module_name = empty( $module->item->wordpress_plugin_metadata->plugin_name ) ? '' : str_replace( ' ', '_', strtolower( $module->item->wordpress_plugin_metadata->plugin_name ) );

						$posted_module_name = self::wk_get_request_data( 'moduleName', array( 'method' => 'post' ) );
						$module_data        = array();

						if ( str_replace( ' ', '_', strtolower( $posted_module_name ) ) === $module_name ) {
							$module_data['purchase_code']   = self::wk_get_request_data( 'purchaseCode', array( 'method' => 'post' ) );
							$module_data['supported_until'] = ! empty( $module->supported_until ) ? $module->supported_until : $envato_data->supported_until;

							$module_data['license']        = ! empty( $module->license ) ? $module->license : $envato_data->license;
							$module_data['purchase_count'] = ! empty( $module->purchase_count ) ? $module->purchase_count : ( ! empty( $envato_data->purchase_count ) ? $envato_data->purchase_count : 0 );
							$module_data['id']             = ! empty( $module->item->id ) ? $module->item->id : $envato_data->item->id;

							$posted_module_data = self::wk_get_request_data( 'moduleData', array( 'method' => 'post' ) );

							update_option( 'wp_pcc_' . $posted_module_data, maybe_serialize( $module_data ) );

							$plugin_dir  = $helper->wp_pcc_get_plugin_dir( $posted_module_name );
							$admin_email = get_option( 'admin_email' );

							if ( ! empty( $module ) ) {
								$module->plugin_dir  = $plugin_dir;
								$module->admin_email = $admin_email;
							} else {
								$envato_data->plugin_dir  = $plugin_dir;
								$envato_data->admin_email = $admin_email;
							}

							wp_send_json_success(
								array(
									'msg'    => esc_html__( 'Purchase Code Saved', 'wkwc_addons' ),
									'envato' => empty( $module ) ? $envato_data : $module,
								)
							);
						} else {
							throw new \Exception( esc_html__( 'Purchase Code is not Correct', 'wkwc_addons' ), 1 );
						}
					} elseif ( 'webkul_store' === $store_type || 'woocommerce' === $store_type ) {
						wp_send_json_success(
							array(
								'msg'    => esc_html__( 'Purchase Code Saved', 'wkwc_addons' ),
								'envato' => $this->wp_pcc_manage_store_data( $module ),
							)
						);
					} else {
						throw new \Exception( esc_html__( 'Please  provide valid details', 'wkwc_addons' ), 1 );
					}
				} else {
					throw new \Exception( esc_html__( 'Nonce not verified', 'wkwc_addons' ), 1 );
				}
			} catch ( \Exception $e ) {
				wp_send_json_error( $e->getMessage() );
			}
		}

		/**
		 * Manage webkul and WooCommerce store data.
		 *
		 * @param object $module plugin details.
		 *
		 * Note: Always copy from the client records repo.
		 *
		 * @version 1.0.2
		 * @LWDT: 202408121330
		 *
		 * @return void
		 */
		public function wp_pcc_manage_store_data( $module ) {
			$store_type                     = ! empty( $module->store_type ) ? $module->store_type : 'codecanyon';
			$module_data                    = array();
			$plugin_dir                     = ! empty( $module->plugin_dir ) ? $module->plugin_dir : '';
			$module_data['purchase_code']   = $module->purchasecode;
			$module_data['supported_until'] = ! empty( $module->supported_until ) ? $module->supported_until : '';
			$module_data['license']         = ! empty( $module->license ) ? $module->license : 'Regular License';
			$module_data['purchase_count']  = 1;
			$module_data['store_type']      = $store_type;
			$module_data['id']              = ! empty( $module->item->id ) ? $module->item->id : '';
			$posted_module_data             = strtolower( str_replace( ' ', '_', $module->item->name ) );

			update_option( 'wp_pcc_' . $posted_module_data, maybe_serialize( $module_data ) );
			$admin_email         = get_option( 'admin_email' );
			$module->plugin_dir  = $plugin_dir;
			$module->admin_email = $admin_email;

			wp_send_json_success(
				array(
					'msg'    => esc_html__( 'Purchase Code Saved', 'wkwc_addons' ),
					'envato' => $module,
				)
			);
		}

		/**
		 * Remove Code Data.
		 *
		 * Note: Always copy from the client records repo.
		 *
		 * @version 1.0.2
		 * @LWDT: 202408121330
		 *
		 * @throws \Exception Contains exception during saving data.
		 *
		 * @return void.
		 */
		public function wp_pcc_remove() {
			try {
				$nonce = self::wk_get_request_data( 'nonce', array( 'method' => 'post' ) );

				// Verify the nonce for security purposes.
				if ( ! empty( $nonce ) && wp_verify_nonce( $nonce, 'wp_pcc_pos_ajax_nonce' ) ) {
					$posted_module_data = self::wk_get_request_data( 'moduleData', array( 'method' => 'post' ) );

					delete_option( 'wp_pcc_' . $posted_module_data );
					wp_send_json_success(
						array(
							'msg' => esc_html__( 'Purchase Code Removed', 'wkwc_addons' ),
						)
					);
				} else {
					throw new \Exception( esc_html__( 'Nonce not verified', 'wkwc_addons' ), 1 );
				}
			} catch ( \Exception $e ) {
				wp_send_json_error( $e->getMessage() );
			}
		}

		/**
		 * Shows License Listing.
		 *
		 * Note: Always copy form wkwc_addons module.
		 *
		 * @version 1.0.1
		 * @LWDT: 202406251600
		 *
		 * @return void.
		 */
		public function wp_pcc_show_license_listing() {
			require_once WKLICENSE_PLUGIN_FILE . 'class-wp-pcc-licence-table.php';
			$wp_pcc_license_table = new Wp_Pcc_Licence_Table();
			$wp_pcc_license_table->prepare_items();
			?>
			<div class="wrap">
				<h1><?php esc_html_e( 'Module License', 'wkwc_addons' ); ?> </h1>
				<form method="GET">
					<?php
					$page_name = self::wk_get_request_data( 'page' );

					if ( ! empty( $page_name ) ) {
						?>
							<input type="hidden" name="page" value="<?php echo esc_attr( $page_name ); ?>" />
						<?php
					}
					$wp_pcc_license_table->display();
					?>
				</form>
				<?php do_action( 'wkwc_after_wk_module_license_table' ); ?>
			</div>
			<?php
		}

		/**
		 * Add notice in admin side.
		 */
		public function wkwc_add_script_notice() {
			$message = esc_html__( 'You are not authorized. Kindly remove the custom script and add the license key.', 'wkwc_addons' );
			self::wk_show_notice_on_admin( $message, 'error' );
		}
	}
	// Lic file end.

	WKWC_Addons::get_instance();

	if ( ! function_exists( 'wkwc_create_menu' ) ) {
		/**
		 * Create Module Menus.
		 *
		 * @param array   $menus_list Contains all menu.
		 * @param array   $class_obj Contains class object.
		 * @param boolean $is_class Contains contain structure is class based or function based.
		 *
		 * @LWDT: 202406251600
		 * @version 1.0.1
		 *
		 * @return void.
		 */
		function wkwc_create_menu( $menus_list, $class_obj, $is_class = true ) {
			$addon_object = WKWC_Addons::get_instance();
			$plugin_info  = $addon_object->wp_pcc_get_plugin_data();
			$plugin_name  = '';
			if ( ! empty( $plugin_info ) ) {
				$plugin_name = ! empty( $plugin_info['module']['Name'] ) ? $plugin_info['module']['Name'] : '';
			}

			if ( ! empty( $menus_list ) && ! empty( $class_obj ) ) {
				if ( ! empty( $menus_list ) ) {
					foreach ( $menus_list as $value ) {
						$callback_func = empty( $value['callback'] ) ? '' : $value['callback'];

						if ( ! in_array( $value['menu_slug'], $addon_object->validate_license, true ) ) {
							if ( ! empty( $plugin_name ) ) {
								$class_obj     = $addon_object;
								$callback_func = 'wkwc_add_script_notice';
							}
						}

						$callback = empty( $callback_func ) ? '' : array( $class_obj, $callback_func );

						if ( ! $is_class && ! empty( $callback_func ) ) {
							$callback = $callback_func;
						}

						if ( empty( $value['parent_slug'] ) ) {
							$menu_arr = array(
								! empty( $value['page_title'] ) ? $value['page_title'] : '',
								! empty( $value['menu_title'] ) ? $value['menu_title'] : '',
								! empty( $value['capability'] ) ? $value['capability'] : 'manage_options',
								$value['menu_slug'],
								$callback,
								! empty( $value['icon'] ) ? $value['icon'] : '',
								! empty( $value['position'] ) ? $value['position'] : 55,
							);

							$menu_screen_option = call_user_func_array( 'add_menu_page', $menu_arr );
							if ( ! empty( $value['screen_option_callback'] ) && $value['screen_option'] ) {
								add_action( 'load-' . $menu_screen_option, array( $class_obj, $value['screen_option_callback'] ) );
							}
						} else {
							$submenu_arr = array(
								$value['parent_slug'],
								! empty( $value['page_title'] ) ? $value['page_title'] : '',
								! empty( $value['menu_title'] ) ? $value['menu_title'] : '',
								! empty( $value['capability'] ) ? $value['capability'] : 'manage_options',
								$value['menu_slug'],
								$callback,
							);
							if ( ! empty( $value['position'] ) ) {
								$submenu_arr[] = $value['position'];
							}

							$submenu_screen_option = call_user_func_array( 'add_submenu_page', $submenu_arr );
							if ( ! empty( $value['screen_option_callback'] ) && $value['screen_option'] ) {
								if ( 'wkwc_add_script_notice' !== $callback_func ) {
									add_action( 'load-' . $submenu_screen_option, array( $class_obj, $value['screen_option_callback'] ) );
								}
							}
						}
					}
				}
			}
		}
	}
}
