<?php

if ( ! class_exists( 'WP_Importer' ) ) {
	require_once ABSPATH . '/wp-admin/includes/class-wp-importer.php';
}

require_once __DIR__ . '/importers/lib/class-cgdi2-wxrimporter.php';
require_once __DIR__ . '/importers/lib/class-cgdi2-wxrimportinfo.php';
require_once __DIR__ . '/importers/lib/class-cgdi2-wpimporterlogger.php';
require_once __DIR__ . '/importers/lib/class-cgdi2-wpimporterloggercli.php';
require_once __DIR__ . '/importers/lib/class-cgdi2-importer.php';
require_once __DIR__ . '/importers/class-cgdi-importer.php';
require_once __DIR__ . '/importers/class-cgdi-importactions.php';
require_once __DIR__ . '/importers/class-cgdi-helpers.php';
require_once __DIR__ . '/importers/class-cgdi-logger.php';
require_once __DIR__ . '/importers/class-cgdi-widgetimporter.php';
require_once __DIR__ . '/importers/class-cgdi-wpformsimporter.php';
require_once __DIR__ . '/importers/class-cgdi-wxrimporter.php';

define( 'CGDI_PATH', __DIR__ . '/' );
define( 'CGDI_URL', get_template_directory_uri() . '/inc/demo-import/' );


class Shoptimizer_Demo_Import {
	/**
	 * The instance *Singleton* of this class
	 *
	 * @var object
	 */
	private static $instance;

	/**
	 * The instance of the CGDI\Importer class.
	 *
	 * @var object
	 */
	public $importer;

	/**
	 * The resulting page's hook_suffix, or false if the user does not have the capability required.
	 *
	 * @var boolean or string
	 */
	private $plugin_page;

	/**
	 * Holds the verified import files.
	 *
	 * @var array
	 */
	public $import_files;

	/**
	 * The path of the log file.
	 *
	 * @var string
	 */
	public $log_file_path;

	/**
	 * The index of the `import_files` array (which import files was selected).
	 *
	 * @var int
	 */
	private $selected_index;

	/**
	 * The paths of the actual import files to be used in the import.
	 *
	 * @var array
	 */
	private $selected_import_files;

	/**
	 * Holds any error messages, that should be printed out at the end of the import.
	 *
	 * @var string
	 */
	public $frontend_error_messages = array();

	/**
	 * Was the before content import already triggered?
	 *
	 * @var boolean
	 */
	private $before_import_executed = false;

	/**
	 * Make plugin page options available to other methods.
	 *
	 * @var array
	 */
	private $plugin_page_setup = array();

	/**
	 * Imported terms.
	 *
	 * @var array
	 */
	private $imported_terms = array();

	/**
	 * Returns the *Singleton* instance of this class.
	 *
	 * @return Shoptimizer_Demo_Import the *Singleton* instance.
	 */
	public static function get_instance() {
		if ( null === static::$instance ) {
			static::$instance = new static();
		}

		return static::$instance;
	}


	/**
	 * Class construct function, to initiate the plugin.
	 * Protected constructor to prevent creating a new instance of the
	 * *Singleton* via the `new` operator from outside of this class.
	 */
	protected function __construct() {
		// Actions.
		add_action( 'admin_menu', array( $this, 'create_plugin_page' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
		add_action( 'wp_ajax_cgdi_import_demo_data', array( $this, 'import_demo_data_ajax_callback' ) );
		add_action( 'wp_ajax_cgdi_after_import_data', array( $this, 'after_all_import_data_ajax_callback' ) );
		add_action( 'after_setup_theme', array( $this, 'setup_plugin_with_filter_data' ) );
		add_action( 'set_object_terms', array( $this, 'add_imported_terms' ), 10, 6 );
		add_filter( 'wxr_importer.pre_process.post', [ $this, 'skip_failed_attachment_import' ] );
		add_action( 'wxr_importer.process_failed.post', [ $this, 'handle_failed_attachment_import' ], 10, 5 );
		add_action( 'wp_import_insert_post', [ $this, 'save_wp_navigation_import_mapping' ], 10, 4 );
		add_action( 'cgdi/after_import', [ $this, 'fix_imported_wp_navigation' ] );
	}

	/**
	 * Private clone method to prevent cloning of the instance of the *Singleton* instance.
	 *
	 * @return void
	 */
	private function __clone() {}

	/**
	 * Empty unserialize method to prevent unserializing of the *Singleton* instance.
	 *
	 * @return void
	 */
	public function __wakeup() {}

	/**
	 * Creates the plugin page and a submenu item in WP Appearance menu.
	 */
	public function create_plugin_page() {
		$this->plugin_page_setup = CGDI_Helpers::get_plugin_page_setup_data();

		$this->plugin_page = add_submenu_page(
			$this->plugin_page_setup['parent_slug'],
			$this->plugin_page_setup['page_title'],
			$this->plugin_page_setup['menu_title'],
			$this->plugin_page_setup['capability'],
			$this->plugin_page_setup['menu_slug'],
			CGDI_Helpers::apply_filters( 'cgdi/plugin_page_display_callback_function', array( $this, 'display_plugin_page' ) )
		);

		register_importer( $this->plugin_page_setup['menu_slug'], $this->plugin_page_setup['page_title'], $this->plugin_page_setup['menu_title'], CGDI_Helpers::apply_filters( 'cgdi/plugin_page_display_callback_function', array( $this, 'display_plugin_page' ) ) );
	}

	/**
	 * Plugin page display.
	 * Output (HTML) is in another file.
	 */
	public function display_plugin_page() {
		require_once CGDI_PATH . 'views/import.php';
	}


	/**
	 * Enqueue admin scripts (JS and CSS)
	 *
	 * @param string $hook holds info on which admin page you are currently loading.
	 */
	public function admin_enqueue_scripts( $hook ) {
		// Enqueue the scripts only on the plugin page.
		if ( $this->plugin_page === $hook || ( 'themes.php' === $hook && $this->plugin_page_setup['menu_slug'] === 'shoptimizer-demo' ) ) {
			wp_enqueue_script( 'cgdi-admin-js', CGDI_URL . 'assets/js/admin.js' , array( 'jquery' ), SHOPTIMIZER_VERSION );

			// Get theme data.
			$theme = wp_get_theme();

			wp_localize_script( 'cgdi-admin-js', 'cgdi',
				array(
					'ajax_url'         => admin_url( 'admin-ajax.php' ),
					'ajax_nonce'       => wp_create_nonce( 'cgdi-ajax-verification' ),
					'wp_customize_on'  => CGDI_Helpers::apply_filters( 'cgdi/enable_wp_customize_save_hooks', false ),
					'plugin_url'       => CGDI_URL,
					'texts'            => array(
						'import_failed'          => esc_html__( 'Import Failed', 'shoptimizer' ),
						'import_failed_subtitle' => esc_html__( 'Whoops, there was a problem importing your content.', 'shoptimizer' ),
					),
				)
			);

			wp_enqueue_style( 'cgdi-admin-css', CGDI_URL . 'assets/css/admin.css', array() , SHOPTIMIZER_VERSION );
		}
	}

	/**
	 * Main AJAX callback function for:
	 * 1). prepare import files (uploaded or predefined via filters)
	 * 2). execute 'before content import' actions (before import WP action)
	 * 3). import content
	 * 4). execute 'after content import' actions (before widget import WP action, widget import, after import WP action)
	 */
	public function import_demo_data_ajax_callback() {
		// Try to update PHP memory limit (so that it does not run out of it).
		ini_set( 'memory_limit', CGDI_Helpers::apply_filters( 'cgdi/import_memory_limit', '350M' ) );

		// Verify if the AJAX call is valid (checks nonce and current_user_can).
		CGDI_Helpers::verify_ajax_call();

		// Is this a new AJAX call to continue the previous import?
		$use_existing_importer_data = $this->use_existing_importer_data();

		if ( ! $use_existing_importer_data ) {
			// Create a date and time string to use for demo and log file names.
			CGDI_Helpers::set_demo_import_start_time();

			// Define log file path.
			$this->log_file_path = CGDI_Helpers::get_log_path();

			// Get selected file index or set it to 0.
			$this->selected_index = 0;

			/**
			 * 1). Prepare import files.
			 */
			if ( ! empty( $this->import_files[ $this->selected_index ] ) ) { // Use predefined import files.

				// Download the import files (content, widgets files).
				$this->selected_import_files = CGDI_Helpers::download_import_files( $this->import_files[ $this->selected_index ] );

				// Check Errors.
				if ( is_wp_error( $this->selected_import_files ) ) {
					// Write error to log file and send an AJAX response with the error.
					CGDI_Helpers::log_error_and_send_ajax_response(
						$this->selected_import_files->get_error_message(),
						$this->log_file_path,
						esc_html__( 'Downloaded files', 'shoptimizer' )
					);
				}

				// Add this message to log file.
				$log_added = CGDI_Helpers::append_to_file(
					sprintf( /* translators: %s - the name of the selected import. */
						__( 'The import files for: %s were successfully downloaded!', 'shoptimizer' ),
						$this->import_files[ $this->selected_index ]['import_file_name']
					) . CGDI_Helpers::import_file_info( $this->selected_import_files ),
					$this->log_file_path,
					esc_html__( 'Downloaded files' , 'shoptimizer' )
				);
			}
			else {
				// Send JSON Error response to the AJAX call.
				wp_send_json( esc_html__( 'No import files specified!', 'shoptimizer' ) );
			}
		}

		// Save the initial import data as a transient, so other import parts (in new AJAX calls) can use that data.
		CGDI_Helpers::set_cgdi_import_data_transient( $this->get_current_importer_data() );

		if ( ! $this->before_import_executed ) {
			$this->before_import_executed = true;

			/**
			 * 2). Execute the actions hooked to the 'cgdi/before_content_import_execution' action:
			 *
			 * Default actions:
			 * 1 - Before content import WP action (with priority 10).
			 */
			CGDI_Helpers::do_action( 'cgdi/before_content_import_execution', $this->selected_import_files, $this->import_files, $this->selected_index );
		}

		/**
		 * 3). Import content (if the content XML file is set for this import).
		 * Returns any errors greater then the "warning" logger level, that will be displayed on front page.
		 */
		if ( ! empty( $this->selected_import_files['content'] ) ) {
			$this->append_to_frontend_error_messages( $this->importer->import_content( $this->selected_import_files['content'] ) );
		}

		/**
		 * 4). Execute the actions hooked to the 'cgdi/after_content_import_execution' action:
		 *
		 * Default actions:
		 * 1 - Before widgets import setup (with priority 10).
		 * 2 - Import widgets (with priority 20).
		 * 3 - Import WPForms data (with priority 40).
		 */
		CGDI_Helpers::do_action( 'cgdi/after_content_import_execution', $this->selected_import_files, $this->import_files, $this->selected_index );

		// Save the import data as a transient, so other import parts (in new AJAX calls) can use that data.
		CGDI_Helpers::set_cgdi_import_data_transient( $this->get_current_importer_data() );

		// Request the after all import AJAX call.
		if ( false !== CGDI_Helpers::has_action( 'cgdi/after_all_import_execution' ) ) {
			wp_send_json( array( 'status' => 'afterAllImportAJAX' ) );
		}

		// Update terms count.
		$this->update_terms_count();

		// Send a JSON response with final report.
		$this->final_response();
	}

	/**
	 * AJAX callback for the after all import action.
	 */
	public function after_all_import_data_ajax_callback() {
		// Verify if the AJAX call is valid (checks nonce and current_user_can).
		CGDI_Helpers::verify_ajax_call();

		// Get existing import data.
		if ( $this->use_existing_importer_data() ) {
			/**
			 * Execute the after all import actions.
			 *
			 * Default actions:
			 * 1 - after_import action (with priority 10).
			 */
			CGDI_Helpers::do_action( 'cgdi/after_all_import_execution', $this->selected_import_files, $this->import_files, $this->selected_index );
		}

		// Update terms count.
		$this->update_terms_count();

		$import_type = isset( $_POST['import_type'] ) ? sanitize_text_field( wp_unslash( $_POST['import_type'] ) ) : '';
		if ( 'complete' === $import_type ) {
			// Setup CommerceKit features.
			$this->setup_commercekit_features();
		}

		// Send a JSON response with final report.
		$this->final_response();
	}


	/**
	 * Send a JSON response with final report.
	 */
	private function final_response() {
		// Delete importer data transient for current import.
		delete_transient( 'cgdi_importer_data' );
		delete_transient( 'cgdi_importer_data_failed_attachment_imports' );
		delete_transient( 'cgdi_import_menu_mapping' );
		delete_transient( 'cgdi_import_posts_with_nav_block' );

		// Display final messages (success or warning messages).
		$response['title'] = esc_html__( 'Import Complete!', 'shoptimizer' );
		$response['subtitle'] = '<p>' . esc_html__( 'Congrats, your demo was imported successfully. You can now begin editing your site.', 'shoptimizer' ) . '</p>';
		$response['message'] = '<img class="cgdi-imported-content-imported cgdi-imported-content-imported--success" src="' . esc_url( CGDI_URL . 'assets/images/success.svg' ) . '" alt="' . esc_attr__( 'Successful Import', 'shoptimizer' ) . '">';

		if ( ! empty( $this->frontend_error_messages ) ) {
			$response['subtitle'] = '<p>' . esc_html__( 'Your import completed, but some things may not have imported properly.', 'shoptimizer' ) . '</p>';
			$response['subtitle'] .= sprintf(
				wp_kses(
				/* translators: %s - link to the log file. */
					__( '<p><a href="%s" target="_blank">View error log</a> for more information.</p>', 'shoptimizer' ),
					array(
						'p'      => [],
						'a'      => [
							'href'   => [],
							'target' => [],
						],
					)
				),
				CGDI_Helpers::get_log_url( $this->log_file_path )
			);

			$response['message'] = '<div class="notice notice-warning"><p>' . $this->frontend_error_messages_display() . '</p></div>';
		}

		wp_send_json( $response );
	}


	/**
	 * Get content importer data, so we can continue the import with this new AJAX request.
	 *
	 * @return boolean
	 */
	private function use_existing_importer_data() {
		if ( $data = get_transient( 'cgdi_importer_data' ) ) {
			$this->frontend_error_messages = empty( $data['frontend_error_messages'] ) ? array() : $data['frontend_error_messages'];
			$this->log_file_path           = empty( $data['log_file_path'] ) ? '' : $data['log_file_path'];
			$this->selected_index          = empty( $data['selected_index'] ) ? 0 : $data['selected_index'];
			$this->selected_import_files   = empty( $data['selected_import_files'] ) ? array() : $data['selected_import_files'];
			$this->import_files            = empty( $data['import_files'] ) ? array() : $data['import_files'];
			$this->before_import_executed  = empty( $data['before_import_executed'] ) ? false : $data['before_import_executed'];
			$this->imported_terms          = empty( $data['imported_terms'] ) ? [] : $data['imported_terms'];
			$this->importer->set_importer_data( $data );

			return true;
		}
		return false;
	}


	/**
	 * Get the current state of selected data.
	 *
	 * @return array
	 */
	public function get_current_importer_data() {
		return array(
			'frontend_error_messages' => $this->frontend_error_messages,
			'log_file_path'           => $this->log_file_path,
			'selected_index'          => $this->selected_index,
			'selected_import_files'   => $this->selected_import_files,
			'import_files'            => $this->import_files,
			'before_import_executed'  => $this->before_import_executed,
			'imported_terms'          => $this->imported_terms,
		);
	}


	/**
	 * Getter function to retrieve the private log_file_path value.
	 *
	 * @return string The log_file_path value.
	 */
	public function get_log_file_path() {
		return $this->log_file_path;
	}


	/**
	 * Setter function to append additional value to the private frontend_error_messages value.
	 *
	 * @param string $additional_value The additional value that will be appended to the existing frontend_error_messages.
	 */
	public function append_to_frontend_error_messages( $text ) {
		$lines = array();

		if ( ! empty( $text ) ) {
			$text = str_replace( '<br>', PHP_EOL, $text );
			$lines = explode( PHP_EOL, $text );
		}

		foreach ( $lines as $line ) {
			if ( ! empty( $line ) && ! in_array( $line , $this->frontend_error_messages ) ) {
				$this->frontend_error_messages[] = $line;
			}
		}
	}


	/**
	 * Display the frontend error messages.
	 *
	 * @return string Text with HTML markup.
	 */
	public function frontend_error_messages_display() {
		$output = '';

		if ( ! empty( $this->frontend_error_messages ) ) {
			foreach ( $this->frontend_error_messages as $line ) {
				$output .= esc_html( $line );
				$output .= '<br>';
			}
		}

		return $output;
	}


	/**
	 * Get data from filters, after the theme has loaded and instantiate the importer.
	 */
	public function setup_plugin_with_filter_data() {
		if ( ! ( is_admin() || ( defined( 'WP_CLI' ) && WP_CLI ) ) ) {
			return;
		}

		$import_type     = isset( $_POST['import_type'] ) ? sanitize_text_field( wp_unslash( $_POST['import_type'] ) ) : ''; // phpcs:ignore
		$files_directory = CGDI_PATH . 'demo-content/default';
		if ( 'complete' === $import_type ) {
			$files_directory = CGDI_PATH . 'demo-content/complete';
		}
		$import_files = array(
			array(
				'import_file_name'         => esc_html__( 'Shoptimizer Demo Data', 'shoptimizer' ),
				'local_import_file'        => $files_directory . '/content.xml',
				'local_import_widget_file' => $files_directory . '/widgets.wie',
			),
		);

		// Get info of import data files and filter it.
		$this->import_files = CGDI_Helpers::validate_import_file_info( $import_files );

		/**
		 * Register all default actions (before content import, widget import and other actions)
		 * to the 'before_content_import_execution' and the 'cgdi/after_content_import_execution' action hook.
		 */
		$import_actions = new CGDI_ImportActions();
		$import_actions->register_hooks();

		// Importer options array.
		$importer_options = CGDI_Helpers::apply_filters( 'cgdi/importer_options', array(
			'fetch_attachments' => true,
		) );

		// Logger options for the logger used in the importer.
		$logger_options = CGDI_Helpers::apply_filters( 'cgdi/logger_options', array(
			'logger_min_level' => 'warning',
		) );

		// Configure logger instance and set it to the importer.
		$logger            = new CGDI_Logger();
		$logger->min_level = $logger_options['logger_min_level'];

		// Create importer instance with proper parameters.
		$this->importer = new CGDI_Importer( $importer_options, $logger );
	}

	/**
	 * Getter for $plugin_page_setup.
	 *
	 * @return array
	 */
	public function get_plugin_page_setup() {
		return $this->plugin_page_setup;
	}

	/**
	 * Get the URL of the plugin settings page.
	 *
	 * @return string
	 */
	public function get_plugin_settings_url( $query_parameters = [] ) {
		if ( empty( $this->plugin_page_setup ) ) {
			$this->plugin_page_setup = CGDI_Helpers::get_plugin_page_setup_data();
		}

		$parameters = array_merge(
			array( 'page' => $this->plugin_page_setup['menu_slug'] ),
			$query_parameters
		);

		$url = menu_page_url( $this->plugin_page_setup['parent_slug'], false );

		if ( empty( $url ) ) {
			$url = self_admin_url( $this->plugin_page_setup['parent_slug'] );
		}

		return add_query_arg( $parameters, $url );
	}

	/**
	 * Add imported terms.
	 *
	 * Mainly it's needed for saving all imported terms and trigger terms count updates.
	 * WP core term defer counting is not working, since import split to chunks and we are losing `$_deffered` array
	 * items between ajax calls.
	 */
	public function add_imported_terms( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ){

		if ( ! isset( $this->imported_terms[ $taxonomy ] ) ) {
			$this->imported_terms[ $taxonomy ] = array();
		}

		$this->imported_terms[ $taxonomy ] = array_unique( array_merge( $this->imported_terms[ $taxonomy ], $tt_ids ) );
	}

	/**
	 * Returns an empty array if current attachment to be imported is in the failed imports list.
	 *
	 * This will skip the current attachment import.
	 *
	 * @since 3.2.0
	 *
	 * @param array $data Post data to be imported.
	 *
	 * @return array
	 */
	public function skip_failed_attachment_import( $data ) {
		// Check if failed import.
		if (
			! empty( $data ) &&
			! empty( $data['post_type'] ) &&
			$data['post_type'] === 'attachment' &&
			! empty( $data['attachment_url'] )
		) {
			// Get the previously failed imports.
			$failed_media_imports = CGDI_Helpers::get_failed_attachment_imports();

			if ( ! empty( $failed_media_imports ) && in_array( $data['attachment_url'], $failed_media_imports, true ) ) {
				// If the current attachment URL is in the failed imports, then skip it.
				return [];
			}
		}

		return $data;
	}

	/**
	 * Save the failed attachment import.
	 *
	 * @since 3.2.0
	 *
	 * @param WP_Error $post_id Error object.
	 * @param array    $data Raw data imported for the post.
	 * @param array    $meta Raw meta data, already processed.
	 * @param array    $comments Raw comment data, already processed.
	 * @param array    $terms Raw term data, already processed.
	 */
	public function handle_failed_attachment_import( $post_id, $data, $meta, $comments, $terms ) {

		if ( empty( $data ) || empty( $data['post_type'] ) || $data['post_type'] !== 'attachment' ) {
			return;
		}

		CGDI_Helpers::set_failed_attachment_import( $data['attachment_url'] );
	}

	/**
	 * Save the information needed to process the navigation block.
	 *
	 * @since 3.2.0
	 *
	 * @param int   $post_id     The new post ID.
	 * @param int   $original_id The original post ID.
	 * @param array $postdata    The post data used to insert the post.
	 * @param array $data        Post data from the WXR file.
	 */
	public function save_wp_navigation_import_mapping( $post_id, $original_id, $postdata, $data ) {

		if ( empty( $postdata['post_content'] ) ) {
			return;
		}

		if ( $postdata['post_type'] !== 'wp_navigation' ) {

			/*
			 * Save the post ID that has navigation block in transient.
			 */
			if ( strpos( $postdata['post_content'], '<!-- wp:navigation' ) !== false ) {
				// Keep track of POST ID that has navigation block.
				$cgdi_post_nav_block = get_transient( 'cgdi_import_posts_with_nav_block' );

				if ( empty( $cgdi_post_nav_block ) ) {
					$cgdi_post_nav_block = [];
				}

				$cgdi_post_nav_block[] = $post_id;

				set_transient( 'cgdi_import_posts_with_nav_block', $cgdi_post_nav_block, HOUR_IN_SECONDS );
			}
		} else {

			/*
			 * Save the `wp_navigation` post type mapping of the original menu ID and the new menu ID
			 * in transient.
			 */
			$cgdi_menu_mapping = get_transient( 'cgdi_import_menu_mapping' );

			if ( empty( $cgdi_menu_mapping ) ) {
				$cgdi_menu_mapping = [];
			}

			// Let's save the mapping of the original menu ID and the new menu ID.
			$cgdi_menu_mapping[] = [
				'original_menu_id' => $original_id,
				'new_menu_id'      => $post_id,
			];

			set_transient( 'cgdi_import_menu_mapping', $cgdi_menu_mapping, HOUR_IN_SECONDS );
		}
	}

	/**
	 * Fix issue with WP Navigation block.
	 *
	 * We did this by looping through all the imported posts with the WP Navigation block
	 * and replacing the original menu ID with the new menu ID.
	 *
	 * @since 3.2.0
	 */
	public function fix_imported_wp_navigation() {

		// Get the `wp_navigation` import mapping.
		$nav_import_mapping = get_transient( 'cgdi_import_menu_mapping' );

		// Get the post IDs that needs to be updated.
		$posts_nav_block = get_transient( 'cgdi_import_posts_with_nav_block' );

		if ( empty( $nav_import_mapping ) || empty( $posts_nav_block ) ) {
			return;
		}

		$replace_pairs = [];

		foreach ( $nav_import_mapping as $mapping ) {
			$replace_pairs[ '<!-- wp:navigation {"ref":' . $mapping['original_menu_id'] . '} /-->' ] = '<!-- wp:navigation {"ref":' . $mapping['new_menu_id'] . '} /-->';
		}

		// Loop through each the posts that needs to be updated.
		foreach ( $posts_nav_block as $post_id ) {
			$post_nav_block = get_post( $post_id );

			if ( empty( $post_nav_block ) || empty( $post_nav_block->post_content ) ) {
				return;
			}

			wp_update_post(
				[
					'ID'           => $post_id,
					'post_content' => strtr( $post_nav_block->post_content, $replace_pairs ),
				]
			);
		}
	}

	/**
	 * Update imported terms count.
	 */
	private function update_terms_count() {

		foreach ( $this->imported_terms as $tax => $terms ) {
			wp_update_term_count_now( $terms, $tax );
		}
	}

	/**
	 * Get the import buttons HTML for the successful import page.
	 *
	 * @since 3.2.0
	 *
	 * @return string
	 */
	public function get_import_successful_buttons_html() {

		/**
		 * Filter the buttons that are displayed on the successful import page.
		 *
		 * @since 3.2.0
		 *
		 * @param array $buttons {
		 *     Array of buttons.
		 *
		 *     @type string $label  Button label.
		 *     @type string $class  Button class.
		 *     @type string $href   Button URL.
		 *     @type string $target Button target. Can be `_blank`, `_parent`, `_top`. Default is `_self`.
		 * }
		 */
		$buttons = CGDI_Helpers::apply_filters(
			'cgdi/import_successful_buttons',
			[
				[
					'label'  => __( 'Theme Settings' , 'shoptimizer' ),
					'class'  => 'button button-primary button-hero',
					'href'   => admin_url( 'customize.php' ),
					'target' => '_blank',
				],
				[
					'label'  => __( 'Visit Site' , 'shoptimizer' ),
					'class'  => 'button button-primary button-hero',
					'href'   => get_home_url(),
					'target' => '_blank',
				],
			]
		);

		if ( empty( $buttons ) || ! is_array( $buttons ) ) {
			return '';
		}

		ob_start();

		foreach ( $buttons as $button ) {

			if ( empty( $button['href'] ) || empty( $button['label'] ) ) {
				continue;
			}

			$target = '_self';
			if (
				! empty( $button['target'] ) &&
				in_array( strtolower( $button['target'] ), [ '_blank', '_parent', '_top' ], true )
			) {
				$target = $button['target'];
			}

			$class = 'button button-primary button-hero';
			if ( ! empty( $button['class'] ) ) {
				$class = $button['class'];
			}

			printf(
				'<a href="%1$s" class="%2$s" target="%3$s">%4$s</a>',
				esc_url( $button['href'] ),
				esc_attr( $class ),
				esc_attr( $target ),
				esc_html( $button['label'] )
			);
		}

		$buttons_html = ob_get_clean();

		return empty( $buttons_html ) ? '' : $buttons_html;
	}

	/**
	 * Setup CommerceKit features.
	 */
	public function setup_commercekit_features() {
		global $wpdb;

		$defaults = get_option( 'commercekit', array() );
		if ( function_exists( 'commercekit_get_default_settings' ) ) {
			$defaults = commercekit_get_default_settings( '', $defaults );
		} elseif ( class_exists( 'CommerceKit_Helper' ) && method_exists( 'CommerceKit_Helper', 'get_default_settings' ) ) {
			$defaults = CommerceKit_Helper::get_default_settings( '', $defaults );
		}

		// Enable all features.
		$options = array(
			'ajax_search'            => 1,
			'attribute_swatches'     => 1,
			'attribute_swatches_plp' => 1,
			'as_activate_atc'        => 1,
			'as_disable_facade'      => 1,
			'countdown_timer'        => 1,
			'order_bump'             => 1,
			'multiple_obp'           => 1,
			'order_bump_mini'        => 1,
			'multiple_obp_mini'      => 1,
			'sticky_atc_desktop'     => 1,
			'sticky_atc_mobile'      => 1,
			'sticky_atc_tabs'        => 1,
			'fsn_cart_page'          => 1,
			'fsn_mini_cart'          => 1,
			'fsn_shop_page'          => function_exists( 'wc_get_page_id' ) ? wc_get_page_id( 'shop' ) : 0,
			'size_guide'             => 1,
			'store_badge'            => 1,
			'inventory_display'      => 1,
			'inventory_condition'    => 'all',
			'inventory_pids'         => '',
			'waitlist'               => 1,
			'wishlist'               => 1,
			'pdp_attributes_gallery' => 1,
			'pdp_gallery'            => 1,
			'pdp_lightbox'           => 1,
			'pdp_lightbox_cap'       => 1,
			'pdp_thumb_arrows'       => 1,
			'pdp_image_caption'      => 1,
		);

		// Setup default countdown timer options.
		$options['countdown'] = array(
			'product'  => array(
				'active'           => array( 1 ),
				'activeo'          => array( 1 ),
				'title'            => array( 'Hurry! This sale ends in' ),
				'days'             => array( 0 ),
				'hours'            => array( 0 ),
				'minutes'          => array( 30 ),
				'seconds'          => array( 30 ),
				'days_label'       => array( 'Days' ),
				'hours_label'      => array( 'Hours' ),
				'minutes_label'    => array( 'Mins' ),
				'seconds_label'    => array( 'Secs' ),
				'hide_timer'       => array( 0 ),
				'custom_msg'       => array( '' ),
				'type'             => array( 0 ),
				'from_date'        => array( '' ),
				'to_date'          => array( '' ),
				'global_timer'     => array( 0 ),
				'global_from_date' => array( '' ),
				'condition'        => array( 'all' ),
				'pids'             => array( '' ),
			),
			'checkout' => array(
				'active'         => 1,
				'title'          => 'Your order is reserved for:',
				'expiry_message' => 'Times up! But good news! We have extended your checkout time :)',
				'minutes'        => 30,
				'seconds'        => 30,
			),
		);

		// Setup Order Bump
		$product_ids    = array();
		$product_ids[0] = 0;
		$product_ids[1] = 0;
		$product_titles = array(
			0 => 'Denim Jacket',
			1 => 'Hooded Jacket',
		);
		foreach ( $product_titles as $key => $title ) {
			$sql    = $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND post_status = %s AND post_title = %s LIMIT 1", 'product', 'publish', $title );
			$new_id = $wpdb->get_var( $sql );
			if ( $new_id ) {
				$product_ids[ $key ] = $new_id;
			}
		}
		$obp_data = array(
			'product' => array(
				'active'        => array( 1, 1 ),
				'activeo'       => array( 1, 1 ),
				'id'            => $product_ids,
				'title'         => array( 'You may like Denim Jacket', 'You may like Hooded Jacket' ),
				'button_text'   => array( 'Click to add', 'Click to add' ),
				'condition'     => array( 'all', 'all' ),
				'pids'          => array( '', '' ),
				'cart_total_min' => array( 0, 0 ),
				'cart_total_max' => array( 0, 0 ),
			),
		);
		$options['order_bump_product']  = $obp_data;
		$options['order_bump_minicart'] = $obp_data;

		$options['badge'] = array(
			'product' => array(
				'title'     => array( 'Super Sale' ),
				'bg_color'  => array( '#1e18bf' ),
				'color'     => array( '#ffffff' ),
				'condition' => array( 'all' ),
				'pids'      => array( '' ),
				'catalog'   => array( 1 ),
				'product'   => array( 1 ),
			),
			'new' => array(
				'title'    => 'New!',
				'bg_color' => '#e21e1d',
				'color'    => '#ffffff',
				'days'     => 30,
				'catalog'  => 1,
				'product'  => 1,
			),
		);

		$options['wsl_page'] = $this->cgkit_get_wishlist_page_id();

		$options['default_size_guide'] = $this->cgkit_get_size_guide_page_id();

		foreach ( $options as $key => $value ) {
			$defaults[ $key ] = $value;
		}
		update_option( 'commercekit', $defaults, false );

		$this->create_cgkit_gallery_demo_product();
	}

	/**
	 * Create "Wishlist" page if it does not already exist (using $wpdb).
	 */
	public function cgkit_get_wishlist_page_id() {
		global $wpdb;
	
		$page_title   = 'Wishlist';
		$page_content = '[commercegurus_wishlist]';
		$page_like    = '%' . $wpdb->esc_like( $page_content ) . '%';
	
		// Lookup page by exact post_title using $wpdb.
		$page_id = $wpdb->get_var(
			$wpdb->prepare(
				"
				SELECT ID 
				FROM {$wpdb->posts}
				WHERE post_content LIKE %s
				  AND post_type = 'page'
				  AND post_status IN ('publish','draft','pending')
				LIMIT 1
				",
				$page_like
			)
		);
	
		// If no page exists, create it.
		if ( ! $page_id ) {
			$page_id = wp_insert_post(
				array(
					'post_title'   => $page_title,
					'post_name'    => sanitize_title( $page_title ),
					'post_content' => $page_content,
					'post_status'  => 'publish',
					'post_type'    => 'page',
				)
			);
		}
	
		return absint( $page_id );
	}

	/**
	 * Create "Size Guide" page if it does not already exist (using $wpdb).
	 */
	public function cgkit_get_size_guide_page_id() {
		global $wpdb;
	
		$page_title   = 'Demo Size Guide';
		$page_content = '<h3 class="has-medium-font-size">1. Measure your chest</h3><p>With good posture, wrap a measuring tape under your arms around your back and take the measurement at fullest part of your chest. Be sure to keep the measuring tape parallel to the floor.</p><h3 class="has-medium-font-size">2. Measure your waist</h3><p>Our waist can be a difficult area to measure! The natural waistline is halfway between the lowest rib you can feel and the top, outside edge of the hip bone. One trick might help you find this spot are to stand up straight and tilt over. Where your torso creases is where your waistline is.</p><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Size</th><th class="has-text-align-left" data-align="left">Chest</th><th class="has-text-align-left" data-align="left">Waist</th></tr></thead><tbody><tr><td class="has-text-align-left" data-align="left">XS</td><td class="has-text-align-left" data-align="left">33-35</td><td class="has-text-align-left" data-align="left">28-30</td></tr><tr><td class="has-text-align-left" data-align="left">S</td><td class="has-text-align-left" data-align="left">35-37</td><td class="has-text-align-left" data-align="left">30-32</td></tr><tr><td class="has-text-align-left" data-align="left">M</td><td class="has-text-align-left" data-align="left">37-39</td><td class="has-text-align-left" data-align="left">31.5-33.5</td></tr><tr><td class="has-text-align-left" data-align="left">L</td><td class="has-text-align-left" data-align="left">40-42</td><td class="has-text-align-left" data-align="left">34.5-36.5</td></tr><tr><td class="has-text-align-left" data-align="left">XL</td><td class="has-text-align-left" data-align="left">43-45</td><td class="has-text-align-left" data-align="left">37.5-40</td></tr><tr><td class="has-text-align-left" data-align="left">XXL</td><td class="has-text-align-left" data-align="left">46-49</td><td class="has-text-align-left" data-align="left">41-44</td></tr></tbody></table>';
	
		// Lookup page by exact post_title using $wpdb.
		$page_id = $wpdb->get_var(
			$wpdb->prepare(
				"
				SELECT ID 
				FROM {$wpdb->posts}
				WHERE post_title = '%s'
				  AND post_type = 'ckit_size_guide'
				  AND post_status IN ('publish','draft','pending')
				LIMIT 1
				",
				$page_title
			)
		);
	
		// If no page exists, create it.
		if ( ! $page_id ) {
			$page_id = wp_insert_post(
				array(
					'post_title'   => $page_title,
					'post_name'    => sanitize_title( $page_title ),
					'post_content' => $page_content,
					'post_status'  => 'publish',
					'post_type'    => 'ckit_size_guide',
				)
			);
		}
	
		return absint( $page_id );
	}
	
	/**
	* Create CommerceKit Attribute Swatches & Gallery demo product.
	*/
	
	public function create_cgkit_gallery_demo_product() {
		// Check if WooCommerce is active.
		if ( ! class_exists( 'WooCommerce' ) ) {
			return;
		}

		// Create the main variable product.
		$product = new WC_Product_Variable();
		$product->set_name( 'CommerceKit Attribute Gallery Demo' );
		$product->set_description( 'CommerceKit Attribute Gallery and Attribute Swatches Demo' );
		$product->set_status( 'publish' );
		$product->set_catalog_visibility( 'visible' );
		$product->save();
		$product_id = $product->get_id();

		// Create attributes.
		$attributes = array();

		// Bottom Color Attribute.
		$bottom_color_attribute = new WC_Product_Attribute();
		$bottom_color_attribute->set_name( 'Bottom Color' );
		$bottom_color_attribute->set_options( array( 'Red', 'Green', 'Blue' ) );
		$bottom_color_attribute->set_position( 1 );
		$bottom_color_attribute->set_visible( true );
		$bottom_color_attribute->set_variation( true );
		$attributes[] = $bottom_color_attribute;

		// Top Color Attribute.
		$top_color_attribute = new WC_Product_Attribute();
		$top_color_attribute->set_name( 'Top Color' );
		$top_color_attribute->set_options( array( 'Yellow', 'Black', 'Pink' ) );
		$top_color_attribute->set_position( 0 );
		$top_color_attribute->set_visible( true );
		$top_color_attribute->set_variation( true );
		$attributes[] = $top_color_attribute;

		// Set attributes to product.
		$product->set_attributes( $attributes );
		$product->save();

		// Upload gallery images.
		require_once ABSPATH . 'wp-admin/includes/image.php';
		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/media.php';

		$theme_dir = CGDI_PATH . 'assets/images/';
		$upload_dir = wp_upload_dir();

		$images = array( 'RED1.png', 'RED2.png', 'RED3.png', 'RED4.png', 'GREEN1.png', 'GREEN2.png', 'GREEN3.png', 'GREEN4.png', 'BLUE1.png', 'BLUE2.png', 'BLUE3.png', 'BLUE4.png' );
		$image_ids   = array();
		$img_gal_ids = array();;
		foreach ( $images as $image_file ) {
			$image_path = $theme_dir . $image_file;
			if ( file_exists( $image_path ) ) {
				// Copy file to uploads directory.
				$upload_file = wp_upload_bits( $image_file, null, file_get_contents( $image_path ) ); // phpcs:ignore
	
				if ( ! $upload_file['error'] ) {
					$file_path = $upload_file['file'];
					$file_name = basename( $file_path );
					$file_type = wp_check_filetype( $file_name, null );
	
					// Prepare attachment data.
					$attachment = array(
						'post_mime_type' => $file_type['type'],
						'post_title'     => sanitize_file_name( $file_name ),
						'post_content'   => '',
						'post_status'    => 'inherit'
					);
					// Insert attachment.
					$attachment_id = wp_insert_attachment( $attachment, $file_path, $product_id );
			
					if ( ! is_wp_error( $attachment_id )) {
						// Generate metadata and thumbnails.
						$attachment_data = wp_generate_attachment_metadata( $attachment_id, $file_path );
						wp_update_attachment_metadata( $attachment_id, $attachment_data );
					
						$image_ids[]                = $attachment_id;
						$img_gal_ids[ $image_file ] = $attachment_id;
					}
				}
			}
		}

		// Set featured image (first image).
		if ( ! empty( $image_ids ) ) {
			set_post_thumbnail( $product_id, $image_ids[0] );

			// Set gallery images.
			if ( count( $image_ids ) > 1 ) {
				$product->set_gallery_image_ids( array_slice( $image_ids, 1 ) );
				$product->save();
			}
		}

		// Create variations.
		$bottom_colors   = array( 'Red', 'Green', 'Blue' );
		$top_colors      = array( 'Yellow', 'Black', 'Pink' );
		$base_price      = 29.99;
		$price_increment = 0;

		foreach ( $bottom_colors as $bottom_color ) {
			foreach ( $top_colors as $top_color ) {
				$variation = new WC_Product_Variation();
				$variation->set_parent_id( $product_id );

				// Set variation attributes.
				$variation->set_attributes( array(
					'bottom-color' => $bottom_color,
					'top-color'    => $top_color,
				) );

				// Set SKU (uppercase, no spaces).
				$sku = strtoupper( str_replace( ' ', '', $bottom_color . $top_color ) );
				$variation->set_sku( $sku );

				// Set price (increment for variety).
				$variation_price = $base_price + $price_increment;
				$variation->set_regular_price( $variation_price );
				$variation->set_price( $variation_price );

				// Set stock.
				$variation->set_stock_status( 'instock' );
				$variation->set_manage_stock( false );
				$variation->save();

				$price_increment += 10; // Increase price for each variation
			}
		}

		// Set attribute gallery options.
		if ( ! empty( $img_gal_ids ) ) {
			$attribute_swatches = array(
				'bottom-color' => array(
					'cgkit_type' => 'image',
					'Red' => array(
						'img'  => $img_gal_ids['RED1.png'],
						'ctyp' => '1',
						'clr'  => '',
						'clr2' => '',
						'btn'  => 'Red',
					),
					'Green' => array(
						'img'  => $img_gal_ids['GREEN1.png'],
						'ctyp' => '1',
						'clr'  => '',
						'clr2' => '',
						'btn'  => 'Green',
					),
					'Blue' => array(
						'img'  => $img_gal_ids['BLUE1.png'],
						'ctyp' => '1',
						'clr'  => '',
						'clr2' => '',
						'btn'  => 'Blue',
					),
				),
				'top-color' => array(
					'cgkit_type' => 'color',
					'Yellow' => array(
						'img'  => '',
						'ctyp' => '1',
						'clr'  => '#eeee22',
						'clr2' => '',
						'btn'  => 'Yellow',
					),
					'Black'  => array(
						'img'  => '',
						'ctyp' => '1',
						'clr'  => '#000000',
						'clr2' => '',
						'btn'  => 'Black',
					),
					'Pink'   => array(
						'img'  => '',
						'ctyp' => '1',
						'clr'  => '#dd00ed',
						'clr2' => '',
						'btn'  => 'Pink',
					),
				),
				'enable_loop'    => '1',
				'enable_product' => '1',
			);

			$temps          = array();
			$temps['red']   = array();
			$temps['green'] = array();
			$temps['blue']  = array();
			foreach ( $img_gal_ids as $file_name => $image_id ) {
				if ( false !== stripos( $file_name, 'red' ) ) {
					$temps['red'][] = $image_id;
				}
				if ( false !== stripos( $file_name, 'green' ) ) {
					$temps['green'][] = $image_id;
				}
				if ( false !== stripos( $file_name, 'blue' ) ) {
					$temps['blue'][] = $image_id;
				}
			}
			$attribute_gallery = array(
				'red'   => implode( ',', $temps['red'] ),
				'green' => implode( ',', $temps['green'] ),
				'blue'  => implode( ',', $temps['blue'] ),
			);

			update_post_meta( $product_id, 'commercekit_attribute_swatches', $attribute_swatches );
			update_post_meta( $product_id, 'commercekit_image_gallery', $attribute_gallery );
			update_post_meta( $product_id, 'commercekit_video_gallery', array() );
			update_post_meta( $product_id, 'commercekit_wc_video_gallery', array() );
		}

		// Sync the product with variations
		WC_Product_Variable::sync( $product_id );

		return $product_id;
	}
}
Shoptimizer_Demo_Import::get_instance();
