<?php
/**
 * Import Theme Class
 *
 * @author Jegstudio
 * @since 1.0.0
 * @package gutenverse-themes-builder
 */

namespace Gutenverse_Themes_Builder;

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

use Gutenverse\Framework\Global_Variable;
use Gutenverse_Themes_Builder\Database\Database;
use Gutenverse_Themes_Builder\Export\Misc;
use PO;
use WP_Error;
use WP_Theme_JSON_Resolver;

/**
 * Import Theme Class
 *
 * @package gutenverse-themes-builder
 */
class Import_Backup {

	/**
	 * Zip file id
	 *
	 * @var $file_id
	 */
	public $file_id;

	/**
	 * List of Images
	 *
	 * @var array
	 */
	private $image_list = array();

	/**
	 * List of Menus
	 *
	 * @var array
	 */
	private $menu_list = array();

	/**
	 * Imported Theme
	 *
	 * @var array
	 */
	private $imported_theme;

	/**
	 * Imported menus
	 *
	 * @var array
	 */
	private $imported_menus = array();

	/**
	 * Init constructor.
	 *
	 * @param string $id .
	 */
	public function __construct( $id ) {
		$this->file_id = $id;
		$this->start();
	}

	/**
	 * Import Theme
	 */
	private function start() {
		$path = $this->extract_zip_file();

		if ( ! empty( $path ) ) {
			/** For each root files  */
			$json_files = glob( $path . '/*.json' );

			/** Theme Info */
			$theme_info_path               = $path . '/theme_details.json';
			$theme_info_son_string         = file_get_contents( $theme_info_path );
			$theme_info_data               = json_decode( $theme_info_son_string, true );
			$theme_info_data['theme_data'] = maybe_serialize( $theme_info_data['theme_data'] );
			$theme_info_data['theme_json'] = maybe_serialize( $theme_info_data['theme_json'] );
			$theme_info_data['other']      = maybe_serialize( $theme_info_data['other'] );
			$this->imported_theme          = Misc::sluggify( $theme_info_data['slug'] );
			$theme_info_data['slug']       = $this->imported_theme;

			$info_db                 = Database::instance()->theme_info;
			$check                   = $info_db->get_theme_data( $theme_info_data['theme_id'] );
			$theme_id                = $theme_info_data['theme_id'];

			if ( ! empty( $check ) ) {
				$theme_id = $check[0]['theme_id'];
				$info_db->update_data( $theme_info_data, $theme_id );
			} else {
				$info_db->create_data( $theme_info_data );
			}

			$this->check_directory( gutenverse_themes_builder_theme_folder_path( $theme_id ) );

			foreach ( $json_files as $file_path ) {
				$filename    = basename( $file_path );
				$json_string = file_get_contents( $file_path );
				$data        = json_decode( $json_string, true );
				switch ( $filename ) {
					case 'post_categories.json':
						$this->import_taxonomies( $data, 'category' );
						break;
					case 'post_tags.json':
						$this->import_taxonomies( $data, 'post_tag' );
						break;
					case 'images.json':
						foreach ( $data as $image ) {
							$imagename = $image['name'];
							$image_id  = $this->upload_to_media( $path, $imagename );
							if ( ! is_wp_error( $image_id ) ) {
								$this->image_list[ $imagename ] = array(
									'id'          => $image_id,
									'url'         => wp_get_attachment_url( $image_id ),
									'placeholder' => $image['image_url'],
									'old_id'      => $image['id'],
								);
							}
						}
						break;
					case 'menus.json':
						foreach ( $data as $menu ) {
							$this->menu_list[] = $menu;
						}
						break;
					case 'assets.json':
						$assets_db = Database::instance()->theme_assets;

						foreach ( $data as  $asset ) {
							$check = $assets_db->get_data( $asset['id'] );

							if ( ! empty( $check ) ) {
								$id = $asset['id'];
								unset( $asset['id'] );
								$where = array(
									'id' => $id,
								);
								$assets_db->update_data( $asset, $id );
							} else {
								$assets_db->create_data( $asset );
							}
						}
						break;
					case 'globals.json':
						$globals_db = Database::instance()->theme_globals;
						$theme_db   = Database::instance()->theme_info;

						foreach ( $data as  $global ) {
							$check     = $globals_db->get_data_by_title( $global['title'] );
							$global_id = $global['id'];
							if ( ! empty( $check ) ) {
								unset( $global['id'] );
								$global_data = array(
									'fonts'  => $global['fonts'],
									'colors' => $global['colors'],
									'styles' => $global['styles'],
								);
								$where       = array(
									'id' => $global_id,
								);
								$globals_db->update_data( $global_data, $where );
							} else {
								$global_data = array(
									'title'  => $global['title'],
									'file'   => '',
									'fonts'  => $global['fonts'],
									'colors' => $global['colors'],
									'styles' => $global['styles'],
								);
								$global_id   = $globals_db->create_data( $global_data );
							}
							$theme_db->update_data(
								array(
									'global_id' => $global_id,
								),
								$theme_id
							);
							$active_theme_id  = get_option( 'gtb_active_theme_id' );
							$theme_info       = $theme_db->get_theme_data( $active_theme_id );
							$active_global_id = ! empty( $theme_info ) ? $theme_info[0]['global_id'] : null;
							if ( $active_global_id === $global_id ) {
								$wp_active_theme      = wp_get_theme();
								$wp_active_theme_data = WP_Theme_JSON_Resolver::get_user_data_from_wp_global_styles( $wp_active_theme );
								$post_id              = wp_update_post(
									array(
										'ID'           => $wp_active_theme_data['ID'],
										'post_content' => wp_json_encode( maybe_unserialize( $global['styles'] ) ),
									)
								);
								if ( $post_id && ! is_wp_error( $post_id ) ) {
									$term = term_exists( get_stylesheet(), 'wp_theme' );
									if ( ! $term || is_wp_error( $term ) ) {
										$term = wp_insert_term( get_stylesheet(), 'wp_theme' );
									}
									$term_id = is_array( $term ) ? $term['term_id'] : $term;

									wp_set_object_terms( $post_id, intval( $term_id ), 'wp_theme' );
								}
								$globals = new Global_Variable();
								$globals->set_global_variable(
									array(
										'fonts'  => maybe_unserialize( $global['fonts'] ),
										'colors' => maybe_unserialize( $global['colors'] ),
									)
								);
							}
						}
						break;
					default:
						// code...
						break;
				}
			}

			$this->import_theme_images( $data['other'], $path );

			/** Patterns */
			$patterns_folder = $path . '/patterns';
			if ( is_dir( $patterns_folder ) ) {
				$pattern_files = glob( $patterns_folder . '/*.json' );

				foreach ( $pattern_files as $pattern ) {
					$pattern_data = file_get_contents( $pattern );
					$pattern_data = json_decode( $pattern_data, true );

					$slug     = $pattern_data['post_data']['post_name'];
					$sync     = $pattern_data['post_meta']['sync'];
					$category = $pattern_data['post_meta']['category'];

					$post_exists = get_page_by_path( $slug, OBJECT, 'gutenverse-pattern' );

					$post_data                 = $pattern_data['post_data'];
					$post_data['post_content'] = $this->replace_images( $post_data['post_content'] );
					$post_data['post_content'] = $this->handle_menus( $post_data['post_content'] );

					if ( null === $post_exists ) {
						unset( $post_data['ID'] );

						$post_id = wp_insert_post( $post_data );

						add_post_meta( $post_id, '_pattern_category', $category );
						add_post_meta( $post_id, '_pattern_theme_id', $theme_id );
						add_post_meta( $post_id, '_pattern_sync', $sync );
					} else {
						$post_data['ID'] = $post_exists->ID;

						wp_update_post( $post_data );

						update_post_meta( $post_exists->ID, '_pattern_category', $category );
						update_post_meta( $post_exists->ID, '_pattern_theme_id', $theme_id );
						update_post_meta( $post_exists->ID, '_pattern_sync', $sync );
					}
				}
			}

			/** Templates  */
			$templates_folder = $path . '/templates';
			if ( is_dir( $templates_folder ) ) {
				$category_list = file_get_contents( $templates_folder . '/categories.json' );
				$category_list = json_decode( $category_list, true );

				require_once ABSPATH . 'wp-admin/includes/file.php';
				WP_Filesystem();
				global $wp_filesystem;

				foreach ( $category_list as $category ) {
					$template_files = glob( $templates_folder . '/' . $category . '/*.json' );
					foreach ( $template_files as $template ) {
						$template_data  = file_get_contents( $template );
						$template_data  = json_decode( $template_data, true );
						$allow_template = gutenverse_themes_builder_check_theme_mode( $template_data['category'], $theme_id );
						if ( ! empty( $template_data ) && $theme_id && $allow_template ) {
							$theme_dir       = gutenverse_themes_builder_theme_folder_path( $theme_id );
							$category        = $template_data['category'];
							$category_folder = $theme_dir . '/' . $category;
							$template_type   = in_array( $template_data['template_type'], gutenverse_themes_builder_parts(), true ) ? 'parts' : 'templates';
							$template_name   = Misc::sluggify( $template_data['name'] );
							$file_path       = $category_folder . '/' . $template_type . '/' . $template_name . '.html';

							$template_data['content'] = $this->replace_images( $template_data['content'] );
							$template_data['content'] = $this->handle_menus( $template_data['content'] );

							$this->check_directory( $category_folder );
							$this->check_directory( $category_folder . '/templates' );
							$this->check_directory( $category_folder . '/parts' );

							$wp_filesystem->put_contents(
								$file_path,
								$template_data['content'],
								FS_CHMOD_FILE
							);

							$templates_db = Database::instance()->theme_templates;

							$is_exist = $templates_db->get_name_category( $template_data['name'], $category, $theme_id );

							if ( ! empty( $is_exist ) ) {
								$id = $is_exist[0]['id'];

								$data = array(
									'theme_id'      => $theme_id,
									'name'          => $template_data['name'],
									'template_type' => $template_data['template_type'],
									'category'      => $category,
								);

								$templates_db->update_data( $data, $id );
							} else {
								$data = array(
									'theme_id'      => $theme_id,
									'name'          => $template_data['name'],
									'template_type' => $template_data['template_type'],
									'category'      => $category,
								);

								$templates_db->create_data( $data );

							}
						}
					}
				}
			}

			/** Pages */
			$pages_folder = $path . '/pages';

			if ( is_dir( $pages_folder ) ) {
				$page_files = glob( $pages_folder . '/*.json' );

				foreach ( $page_files as $page ) {
					$page_data = file_get_contents( $page );
					$page_data = json_decode( $page_data, true );
					$post_data = $page_data['post_data'];

					$post_data['post_content'] = $this->replace_images( $post_data['post_content'] );
					$post_data['post_content'] = $this->handle_menus( $post_data['post_content'] );

					$args = array(
						'name'        => $this->imported_theme . '-' . $post_data['post_name'],
						'post_type'   => 'page',
						'numberposts' => 1,
					);

					$page = array(
						'post_type'    => 'page',
						'post_title'   => $post_data['post_title'],
						'post_content' => $post_data['post_content'],
						'post_status'  => 'publish',
						'post_author'  => get_current_user_id(),
						'post_name'    => $this->imported_theme . '-' . $post_data['post_name'],
					);

					$page_data['post_meta'] = $this->import_page_meta_images( $page_data['post_meta'] );
					if ( ! empty( $page_data['post_meta'] ) ) {
						$page['meta_input'] = array(
							'_wp_page_template'     => $page_data['post_meta']['tb_used_template'],
							'_gtb_page_theme_id'    => $theme_id,
							'_gtb_page_preview'     => $page_data['post_meta']['page_preview'],
							'_gtb_page_image'       => $page_data['post_meta']['page_image']['id'],
							'_gtb_page_is_homepage' => $page_data['post_meta']['is_homepage'],
							'_gtb_page_order'       => $page_data['post_meta']['order'],
						);
					}

					$my_posts = get_posts( $args );

					if ( $my_posts ) {
						$page['ID'] = $my_posts[0]->ID;

						wp_update_post( $page );
					} else {
						wp_insert_post( $page );
					}
				}
			}

			/** Posts */
			$post_folder = $path . '/posts';

			if ( is_dir( $post_folder ) ) {
				$post_files = glob( $post_folder . '/*.json' );
				foreach ( $post_files as $post ) {
					$post_data = file_get_contents( $post );
					$post_data = json_decode( $post_data, true );

					$post_data['content'] = $this->replace_images( $post_data['content'] );
					$post_data['content'] = $this->handle_menus( $post_data['content'] );

					$args = array(
						'name'        => $this->imported_theme . '-' . $post_data['name'],
						'post_type'   => 'post',
						'numberposts' => 1,
					);

					$the_post = array(
						'post_type'    => 'post',
						'post_title'   => $post_data['title'],
						'post_content' => $post_data['content'],
						'post_status'  => 'publish',
						'post_author'  => get_current_user_id(),
						'post_name'    => $this->imported_theme . '-' . $post_data['name'],
					);

					$my_posts = get_posts( $args );
					$post_id  = null;
					if ( $my_posts ) {
						$the_post['ID'] = $my_posts[0]->ID;
						wp_update_post( $the_post );
						$post_id = $my_posts[0]->ID;
					} else {
						$post_id = wp_insert_post( $the_post );
					}
					// Featured Image.
					if ( ! empty( $post_data['featured_image'] ) ) {
						$featured_image_name = $post_data['featured_image']['name'];
						$featured_image_url  = $post_data['featured_image']['url'];
						$featured_image_data = $this->image_list[ $featured_image_name ] ?? null;

						if ( ! $featured_image_data ) {
							foreach ( $this->image_list as $key => $value ) {
								if ( $value['placeholder'] === $featured_image_url ) {
									$featured_image_data = $value;
									break;
								}
							}
						}
						if ( $featured_image_data ) {
							$featured_image_id = $featured_image_data['id'];
							set_post_thumbnail( $post_id, $featured_image_id );
						}
					}

					// ✅ Handle categories
					if ( ! empty( $post_data['categories'] ) ) {
						$cat_ids = array();

						foreach ( $post_data['categories'] as $cat ) {
							$term = get_term_by( 'slug', $cat['slug'], 'category' );

							if ( ! $term ) {
								$new_term = wp_insert_term(
									$cat['name'],
									'category',
									array( 'slug' => $cat['slug'] )
								);

								if ( ! is_wp_error( $new_term ) ) {
									$cat_ids[] = $new_term['term_id'];
								}
							} else {
								$cat_ids[] = $term->term_id;
							}
						}
						if ( $cat_ids ) {
							wp_set_post_terms( $post_id, $cat_ids, 'category' );
						}
					}

					// ✅ Handle tags
					if ( ! empty( $post_data['tags'] ) ) {
						$tag_ids = array();

						foreach ( $post_data['tags'] as $tag ) {
							$term = get_term_by( 'slug', $tag['slug'], 'post_tag' );

							if ( ! $term ) {
								$new_term = wp_insert_term(
									$tag['name'],
									'post_tag',
									array( 'slug' => $tag['slug'] )
								);

								if ( ! is_wp_error( $new_term ) ) {
									$tag_ids[] = $new_term['term_id'];
								}
							} else {
								$tag_ids[] = $term->term_id;
							}
						}

						if ( $tag_ids ) {
							wp_set_post_terms( $post_id, $tag_ids, 'post_tag' );
						}
					}
				}
			}

			foreach ( $this->menu_list as $menu ) {
				if ( empty( $menu['new_id'] ) ) {
					continue;
				}

				$menu_id   = $menu['new_id'];
				$parent_id = array();

				foreach ( $menu['data'] as $key => $item ) {
					$item_title  = isset( $item['title'] ) ? $item['title'] : '';
					$item_url    = isset( $item['url'] ) ? $item['url'] : '';
					$item_type   = isset( $item['type'] ) ? $item['type'] : 'custom';
					$object_slug = isset( $item['object_slug'] ) ? $this->imported_theme . '-' . $item['object_slug'] : null;
					$object_id   = 0;
					$menu_parent = 0;
					if ( null !== $item['parent'] ) {
						foreach ( $parent_id as $pr_id ) {
							if ( strval( $pr_id['idx'] ) === strval( $item['parent'] ) ) {
								$menu_parent = $pr_id['menu_id'];
							}
						}
					}

					$menu_items   = wp_get_nav_menu_items( $menu_id );
					$menu_item_id = 0;
					if ( $menu_items ) {
						foreach ( $menu_items as $menu_item ) {
							if ( $menu_item->title === $item['title'] ) {
								$menu_item_id = $menu_item->ID;
							}
						}
					}

					if ( 'page' === $item_type && $object_slug ) {
						$page = get_page_by_path( $object_slug, OBJECT, 'page' );
						if ( $page ) {
							$object_id = $page->ID;
							$item_url  = get_permalink( $object_id );
						}
					}

					$args = array(
						'menu-item-title'     => $item_title,
						'menu-item-url'       => $item_url,
						'menu-item-parent-id' => $menu_parent,
						'menu-item-status'    => 'publish',
					);

					if ( 'page' === $item_type && $object_id > 0 ) {
						$args['menu-item-type']      = 'post_type';
						$args['menu-item-object']    = 'page';
						$args['menu-item-object-id'] = $object_id;
					} else {
						$args['menu-item-type'] = 'custom';
					}

					$menu_item_id = wp_update_nav_menu_item( $menu_id, $menu_item_id, $args );
					if ( $item['have_child'] ) {
						$parent_id[] = array(
							'idx'     => $key,
							'menu_id' => $menu_item_id,
						);
					}
				}
			}
		}
	}

	/**
	 * Import Taxonomies
	 *
	 * @param array  $data .
	 * @param string $type .
	 * @return void
	 */
	private function import_taxonomies( $data, $type ) {
		$taxonomy_bin = array();
		$inserted_any = false; // ✅ Track if any taxonomy was inserted in this run
		foreach ( $data as $taxonomy ) {
			// Skip if already exists.
			$check_if_exist = get_term_by( 'slug', $taxonomy['slug'], $type );
			if ( $check_if_exist && ! is_wp_error( $check_if_exist ) ) {
				continue;
			}

			$parent_id  = 0;
			$can_insert = true;

			// Handle parent term if defined.
			if ( ! empty( $taxonomy['parent'] ) ) {
				$parent = get_term_by( 'slug', $taxonomy['parent'], $type );

				// Parent doesn't exist yet — postpone.
				if ( ! $parent || is_wp_error( $parent ) ) {
					$can_insert = false;
				} else {
					$parent_id = $parent->term_id; // ✅ use correct property.
				}
			}

			if ( $can_insert ) {
				$result = wp_insert_term(
					$taxonomy['name'],
					$type,
					array(
						'slug'   => $taxonomy['slug'],
						'parent' => $parent_id,
					)
				);
				if ( ! is_wp_error( $result ) ) {
					$inserted_any = true; // ✅ We made progress.
				} else {
					// Log error for debugging.
					gutenverse_rlog( 'Failed to insert term: ' . $taxonomy['slug'] . ' - ' . $result->get_error_message() );
				}
			} else {
				// Can't insert now, try again in the next round.
				$taxonomy_bin[] = $taxonomy;
			}
		}

		// ✅ Only recurse if there are still items AND progress was made this round
		if ( ! empty( $taxonomy_bin ) && $inserted_any ) {
			$this->import_taxonomies( $taxonomy_bin, $type );
		} elseif ( ! empty( $taxonomy_bin ) && ! $inserted_any ) {
			// 🛑 Stop recursion and log unresolved taxonomies to avoid infinite loop
			gutenverse_rlog( 'Some taxonomies could not be imported due to missing parents:' );
			gutenverse_rlog( $taxonomy_bin );
		}
	}

	/**
	 * Check directory, if there is none, create.
	 *
	 * @param string  $dir .
	 * @param boolean $condition .
	 */
	private function check_directory( $dir, $condition = true ) {
		if ( ! is_dir( $dir ) && $condition ) {
			wp_mkdir_p( $dir );
		}
	}

	/**
	 * Handle Menu
	 *
	 * @param string $content .
	 *
	 * @return string
	 */
	private function handle_menus( $content ) {
		$strings = wp_json_encode( $content );

		foreach ( $this->menu_list as &$menu ) {
			if ( ! isset( $menu['name'] ) ) {
				continue;
			}
			$existing_menu = wp_get_nav_menu_object( $this->imported_theme . '-' . $menu['name'] );
			if ( $existing_menu ) {
				$menu_id    = $existing_menu->term_id;
				$menu_items = wp_get_nav_menu_items( $menu_id );
				/**Check Here again */
				if ( $menu_items && ! in_array( $menu_id, $this->imported_menus, true ) ) {
					foreach ( $menu_items as $menu_item ) {
						wp_delete_post( $menu_item->ID, true );
					}
					$this->imported_menus[] = $menu_id;
					$menu['new_id']         = $menu_id;
				}
			} else {
				$menu_id        = wp_create_nav_menu( $this->imported_theme . '-' . $menu['name'] );
				$menu['new_id'] = $menu_id;
			}

			// replace url.
			$search  = '\"menuId\":' . $menu['placeholder'];
			$replace = '\"menuId\":' . $menu_id;
			$strings = str_replace( $search, $replace, $strings );
		}

		return json_decode( $strings );
	}

	/**
	 * Replace Images
	 *
	 * @param string $content .
	 *
	 * @return string
	 */
	private function replace_images( $content ) {
		$strings = wp_json_encode( $content );

		foreach ( $this->image_list as $image ) {
			// replace id.
			$search_id  = '"id":"' . $image['old_id'] . '"';
			$replace_id = '"id":"' . $image['id'] . '"';
			$strings    = str_replace( $search_id, $replace_id, $strings );

			// replace url.
			$search_url  = str_replace( '/', '\/', $image['placeholder'] );
			$replace_url = str_replace( '/', '\/', $image['url'] );
			$strings     = str_replace( $search_url, $replace_url, $strings );
		}

		return json_decode( $strings );
	}

	/**
	 * Import Page Meta Images
	 *
	 * @param array $data .
	 */
	private function import_page_meta_images( $data ) {
		$page_image = $data['page_image'] ? $data['page_image'] : array();

		if ( empty( $page_image ) ) {
			return;
		}

		$filename = $page_image['filename'];

		if ( ! empty( $this->image_list[ $filename ] ) ) {
			$data['page_image'] = array(
				'id'       => $this->image_list[ $filename ]['id'],
				'filename' => $filename,
				'url'      => $this->image_list[ $filename ]['url'],
			);
		}

		return $data;
	}

	/**
	 * Import Theme Images
	 *
	 * @param array $data .
	 */
	private function import_theme_images( &$data ) {
		if ( isset( $data ) && ! empty( $data ) ) {
			foreach ( $data as $id => &$value ) {
				switch ( $id ) {
					case 'dashboard':
						$logo = $value['logo'] ? $value['logo'] : array();

						if ( empty( $logo ) ) {
							return;
						}

						$filename = $logo['filename'];

						if ( ! empty( $this->image_list[ $filename ] ) ) {
							$value['logo'] = array(
								'id'       => $this->image_list[ $filename ]['id'],
								'filename' => $filename,
								'url'      => $this->image_list[ $filename ]['url'],
							);
						}

						break;
					case 'notice':
						$notice = $value['eventNotice'] ? $value['eventNotice'] : array();

						if ( empty( $notice['banner'] ) ) {
							return;
						}

						$banner   = $notice['banner'];
						$filename = $banner['filename'];

						if ( ! empty( $this->image_list[ $filename ] ) ) {
							$value['eventNotice']['banner'] = array(
								'id'       => $this->image_list[ $filename ]['id'],
								'filename' => $filename,
								'url'      => $this->image_list[ $filename ]['url'],
							);
						}

						break;
					case 'screenshots':
						// thumbnail.
						$thumbnail = $value['thumbnail'] ? $value['thumbnail'] : array();

						if ( empty( $thumbnail ) ) {
							return;
						}

						$filename = $thumbnail['filename'];

						if ( ! empty( $this->image_list[ $filename ] ) ) {
							$value['thumbnail'] = array(
								'id'       => $this->image_list[ $filename ]['id'],
								'filename' => $filename,
								'url'      => $this->image_list[ $filename ]['url'],
							);
						}

						// screenshots .
						$dashboard = $value['dashboard'] ? $value['dashboard'] : array();

						if ( empty( $dashboard ) ) {
							return;
						}

						$newarray = array();

						foreach ( $dashboard as $screenshot ) {
							$filename = $screenshot['filename'];

							if ( ! empty( $this->image_list[ $filename ] ) ) {
								$newarray[] = array(
									'id'       => $this->image_list[ $filename ]['id'],
									'filename' => $filename,
									'url'      => $this->image_list[ $filename ]['url'],
								);
							}
						}

						$value['dashboard'] = $newarray;

						break;
					default:
						break;
				}
			}
		}
	}

	/**
	 * Check Image
	 *
	 * @param string $filename .
	 * @return bool/string
	 */
	private function check_image( $filename ) {
		global $wpdb;

		$query = $wpdb->prepare(
			"SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'attachment'",
			preg_replace( '/\.[^.]+$/', '', $filename )
		);

		$results = $wpdb->get_results( $query );

		if ( ! empty( $results ) && count( $results ) === 1 ) {
			return $results[0]->ID;
		}

		return false;
	}

	/**
	 * Media Upload
	 *
	 * @param string $path .
	 * @param string $filename .
	 *
	 * @return WP_Error/string the ID of the media.
	 */
	private function upload_to_media( $path, $filename ) {
		$clean_name = Misc::image_separate_resolution( $filename );
		$filepath   = $path . '/images/' . $clean_name;
		if ( ! file_exists( $filepath ) ) {
			return new WP_Error( 'file_not_found', 'The specified local file does not exist.' );
		}

		$existing_id = $this->check_image( $clean_name );
		if ( $existing_id ) {
			return $existing_id;
		}

		global $wp_filesystem;

		if ( empty( $wp_filesystem ) ) {
			$init = WP_Filesystem();
			if ( false === $init ) {
				return new WP_Error( 'filesystem_error', 'Unable to initialize WP_Filesystem.' );
			}
		}

		$wp_filetype      = wp_check_filetype( $filename, null );
		$upload_dir       = wp_upload_dir();
		$destination_path = trailingslashit( $upload_dir['path'] ) . $filename;

		$copy_success = $wp_filesystem->copy( $filepath, $destination_path, true );
		if ( ! $copy_success ) {
			return new WP_Error( 'file_copy_failed', 'Unable to copy the file to the uploads directory.' );
		}

		$attachment = array(
			'guid'           => $upload_dir['url'] . '/' . $filename,
			'post_mime_type' => $wp_filetype['type'],
			'post_title'     => preg_replace( '/\.[^.]+$/', '', $filename ),
			'post_content'   => '',
			'post_status'    => 'inherit',
		);

		$attachment_id = wp_insert_attachment( $attachment, $destination_path, 0 );

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

		if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) {
			require_once ABSPATH . 'wp-admin/includes/image.php';
		}

		$attachment_data = wp_generate_attachment_metadata( $attachment_id, $destination_path );

		wp_update_attachment_metadata( $attachment_id, $attachment_data );

		return $attachment_id;
	}

	/**
	 * Extract ZIP File
	 */
	private function extract_zip_file() {
		$zip_file_path = get_attached_file( $this->file_id );

		if ( ! file_exists( $zip_file_path ) ) {
			return false;
		}

		$upload_dir       = wp_upload_dir();
		$destination_path = $upload_dir['basedir'] . '/gtb_extracted_zips/' . basename( $zip_file_path, '.zip' );

		if ( ! wp_mkdir_p( $destination_path ) ) {
			return false;
		}

		$unzip_result = unzip_file( $zip_file_path, $destination_path );

		if ( is_wp_error( $unzip_result ) ) {
			return false;
		}

		return $destination_path;
	}

	/**
	 * Return image
	 *
	 * @param string $url Image attachment url.
	 *
	 * @return array|null
	 */
	public function check_image_exist( $url ) {
		$attachments = new \WP_Query(
			array(
				'post_type'   => 'attachment',
				'post_status' => 'inherit',
				'meta_query'  => array(
					array(
						'key'     => '_import_source',
						'value'   => $url,
						'compare' => 'LIKE',
					),
				),
			)
		);

		foreach ( $attachments->posts as $post ) {
			$attachment_url = wp_get_attachment_url( $post->ID );
			return array(
				'id'  => $post->ID,
				'url' => $attachment_url,
			);
		}

		return $attachments->posts;
	}

	/**
	 * Import Images
	 *
	 * @param object $request images.
	 */
	public function import_images( $request ) {
		$image = $request->get_param( 'imageUrl' );

		$data = $this->check_image_exist( $image );
		if ( ! $data ) {
			$data = $this->import_image( $image );
		}

		return $data;
	}

	/**
	 * Import an image into the media library
	 *
	 * @param string $url Image URL to import.
	 * @return array|null
	 */
	public function import_image( $url ) {
		$upload = $this->upload_image( $url );
		if ( ! $upload ) {
			return null;
		}
		$attach_id = $upload['attach_id'];

		add_post_meta( $attach_id, '_import_source', $url, true );

		$imported_options = get_option( 'gutenverse-companion-imported-options' );
		if ( $imported_options ) {
			$imported_media            = $imported_options['media'] ?? array();
			$imported_media[]          = $attach_id;
			$imported_options['media'] = $imported_media;
			update_option( 'gutenverse-companion-imported-options', $imported_options );
		}

		return array(
			'id'  => $attach_id,
			'url' => $upload['url'],
		);
	}

	/**
	 * Upload Image
	 *
	 * @param string $url Image URL to import.
	 * @return array|null
	 */
	public function upload_image( $url ) {
		$response = wp_remote_get( $url );
		if ( is_wp_error( $response ) ) {
			return null;
		}

		$image_data = wp_remote_retrieve_body( $response );

		$filename = basename( $url );

		$upload = wp_upload_bits( $filename, null, $image_data );

		if ( $upload['error'] ) {
			return null;
		}

		$attachment = array(
			'guid'           => $upload['url'],
			'post_mime_type' => $upload['type'],
			'post_title'     => sanitize_file_name( $filename ),
			'post_content'   => '',
			'post_status'    => 'inherit',
		);

		$attach_id = wp_insert_attachment( $attachment, $upload['file'] );

		require_once ABSPATH . 'wp-admin/includes/image.php';

		$attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
		wp_update_attachment_metadata( $attach_id, $attach_data );
		return array(
			'id'  => $attach_id,
			'url' => $upload['url'],
		);
	}
}
