<?php

/**
 * Contains the main class for the plugin.
 *
 * @package StockSyncWithGoogleSheetForWooCommerce
 * @since 1.0.0
 */

// Namespace.
namespace StockSyncWithGoogleSheetForWooCommerce;

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

if ( ! class_exists( '\StockSyncWithGoogleSheetForWooCommerce\App' ) ) {
	/**
	 * Contains the main class for the plugin.
	 *
	 * @package StockSyncWithGoogleSheetForWooCommerce
	 * @since 1.0.0
	 */
	class App {
		// Utilities Trait to use in all classes globally.
		use Utilities;

		/**
		 * WooCommerce plugin file name
		 *
		 * @var string
		 */
		public $woo_commerce = 'woocommerce/woocommerce.php';

		/**
		 * Ultimate plugin file name
		 *
		 * @var string
		 */
		public $ultimate = 'stock-sync-with-google-sheet-for-woocommerce-ultimate/stock-sync-with-google-sheet-for-woocommerce-ultimate.php';
		public $multi_vendor = 'multivendor-addon-for-flexstock/multivendor-addon-for-flexstock.php';
		public $multi_store   = 'multi-store-sync-addon-for-flexstock/multi-store-sync-addon-for-flexstock.php';
		/**
		 * Default options
		 *
		 * @return array Default options
		 */
		public function get_default_options() {
			$default_filters = [
				['field' => 'post_status', 'operator' => 'equals', 'value' => 'Published'],
			];
			$options = [
				'credentials'             => [],
				'show_custom_fileds'      => [],
				'credential_file'         => '',
				'spreadsheet_url'         => '',
				'spreadsheet_id'          => '',

				'sheet_tab'               => 'Sheet1',
				'sheet_id'                => '',

				'setup_step'              => 0,

				'add_products_from_sheet' => false,
				'freeze_headers'          => false,

				'show_sku'                => false,
				'show_short_description'  => false,
				'show_product_category'   => false,
				'show_total_sales'        => false,
				'show_attributes'         => false,
				'show_custom_meta_fileds' => false,
				'bulk_edit_option'        => true,
				'formula_active'          => false,
				'token'                   => '',
				'apps_script__notice'     => 0,
				'show_product_images'     => false,
				'show_product_url'        => false,
				'show_long_description'   => false,
				'show_product_tags'       => false,
				'show_product_image_alt'  => false,
				'show_upsell_ids'         => false,
				'show_crosssell_ids'      => false,
				'show_custom_badge'       => false,
				'show_product_brand'      => false,
				'filter_active'	          => false,
				'multi_vendor_active'     => false,
				'product_sync_cron'       => false,
				'cron_sync_day'           => 'daily',
				'sync_time'				  => 0,
				'vendor_menu_name'        => 'Sync GSheet',
 				'show_product_status'     => false,
				'vendor_active_instance'  => false,
				'shop_name_sync'          => false,
				'selected_sync_mode'      => 'live-sync',
				'live_sync_direction'     => 'bidirectional',
				'peroidic_sync_direction' => 'woocommerce-to-sheets',
				'cron_formula_perdic_sync' => '10',
				'cron_perdic_sync'         => '10',
				'perdic_formula_sync_day'  => 'sunday',
				'perdic_sync_day'          => 'sunday',
				'perdic_sync_time'         => '12',
				'perdic_formula_sync_time' => '12',
				'multi_vendor_inactive'   => ssgsw_is_vendor_active(),
				'show_product_status_data' => ssgsw_get_all_product_statuses(),
				'all_product_filter_info'	   => $default_filters,
				'separate_attributes'      => false,
				'allowed_attributes'       => null,
				'skipped_attributes'       => [],
				'save_and_sync'           => false,
			];

			return apply_filters( 'ssgsw_options', $options );
		}

		/**
		 * Get saved options.
		 *
		 * @return object Saved options
		 */
		public function get_options() {
			$ssgsw_options = [];
			foreach ( $this->get_default_options() as $key => $value ) {
				if($key == 'multi_vendor_active') {
					if (!ssgsw_is_vendor_active()) {
						$ssgsw_options[ $key ] = false;
					} else {
						$ssgsw_options[ $key ] = ssgsw_get_option( $key, $value);
					}
				} else {
					$ssgsw_options[ $key ] = ssgsw_get_option( $key, $value);
				}
				
			}

			$ssgsw_options = (object) $ssgsw_options;
			return $ssgsw_options;
		}

		/**
		 * Checks if WooCommerce is installed.
		 *
		 * @return bool
		 */
		public function is_woocommerce_installed() {
			// Check if WooCommerce is installed in plugin folder.
			if ( file_exists( WP_PLUGIN_DIR . '/' . $this->woo_commerce ) ) {
				return true;
			}

			return false;
		}

		/**
		 * Checks if WooCommerce is activated.
		 *
		 * @return bool
		 */
		public function is_woocommerce_activated() {
			if (
				in_array(
					$this->woo_commerce,
					apply_filters(
						'active_plugins',
						get_option( 'active_plugins' ),
						false
					)
				)
			) {
				return true;
			}

			return false;
		}

		/**
		 * Is Ultimate version installed
		 */
		public function is_multi_vendor_installed() {
			if ( file_exists( WP_PLUGIN_DIR . '/' . $this->multi_vendor ) ) {
				return true;
			}

			return false;
		}
		/**
		 * Is Ultimate version installed
		 */
		public function is_multi_store_installed() {
			if ( file_exists( WP_PLUGIN_DIR . '/' . $this->multi_store ) ) {
				return true;
			}

			return false;
		}
		/**
		 * Is Ultimate version installed
		 */
		public function is_ultimate_installed() {
			if ( file_exists( WP_PLUGIN_DIR . '/' . $this->ultimate ) ) {
				return true;
			}

			return false;
		}

		/**
		 * Is Ultimate activated?
		 */
		public function is_ultimate_activated() {
			if (
				$this->is_ultimate_installed() &&
				in_array(
					$this->ultimate,
					apply_filters(
						'active_plugins',
						get_option( 'active_plugins' )
					)
				)
			) {
				return true;
			}

			return false;
		}

		/**
		 * Check if license is activated and valid.
		 *
		 * @return bool
		 */
		public function is_license_valid() {
			global $ssgsw_license;

			if ( ! $ssgsw_license ) {
				return false;
			}

			return $ssgsw_license->is_valid();
		}

		/**
		 * Check if setup is completed.
		 *
		 * @return bool
		 */
		public function is_setup_complete() {
			$options = $this->get_options();
			return $options->setup_step >= 5;
		}

		/**
		 * Check if plugin is ready to use.
		 *
		 * @return bool|\Exception
		 */
		public function is_plugin_ready() {
			$options = $this->get_options();

			if ( ! $options ) {
				return new \Exception(
					__(
						'Setup not complete yet',
						'stock-sync-with-google-sheet-for-woocommerce'
					)
				);
			}

			if ( empty( $options->credentials ) ) {
				return new \Exception(
					__(
						'Credentials not set',
						'stock-sync-with-google-sheet-for-woocommerce'
					)
				);
			}

			if ( empty( $options->spreadsheet_url ) ) {
				return new \Exception(
					__(
						'Spreadsheet URL not set',
						'stock-sync-with-google-sheet-for-woocommerce'
					)
				);
			}

			if ( empty( $options->sheet_tab ) ) {
				return new \Exception(
					__(
						'Sheet tab not set',
						'stock-sync-with-google-sheet-for-woocommerce'
					)
				);
			}

			if ( ! $this->is_woocommerce_activated() ) {
				return new \Exception(
					__(
						'WooCommerce not activated',
						'stock-sync-with-google-sheet-for-woocommerce'
					)
				);
			}

			return true;
		}
		/**
		 * Check if plugin is ready to use.
		 *
		 * @return bool|\Exception
		 */
		public function is_plugin_ready_setup() {
			$options = $this->get_options();
		
			if ( ! $options ) {
				return false;
			}
			

			if ( empty( $options->credentials ) ) {
				return false;
			}

			if ( empty( $options->spreadsheet_url ) ) {
				return false;
			}

			if ( empty( $options->sheet_tab ) ) {
				return false;
			}

			if ( ! $this->is_woocommerce_activated() ) {
				return false;
			}

			return true;
		}
		/**
		 * Retrieves a list of categories with their IDs as keys and names as labels.
		 *
		 * This function fetches all categories, including empty ones (configurable via 'hide_empty'),
		 * and returns an associative array where the category ID is the key and the category name is the value.
		 *
		 * @return array Associative array of category IDs as keys and category names as values.
		 */
		public function get_category_list() {

			$categories = get_categories(array(
				'taxonomy'   => 'product_cat', // Ensures it retrieves WooCommerce product categories
				'hide_empty' => false, // Set to true to hide empty product categories
			));
		
			$category_list = array();
			if ($categories) {
				foreach ($categories as $category) {
					$category_list[$category->term_id] = $category->name;
				}
			}

		
			return $category_list;
		}
		/**
		 * Returns localized script.
		 *
		 * @return array Localized script
		 */
		public function localized_script_vendor() {
			$script_file = plugin_dir_path( SSGSW_FILE ) . '/public/js/AppsScript.js';
			$script      = '';

			if ( file_exists( $script_file ) ) {
				$script = file_get_contents( $script_file ); // phpcs:ignore
			}
			$admin = false;
			$vendor_request = true;
			if(is_admin()) {
				$admin = true;
				$vendor_request = false;
			} 
			$product_types = ssgsw_get_all_product_type_taxonomy_ids();
			
			$product_status = ssgsw_get_all_product_statuses();
		
			usort($product_status, function($a, $b) {
				if ($a === 'Published') return -1;
				if ($b === 'Published') return 1;
				return 0;
			});
			
			$options_data = $this->get_options();
			
			$options_data->token = get_option('ssgsw_token');
			$vendor_active = false;
			if(ssgsw_platinum_activated()) {
				$vendor_active = true;
				
			}
			if(!$this->is_license_valid()) {
				if($options_data->selected_sync_mode == 'live-sync') {
					if ($options_data->live_sync_direction == 'sheets-to-woocommerce') {
						$options_data->live_sync_direction = 'bidirectional';
					}
				} 
				if($options_data->selected_sync_mode == 'perodic-sync') {
					$options_data->peroidic_sync_direction = 'woocommerce-to-sheets';
				}
			}

			// print_r(ssgsw_multi_vendor_license_valid());
			$keys = [
				'ajax_url'                 => admin_url( 'admin-ajax.php' ),
				'site_url'                 => home_url(),
				'token_id'                 => get_current_user_id(),
				'nonce'                    => wp_create_nonce( 'ssgsw_nonce_frontend' ),
				'is_license_valid'         => $this->is_license_valid(),
				'another_license'          => ssgsw_multi_vendor_license_valid(),
				'vendor_active'			   => $vendor_active,
				'is_ultimate_installed'    => $this->is_ultimate_installed(),
				'multi_vendor_install'     => $this->is_multi_vendor_installed(),
				'is_woocommerce_activated' => $this->is_woocommerce_activated(),
				'is_multistore_installed'  => $this->is_multi_store_installed(),
				'is_multistore_activate'   => ssgsw_multi_store_activated(),
				'is_woocommerce_installed' => $this->is_woocommerce_installed(),
				'is_admin'                 => $admin,
				'vendor_request'           => $vendor_request,
				'is_setup_complete'        => $this->is_setup_complete(),
				'is_plugin_ready'          => true === wp_validate_boolean( $this->is_plugin_ready()),
				'options'                  => $options_data,
				'product_type'		       => $product_types,
				'product_status'			=> $product_status,              
				'product_category' 		   => $this->get_category_list(),
				'all_filter'                => ssgsw_all_filters_data(),
				'site_attributes'          => ssgsw_get_all_attributes(),
				'public_url'               => SSGSW_PUBLIC,
				'apps_script'              => $script,
				'currentScreen'            => '',
				'setting_page_url'         => esc_url(ssgsw_vendor_page_url()),
				'vendor_page'				=> true,		
				'limit'                    => apply_filters( 'ssgsw_product_limit', 500 ),
				'ssgsw_license_trigger'    => get_option('ssgsw_license_sync', false),
				'is_debug'                 => defined( 'WP_DEBUG' ) && WP_DEBUG,
			];

			return apply_filters( 'ssgsw_localized_script', $keys );
		}
		/**
		 * Returns localized script.
		 *
		 * @return array Localized script
		 */
		public function localized_script() {
			$script_file = plugin_dir_path( SSGSW_FILE ) . '/public/js/AppsScript.js';
			$script      = '';

			if ( file_exists( $script_file ) ) {
				$script = file_get_contents( $script_file ); // phpcs:ignore
			}
			$vendor_request = true;
			$admin = false;
			if(is_admin()) {
				$admin = true;
				$vendor_request  = false;
			}
			$product_types = ssgsw_get_all_product_type_taxonomy_ids();
			
			$product_status = ssgsw_get_all_product_statuses();
			$vendor_active = false;
			if(ssgsw_platinum_activated()) {
				$vendor_active = true;
			
			}

			usort($product_status, function($a, $b) {
				if ($a === 'Published') return -1;
				if ($b === 'Published') return 1;
				return 0;
			});
			$new_options = $this->get_options();
			if(!$this->is_license_valid()) {
				if($new_options->selected_sync_mode == 'live-sync') {
					if ($new_options->live_sync_direction == 'sheets-to-woocommerce') {
						$new_options->live_sync_direction = 'bidirectional';
					}
				} 
				if($new_options->selected_sync_mode == 'perodic-sync') {
					$new_options->peroidic_sync_direction = 'woocommerce-to-sheets';
				}
			}

			// print_r($this->get_options());
			$keys = [
				'ajax_url'                 => admin_url( 'admin-ajax.php' ),
				'site_url'                 => home_url(),
				'nonce'                    => wp_create_nonce( 'ssgsw_nonce' ),
				'another_license'          => ssgsw_multi_vendor_license_valid(),
				'vendor_active'			   => $vendor_active,
				'token_id'                 => get_current_user_id(),
				'is_license_valid'         => $this->is_license_valid(),
				'is_ultimate_installed'    => $this->is_ultimate_installed(),
				'multi_vendor_install'     => $this->is_multi_vendor_installed(),
				'is_woocommerce_activated' => $this->is_woocommerce_activated(),
				'is_multistore_installed'  => $this->is_multi_store_installed(),
				'is_multistore_activate'   => ssgsw_multi_store_activated(),
				'is_admin'                 => $admin,
				'vendor_request'           => $vendor_request,
				'is_woocommerce_installed' => $this->is_woocommerce_installed(),
				'is_setup_complete'        => $this->is_setup_complete(),
				'is_plugin_ready'          => true === wp_validate_boolean( $this->is_plugin_ready() ),
				'options'                  => $new_options,
				'multi_vendor_inactive'    => ssgsw_is_vendor_active(),
				'product_type'		       => $product_types,
				'product_status'			=> $product_status,
				'product_category' 		   => $this->get_category_list(),
				'all_filter'                => ssgsw_all_filters_data(true),
				'site_attributes'          => ssgsw_get_all_attributes(),
				'public_url'               => SSGSW_PUBLIC,
				'apps_script'              => $script,
				'currentScreen'            => get_current_screen(),
				'vendor_page'              => false,
				'setting_page_url'         => admin_url('admin.php?page=ssgsw-admin'),
				'limit'                    => apply_filters( 'ssgsw_product_limit', 500 ),
				'ssgsw_license_trigger'    => get_option('ssgsw_license_sync', false),
				'is_debug'                 => defined( 'WP_DEBUG' ) && WP_DEBUG,
			];
			// print_r($keys);

			return apply_filters( 'ssgsw_localized_script', $keys );
		}

		/**
		 * Reset options.
		 *
		 * @param bool $force Force reset.
		 * @return bool
		 */
		public function reset_options( $force = false ) {
			$options = $this->get_default_options();

			foreach ( $options as $key => $value ) {
				if ( $force ) {
					delete_option( SSGSW_PREFIX . $key );
				}

				add_option( SSGSW_PREFIX . $key, $value );
			}
			return true;
		}

		/**
		 * Returns all product columns.
		 *
		 * @return array
		 */
		public function get_product_columns() {
			$columns = [
				'ID'            => [
					'label'       => __(
						'ID',
						'stock-sync-with-google-sheet-for-woocommerce'
					),
					'type'        => 'number',
					'description' => __(
						'Product ID',
						'stock-sync-with-google-sheet-for-woocommerce'
					),
					'required'    => true,
				],
				'post_type'     => 'Type',
				'post_title'    => 'Name',
				'stock_status'  => 'Stock Status',
				'post_excerpt'  => 'Short description',
				'regular_price' => 'Regular Price',
				'sale_price'    => 'Sale Price',
				'category'      => 'Category',
				'sales'         => 'Sales',
			];

			return apply_filters( 'ssgsw_product_columns', $columns );
		}

		/**
		 * Activates WooCommerce.
		 *
		 * @return mixed
		 */
		public function activate_woocommerce() {
			if ( ! defined( 'WP_ADMIN') ) {
				define( 'WP_ADMIN', true );
			}
			if ( ! defined( 'WP_NETWORK_ADMIN' ) ) {
				define( 'WP_NETWORK_ADMIN', true );
			}
			if ( ! defined( 'WP_USER_ADMIN' ) ) {
				define( 'WP_USER_ADMIN', true );
			}

			$woocommerce =
				ABSPATH . 'wp-content/plugins/woocommerce/woocommerce.php';

			if ( file_exists( $woocommerce ) ) {
				require_once ABSPATH . 'wp-load.php';
				require_once ABSPATH . 'wp-admin/includes/admin.php';
				require_once ABSPATH . 'wp-admin/includes/upgrade.php';
				require_once ABSPATH . 'wp-admin/includes/plugin.php';

				activate_plugin( $woocommerce );
			} else {
				require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
				require_once ABSPATH .
					'wp-admin/includes/class-wp-upgrader.php';
				require_once ABSPATH .
					'wp-admin/includes/class-wp-ajax-upgrader-skin.php';
				require_once ABSPATH .
					'wp-admin/includes/class-plugin-upgrader.php';

				// Get Plugin Info.
				$api      = plugins_api( 'plugin_information', [
					'slug'   => 'woocommerce',
					'fields' => [
						'short_description' => false,
						'sections'          => false,
						'requires'          => false,
						'rating'            => false,
						'ratings'           => false,
						'downloaded'        => false,
						'last_updated'      => false,
						'added'             => false,
						'tags'              => false,
						'compatibility'     => false,
						'homepage'          => false,
						'donate_link'       => false,
					],
				] );
				$skin     = new \WP_Ajax_Upgrader_Skin();
				$upgrader = new \Plugin_Upgrader( $skin );

				if ( is_wp_error( $api ) ) {
					return;
				}

				$upgrader->install( $api->download_link ); // phpcs:ignore

				activate_plugin( $woocommerce );
			}
		}
	}
}
