<?php
/**
 * Routes all the hooks to their respective actions and filters.
 *
 * @package StockSyncWithGoogleSheetForWooCommerce
 * @since 1.0.0
 */
// Namespace.
namespace StockSyncWithGoogleSheetForWooCommerce;

use Error;

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

if ( ! class_exists('\StockSyncWithGoogleSheetForWooCommerce\Hooks') ) {

	/**
	 * Routes all the hooks to their respective actions and filters.
	 *
	 * @package StockSyncWithGoogleSheetForWooCommerce
	 * @since 1.0.0
	 */
	class Hooks extends Base {
		/**
		 * The single instance of the class.
		 *
		 * @var Hooks
		 */
		public static $instance = null;
		/**
		 * Main plugin file
		 *
		 * @var string
		 */
		public $ult_version = 'stock-sync-with-google-sheet-for-woocommerce-ultimate/stock-sync-with-google-sheet-for-woocommerce-ultimate.php';
  		public static $sync_run_once = false;
		/**
		 * Initializes the class.
		 */
		public static function init() {
			if ( ! self::$instance ) {
				self::$instance = new self();
			}

			self::$instance->add_filters();
			self::$instance->add_actions();
		}
		/**
		 * Actions to be added for the plugin.
		 *
		 * @since 1.0.0
		 */
		public function add_actions() {

			$this->init_appsero_client();

			add_action('admin_menu', [ $this, 'add_admin_menu' ]);
			add_action('admin_init', [ $this, 'redirect_to_admin_page' ], 1);
			add_action('current_screen', [ $this, 'redirect_to_admin_pag_sync' ], 10, 1);
			add_action('init', [ $this, 'check_ssgsw_synced' ], 99999);

			// Footer CSS for admin menu icon.
			add_action('admin_head', [ $this, 'admin_menu_icon_css' ]);

			// Admin enqueue scripts.
			add_action('admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ]);
			add_action('wp_enqueue_scripts', [ $this, 'wp_enqueue_scripts' ]);
			

			// Parse ID from Sheet URL and save for later use.
			add_action('ssgsw_updated_spreadsheet_url', [ $this, 'updated_spreadsheet_url_callback' ]);
			// add_action('ssgsw_updated_save_and_sync', [ $this, 'ssgsw_sync_sheet_callback' ]);
			add_action('admin_footer', [ $this, 'add_some_css' ] );
			/**
			 * Updating sheet hooks
			 */

			/**
			 * When a post type product is created or updated
			 */

			/**
			 * When stock is updated
			 */
			add_action('woocommerce_product_set_stock', [ $this, 'ssgs_woocommerce_product_set_stock' ], 10, 1);

			/**
			 * When product is moved to trash
			 */
			add_action('trashed_post', [ $this, 'trashed_post_callback' ], 10, 1);

			/**
			 * When product is restored from trash
			 */
			add_action('untrashed_post', [ $this, 'untashed_post_callback' ], 10, 1);

			/**
			 * When product is created, or updated or deleted
			 */
			// print_r(wcfm_is_vendor(get_current_user_id()));
		
			add_action('woocommerce_after_product_object_save', [ $this, 'after_save_product' ], 10, 2 );
			add_action('woocommerce_order_status_changed', [ $this, 'woocommerce_order_status_changed' ], 10, 4);
			// add_action('woocommerce_new_order_refund', [ $this, 'woocommerce_new_order_refund' ], 10, 2);
			add_action('woocommerce_product_bulk_edit_save', [ $this, 'after_product_quick_edit' ], 10, 1 );
			// add_action('woocommerce_new_product_variation', [ $this,'after_save_product' ], 10, 2 );.
			add_action('woocommerce_save_product_variation', [ $this,'after_update_product_variation' ], 10, 2 );
			add_action('woocommerce_product_quick_edit_save', [ $this, 'after_product_quick_edit' ], 10, 1 );
			add_action('wp_ajax_sssgw_appscript_improved', [ $this, 'sssgw_appscript_improved' ] );
			add_action('wp_ajax_sssgw_already_updated', [ $this, 'ssgsw_already_updated_keyd' ] );
			add_action('woocommerce_before_delete_product_variation', [ $this, 'trashed_post_callback' ]);
			add_action('admin_init', [ $this, 'add_custom_product_status' ]);
			add_action('admin_init', [ $this, 'add_custom_badge_dropdown' ]);
			add_action('ssgsw_sales_update', [$this, 'ssgsw_sales_to_sheet'], 10, 1);
			add_action('ssgsw_vendor_product_update', [$this, 'ssgsw_vendor_product_update_to_sheet'], 10, 1);
			add_action('admin_init', [ $this, 'install_multi_vendor_plugin']);
			add_action('woocommerce_thankyou', [ $this, 'woocommerce_order_thankyou_handler' ], 10, 1);
			add_action('ssgsw_render_multistore_addon_card', [ $this, 'mulit_store_cart' ]);
			add_action('init', [ $this, 'ssgsw_initial_setup_vendor_cron' ] );
		}
		/**
		 * Executes initial one-time setup tasks for vendor users via an action hook.
		 * * This function is designed to run only once per user (specifically vendors)
		 * when they first access the WordPress admin area after an update or installation.
		 * * @hook admin_init (Typically the hook used for this type of function)
		 *
		 * Steps:
		 * 1. Checks if a user is logged in.
		 * 2. Checks the user metadata for the 'ssgsw_vendor_init_done' flag to ensure the 
		 * setup runs only once per user.
		 * 3. Determines if the current user has a vendor role ('seller' or 'wcfm_vendor').
		 * Administrators are explicitly checked but currently result in no vendor request.
		 * 4. Triggers the action hook 'ssgsw_schedule_formula_mode', passing the vendor status 
		 * and the user ID, if the setup flag is not yet set.
		 * 5. Sets the 'ssgsw_vendor_init_done' user meta flag to prevent future execution.
		 *
		 * @return void
		 */
		public function ssgsw_initial_setup_vendor_cron() {
			// Add filters here.
			$user = wp_get_current_user();
			// Jodi kono user login na thake, tahole skip koro
			if ( 0 == $user->ID ) {
   				 return; // Stop execution
			}
		
			
			$init_done = get_user_meta( $user->ID, 'ssgsw_vendor_init_done', true );
			if( ! $init_done ) {
				$vendor_request = '';
				if ( in_array( 'administrator', (array) $user->roles ) ) {
					$vendor_request = '';
				} else {
					if ( in_array( 'seller', (array) $user->roles ) ) {
						$vendor_request = true;
					} else if ( in_array( 'wcfm_vendor', (array) $user->roles ) ) {
						$vendor_request = true;
					} 
				}
				do_action('ssgsw_schedule_formula_mode', $vendor_request, $user->ID);
				update_user_meta( $user->ID, 'ssgsw_vendor_init_done', true );
			}

		}
		/**
		 * Display Multi-Store Addon Card
		 *
		 * Renders the multi-store addon card in the add-ons dashboard with status,
		 * activation, and settings options based on the plugin's installation and
		 * activation state.
		 *
		 * Features:
		 * - Displays addon icon and description
		 * - Shows activation status dynamically using Alpine.js
		 * - Provides activation link with proper nonce security
		 * - Links to addon settings page
		 * - Offers install option from WordPress plugin repository
		 *
		 * @since   1.0.0
		 * @access  public
		 * @return  void Outputs HTML markup
		 *
		 * @uses    SSGSW_PUBLIC Constant for public assets directory path
		 * @uses    esc_html_e() To safely escape and localize text
		 * @uses    esc_url() To safely escape URLs
		 * @uses    wp_nonce_url() To add security nonce to activation URL
		 * @uses    admin_url() To get WordPress admin URLs
		 * @uses    home_url() To get site home URL
		 * @uses    urlencode() To encode plugin basename for URL parameter
		 * @uses    sanitize_title() To sanitize action name
		 *
		 * @example
		 * $this->mulit_store_cart();
		 *
		 * Frontend Dependencies:
		 * - Alpine.js for dynamic state management (isMultiStoreActive, isMultiStoreInstalled)
		 * - Bootstrap classes for button styling
		 * - Dashicons for icon display
		 *
		 * Security Notes:
		 * - URLs are properly escaped with esc_url()
		 * - Text is localized with esc_html_e()
		 * - Activation URL includes wp_nonce_url() for CSRF protection
		 * - Plugin basename is URL encoded
		 */
		public function mulit_store_cart() {
			?>
			 <div class="addon-card">
                <?php 
                    $flex_image = SSGSW_PUBLIC . 'images/multi-vendor.svg';
                ?>
                <div class="header_wrapper_addon">
                    <img src="<?php echo esc_url($flex_image);?>" class="ssgsw_vendor_icon">

                    <h3 class="header_title_ssgsw"><?php esc_html_e('Multi-Store Addon','stock-sync-with-google-sheet-for-woocommerce');?></h3>
                </div>
                <p class="ssgsw_addon_extra"><?php esc_html_e('This plugin integrates with external websites to gather their data and intelligently merge it into a unified Google Sheet, giving you a comprehensive overview from a single source.','stock-sync-with-google-sheet-for-woocommerce');?></p>
                <div class="addon-status">
                    <p x-show="isMultiStoreActive"><?php esc_html_e('Activated','stock-sync-with-google-sheet-for-woocommerce');?></p>
                    <?php 
                        $plugin_basename = 'multi-store-sync-addon-for-flexstock/multi-store-sync-addon-for-flexstock.php'; // Your plugin's basename
                        $action_name = 'activate_plugin_' . sanitize_title($plugin_basename); // Unique action name
                        $activation_url = wp_nonce_url(
                            admin_url('admin.php?page=ssgsw-add-ons&action=' . $action_name . '&plugin=' . urlencode($plugin_basename)),
                            $action_name
                        );

                    ?>
                    <a class="button upgrade_active_now" href="<?php echo esc_url($activation_url);?>" x-show="isMultiStoreInstalled && !isMultiStoreActive"><?php esc_html_e('Activate Now','stock-sync-with-google-sheet-for-woocommerce');?></a>

                    <a href="<?php echo esc_url(home_url('/wp-admin/admin.php?page=ssgsw-multistore'));?>" class="ssgsw_setting_button" x-show="isMultiStoreActive" ><?php esc_html_e('Settings','stock-sync-with-google-sheet-for-woocommerce');?><span class="dashicons dashicons-arrow-right-alt ssgsw_setting_color"></span></a>   
                    <a x-show="!isMultiStoreInstalled && !isMultiStoreActive" style="display: none;"  class="upgrade_to_platinam_button" href="<?php echo esc_url(home_url('wp-admin/plugin-install.php?s=multistore-addon-for-flexstock&tab=search&type=term'));?>" target="_blank"><?php esc_html_e('Install & Activate →','stock-sync-with-google-sheet-for-woocommerce'); ?></a>
                </div>
            </div>
			<?php
		}
		/**
		 * Handles stock update logic when a new WooCommerce refund is created.
		 *
		 * This function schedules a single event to update sales data after a new
		 * refund is processed for an order. It first clears any existing scheduled
		 * event to prevent duplicates.
		 *
		 * @param int $refund_id The ID of the newly created refund object.
		 * @param int $order_id  The ID of the parent order associated with the refund.
		 * @return void
		 */
		public function woocommerce_new_order_refund($refund_id, $order_id) {
			
			// 1. Order Object Fetching
			// Guruttopurno Correction: $order variable-ti toiri korte hobe.
			$order = wc_get_order( $order_id );
			
			if ( ! $order ) {
				// Jodi order na pawa jay, tahole beriye jaoa uchit.
				return; 
			}
			
			// Plugin ready check. Note: Ekhane return-e string dewa thik na, 
			// karon action hook kono output expect kore na. Shudhu 'return' korben.
			if ( ! $this->app->is_plugin_ready_setup() ) {
				return;
			} 
			
			// 2. Get Product IDs
			$items = $order->get_items();
			$product_ids = array();
			
	
			foreach ( $items as $item_id => $item ) {
				$product_id = $item->get_product_id();
				
				if ( $item->get_variation_id() ) {
					$product_ids[] = $item->get_variation_id();
				}
				$product_ids[] = $product_id;
			}
			
			// Duplicate product IDs remove kora valo
			$product_ids = array_unique( array_filter( $product_ids ) );
			
			if ( empty( $product_ids ) ) {
				return;
			}

			// 3. Scheduling the Event
			$args = [
				[
					'order_id'    => $order_id,
					'product_ids' => $product_ids,
					'status'      => 'wc-refund' 
				]
			];
			
			// Clear and Schedule
			wp_clear_scheduled_hook( 'ssgsw_sales_update', $args );
			wp_schedule_single_event( time() + 5, 'ssgsw_sales_update', $args );
		}
				
		/**
		 * Handle new WooCommerce orders and schedule a sales update cron event.
		 *
		 * This function runs when a new order is created. It collects all product IDs
		 * from the order, retrieves the order status, and schedules a single cron
		 * event to update sales for these products.
		 *
		 * @param int $order_id The ID of the newly created WooCommerce order.
		 */
		public function woocommerce_order_thankyou_handler( $order_id ) {
			$order = wc_get_order( $order_id );
			if ( ! $order ) return;

			// Collect product IDs
			$product_ids = [];
			foreach ( $order->get_items() as $item_id => $item ) {
				$product_id = $item->get_product_id();
				if ( $product_id ) $product_ids[] = $product_id;
			}

			// Order status
			$status = $order->get_status();

			// Prepare cron arguments
			$args = [
				'order_id'    => $order_id,
				'product_ids' => $product_ids,
				'status'      => $status
			];

			// Clear previous cron and schedule new
			wp_clear_scheduled_hook( 'ssgsw_sales_update', [ $args ] );
			wp_schedule_single_event( time() + 5, 'ssgsw_sales_update', [ $args ] );
		}
	
		/**
		 * Installs the multi-vendor plugin.
		 *
		 * This function is intended to handle the programmatic installation
		 * of the 'multivendor-addon-for-flexstock' plugin.
		 *
		 * @return void
		 */
		public function install_multi_vendor_plugin() {
			// Only run if we are on our custom admin page and the 'action' parameter is set
			if ( ! isset($_GET['page']) || $_GET['page'] !== 'ssgsw-add-ons' ) {
				return;
			}
			if ( ! isset($_GET['action']) || ! isset($_GET['plugin']) ) {
				return;
			}

			$requested_plugin_basename = sanitize_text_field( wp_unslash( $_GET['plugin'] ) );
			$action_name = 'activate_plugin_' . sanitize_title($requested_plugin_basename);

			// 1. Verify Nonce: Security check
			if ( ! isset( $_GET['_wpnonce'] ) ) {
				wp_die( 'Security check failed. Please try again.' );
			}

			$nonce = sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) );

			if ( ! wp_verify_nonce( $nonce, $action_name ) ) {
				wp_die( 'Security check failed. Please try again.' );
			}

			// 2. Capability Check: Ensure user has permission
			if ( ! current_user_can( 'activate_plugins' ) ) {
				wp_die( 'You do not have sufficient permissions to activate plugins.' );
			}

			// 3. Include necessary file for activation function
			if ( ! function_exists( 'activate_plugin' ) ) {
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
			}

			// 4. Perform Activation
			$result = activate_plugin( $requested_plugin_basename );

			// 5. Redirect back with status message
			if ( is_wp_error( $result ) ) {
				$error_message = $result->get_error_message();
				// Use a transient to display a message on the next page load
				set_transient( 'ssgsw_plugin_activation_message', '<div class="notice notice-error is-dismissible"><p>' . esc_html($error_message) . '</p></div>', 30 );
			} else {
				set_transient( 'ssgsw_plugin_activation_message', '<div class="notice notice-success is-dismissible"><p>Plugin activated successfully!</p></div>', 30 );
			}
			if ( 'multivendor-addon-for-flexstock/multivendor-addon-for-flexstock.php' === $requested_plugin_basename) {
				wp_safe_redirect(admin_url('admin.php?page=ssgsw-multivendor#license'));
			} else {
				wp_safe_redirect(admin_url('admin.php?page=ssgsw-multistore'));
			}
		}
		/**
		 * Handles the background sales update and sync to Google Sheet via cron.
		 *
		 * This function is hooked to a WordPress cron event (e.g., 'ssgsw_sales_update').
		 * It iterates through a list of product IDs provided in the arguments and
		 * initiates a batch update/sync operation for each product.
		 *
		 * @param array $args An associative array of arguments passed to the cron event.
		 * Expected keys:
		 * - 'product_ids' (array): An array of integer product IDs to be processed.
		 * Each ID represents a product whose sales data needs
		 * to be synced or updated in the Google Sheet.
		 * If this key is missing or empty, no products will be processed.
		 *
		 * @return void
		 */
		public function ssgsw_sales_to_sheet($args) {
			$product_ids = isset($args['product_ids']) ? $args['product_ids'] : [];
			if(is_array($product_ids) && !empty($product_ids)) {
				foreach ( $product_ids as $product_id ) {
					$cleaned_product_id = absint( $product_id );
					if ( $cleaned_product_id > 0 ) {
						$author_id = get_post_field( 'post_author', $product_id );
						$vendor_request = sssgsw_is_any_marketplace_vendor( $author_id );
						if (!$vendor_request) {
							$enable_checker = ssgsw_sync_validation_mode('woocommerce-to-sheets');
							if ($enable_checker) {
								ssgsw_sales_update_post_request($cleaned_product_id, $author_id, $vendor_request, true);
							}
						} else {
							ssgsw_sales_update_post_request($cleaned_product_id, $author_id, $vendor_request, true);
						}
						
					}
				}
			}
		}
		/**
		 * Handles updating product information to a sheet (likely a Google Sheet or similar)
		 * triggered by a vendor product update event.
		 *
		 * This method is designed to be hooked into a scheduled event (e.g., 'ssgsw_vendor_product_update' action).
		 * It extracts product, author, and vendor request data from the provided arguments
		 * and then calls a helper function to perform the actual update.
		 *
		 * @param array $args An array of arguments passed to the scheduled event. Expected keys:
		 * - 'product_id'   (int): The ID of the product that was updated.
		 * - 'token_id'     (int): The user ID (either the actual vendor author ID or admin ID)
		 * relevant to the update.
		 * - 'vendor_request' (bool): A flag indicating if the update originated from a vendor request.
		 * @return void This method does not return any value.
		 */
		public function ssgsw_vendor_product_update_to_sheet($args) {
			$product_id = isset($args['product_id']) ? $args['product_id'] : 0;
			$function_id = isset($args['function_id']) ? $args['function_id'] : false;
	
			if($product_id) {
				$author_id = isset($args['token_id']) ? $args['token_id'] : 0;
				$vendor_request = isset($args['vendor_request']) ? $args['vendor_request'] : 0;
				ssgsw_sales_update_post_request($product_id, $author_id, $vendor_request, $function_id);
			}
		}
		/**
		 * Add custom product statuses to WooCommerce.
		 *
		 * This function allows you to add custom product statuses to WooCommerce.
		 * Custom statuses can be used to organize or categorize products more effectively.
		 *
		 * Example Usage:
		 * You can hook this function into WooCommerce's filters to register custom statuses.
		 *
		 * @return void
		 */
		public function add_custom_product_status() {
			if ( ! $this->app->is_plugin_ready_setup() ) {
				return __('Plugin is not ready to use.', 'stock-sync-with-google-sheet-for-woocommerce');
			}
			$get_status_active = ssgsw_get_option('show_product_status', false);
			if ( ! $get_status_active ) {
				return false;
			}
			if ( ! ssgsw_is_license_valid() ) {
				return false;
			}
			$prev_count = ssgsw_get_option('product_status_count', 0);
			$dropdown = ssgsw_get_all_product_statuses();
			$status_count = count($dropdown);
			if ($status_count != $prev_count ) { //phpcs:ignore
				$google_colmun = new Column();
				$google_sheet = new Sheet();
				$sheet_info = $google_sheet->get_formula_value();
				if (empty($sheet_info)) {
					$sheet_info = $google_sheet->get_formula_value();
				}
				$sheet_header = isset($sheet_info[0]) ? $sheet_info[0] : [];
				$column_info = $google_colmun->get_columns_no_edit_remove();
				$keys_headers = ssgsw_format_headers_with_sheet_header($sheet_header, $column_info);
				$keys_values = isset($keys_headers[0]) ? $keys_headers[0] : [];
				$new_colmun = array_search('post_status', $keys_values);
				$sync = $google_sheet->update_google_sheet_dropdowns(false, $new_colmun, $new_colmun + 1, $dropdown );
				if ( ! $sync ) {
					$sync = $google_sheet->update_google_sheet_dropdowns(false, $new_colmun - 1, $new_colmun, $dropdown );
				}
				ssgsw_update_option('product_status_count', $status_count );
			}
		}
	
		/**
		 * Checks if the plugin is installed
		 *
		 * @return bool
		 */
		public function is_plugin_installed_ult() {
			// Check if WooCommerce is installed in plugin folder.
			if ( file_exists( WP_PLUGIN_DIR . '/' . $this->ult_version ) ) {
				return true;
			}
			return false;
		}

		/**
		 * Checks if the plugin is activated
		 *
		 * @return bool
		 */
		public function is_plugin_activated_ult() {
			if ( is_plugin_active( $this->ult_version ) ) {
				return true;
			}

			return false;
		}
		/**
		 * Get Ult version number
		 */
		public function get_ult_version() {
			$plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . $this->ult_version );
			if ( $plugin_data ) {
				 $plugin_version = $plugin_data['Version'];
				if ( $plugin_version > '2.0.2' && $plugin_version < '2.0.5' ) {
					return true;
				} else {
					return false;
				}
			}
			return true;
		}
		/**
		 * AppScript setup again
		 */
		public function sssgw_appscript_improved() {
			if ( isset( $_POST ) ) {
				$security = isset($_POST['nonce']) ? sanitize_text_field( wp_unslash($_POST['nonce']) ) : '';
				if ( ! isset( $security ) || ! wp_verify_nonce( $security, 'ssgsw_nonce2' ) ) {
					wp_die( -1, 403 );
				}
				if ( ! current_user_can( 'manage_options' ) ) {
					return false;
				}
				if ( ! is_user_logged_in() ) {
					return false;
				}
				update_option('ssgsw_setup_step', 4 );
				wp_send_json([
					'url' => admin_url('admin.php?page=ssgsw-admin'),
				]);
			}
			die();
		}

		/**
		 * Hide Notice if already updated
		 */
		public function ssgsw_already_updated_keyd() {
			if ( isset( $_POST ) ) {
				$security = isset($_POST['nonce']) ? sanitize_text_field( wp_unslash($_POST['nonce']) ) : '';
				if ( ! isset( $security ) || ! wp_verify_nonce( $security, 'ssgsw_nonce2' ) ) {
					wp_die( -1, 403 );
				}
				if ( ! current_user_can( 'manage_options' ) ) {
					return false;
				}
				if ( ! is_user_logged_in() ) {
					return false;
				}
				update_option('ssgsw_new_user_activated_key12', '1' );
				update_option('ssgsw_already_updated_key12', '1' );
				wp_send_json([
					'success' => true,
				]);
			}

			die();
		}
		/**
		 * Check if import is running to prevent sync.
		 * 
		 * @return bool
		 */
		public function is_importing_check() {
			if ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
				$query = parse_url( $_SERVER['HTTP_REFERER'], PHP_URL_QUERY );
				parse_str( $query, $params );
				if ( isset( $params['page'] ) ) {
					if ( 'product_importer' === $params['page'] ) {
						// error_log(print_r('product_importer',true));
						return true;
					}
					if ( 'pmxi-admin-import' === $params['page'] ) {
						// error_log(print_r('pmxi-admin-import',true));
						return true;
					}
					if ( 'wt_import_export_for_woo_basic_import' === $params['page'] ) {
						// error_log(print_r('wt_import_export_for_woo_basic_import',true));
						return true;
					}
				}
			}

			return apply_filters( 'ssgsw_is_importing', false );
		}

		/**
		 * Saves post callback.
		 *
		 * @param int      $product_id Product ID.
		 * @param \WP_Post $products product object.
		 * @param int      $update save data.
		 * @return string
		 */
		public function after_save_product( $products, $data_store  ) {
		
			if ( $this->is_importing_check() ) {
				if ( ! get_option( 'ssgsw_license_sync', false ) ) {
					update_option( 'ssgsw_license_sync', true );
				}
				if ( ! get_option( 'ssgsw_ultimate_license_active', false ) ) {
					update_option( 'ssgsw_ultimate_license_active', true );
				}
				return;
			}
			
			$get_body = ssgsw_multistore_get_body_data();
			if(isset($get_body->refarance_shop) && $get_body->refarance_shop) {
				return false;
			}
			$product_id = $products->get_id();
			do_action('ssgsw_collection_of_update_ids', [$product_id], false, '');
			if ( ! $this->app->is_plugin_ready_setup() ) {
				return __('Plugin is not ready to use.', 'stock-sync-with-google-sheet-for-woocommerce');
			}

		

			if ( 'product' === get_post_type($product_id) || 'product_variation' === get_post_type($product_id) ) {
				$this->cron_event_set($product_id, true);
				// error_log(print_r('Product Saved Hook Triggered for Product ID: ' . $product_id, true));
			}
		}
		/**
		 * Schedules a single cron event for product updates, handling both
		 * current user and potential multi-vendor scenarios.
		 *
		 * This function attempts to schedule a 'ssgsw_vendor_product_update' cron hook
		 * to run 5 seconds after it's called. It passes various product and vendor-related
		 * data as arguments to the scheduled hook.
		 *
		 * A second cron event is conditionally scheduled based on multi-vendor settings
		 * and plugin activation.
		 *
		 * @param int     $product_id   The ID of the product that was created or updated.
		 * @param bool    $function_id  Optional. A boolean flag indicating a specific function context.
		 * Defaults to false. This value is passed directly to the cron event.
		 * @return bool|void Returns false if certain multi-vendor conditions prevent scheduling
		 * the second event, otherwise void.
		 */
		public function cron_event_set($product_id, $function_id = false ) {

			$current_user_id = get_current_user_id();
			$check_exit = sssgsw_is_any_marketplace_vendor($current_user_id);
			$enable_live= ssgsw_sync_validation_mode('woocommerce-to-sheets');
			if ($enable_live) {
				ssgsw_sales_update_post_request($product_id, $current_user_id, $check_exit, $function_id);
			}
			//sent live-sync data to sheet

			//sent live sync data to sheet.
			$check_multi_vendor_active = get_option('ssgsw_multi_vendor_active', false);
			
			if($check_multi_vendor_active && ssgsw_platinum_activated() ) {
				$author_id = get_post_field( 'post_author', $product_id );
				$product_vendor_check = true;
				$vendor_setup_exits = ssgsw_vendor_setup_exits($author_id);
				if ( ($current_user_id == $author_id ) && $vendor_setup_exits ) {
					$author_id = 1;
					$options_values = get_option(SSGSW_PREFIX . 'spreadsheet_url');
					if(!$options_values) {
						return false;
					}
					$product_vendor_check = false;
				} else {
					if ($current_user_id == $author_id) {
						return false;
					} else {
						if ( ! $vendor_setup_exits ) {
							return false;
						}
					}
					
				}

				$args = [
							[
								'product_id'      => $product_id,
								'token_id'        => $author_id,
								'vendor_request'  => $product_vendor_check,
								'function_id'     => $function_id
							]
						];
				// error_log(print_r( $args, true));
				wp_clear_scheduled_hook( 'ssgsw_vendor_product_update', $args );
				wp_schedule_single_event( time() + 5, 'ssgsw_vendor_product_update', $args);
			}
		}

		/**
		 * Order status updated
		 *
		 * @param int      $order_id order_id ID.
		 * @param string   $old_status old status.
		 * @param string   $new_status new status data.
		 * @param \WP_Post $order order object.
		 *
		 * @return mixed
		 */
		public function woocommerce_order_status_changed( $order_id, $old_status, $new_status, $order ) {

			$items = $order->get_items();
			$product_ids = array();
			foreach ( $items as $item_id => $item ) {
				$product_id = $item->get_product_id();
				$product_ids[] = $product_id;
			}

			$args = [
				[
					'order_id'   => $order_id,
					'product_ids' => $product_ids,
					'status'     => $new_status 
				]
			];
			do_action('ssgsw_sale_update_hook', $args);
			if(is_array($product_ids) && !empty($product_ids)) {
				do_action('ssgsw_collection_of_update_ids', $product_ids, false, '');
			}
			if ( ! $this->app->is_plugin_ready_setup() ) {
				return __('Plugin is not ready to use.', 'stock-sync-with-google-sheet-for-woocommerce');
			} 
			wp_clear_scheduled_hook( 'ssgsw_sales_update', $args );
			wp_schedule_single_event( time() + 5, 'ssgsw_sales_update', $args );
			
		}
		/**
		 * Saves post callback.
		 *
		 * @param \WP_Post $products product object.
		 * @return string
		 */
		public function after_product_quick_edit( $products ) {
		
			if ( $this->is_importing_check() ) {
				if ( ! get_option( 'ssgsw_license_sync', false ) ) {
					update_option( 'ssgsw_license_sync', true );
				}
				if ( ! get_option( 'ssgsw_ultimate_license_active', false ) ) {
					update_option( 'ssgsw_ultimate_license_active', true );
				}
				return;
			}

			$product_id = $products->get_id();
			$get_body = ssgsw_multistore_get_body_data();
			if(isset($get_body->refarance_shop) && $get_body->refarance_shop) {
				return false;
			}
			do_action('ssgsw_collection_of_update_ids', [$product_id], false, '');
			if ( ! $this->app->is_plugin_ready_setup() ) {
				return __('Plugin is not ready to use.', 'stock-sync-with-google-sheet-for-woocommerce');
			}

			$this->cron_event_set($product_id, false);
		}
		/**
		 * Update post callback.
		 *
		 * @param int      $product_id Product ID.
		 * @param \WP_Post $products product object.
		 * @return string
		 */
		public function after_update_product_variation( $product_id, $products ) {
			
			if ( $this->is_importing_check() ) {
				if ( ! get_option( 'ssgsw_license_sync', false ) ) {
					update_option( 'ssgsw_license_sync', true );
				}
				if ( ! get_option( 'ssgsw_ultimate_license_active', false ) ) {
					update_option( 'ssgsw_ultimate_license_active', true );
				}
				return;
			}
		
			$get_body = ssgsw_multistore_get_body_data();
			if(isset($get_body->refarance_shop) && $get_body->refarance_shop) {
				return false;
			}
			do_action('ssgsw_collection_of_update_ids', [$product_id], false, '');
			if ( ! $this->app->is_plugin_ready_setup() ) {
				return __('Plugin is not ready to use.', 'stock-sync-with-google-sheet-for-woocommerce');
			}
			$this->cron_event_set( $product_id,  false);
		}
		/**
		 * Public function add some css
		 */
		public function add_some_css() {
			$settings_url = admin_url('/admin.php?page=ssgsw-admin#settings');
			?>
				<style>

					<?php
					$start_date = strtotime( '2025-11-17' );
					$end_date   = strtotime( '2025-12-04' );
					$current_time = current_time( 'timestamp' );
					if ( $current_time >= $start_date && $current_time <= $end_date ) {
						?>
						._wppool-popup-button {
							padding: 10px 30px !important;
							height: 51px !important;
						}
						<?php
					} else {
					?>
						._wppool-popup-button {
							padding: 0px 40px !important;
							height: 51px !important;
						}
					<?php 
					}
					 ?>

					/* 1. Border-top for 'Add-ons' */
					/* Target the 'Add-ons' menu item's link */
					#adminmenu .wp-submenu li a[href*="ssgsw-add-ons"] {
						border-top: 0.5px solid #5a5f67 !important; /* Add top border */
						padding-top: 9px !important; /* Adjust padding due to border thickness */
					}
					#adminmenu .wp-submenu li a[href*="ssgsw-multivendor"] {
						  
							/* padding-top: 8px !important;
							padding-bottom: 8px !important;
							font-size: 12px; */
					}
					#adminmenu .wp-submenu li a[href*="ssgsw-admin-log"] {
						border-top: 0.5px solid #5a5f67 !important; /* Add top border */
						padding-top: 5px !important; /* Adjust padding due to border thickness */
					}
				

					/* Remove any potential top borders on the Multivendor item itself if not intended */
					#adminmenu .wp-submenu li a[href*="ssgsw-multivendor"] {
						border-top: none !important;
					}

					/* Hide the default submenu head if present in the nested structure */
					#adminmenu .wp-submenu li:has(a[href*="ssgsw-add-ons"]) > .wp-submenu li.wp-submenu-head {
						display: none;
					}

					
					span.flex_new_icons_nav {
						background: #D1FAE5;
						/* padding: 1px; */
						/* padding-left: 10px; */
						padding: 0px 6px 2px 6px;
						border-radius: 10px;
						color: #065f46;
						font-weight: 600;
						font-size:12px;
						/* width: 12px; */
					}
					.ssgsw_appscript_notice3 {
						padding: 1px;
						background: #f6dade;
						text-align: center;
						border-radius: 1px;
						font-size: 14px !important;
						margin: none !important;
						position: relative;
						margin-top:5px;
						margin-bottom: 5px;
					};
					.ssgsw_remove_text_dec{
						text-decoration: none !important;
						font-size: 14px;
					}
					.ssgsw_appscript_notice3 a{
						text-decoration: none !important;
						font-size: 14px;
					};
					.ssgsw_appscript_notice3 p {
						font-size:14px !important;
					};
					.ssgsw_extra_strong {
						font-weight: 700 !important;
					}
					.ssgsw-wrapper .ssgs-check .check2:checked{
						background: #FC4486;
						border: none !important;
					}
					.ssgsw-wrapper .ssgs-check .check2{
						background: #E74F6A;
						border: none !important;
					}
					.ssgsw_list_option {
						position: absolute;
						right: 35px;
						top: 20px;
						z-index: 99;
						background-color: #f0f0f1;
						text-align: left !important;
						padding-left: 14px;
						padding-right: 20px;
					}
					.ssgsw_skip_next_time {
						font-weight: 600;
					}
					span.ssgsw_dismiss_notice {
						opacity: 0.7;
					}
					@media screen and (max-width: 782px) {
						.ssgsw_notice_dismiss {
							padding: 13px;
						}
					}
					.ssgsw_notice_dismiss {
						position: absolute;
						top: 0;
						right: 1px;
						border: none;
						margin: 0;
						padding: 9px;
						background: 0 0;
						color: #787c82;
						cursor: pointer;
					}
					.ssgsw_appscript_notice3 .notice-dismiss {
						display: none;
					}
					.ssgsw_remove_text_dec{
						color:#005ae0;
						cursor:pointer;
					}
					.ssgss_imporved_tooltip {
						cursor: pointer;
						position: relative;
						background: #e4e6eb;
						color: gray;
						display: flex;
						align-items: center;
						justify-content: center;
						width: 30px;
						height: 30px;
						box-sizing: border-box;
						border-radius: 42px;
						cursor: pointer;
						transition: all 0.2s ease;
					}
					.ssgss_imporved_tooltip:hover {
						background:#0C5F9A;
						color:#fff !important;
					}
					.ssgsw_appscript_notice {
						position: absolute;
						top: -14px;
						right: -10px;
						z-index: 9999;
						padding: 17px;
						color: #767676;
						opacity: 0.8;
					}
					.ssgsw_bulet_point_option {
						width: 10px;
						background-color: #ffba00;
						z-index: 9999;
						height: 10px;
						top: 20px;
						left: 38px;
						border-radius: 50%;
						position: absolute;
					}
					.ssgsw_dismiss_common {
						cursor: pointer;
					}
					.ssgsw_tooltip .ssgsw_tooltiptext {
						visibility: hidden;
						width: 220px;
						color: #fff;
						background: #141b38;
						text-align: center;
						border-radius: 6px;
						padding: 5px 0;
						position: absolute;
						z-index: 1;
						right: 40px;
						top: 20px;
					}
					.ssgsw_tooltip:hover .ssgsw_tooltiptext {
						visibility: visible;
					}
				</style>
				<?php
				$safe_settings_url = esc_url( $settings_url );
				?>
				<script>
					jQuery(document).ready(function($) {
						const settingsUrl = "<?php echo wp_json_encode( $safe_settings_url ); ?>";

						// Attach a click event listener to the "Settings" link
						$('#toplevel_page_ssgsw-admin ul li a').on('click', function(event) {
							if (this.href.includes('admin.php?page=ssgsw-admin#settings')) {
								event.preventDefault();
								window.location.replace(this.href); // Navigate to the new URL
								location.reload();
							}
						});

						// Check the current URL and update classes
						if (window.location.href === settingsUrl) {
							const dashboardLink = $('#toplevel_page_ssgsw-admin .wp-first-item.current');
							const settingsLink = $('a[href="admin.php?page=ssgsw-admin#settings"]');

							if (dashboardLink.length) {
								dashboardLink.removeClass('current'); // Remove "current" class from Dashboard link
							}

							if (settingsLink.length) {
								settingsLink.closest('li').addClass('current'); // Add "current" class to Settings parent <li>
							}
						}
					});
				</script>
			<?php
		}

		/**
		 * Filters to be added for the plugin.
		 *
		 * @since 1.0.0
		 */
		public function add_filters() {
			// Add promotional link to plugin action links.
			add_filter('plugin_action_links_' . plugin_basename(SSGSW_FILE), [ $this, 'add_plugin_action_links' ]);

			// Add promotional link to plugin meta links.
			add_filter('plugin_row_meta', [ $this, 'add_plugin_meta_links' ], 10, 2);

			add_filter('ssgsw_get_credentials', [ $this, 'ssgsw_get_credentials_callback' ]);

			add_filter('ssgs_get_column', [ $this, 'ssgsw_get_column_callback' ], 10, 3);
		}

		/**
		 * Add admin menu callback.
		 *
		 * @since 1.0.0
		 */
		public function add_admin_menu() {
			add_menu_page(
			__('FlexStock', 'stock-sync-with-google-sheet-for-woocommerce'),
			__('FlexStock', 'stock-sync-with-google-sheet-for-woocommerce'),
			'manage_options',
			'ssgsw-admin',
			[ $this, $this->app->is_setup_complete() ? 'render_admin_page' : 'render_setup_page' ],
			SSGSW_PUBLIC . 'images/logo.svg',
			56
			);

			if ( ! $this->app->is_setup_complete() || ! $this->app->is_woocommerce_activated() ) {
				add_submenu_page(
				'ssgsw-admin',
				__('FlexStock', 'stock-sync-with-google-sheet-for-woocommerce'),
				__('Setup', 'stock-sync-with-google-sheet-for-woocommerce'),
				'manage_options',
				'ssgsw-admin',
				[ $this, 'render_setup_page' ],
				0
				);
			} else {
				add_submenu_page(
				'ssgsw-admin',
				__('FlexStock', 'stock-sync-with-google-sheet-for-woocommerce'),
				__('Dashboard', 'stock-sync-with-google-sheet-for-woocommerce'),
				'manage_options',
				'ssgsw-admin',
				[ $this, 'render_admin_page' ],
				99
				);
				add_submenu_page(
					'ssgsw-admin',
					__('FlexStock', 'stock-sync-with-google-sheet-for-woocommerce'),
					__('Settings', 'stock-sync-with-google-sheet-for-woocommerce'),
					'manage_options',
					'ssgsw-admin&tab=settings',
					[ $this, 'render_admin_page' ],
					99
					);
				
			}
			add_submenu_page(
				'ssgsw-admin',
				__('FlexStock', 'stock-sync-with-google-sheet-for-woocommerce'),
				__('Add-ons <span class="flex_new_icons_nav">New</span>', 'stock-sync-with-google-sheet-for-woocommerce'),
				'manage_options',
				'ssgsw-add-ons',
				[ $this, 'render_addons_page' ],
				99
				);
				do_action('ssgsw_before_log_menu');

				do_action('ssgsw_multistore_menu');
				add_submenu_page(
					'ssgsw-admin',
					__('FlexStock', 'stock-sync-with-google-sheet-for-woocommerce'),
					__('Log', 'stock-sync-with-google-sheet-for-woocommerce'),
					'manage_options',
					'ssgsw-admin-log',
					[ $this, 'render_log_page' ],
					99
				);
				do_action('ssgsw_end_of_menu');
		

		}

		/**
		 * Render admin page callback.
		 *
		 * @since 1.0.0
		 */
		public function render_admin_page() {
	
			$current_tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : 'general';
			if ( $this->app->is_ultimate_activated() && ! $this->app->is_license_valid() ) {
				$this->load_template('dashboard/activate-license');
			}
			$this->load_template('dashboard/base');
			if ($current_tab === 'settings') {
				wp_safe_redirect(admin_url('admin.php?page=ssgsw-admin#settings'));
				exit();
			}
		}
	
		/**
		 * Render admin page callback.
		 *
		 * @since 1.0.0
		 */
		public function render_addons_page() {
	
			$this->load_template('dashboard/addons');
		}
		/**
		 * Render admin page callback.
		 *
		 * @since 1.0.0
		 */
		public function render_log_page() {
			$this->load_template('dashboard/log');
		}
		/**
		 * Render setup page
		 */
		public function render_setup_page() {
			$this->app->reset_options(false);
			$this->load_template('setup/base');
		}
		/**
		 * Redirect to admin page
		 */
		public function redirect_to_admin_pag_sync($hook) {
			if ( ! $this->app->is_plugin_ready_setup() ) {
				update_option('ssgsw_version_3_12_sync', true);
				return;
			}
			if (headers_sent()) {
				return;
			}
			$version = get_option('ssgsw_version_3_12_sync', false);
			if(!$version) {
				update_option('ssgsw_license_sync', true);
				update_option('ssgsw_version_3_12_sync', true);
				wp_redirect(admin_url('admin.php?page=ssgsw-admin#settings'));
				exit();
			}
		
		}

		/**
		 * Redirect to admin page
		 */
		public function redirect_to_admin_page() {
			
			$redirect_to_admin_page = get_option('ssgsw_redirect_to_admin_page', 0);
			if ( wp_validate_boolean( $redirect_to_admin_page ) ) {
				update_option('ssgsw_redirect_to_admin_page', 0);
				wp_safe_redirect( admin_url( 'admin.php?page=ssgsw-admin' ) );
				exit;
			}
		}

		/**
		 * Add plugin action links callback.
		 *
		 * @param array $links Plugin action links.
		 * @return array
		 */
		public function add_plugin_action_links( $links ) {

			if ( $this->app->is_setup_complete() ) {
				$links[] = '<a href="' . admin_url('admin.php?page=ssgsw-admin') . '">' . __('Settings', 'stock-sync-with-google-sheet-for-woocommerce') . '</a>';
			} else {
				$links[] = '<a href="' . admin_url('admin.php?page=ssgsw-admin') . '">' . __('Setup', 'stock-sync-with-google-sheet-for-woocommerce') . '</a>';
			}

			if ( ! $this->app->is_license_valid() ) {
				$links[] = wp_sprintf( '<a class="ssgsw-promo ssgsw-ultimate-button small" href="javascript:;"> <span class="ssgsw-ultimate-button">%s</span></a>', __('Get Ultimate', 'stock-sync-with-google-sheet-for-woocommerce') );
			}

			return $links;
		}

		/**
		 * Add plugin meta links callback.
		 *
		 * @param array  $links Plugin meta links.
		 * @param string $file Plugin file.
		 * @return array
		 */
		public function add_plugin_meta_links( $links, $file ) { //phpcs:ignore
			if ( ! plugin_basename( SSGSW_FILE ) ) {
				$links[] = wp_sprintf('<a target="_blank" href="https://wppool.dev/docs-category/stock-sync-with-google-sheet-for-woocommerce/"> <span class="dashicons dashicons-media-document" aria-hidden="true" style="font-size:16px;line-height:1.2"></span>%s</a>', __('Docs', 'stock-sync-with-google-sheet-for-woocommerce'));
				$links[] = wp_sprintf('<a target="_blank" href="https://wppool.dev/contact/"> <span class="dashicons dashicons-editor-help" aria-hidden="true" style="font-size:16px;line-height:1.2"></span>%s</a>', __('Support', 'stock-sync-with-google-sheet-for-woocommerce'));
			}
			return $links;
		}

		/**
		 * Admin menu icon css callback.
		 *
		 * @since 1.0.0
		 */
		public function admin_menu_icon_css() {
			printf('<style>%s</style>', '#adminmenu .toplevel_page_ssgsw-admin div.wp-menu-image img { 
				width: 18px;
				height: 18px;
			};');
			?>
			<style>
		
			.addons-container {
				opacity: 0; /* Start invisible */
				transform: rotateY(-90deg); /* Start rotated */
				animation: flipIn 1s ease-out forwards; /* Apply animation */
				transform-origin: center center; /* Ensure it flips from its center */
			}

				@keyframes flipIn {
					0% {
						opacity: 0;
						transform: rotateY(-90deg) scale(0.8);
					}
					50% {
						opacity: 1;
						transform: rotateY(0deg) scale(1.05); /* Slight overshoot for bounce */
					}
					100% {
						opacity: 1;
						transform: rotateY(0deg) scale(1);
					}
				}
			</style>
			
			<?php
		}
		
		/**
		 * Admin enqueue scripts callback.
		 *
		 * @param string $hook Current page hook.
		 * @since 1.0.0
		 */
		public function admin_enqueue_scripts( $hook ) {
	
			wp_enqueue_style('ssgsw-global-css', SSGSW_PUBLIC . 'css/global.css', [], SSGSW_VERSION);
			$pages = [ 'toplevel_page_ssgsw-admin', 'stock-sync-with-google-sheet_page_ssgsw-settings', 'edit.php', 'plugins.php', 'index.php', 'pages2', 'stock-sync-with-google-sheet_page_ssgsw-license', 'flexstock_page_ssgsw-add-ons','flexstock_page_ssgsw-multivendor', 'flexstock_page_ssgsw-multistore' ];
			$pages2 = [ 'toplevel_page_ssgsw-admin', 'stock-sync-with-google-sheet_page_ssgsw-license', 'flexstock_page_ssgsw-add-ons','flexstock_page_ssgsw-multivendor','flexstock_page_ssgsw-multistore' ];

			if ( ! in_array($hook, $pages) ) {
				return;
			}

			if ( in_array($hook, $pages) ) {
				wp_enqueue_script('ssgsw-notice-js', SSGSW_PUBLIC . 'js/notice.js', [ 'jquery', 'wp-i18n' ], SSGSW_VERSION, true);
				wp_set_script_translations( 'ssgsw-notice-js', 'stock-sync-with-google-sheet-for-woocommerce', SSGSW_PATH . 'languages' );
				wp_localize_script('ssgsw-notice-js', 'ssgsw_notice_data', [
					'ajax_url' => admin_url('admin-ajax.php'),
					'nonce'    => wp_create_nonce('ssgsw_nonce2'),
					'current_page' => $hook,
				]);
			}

			// check if we are on product edit page.
			if ( 'edit.php' === $hook && 'product' !== get_current_screen()->post_type ) {
				return;
			}

			wp_enqueue_style('ssgsw-admin-css', SSGSW_PUBLIC . 'css/admin.min.css', [], SSGSW_VERSION);
			wp_enqueue_style('ssgsw-setup-wizard-css', SSGSW_PUBLIC . 'css/setup-wizard.css', [], SSGSW_VERSION);
			if ( in_array( $hook, $pages2 ) ) {
				wp_enqueue_style('ssgsw-custom-css', SSGSW_PUBLIC . 'css/custom.css', [], SSGSW_VERSION);
			}

			wp_enqueue_style('ssgsw-select2-css', SSGSW_PUBLIC . 'css/select2.css', [], SSGSW_VERSION);
			wp_enqueue_script('ssgsw-select2-js', SSGSW_PUBLIC . 'js/select2.js', [ 'jquery' ], SSGSW_VERSION, true);
			wp_enqueue_script('ssgsw-admin-js', SSGSW_PUBLIC . 'js/admin.min.js', [ 'jquery', 'wp-i18n' ], SSGSW_VERSION, true);
			wp_set_script_translations( 'ssgsw-admin-js', 'stock-sync-with-google-sheet-for-woocommerce', SSGSW_PATH . 'languages' );
			// Localize script.
			wp_localize_script('ssgsw-admin-js', 'ssgsw_script', $this->app->localized_script());
		}
		
		/**
 		 * Admin enqueue scripts callback.
 		 *
 		 * @param string $hook Current page hook.
 		 * @since 1.0.0
 		 */
		  public function wp_enqueue_scripts( $hook ) {
			
			$page_id =  get_queried_object_id();
			

			if (ssgsw_has_wcfm_shortcode($page_id) || ssgws_dokan_saller_page() ) {
				wp_enqueue_style('ssgsw-global-css', SSGSW_PUBLIC . 'css/global.css', [], SSGSW_VERSION);
				wp_enqueue_style('ssgsw-admin-css', SSGSW_PUBLIC . 'css/admin.min.css', [], SSGSW_VERSION);
				wp_enqueue_style('ssgsw-custom-css', SSGSW_PUBLIC . 'css/custom.css', [], SSGSW_VERSION);
				wp_enqueue_style('ssgsw-select2-css', SSGSW_PUBLIC . 'css/select2.css', [], SSGSW_VERSION);
				wp_enqueue_script('ssgsw-select2-js', SSGSW_PUBLIC . 'js/select2.js', [ 'jquery' ], SSGSW_VERSION, true);
				wp_enqueue_script('ssgsw-admin-js', SSGSW_PUBLIC . 'js/admin.min.js', [ 'jquery', 'wp-i18n' ], SSGSW_VERSION, true);
				wp_set_script_translations( 'ssgsw-admin-js', 'stock-sync-with-google-sheet-for-woocommerce', SSGSW_PATH . 'languages' );
				// Localize script.
				wp_localize_script('ssgsw-admin-js', 'ssgsw_script', $this->app->localized_script_vendor());

			}
		}

		/**
		 * Updated spreadsheet url callback.
		 *
		 * @param string $spreadsheet_url Spreadsheet url.
		 * @since 1.0.0
		 */
		public function updated_spreadsheet_url_callback( $spreadsheet_url ) {
			/**
			 * Get Sheet ID from Sheet URL Regex
			 */
			$sheet_id = preg_replace('/^.*\/d\/(.*)\/.*$/', '$1', $spreadsheet_url);

			/**
			 * Get Sheet ID from Sheet URL
			 */
			if (empty($sheet_id)) {
				$sheet_id = preg_replace('/^.*\/d\/(.*)$/', '$1', $spreadsheet_url);

				if (empty($sheet_id)) {
					$sheet_id = preg_replace('/^.*\/(.*)$/', '$1', $spreadsheet_url);
				}
			}

			// error_log('Spreadsheet ID: ' . $sheet_id);
			ssgsw_update_option('spreadsheet_id', $sheet_id);
		}

		/**
		 * Get credentials callback.
		 *
		 * @param string $credentials Credentials.
		 * @return array
		 */
		public function ssgsw_get_credentials_callback( $credentials ) {
			$credentials = json_decode($credentials, true);

			return array_map('wp_unslash', $credentials);
		}

		/**
		 * Get column callback.
		 *
		 * @param mixed  $value Column value.
		 * @param string $key Column key.
		 * @param object $row Row object.
		 * @return mixed
		 */
		public function ssgsw_get_column_callback( $value, $key, $row ) {
			
			// error_log(print_r($value,true));
			$column = new Column();
			
			if ( '_stock' === $key ) {

				if ( isset($row->_stock) && is_numeric($row->_stock) && $row->_stock != 0 ) { //phpcs:ignore
					return $row->_stock;
				}

				if ( isset($row->_stock_status) ) {
					if ( empty($row->_stock_status) ) {
						return 'In Stock';
					}
					return $column->get_stock_status($row->_stock_status);
				}
			}

			// ID.
			if ( 'ID' === $key || 'total_sales' === $key ) {

				if ( 'total_sales' === $key && $row->product_type == '' ) {
					return $this->get_variation_sales_count($row->ID);
				} 
				return absint( $value );
			}

			// Price.
			if ( in_array( $key, [ '_sale_price', '_regular_price', '_price' ] ) ) {
				if ( is_scalar($value) && is_numeric($value) && $value > 0 ) {
					return "'" . $value;
				}
				return $value;
			}

			if ( 'post_status' === $key) {
    			$status_to_check = $value;
				$product_type = $column->get_product_type($row->product_type);
			
				if ( isset($product_type) && 'Variation' == $product_type ) {
					$parent_id = ssgsw_get_parent_id_by_child($row->ID);
					
					$parent_status = ssgsw_check_post_status($parent_id);
				
					if ( $parent_status ) {
						$status_to_check = $parent_status;
					}
				}
				if ($status_to_check === 'publish') {
					return 'Published';
				} elseif ($status_to_check === 'pending') {
					return 'Pending Review';
				}
				return ucfirst($status_to_check);
			}
			// Product Category.
			if ( 'product_cat' === $key ) {
				if ( ! $row->product_type ) {

					$cat_info = ssgsw_get_product_categories($row->ID);
					if ( $cat_info ) {
						return $column->get_items_by_comma($cat_info);
					}
					return $column->get_items_by_comma($value);
				} else {
					return $column->get_items_by_comma($value);
				}
			}
			if ( in_array( $key, [ 'product_tag', 'product_brand' ], true ) ) {
				return $column->get_items_by_comma( $value );
			}
			
			// Product type.
			if ( 'product_type' === $key ) {
				return $column->get_product_type($value);
			}

			if ( 'post_excerpt' === $key ) {
				return $row->_variation_description ?? $value;
			}

			if ( '_product_attributes' === $key ) {
				if ( $value ) {
					$value = maybe_unserialize($value);
				
					$attributes = [];

					foreach ( $value as $attribute ) {
				
						if ( $attribute['is_taxonomy'] ) {
							$taxonomy_values = wp_get_post_terms( $row->ID, $attribute['name'], [ 'fields' => 'slugs' ] );
							
							if ( is_array($taxonomy_values) && ! empty($taxonomy_values ) ) {
								$url = [];
								foreach ( $taxonomy_values as $key => $urls ) {
									$url[ $key ] = urldecode($urls);
								}
								$attributes[]    = $attribute['name'] . ': ' . implode(' | ', $url);
							} else {
								$attributes[]    = $attribute['name'] . ': ' . '';
							}
						} elseif ( ! empty($attribute['value']) ) {
							$attributes[] = $attribute['name'] . ': ' . $attribute['value'];
						}
					}

					$attributes = array_filter($attributes);

					return implode(', ', $attributes);
				}
				$attributes = array_filter( (array) $row, function ( $key ) {
					return strpos($key, 'attribute_') !== false;
				}, ARRAY_FILTER_USE_KEY);
				$attributes = array_map(function ( $key, $value ) {
					if ( $value ) {
						return str_replace('attribute_', '', $key) . ': ' . $value;
					} else {
						return '';
					}
				}, array_keys($attributes), $attributes);

				$attributes = array_filter($attributes);

				return implode(', ', $attributes);
			}
			if ( $key === '_sku' ) {
    			return $value; 
			}

			if ( 'product_image_alt' === $key ) {
				if ( isset( $row->product_image_alt ) ) {
					return $row->product_image_alt;
				}
				$thumbnail_id = get_post_thumbnail_id( $row->ID );
				if ( $thumbnail_id ) {
					return get_post_meta( $thumbnail_id, '_wp_attachment_image_alt', true );
				}
				return '';
			}

			if ( 'Upsell_IDS' === $key ) {
				$ids = get_post_meta( $row->ID, '_upsell_ids', true );
				return is_array( $ids ) ? implode( ', ', $ids ) : '';
			}

			if ( 'Crosssell_IDS' === $key ) {
				$ids = get_post_meta( $row->ID, '_crosssell_ids', true );
				return is_array( $ids ) ? implode( ', ', $ids ) : '';
			}

			if ( 'CustomBadge' === $key ) {
				$badge_ids = get_post_meta( $row->ID, '_yith_wcbm_badge_ids', true );
				
				// Fetch the first ID from the array or the single ID
				$badge_id = is_array( $badge_ids ) ? reset( $badge_ids ) : $badge_ids;
				$badge_id = absint( $badge_id );

				if ( $badge_id > 0 ) {
					// Fetch the title of the badge directly from the database for performance
					global $wpdb;
					$badge_title = $wpdb->get_var( $wpdb->prepare( "SELECT post_title FROM {$wpdb->posts} WHERE ID = %d", $badge_id ) );
					return $badge_title ? $badge_title : '';
				}
				return '';
			}

			if ( strpos( $key, 'attribute_' ) === 0 ) {

				$values = get_post_meta( $row->ID, '_product_attributes', true );
			
				// error_log(print_r($row->ID, true));

				$taxonomy_key = str_replace( 'attribute_', '', $key );
				// error_log(print_r($taxonomy_key, true));
				// error_log(print_r($values, true));
				if ( is_array( $values ) && isset( $values[ $taxonomy_key ] ) ) {
					$attribute = $values[ $taxonomy_key ];
					// error_log(print_r($attribute, true));
					if ( isset( $attribute['is_taxonomy'] ) && $attribute['is_taxonomy'] ) {
						// It's a taxonomy: Fetch terms
						$taxonomy_values = wp_get_post_terms( $row->ID, $attribute['name'], [ 'fields' => 'slugs' ] );
						// error_log(print_r($taxonomy_values, true));
						if ( is_array( $taxonomy_values ) && ! empty( $taxonomy_values ) ) {
							$url = [];
							foreach ( $taxonomy_values as $t_val ) {
								$url[] = urldecode( $t_val );
							}

							return implode( ' | ', $url );
						} else {
							// Found in meta but no terms assigned: return empty or original value?
							// User prompt said: "hoile $attribute['value']... er value nibe sudhu ai r ki"
							// Usually for taxonomy attributes, 'value' in meta is NOT the selected terms, it's just the definition.
							// But let's return empty string as requested if terms are missing.
							return '';
						}
					} elseif ( ! empty( $attribute['value'] ) ) {
						// It's a local attribute: Return value directly
						return $attribute['value'];
					}
				}
				
				// Fallback: Return original value if key not found in meta
				return $value;
			}

			// Risk-free check: Only convert if key suggests it is a date AND value is in valid timestamp range (1990-2050)
			$key_lower = strtolower( $key );

			// Define default keywords that likely indicate a date field
			$date_keywords = [ 'date', 'time', '_at', 'start', 'end', 'dob', 'expiry', 'expires' ];
			
			// Allow expanding this list via filter for other custom fields
			$date_keywords = apply_filters( 'ssgsw_date_detection_keywords', $date_keywords );

			$is_date_field = false;
			foreach ( $date_keywords as $keyword ) {
				if ( strpos( $key_lower, $keyword ) !== false ) {
					$is_date_field = true;
					break;
				}
			}

			if ( $is_date_field && ! empty( $value ) && is_numeric( $value ) ) {
				if ( strval( $value ) != strval( intval( $value ) ) ) {
					return $value;
				}
				
				$timestamp = intval( $value );
				// Range check: > 1990-01-01 and < 2050-01-01 (approx)
				if ( $timestamp > 631147200 && $timestamp < 2524608000 ) {
					$date = gmdate( 'Y-m-d', $timestamp );
					if ( $date && $date !== '1970-01-01' ) {
						return $date;
					}
				}
			}
			if ( is_scalar($value) && is_numeric($value) && $value > 0 ) {
				return "'" . $value;
			}
			return (string) $value;
		}

		/**
		 * Get Variation Sales Count (HPOS Compatible)
		 *
		 * This function attempts to get the sales count for a specific product variation ID.
		 * It intelligently uses the correct method based on whether High-Performance Order Storage (HPOS)
		 * is enabled in WooCommerce.
		 *
		 * @param int $variation_id The ID of the product variation.
		 * @return int The total sales count for the variation, or 0 if not found/sold.
		 */
		public function get_variation_sales_count( $variation_id ) {
			global $wpdb;

			$variation_id = absint( $variation_id );

			if ( ! $variation_id ) {
				return 0;
			}

			$hpos_is_enabled = get_option( 'woocommerce_custom_orders_table_enabled' );
			$sales_count = 0;

			$order_statuses_to_count = apply_filters( 'woocommerce_variation_sales_count_order_statuses', array( 'completed', 'processing' ) );

			$placeholders = implode( ', ', array_fill( 0, count( $order_statuses_to_count ), '%s' ) );
			$statuses_for_query = array_map( function( $status ) {
				return 'wc-' . $status; 
			}, $order_statuses_to_count );
			if ( 'yes' === $hpos_is_enabled ) {
				$sales_count = $wpdb->get_var($wpdb->prepare( "
					SELECT SUM(lookup.product_qty)
					FROM {$wpdb->prefix}wc_order_product_lookup AS lookup
					JOIN {$wpdb->prefix}wc_orders AS wc_orders ON lookup.order_id = wc_orders.id
					WHERE lookup.variation_id = %d
					AND wc_orders.status IN ({$placeholders})
				", array_merge( array( $variation_id ), $statuses_for_query ) )); 
			} else {
				$sales_count = $wpdb->get_var($wpdb->prepare( "
					SELECT SUM(order_item_meta.meta_value)
					FROM {$wpdb->prefix}woocommerce_order_items AS order_items
					LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
					LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
					WHERE posts.post_type = 'shop_order'
					AND posts.post_status IN ({$placeholders})
					AND order_items.order_item_type = 'line_item'
					AND order_item_meta.meta_key = '_qty'
					AND order_items.order_item_id IN (
						SELECT order_item_id
						FROM {$wpdb->prefix}woocommerce_order_itemmeta
						WHERE meta_key = '_variation_id'
						AND meta_value = %d
					)
				", array_merge( $statuses_for_query, array( $variation_id ) ) ));
			}

			return absint( $sales_count );
		}
		/**
		 * Save option freeze headers callback.
		 *
		 * @param mixed $value Freeze headers value.
		 * @return string
		 */
		public function ssgsw_save_option_freeze_headers_callback( $value ) {
			if ( ! $this->app->is_plugin_ready_setup() ) {
				return __('Plugin is not ready to use.', 'stock-sync-with-google-sheet-for-woocommerce');
			}
			$sheet   = new Sheet();
			$updated = $sheet->freeze_headers( true === wp_validate_boolean( $value ) );
			$this->send_json($updated);
		}

		/**
		 * Sync sheet callback.
		 *
		 * @return void
		 */
		public function ssgsw_sync_sheet_callback() {

			if ( isset( $GLOBALS['ssgs_sync_all_products'] ) && true === $GLOBALS['ssgs_sync_all_products'] ) {
				return;
			}
			$product = new Product();
			$product->sync_all();
		}

		/**
		 * Initiates Appsero Client.
		 *
		 * @return mixed
		 */
		public function init_appsero_client() {

			if ( ! class_exists( '\StockSyncWithGoogleSheetForWooCommerce\Appsero\Client' ) ) {
				require_once SSGSW_INCLUDES . '/appsero/src/Client.php';
			}

			$client = new \StockSyncWithGoogleSheetForWooCommerce\Appsero\Client( '2153b02c-08d6-45e0-8295-6afc39509fe5', 'FlexStock', SSGSW_FILE );
			// Active insights.
			$client->insights()->init();

			// Init WPPOOL Plugin.
			if ( function_exists( 'wppool_plugin_init' ) ) {
				$default_image = SSGSW_URL . '/includes/wppool/background-image.png';
				$ssgs_plugin = wppool_plugin_init( 'stock_sync_with_google_sheet_for_woocommerce', $default_image );
				$image = SSGSW_URL . '/includes/wppool/FlexStock.png';
				$from = '2025-11-17';
				$to = '2025-12-04';
				if ( $ssgs_plugin && is_object( $ssgs_plugin ) && method_exists( $ssgs_plugin, 'set_campaign' ) ) {

					$ssgs_plugin->set_campaign($image, $to, $from );
				}
			}
		}
		/**
		 * Set update when product stock update
		 *
		 * @param object $product product info.
		 */
		public function ssgs_woocommerce_product_set_stock( $product ) {
			if ( $this->is_importing_check() ) {
				if ( ! get_option( 'ssgsw_license_sync', false ) ) {
					update_option( 'ssgsw_license_sync', true );
				}
				if ( ! get_option( 'ssgsw_ultimate_license_active', false ) ) {
					update_option( 'ssgsw_ultimate_license_active', true );
				}
				return;
			}
			$product_id = $product->get_id();
			$get_body = ssgsw_multistore_get_body_data();
			if (isset($get_body->refarance_shop) && $get_body->refarance_shop) {
				return false;
			}
			do_action('ssgsw_collection_of_update_ids', [$product_id], false, '');
			if ( ! $this->app->is_plugin_ready_setup() ) {
				return __('Plugin is not ready to use.', 'stock-sync-with-google-sheet-for-woocommerce');
			}
			$this->cron_event_set( $product_id,  false);
		}
		/**
		 * Trashed post callback.
		 *
		 * @param int $post_id Post ID.
		 * @return string
		 */
		public function trashed_post_callback( $post_id ) {
			if ( 'product' === get_post_type($post_id) || 'product_variation' === get_post_type($post_id) ) {
				if ( ! $this->app->is_plugin_ready_setup() ) {
					return __('Plugin is not ready to use.', 'stock-sync-with-google-sheet-for-woocommerce');
				}
				$product = new Product();

				// $product->delete_product_from_sheet($post_id);
			}
		}
		/**
		 * Un trashed post callback.
		 *
		 * @param int $post_id Post ID.
		 * @return string
		 */
		public function untashed_post_callback( $post_id ) {
			if ( $this->is_importing_check() ) {
				if ( ! get_option( 'ssgsw_license_sync', false ) ) {
					update_option( 'ssgsw_license_sync', true );
				}
				if ( ! get_option( 'ssgsw_ultimate_license_active', false ) ) {
					update_option( 'ssgsw_ultimate_license_active', true );
				}
				return;
			}
			$get_body = ssgsw_multistore_get_body_data();
			if(isset($get_body->refarance_shop) && $get_body->refarance_shop) {
				return false;
			}
			do_action('ssgsw_collection_of_update_ids', [$post_id], false, '');
			if ( 'product' === get_post_type($post_id) ) {
				if ( ! $this->app->is_plugin_ready_setup() ) {
					return __('Plugin is not ready to use.', 'stock-sync-with-google-sheet-for-woocommerce');
				}
				$this->cron_event_set( $post_id,  false);
			}
		}
		/**
		 * Checks if ssgsw synced.
		 *
		 * @return void
		 */
		public function check_ssgsw_synced() {

		
			$ssgsw_synced = wp_validate_boolean( get_option('ssgsw_synced') );

			if ( $ssgsw_synced ) {
				return;
			}
			update_option('ssgsw_synced', true);
			$product = new Product();
			$product->sync_all();
		}

		/**
		 * Add custom badge dropdown to Google Sheet.
		 * 
		 * @return void
		 */
		public function add_custom_badge_dropdown() {
			if ( ! $this->app->is_plugin_ready_setup() ) {
				return;
			}
			$get_badge_active = ssgsw_get_option('show_custom_badge', false);
			if ( ! $get_badge_active ) {
				return;
			}
			if ( ! ssgsw_is_license_valid() ) {
				return;
			}
			
			$badges = ssgsw_get_yith_badge_titles();
			$badge_count = count($badges);
			$prev_count = ssgsw_get_option('custom_badge_count', 0);
			
			if ( $badge_count != $prev_count ) {
				$google_colmun = new Column();
				$google_sheet = new Sheet();
				$sheet_info = $google_sheet->get_formula_value();
				if (empty($sheet_info)) {
					$sheet_info = $google_sheet->get_formula_value();
				}
				$sheet_header = isset($sheet_info[0]) ? $sheet_info[0] : [];
				$column_info = $google_colmun->get_columns_no_edit_remove();
				$keys_headers = ssgsw_format_headers_with_sheet_header($sheet_header, $column_info);
				$keys_values = isset($keys_headers[0]) ? $keys_headers[0] : [];
				$badge_column_index = array_search('CustomBadge', $keys_values);
				
				if ( false !== $badge_column_index ) {
					// Add an empty option as the first value
					array_unshift($badges, '');
					
					$sync = $google_sheet->update_google_sheet_dropdowns(false, $badge_column_index, $badge_column_index + 1, $badges );
					if ( ! $sync ) {
						// Fallback if index logic is off by 1
						$google_sheet->update_google_sheet_dropdowns(false, $badge_column_index - 1, $badge_column_index, $badges );
					}
					ssgsw_update_option('custom_badge_count', $badge_count );
				}
			}
		}
		
	}

	// Initiate the class.
	Hooks::init();
}