<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 *
 * Handles the logic for reading files and importing data into WordPress.
 */
final class Sifency_Importer {

	/**
	 * Imports a single data file.
	 *
	 * @param string $type The type of data to import.
	 * @return array The results of the operation.
	 */
	public function run_import( $type ) {
		$method_name = "import_{$type}";
		if ( method_exists( $this, $method_name ) ) {
			$result = $this->{$method_name}();
			if ( true === $result ) {
				return array( 'success' => array( $type ) );
			}
			$error_code = is_string( $result ) ? $result : $type;
			return array( 'failed' => array( $error_code ) );
		}
		return array( 'failed' => array( "unknown_type_{$type}" ) );
	}

	/**
	 * Imports all available data files in a specific order.
	 *
	 * @return array The results of the operation.
	 */
	public function run_all_imports() {
		$results      = array(
			'success' => array(),
			'failed'  => array(),
		);
		$import_types = Sifency_Demo_Helper::get_import_types();

		foreach ( $import_types as $type ) {
			$result = $this->run_import( $type );
			if ( ! empty( $result['success'] ) ) {
				$results['success'] = array_merge( $results['success'], $result['success'] );
			} else {
				$results['failed'] = array_merge( $results['failed'], $result['failed'] );
			}
		}
		return $results;
	}

	private function import_csf_options() {
		$file_path = Sifency_Demo_Helper::get_filepath( 'admin_options' );
		if ( ! file_exists( $file_path ) ) {
			return 'file_missing';
		}

		$options_data = json_decode( file_get_contents( $file_path ), true );
		if ( is_array( $options_data ) ) {
			foreach ( $options_data as $key => $value ) {
				update_option( $key, $value );
			}
			return true;
		}
		return 'invalid_data';
	}

	private function import_csf_meta() {
		$file_path = Sifency_Demo_Helper::get_filepath( 'meta-options' );
		if ( ! file_exists( $file_path ) ) {
			return 'file_missing';
		}

		$meta_data = json_decode( file_get_contents( $file_path ), true );
		if ( is_array( $meta_data ) ) {
			foreach ( $meta_data as $post_type => $posts ) {
				foreach ( $posts as $slug => $metas ) {
					$post = get_page_by_path( $slug, OBJECT, $post_type );
					if ( $post ) {
						foreach ( $metas as $meta_key => $meta_value ) {
							update_post_meta( $post->ID, $meta_key, $meta_value );
						}
					}
				}
			}
			return true;
		}
		return 'invalid_data';
	}

	private function import_customizer() {
		$file_path = Sifency_Demo_Helper::get_filepath( 'customizer' );
		if ( ! file_exists( $file_path ) ) {
			return 'file_missing';
		}

		$data = maybe_unserialize( file_get_contents( $file_path ) );
		if ( is_array( $data ) && isset( $data['mods'] ) ) {
			update_option( 'theme_mods_' . get_stylesheet(), $data['mods'] );
			return true;
		}
		return 'invalid_data';
	}

	private function import_widgets() {
		$file_path = Sifency_Demo_Helper::get_filepath( 'widgets' );
		if ( ! file_exists( $file_path ) ) {
			return 'file_missing';
		}

		$data = json_decode( file_get_contents( $file_path ), true );
		if ( empty( $data ) || ! is_array( $data ) ) {
			return 'invalid_data';
		}

		global $wp_registered_sidebars;
		$sidebars_widgets = get_option( 'sidebars_widgets', array() );

		foreach ( $data as $sidebar_id => $widgets ) {
			if ( isset( $wp_registered_sidebars[ $sidebar_id ] ) ) {
				$sidebars_widgets[ $sidebar_id ] = array();
				foreach ( $widgets as $widget_id => $widget_data ) {
					$base_id        = preg_replace( '/-[0-9]+$/', '', $widget_id );
					$widget_options = get_option( 'widget_' . $base_id, array() );
					$instance_key   = substr( $widget_id, strlen( $base_id ) + 1 );

					$widget_options[ $instance_key ] = $widget_data;
					update_option( 'widget_' . $base_id, $widget_options );
					$sidebars_widgets[ $sidebar_id ][] = $widget_id;
				}
			}
		}
		update_option( 'sidebars_widgets', $sidebars_widgets );
		return true;
	}

	private function import_elementor_kit() {
		if ( ! did_action( 'elementor/loaded' ) || ! class_exists( '\Elementor\Plugin' ) ) {
			return 'elementor_inactive';
		}

		$file_path = Sifency_Demo_Helper::get_filepath( 'elementor_kit' );
		if ( ! file_exists( $file_path ) ) {
			return 'kit_file_missing';
		}

		$kit_data = json_decode( file_get_contents( $file_path ), true );
		if ( ! is_array( $kit_data ) || empty( $kit_data ) ) {
			return 'invalid_kit_data';
		}

		$active_kit_id = \Elementor\Plugin::$instance->kits_manager->get_active_id();
		if ( ! $active_kit_id ) {
			return 'no_active_kit';
		}

		update_post_meta( $active_kit_id, '_elementor_page_settings', wp_slash( $kit_data ) );
		\Elementor\Plugin::$instance->files_manager->clear_cache();
		return true;
	}

	private function import_wxr_import() {

		// Check if the importer plugin is active.
		if ( ! function_exists( 'is_plugin_active' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		if ( ! is_plugin_active( 'wordpress-importer/wordpress-importer.php' ) ) {
			return 'importer_plugin_inactive';
		}

		// Load WordPress Importer API.
		if ( ! function_exists( 'wp_import' ) ) {
			require_once ABSPATH . 'wp-admin/includes/import.php';
		}

		// Load base importer class.
		if ( ! class_exists( 'WP_Importer' ) ) {
			$class_file = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
			if ( file_exists( $class_file ) ) {
				require_once $class_file;
			} else {
				return 'importer_class_missing';
			}
		}

		// Load the WordPress Importer plugin main class.
		$plugin_dir    = wp_normalize_path( WP_PLUGIN_DIR . '/wordpress-importer' );
		$importer_file = $plugin_dir . '/class-wp-import.php';

		if ( ! file_exists( $importer_file ) ) {
			return 'importer_class_missing';
		}

		require_once $importer_file;

		if ( ! class_exists( 'WP_Import' ) ) {
			return 'importer_class_missing';
		}

		// Get WXR file path.
		$file_path = Sifency_Demo_Helper::get_filepath( 'wxr' );

		if ( empty( $file_path ) || ! file_exists( $file_path ) ) {
			return 'xml_file_missing';
		}

		if ( class_exists( 'Sifency_Addons_WXR_Settings' ) ) {
			Sifency_Addons_WXR_Settings::instance()->restore_settings_from_file( $file_path );
		}

		// Increase max execution time safely if allowed
		if ( function_exists( 'set_time_limit' ) && @ini_get( 'safe_mode' ) == false ) {
			@set_time_limit( 0 );
		}

		// Run the importer.
		$importer                    = new WP_Import();
		$importer->fetch_attachments = true;

		ob_start();
		$importer->import( $file_path );
		ob_end_clean();

		return true;
	}

}
