<?php
/**
 * Handles ajax requests for Stock Sync With Google Sheet For WooCommerce admin.
 *
 * @package StockSyncWithGoogleSheetForWooCommerce
 * @since 1.0.0
 */
// Namespace.
namespace StockSyncWithGoogleSheetForWooCommerce;

use Error;

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

if ( ! class_exists( __NAMESPACE__ . '\Ajax') ) {

	/**
	 * Class Ajax.
	 * Handles ajax requests for Stock Sync With Google Sheet For WooCommerce admin.
	 *
	 * @package StockSyncWithGoogleSheetForWooCommerce
	 * @since 1.0.0
	 */
	class Ajax extends Base {

		/**
		 * Contains an instance of this class, if available.
		 *
		 * @var Ajax
		 */
		public static $instance;

		/**
		 * Initialize the class and set its properties.
		 *
		 * @since 1.0.0
		 */
		public static function init() {
			if ( ! self::$instance ) {
				self::$instance = new self();
			}
			self::$instance->add_ajax_actions();
		}


		/**
		 * Add ajax actions.
		 *
		 * @since 1.0.0
		 */
		public function add_ajax_actions() {
			$actions = [
				'update_options'       => [ $this, 'update_options_callback' ],
				'update_vendor_setting' => [ $this, 'update_vendor_active_callback' ],
				'reset_options'        => [ $this, 'reset_options_callback' ],
				'init_sheet'           => [ $this, 'init_sheet_callback' ],
				'sync_sheet'           => [ $this, 'sync_sheet_callback' ],
				'sync_batch_to_sheet'  => [ $this, 'sync_batch_to_sheet_callback' ],
				'reset_sheet'          => [ $this, 'reset_sheet_callback' ],
				'reset_sheet_setting'  => [ $this, 'reset_sheet_setting' ],
				'activate_woocommerce' => [ $this, 'activate_woocommerce_callback' ],
				'hide_upgrade_notice'  => [ $this, 'hide_notice_callback' ],
			];

			foreach ( $actions as $action => $callback ) {
				add_action('wp_ajax_' . SSGSW_PREFIX . $action, $callback);
			}
		}
		/**
		 * Save options callback
		 */
		public function update_vendor_active_callback() {
			// Check nonce.
			$body = $this->get_body();
			

			if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce') ) {
				$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
			}

			// Check permission.
			if ( ! current_user_can('manage_options') ) {
				$this->send_json(false, __('You do not have permission to do this', 'stock-sync-with-google-sheet-for-woocommerce'));
			}

			/**
			 * Get body from request
			 */
			if ( ! isset($body->options) ) {
				$this->send_json(false, __('Options not set', 'stock-sync-with-google-sheet-for-woocommerce'));
			}
			$vendor_name_get = get_option('ssgsw_vendor_menu_name','Sync GSheet');
			$value = $body->options[ 'multi_vendor_active' ] ?? null;
			$vendor_name = $body->options[ 'vendor_menu_name' ] ?? $vendor_name_get;
			$vendor_instance = $body->options[ 'vendor_active_instance' ] ?? null;

			$cron_sync_day = $body->options[ 'cron_sync_day' ] ?? 'daily';
			$sync_time = $body->options[ 'sync_time' ] ?? '0';
			$sync_enable = get_option('ssgsw_multi_vendor_active', false);
			$ssgsw_cron_sync_day = get_option('ssgsw_cron_sync_day', false);
			$ssgsw_sync_time = get_option('ssgsw_sync_time', false);
			set_transient( 'ssgsw_flush_rewrite_rules_on_next_load', true, 0 );
			
			update_option('ssgsw_multi_vendor_active', $value);
			update_option('ssgsw_cron_sync_day', $cron_sync_day);
			update_option('ssgsw_sync_time', $sync_time);
			if($sync_enable != $value)  {
				do_action('ssgsw_schedule_enable');
			}
			if($ssgsw_cron_sync_day != $cron_sync_day)  {
				do_action('ssgsw_schedule_enable');
			}
			if($ssgsw_sync_time != $sync_time)  {
				do_action('ssgsw_schedule_enable');
			}

			update_option('ssgsw_vendor_menu_name', $vendor_name);
			update_option('ssgsw_vendor_active_instance', $vendor_instance);
			$this->send_json(true, __('Options saved', 'stock-sync-with-google-sheet-for-woocommerce'));
		}
		/**
		 * Save options callback
		 */
		public function update_options_callback() {
			// Check nonce and permission logic...
			$body = $this->get_body();
			$is_vendor = isset($body->vendor_request) ? $body->vendor_request : false;
			$token_id = isset($body->token_id) ? $body->token_id : false;
			if (!$is_vendor) {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
				if ( ! current_user_can('manage_options') ) {
					$this->send_json(false, __('You do not have permission to do this', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			} else {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce_frontend') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			}
			
			// Get body from request
			if ( ! isset($body->options) ) {
				$this->send_json(false, __('Options not set', 'stock-sync-with-google-sheet-for-woocommerce'));
			}

			$option_keys = array_keys($this->app->get_default_options());
			
			// Standard Schedule Keys
			$schedule_options_keys = ['selected_sync_mode', 'cron_perdic_sync', 'perdic_sync_time'];
			
			// Formula Schedule Keys
			$schedule_options_keys_formula = ['cron_formula_perdic_sync', 'perdic_formula_sync_day', 'perdic_formula_sync_time', 'selected_sync_mode', 'formula_active'];

			$old_options = [];
			$is_schedule_changed = false;
			$is_formula_schedule_changed = false;

			// Fetch old values for ALL schedule options
			$all_schedule_keys = array_merge($schedule_options_keys, $schedule_options_keys_formula);
			
			foreach ($all_schedule_keys as $key) {
				$default_value = $this->app->get_default_options()[$key] ?? null;
				$old_options[$key] = ssgsw_get_option($key, $default_value);
			}

			// Update all options
			foreach ( $option_keys as $key ) {
				$value = $body->options[ $key ] ?? null;
				
				if ( isset($value) ) {
					ssgsw_update_option($key, $value);
				}
			}

			// Check if schedule settings changed after update
			foreach ($all_schedule_keys as $key) {
				$default_value = $this->app->get_default_options()[$key] ?? null;
				$new_value = ssgsw_get_option($key, $default_value);
				
				if ($new_value !== $old_options[$key]) {
					
					if (in_array($key, $schedule_options_keys)) {
						$is_schedule_changed = true;
					}
					
					if (in_array($key, $schedule_options_keys_formula)) {
						$is_formula_schedule_changed = true;
					}
					
				}
			}

			// Trigger standard schedule action
			if ($is_schedule_changed) {
				do_action('ssgsw_schedule_mode');
			}
			
			// Trigger formula schedule action
			if ($is_formula_schedule_changed) {
				
				do_action('ssgsw_schedule_formula_mode', $is_vendor, $token_id);
			}

			$this->send_json(true, __('Options saved', 'stock-sync-with-google-sheet-for-woocommerce'));
		}

		/**
		 * Reset options callback
		 */
		public function reset_options_callback() {
			// Check nonce.
			$body = $this->get_body();
			$is_vendor = isset($body->vendor_request) ? $body->vendor_request : false;
			if (!$is_vendor) {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
				// Check permission.
				if ( ! current_user_can('manage_options') ) {
					$this->send_json(false, __('You do not have permission to do this', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			} else {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce_frontend') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			}
		

			$this->app->reset_options(true);

			$this->send_json(true, __('Options reset', 'stock-sync-with-google-sheet-for-woocommerce'));
		}

		/**
		 * Check sheet access callback
		 */
		public function init_sheet_callback() {
			// Check nonce.
			$body = $this->get_body();
			$is_vendor = isset($body->vendor_request) ? $body->vendor_request : false;
			if (!$is_vendor) {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
				// Check permission.
				if ( ! current_user_can('manage_options') ) {
					$this->send_json(false, __('You do not have permission to do this', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			} else {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce_frontend') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			}

			try {

				$sheet = new Sheet();

				$sheet_initialized = $sheet->initialize();

				if ( $sheet_initialized ) {
					$this->send_json(true, __('Sheet initialized', 'stock-sync-with-google-sheet-for-woocommerce'));
				} else {
					ssgsw_update_option('setup_step', 3);
					$this->send_json(false, $sheet_initialized);
				}
			} catch ( \Throwable $e ) {
				
				ssgsw_update_option('setup_step', 3);
				$this->send_json(false, $e->getMessage());
			}
		}
		/**
		 * Sync batch processing data
		 */
		public function sync_batch_to_sheet_callback() {

			$body = $this->get_body();
			
			$is_vendor = isset($body->vendor_request) ? $body->vendor_request : false;
			if (!$is_vendor) {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
				// Check permission.
				if ( ! current_user_can('manage_options') ) {
					$this->send_json(false, __('You do not have permission to do this', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			} else {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce_frontend') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			}
			$product = new Product();

			try {
				ssgsw_start_sync();
				$home_url = home_url();
				if ($home_url == $body->site_url) {
					$update = $product->sync_batch_all($body->offset, $body->batchSize, $body->index_number);
				} else {
					if (function_exists('ssgsw_batch_api_request')) {
						$sheets_info = ssgsw_get_sheet_data_from_transient();
						$columns = new Column();
						$columns_info = $columns->get_columns_no_edit_remove();
						$sheet_header = isset($sheets_info[0]) ? $sheets_info[0] : [];
						$key_with_headers = ssgsw_format_headers_with_sheet_header($sheet_header, $columns_info);
						$keys = isset($key_with_headers[0]) ? $key_with_headers[0] : [];
						$domain_url = apply_filters('ssgsw_domain_url', false);
						$get_batch = ssgsw_batch_api_request(
							$body->offset,
							$body->batchSize,
							$body->index_number,
							$body->site_url,
							$body->site_token,
							$keys,
							$domain_url,
							[],
							$sheets_info
						);
					
						$update = $product->sync_batch_all_api($body->offset, $body->batchSize, $body->index_number, $get_batch);
					}
				}
				if ( is_array($update) && $update['success'] ) {
					ssgsw_end_sync();
					ssgsw_update_product_sync_user_id();
					$this->send_json(true, $update );
				} else {
					ssgsw_end_sync();
					$this->send_json(false, $update);
				}
			} catch ( \Exception $e ) {
				ssgsw_end_sync();
				$this->send_json(false, $e->getMessage());
			}

		}
		/**
		 * Update sheet callback
		 */
		public function sync_sheet_callback() {
			// Check nonce.
			$body = $this->get_body();
			$is_vendor = isset($body->vendor_request) ? $body->vendor_request : false;
			if (!$is_vendor) {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce') ) {
					ssgsw_end_sync();
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
				// Check permission.
				if ( ! current_user_can('manage_options') ) {
					ssgsw_end_sync();
					$this->send_json(false, __('You do not have permission to do this', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			} else {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce_frontend') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			}
			if ( ! $this->app->is_plugin_ready() ) {
				ssgsw_end_sync();
				$this->send_json(false, __('Plugin is not ready to use.', 'stock-sync-with-google-sheet-for-woocommerce'));
			}
			try {
				update_option('ssgsw_license_sync', false);

				ssgsw_start_sync();
				$get_all_site = ssgsw_get_all_site_count_product($is_vendor);

				$get_product_count = ssgsw_get_total_syncable_products($get_all_site);
		
				
				if ( ! $get_product_count || $get_product_count == 0 ) { //phpcs:ignore
					ssgsw_end_sync();
					if($is_vendor) {
						$dashboard_page_url = get_vendor_flexstock_url();
						$this->send_json(false, sprintf(
							'%s <a style="text-decoration:none;" href="%s">%s <i class="ssgs-arrow-right"></i></a>',
							__('No products found!', 'stock-sync-with-google-sheet-for-woocommerce'),
							esc_url($dashboard_page_url),
							__('Add New Product', 'stock-sync-with-google-sheet-for-woocommerce')
						));
					} else {
						$this->send_json(false, sprintf(
							'%s <a style="text-decoration:none;" href="%s">%s <i class="ssgs-arrow-right"></i></a>',
							__('No products found!', 'stock-sync-with-google-sheet-for-woocommerce'),
							esc_url(admin_url('edit.php?post_type=product')),
							__('Add New Product', 'stock-sync-with-google-sheet-for-woocommerce')
						));
					}
				
				}

				ssgsw_end_sync();
				$this->send_json(true, $get_all_site);
			} catch ( \Exception $e ) {
				ssgsw_end_sync();
				$this->send_json(false, $e->getMessage());
			}
		}
		/**
		 * Reset sheet callback
		 */
		public function reset_sheet_setting() {
			// Check nonce.
			$body = $this->get_body();
			$is_vendor = isset($body->vendor_request) ? $body->vendor_request : false;
			if (!$is_vendor) {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
				// Check permission.
				if ( ! current_user_can('manage_options') ) {
					$this->send_json(false, __('You do not have permission to do this', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			} else {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce_frontend') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			}

			$sheet = new Sheet();
			$reset = $sheet->reset_all_sheet_information_batch();

			$this->send_json(true, $reset);

			if ( true === $reset ) {
				$this->send_json(true, __('Sheet reset', 'stock-sync-with-google-sheet-for-woocommerce'));
			} else {
				$this->send_json(false, $reset);
			}
		}
		/**
		 * Reset sheet callback
		 */
		public function reset_sheet_callback() {
			// Check nonce.
			$body = $this->get_body();
			$is_vendor = isset($body->vendor_request) ? $body->vendor_request : false;
			if (!$is_vendor) {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
				// Check permission.
				if ( ! current_user_can('manage_options') ) {
					$this->send_json(false, __('You do not have permission to do this', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			} else {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce_frontend') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			}

			$sheet = new Sheet();
			$reset = $sheet->reset_sheet();

			$this->send_json(true, $reset);

			if ( true === $reset ) {
				$this->send_json(true, __('Sheet reset', 'stock-sync-with-google-sheet-for-woocommerce'));
			} else {
				$this->send_json(false, $reset);
			}
		}

		/**
		 * Activate WooCommerce callback
		 */
		public function activate_woocommerce_callback() {
			// Check nonce.
			$body = $this->get_body();
			$is_vendor = isset($body->vendor_request) ? $body->vendor_request : false;
			if (!$is_vendor) {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
				// Check permission.
				if ( ! current_user_can('manage_options') ) {
					$this->send_json(false, __('You do not have permission to do this', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			} else {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce_frontend') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			}

			$this->app->activate_woocommerce();

			$this->send_json(true, __('WooCommerce activated', 'stock-sync-with-google-sheet-for-woocommerce'));
		}

		/**
		 * Hide notice callback
		 *
		 * @since 1.0.0
		 * @return void
		 */
		public function hide_notice_callback() {
			// Check nonce.
			$body = $this->get_body();
			$is_vendor = isset($body->vendor_request) ? $body->vendor_request : false;
			if (!$is_vendor) {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
				// Check permission.
				if ( ! current_user_can('manage_options') ) {
					$this->send_json(false, __('You do not have permission to do this', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			} else {
				if ( ! isset($body->nonce) || ! wp_verify_nonce($body->nonce, 'ssgsw_nonce_frontend') ) {
					$this->send_json(false, __('Invalid nonce', 'stock-sync-with-google-sheet-for-woocommerce'));
				}
			}

			update_option('ssgsw_hide_upgrade_notice', true);

			$this->send_json(true, __('Notice hidden', 'stock-sync-with-google-sheet-for-woocommerce'));
		}
	}

	/**
	 * Initialize Ajax
	 */

	Ajax::init();
}
