<?php
/**
 * REST APIs class
 *
 * @author Jegstudio
 * @since 1.0.0
 * @package gutenverse-themes-builder
 */

namespace Gutenverse_Themes_Builder;

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

use Automatic_Upgrader_Skin;
use Exception;
use Gutenverse_Themes_Builder\Database\Database;
use Gutenverse\Framework\Global_Variable;
use Gutenverse_Themes_Builder\Export\Misc;
use Theme_Upgrader;
use WP;
use WP_Query;
use WP_REST_Response;
use ZipArchive;
use WP_Theme_Json_Resolver;

/**
 * Class Api
 *
 * @package gutenverse-themes-builder
 */
class Backend_Api {

	/**
	 * Endpoint Path
	 *
	 * @var string
	 */
	const ENDPOINT = 'gtb-backend/v1';

	/**
	 * Blocks constructor.
	 */
	public function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
	}

	/**
	 * Register APIs
	 */
	public function register_routes() {
		if ( ! is_admin() && ! current_user_can( 'manage_options' ) ) {
			return;
		}

		/**
		 * Backend routes.
		 */

		// Themes.
		register_rest_route(
			self::ENDPOINT,
			'themes/create',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'create_theme' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'themes/update',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'update_theme' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'themes/other',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'update_theme_other_data' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'themes/delete',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'delete_theme' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'themes/active',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'set_active_theme' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'themes/list',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_theme_list' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'themes/active-theme',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_active_theme_id' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'themes/list',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'get_theme_list_pagination' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'themes/data',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_theme_data' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'themes/export',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'export_theme' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		// Assets.
		register_rest_route(
			self::ENDPOINT,
			'assets/list',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'get_asset_list' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'asset/update',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'update_asset' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'asset/create',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'create_asset' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'asset/delete',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'delete_asset' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		// Templates.
		register_rest_route(
			self::ENDPOINT,
			'templates/list',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_template_list' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'templates/list',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'get_template_list_search' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'templates/create',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'create_template' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'templates/delete',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'delete_template' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		// Pattern.
		register_rest_route(
			self::ENDPOINT,
			'pattern/search',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'search_pattern' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'pattern/create',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'create_pattern' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'pattern/edit',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'edit_pattern' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'pattern',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'get_pattern' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'pattern/data',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_pattern_data' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'pattern/list',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_pattern_list' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'pattern/list',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'get_pattern_list_pagination' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'pattern/delete',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'delete_pattern' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		// Global Styles.

		register_rest_route(
			self::ENDPOINT,
			'globalstyles/update-current-slug',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'update_current_slug' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);
		register_rest_route(
			self::ENDPOINT,
			'globalstyles/list',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_global_list' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'globalstyles/list',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'get_global_list_pagination' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'globalstyle/update',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'update_globalstyle' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'globalstyle/create',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'create_globalstyle' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'globalstyle/delete',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'delete_globalstyle' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'globalstyle/backup',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'backup_globalstyle' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'globalstyle/active',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'set_active_global' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		/**Pages End Point */
		register_rest_route(
			self::ENDPOINT,
			'pages/create',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'create_pages' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'pages/list',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'get_page_list' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'pages/delete',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'delete_page' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'pages/update',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'update_page' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		/** Essential APIs */
		register_rest_route(
			self::ENDPOINT,
			'/essential-proxy',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'essence_proxy' ),
				'permission_callback' => '__return_true',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'themes/backup/export',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'export_backup_data' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'themes/backup/import',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'import_backup_data' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);

		register_rest_route(
			self::ENDPOINT,
			'basic-theme/install',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'basic_theme_install' ),
				'permission_callback' => 'gutenverse_permission_check_admin',
			)
		);
	}

	/**
	 * ==================================================================================================================================
	 * Global Style APIs
	 * ==================================================================================================================================
	 */

	/**
	 * Update Current Slug Global
	 *
	 * @param WP_Object $request .
	 * @return WP_REST_Response
	 */
	public function update_current_slug( $request ) {
		$new     = $request->get_param( 'new' );
		$changed = $request->get_param( 'changed' );

		$theme          = wp_get_theme();
		$themedata      = WP_Theme_Json_Resolver::get_user_data_from_wp_global_styles( $theme );
		$current_styles = json_decode( $themedata['post_content'] );
		$current_styles->settings->color->palette->custom = $new['color'];

		$post_id = wp_update_post(
			array(
				'ID'           => $themedata['ID'],
				'post_content' => wp_json_encode( $current_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' );
		}

		$google_fonts = array();

		foreach ( $new['font'] as $font ) {
			if ( isset( $font['font'] ) && ! empty( $font['font'] ) && 'google' === $font['font']['font']['type'] ) {
				$google_fonts[] = array(
					'label'  => $font['font']['font']['label'],
					'type'   => $font['font']['font']['type'],
					'value'  => $font['font']['font']['value'],
					'weight' => $font['font']['weight'],
				);
			}
		}

		$globals = new Global_Variable();
		$globals->set_global_variable(
			array(
				'fonts'      => $new['font'],
				'colors'     => $new['color'],
				'googlefont' => $google_fonts,
			)
		);

		$theme_id = get_option( 'gtb_active_theme_id' );

		$this->replace_global_pattern( $theme_id, $changed );
		$this->replace_global_template( $theme_id, $changed );
		$this->replace_global_page( $theme_id, $changed );
		$this->replace_global_post( $changed );

		return new WP_REST_Response(
			array(
				'message' => 'Update Slug Success',
			),
			200
		);
	}

	/**
	 * Replace global slug on post content
	 *
	 * @param array $changed .
	 * @return void
	 */
	private function replace_global_post( $changed ) {
		$posts = new \WP_Query(
			array(
				'post_type'      => 'post',
				'posts_per_page' => -1,
			)
		);
		foreach ( $posts->posts as &$post ) {
			$content = $post->post_content;
			$content = $this->replace_global_color( $content, $changed['color'] );
			$content = $this->replace_global_font( $content, $changed['font'] );
			wp_update_post(
				array(
					'ID'           => $post->ID,
					'post_content' => $content,
				)
			);
		}
	}

	/**
	 * Replace global slug on template content
	 *
	 * @param string $theme_id .
	 * @param array  $changed .
	 * @return void
	 */
	private function replace_global_template( $theme_id, $changed ) {
		$templates_db   = Database::instance()->theme_templates;
		$templates_data = $templates_db->get_data( $theme_id );

		$templates_content = get_block_templates(array(), 'wp_template'); // phpcs:ignore
		$parts_content     = get_block_templates(array(), 'wp_template_part'); // phpcs:ignore
		$changed_template  = array();

		foreach ( $templates_content as $template ) {
			$changed_template[ $template->slug ] = $template;
		}

		foreach ( $parts_content as $part ) {
			$changed_template[ $part->slug ] = $template;
		}

		foreach ( $templates_data as &$template_data ) {

			$slug_key = strtolower( $template_data['category'] . '-' . Misc::sluggify( $template_data['name'] ) );

			if ( empty( $changed_template[ $slug_key ] ) ) {
				continue;
			}

			$content = $changed_template[ $slug_key ]->content;
			$content = $this->replace_global_color( $content, $changed['color'] );
			$content = $this->replace_global_font( $content, $changed['font'] );

			$id = $changed_template[ $slug_key ]->id;

			// ✅ If no wp_id, it's a theme file → create a DB override
			if ( empty( $id ) ) {
				wp_insert_post(
					array(
						'post_type'    => $changed_template[ $slug_key ]->type, // "wp_template" or "wp_template_part"
						'post_name'    => $changed_template[ $slug_key ]->slug,
						'post_title'   => $changed_template[ $slug_key ]->title,
						'post_status'  => 'publish',
						'post_content' => $content,
					)
				);
			} else {
				// ✅ If already in DB, update it
				wp_update_post(
					array(
						'ID'           => $changed_template[ $slug_key ]->wp_id,
						'post_content' => $content,
					)
				);
			}
		}
	}

	/**
	 * Replace global slug on page content
	 *
	 * @param string $theme_id .
	 * @param array  $changed .
	 * @return void
	 */
	private function replace_global_page( $theme_id, $changed ) {
		$pages = new \WP_Query(
			array(
				'post_type'      => 'page',
				'posts_per_page' => -1,
				'meta_query'     => array( //phpcs:ignore
					array(
						'key'     => '_gtb_page_theme_id',
						'value'   => $theme_id,
						'compare' => '===',
					),
				),
			)
		);

		foreach ( $pages->posts as &$post ) {
			$content = $post->post_content;
			$content = $this->replace_global_color( $content, $changed['color'] );
			$content = $this->replace_global_font( $content, $changed['font'] );
			wp_update_post(
				array(
					'ID'           => $post->ID,
					'post_content' => $content,
				)
			);
		}
	}

	/**
	 * Replace global slug on pattern content
	 *
	 * @param string $theme_id .
	 * @param array  $changed .
	 * @return void
	 */
	private function replace_global_pattern( $theme_id, $changed ) {
		$patterns = new \WP_Query(
			array(
				'post_type'      => 'gutenverse-pattern',
				'posts_per_page' => -1,
				'meta_query'     => array( //phpcs:ignore
					array(
						'key'     => '_pattern_theme_id',
						'value'   => $theme_id,
						'compare' => '===',
					),
				),
			)
		);

		foreach ( $patterns->posts as &$post ) {
			$content = $post->post_content;
			$content = $this->replace_global_color( $content, $changed['color'] );
			$content = $this->replace_global_font( $content, $changed['font'] );
			wp_update_post(
				array(
					'ID'           => $post->ID,
					'post_content' => $content,
				)
			);
		}
	}

	/**
	 * Replace Global Font Slug in Content
	 *
	 * @param string $content .
	 * @param array  $color_replacer .
	 * @return string
	 */
	private function replace_global_color( $content, $color_replacer ) {
		if ( ! empty( $color_replacer ) ) {
			foreach ( $color_replacer as $key => $replacer ) {
				if ( $key === $replacer ) {
					continue;
				}
				$content = preg_replace_callback(
					'/\{\s*"type"\s*:\s*"variable"\s*,\s*"id"\s*:\s*"([^"]+)"\s*\}/',
					function ( $matching ) use ( $key, $replacer ) {
						$json = json_decode( $matching[0], true );

						// Only replace if JSON has exactly 2 keys AND id matches $key.
						if ( is_array( $json ) && count( $json ) === 2 && $json['id'] === $key ) {
							$json['id'] = $replacer;
							return wp_json_encode( $json, JSON_UNESCAPED_SLASHES );
						}

						// Return original if doesn't match.
						return $matching[0];
					},
					$content
				);
			}
		}
		return $content;
	}

	/**
	 * Replace Global Font Slug in Content
	 *
	 * @param string $content .
	 * @param array  $font_replacer .
	 * @return string
	 */
	private function replace_global_font( $content, $font_replacer ) {
		if ( ! empty( $font_replacer ) ) {
			foreach ( $font_replacer as $key => $replacer ) {
				if ( $key === $replacer ) {
					continue;
				}
				$content = str_replace( '{"type":"variable","id":"' . $key . '",', '{"type":"variable","id":"' . $replacer . '",', $content );
			}
		}
		return $content;
	}

	/**
	 * Import Global Style from Elementor Template kits Equivalent.
	 *
	 * @param array   $filedata .
	 * @param boolean $replace .
	 *
	 * @return array
	 */
	public function global_style_import( $filedata, $replace = false ) {
		if ( empty( $filedata ) ) {
			return array(
				'fonts'  => '',
				'colors' => '',
			);
		}

		$jsondata  = $this->get_file_json_data( $filedata['id'] );
		$globals   = new Global_Variable();
		$converted = array();

		$theme         = wp_get_theme();
		$themedata     = WP_Theme_Json_Resolver::get_user_data_from_wp_global_styles( $theme );
		$update_colors = json_decode( $themedata['post_content'] );

		if ( ! isset( $update_colors->settings ) ) {
			$update_colors->settings = (object) array(
				'color' => (object) array(
					'palette' => (object) array(
						'custom' => (object) array(),
					),
				),
			);
		}

		if ( isset( $update_colors->settings->color->palette->custom ) ) {
			$update_colors->settings->color->palette->custom = array();
		}

		foreach ( $jsondata->page_settings as $key => $settings ) {
			if ( 'system_colors' === $key || 'custom_colors' === $key ) {
				foreach ( $settings as $setting ) {
					$converted_color       = array(
						'slug'  => $setting->_id,
						'name'  => $setting->title,
						'color' => $setting->color,
					);
					$converted['colors'][] = $converted_color;

					$update_colors->settings->color->palette->custom[] = $converted_color;
				}
			}

			if ( 'system_typography' === $key || 'custom_typography' === $key ) {
				if ( empty( $converted['fonts'] ) ) {
					$converted['fonts'] = array();
				}

				foreach ( $settings as $setting ) {
					$converted_font = array(
						'id'   => $setting->_id,
						'name' => $setting->title,
						'font' => array(),
					);

					if ( isset( $setting->typography_font_family ) ) {
						$converted_font['font']['font'] = array(
							'label' => $setting->typography_font_family,
							'value' => $setting->typography_font_family,
							'type'  => $setting->typography_typography ? 'google' : 'system',
						);
					}

					if ( isset( $setting->typography_font_weight ) ) {
						$converted_font['font']['weight'] = $setting->typography_font_weight;
					}

					if ( isset( $setting->typography_font_style ) ) {
						$converted_font['font']['style'] = $setting->typography_font_style;
					}

					if ( isset( $setting->typography_text_decoration ) ) {
						$converted_font['font']['decoration'] = $setting->typography_text_decoration;
					}

					if ( isset( $setting->typography_text_transform ) ) {
						$converted_font['font']['transform'] = $setting->typography_text_transform;
					}

					$converted_font['font']['size'] = array();

					if ( isset( $setting->typography_font_size ) ) {
						$converted_font['font']['size']['Desktop'] = array(
							'unit'  => $setting->typography_font_size->unit,
							'point' => (string) $setting->typography_font_size->size,
						);
					}

					if ( isset( $setting->typography_font_size_tablet ) ) {
						$converted_font['font']['size']['Tablet'] = array(
							'unit'  => $setting->typography_font_size_tablet->unit,
							'point' => (string) $setting->typography_font_size_tablet->size,
						);
					}

					if ( isset( $setting->typography_font_size_mobile ) ) {
						$converted_font['font']['size']['Mobile'] = array(
							'unit'  => $setting->typography_font_size_mobile->unit,
							'point' => (string) $setting->typography_font_size_mobile->size,
						);
					}

					$converted_font['font']['lineHeight'] = array();

					if ( isset( $setting->typography_line_height ) ) {
						$converted_font['font']['lineHeight']['Desktop'] = array(
							'unit'  => $setting->typography_line_height->unit,
							'point' => (string) $setting->typography_line_height->size,
						);
					}

					if ( isset( $setting->typography_line_height_tablet ) ) {
						$converted_font['font']['lineHeight']['Tablet'] = array(
							'unit'  => $setting->typography_line_height_tablet->unit,
							'point' => (string) $setting->typography_line_height_tablet->size,
						);
					}

					if ( isset( $setting->typography_line_height_mobile ) ) {
						$converted_font['font']['lineHeight']['Mobile'] = array(
							'unit'  => $setting->typography_line_height_mobile->unit,
							'point' => (string) $setting->typography_line_height_mobile->size,
						);
					}

					$converted_font['font']['spacing'] = array();

					if ( isset( $setting->typography_letter_spacing ) ) {
						$converted_font['font']['spacing']['Desktop'] = $this->convert_spacing( $setting->typography_letter_spacing );
					}

					if ( isset( $setting->typography_letter_spacing_tablet ) ) {
						$converted_font['font']['spacing']['Tablet'] = $this->convert_spacing( $setting->typography_letter_spacing_tablet );
					}

					if ( isset( $setting->typography_letter_spacing_mobile ) ) {
						$converted_font['font']['spacing']['Mobile'] = $this->convert_spacing( $setting->typography_letter_spacing_mobile );
					}

					$converted['fonts'][] = $converted_font;
				}
			}
		}

		if ( $replace ) {
			$update_colors = wp_json_encode( $update_colors );

			wp_update_post(
				array(
					'ID'           => $themedata['ID'],
					'post_content' => $update_colors,
				)
			);

			$globals->set_global_variable( $converted );
		}

		return $converted;
	}

	/**
	 * Backup Global Style
	 *
	 * @param object $request .
	 */
	public function backup_globalstyle( $request ) {
		$global_tb_check = $this->global_column_checker();
		if ( ! $global_tb_check['status'] ) {
			return new WP_REST_Response(
				array(
					'message' => implode( ', ', $global_tb_check['messages'] ),
				),
				400
			);
		}
		$global_id      = $request->get_param( 'id' ) ? $request->get_param( 'id' ) : $request->id;
		$theme          = wp_get_theme();
		$themedata      = WP_Theme_Json_Resolver::get_user_data_from_wp_global_styles( $theme );
		$current_color  = Misc::get_color_settings();
		$current_styles = json_decode( $themedata['post_content'] );
		$current_fonts  = get_option( 'gutenverse-global-variable-font-' . $theme->get_stylesheet(), false );
		$global_db      = Database::instance()->theme_globals;
		try {
			$data  = array(
				'fonts'  => maybe_serialize( $current_fonts ),
				'colors' => maybe_serialize( $current_color ),
				'styles' => maybe_serialize( $current_styles ),
			);
			$where = array(
				'id' => $global_id,
			);
			$global_db->update_data( $data, $where );
		} catch ( \Throwable $th ) {
			gutenverse_rlog( 'Backup Global Data Failed!' );
			gutenverse_rlog( $th->getMessage() );
			return new WP_REST_Response(
				array(
					'message' => 'Backup Global Data Failed!',
				),
				400
			);
		}
		return new WP_REST_Response(
			array(
				'message' => 'Backup Global Data Success!',
			),
			200
		);
	}

	/**
	 * Checking Global Column;
	 *
	 * @return array
	 */
	public function global_column_checker() {
		$global_column = array( 'styles' );
		$messages      = array();
		$global_db     = Database::instance()->theme_globals;
		foreach ( $global_column as $col ) {
			if ( ! $global_db->column_checker( $col ) ) {
				$messages[] = $col . ' column not found in global table. Deactivate then activate the Theme Builder First!';
			}
		}
		if ( count( $messages ) === 0 ) {
			return array(
				'status' => true,
			);
		} else {
			return array(
				'status'   => false,
				'messages' => $messages,
			);
		}
	}

	/**
	 * Convert spacing value from template kit global.json
	 *
	 * @param object $spacing .
	 *
	 * @return int|string
	 */
	private function convert_spacing( $spacing ) {
		$basesize = 16;

		if ( isset( $spacing->unit ) ) {
			switch ( $spacing->unit ) {
				case 'rem':
					return (float) $spacing->size * $basesize;
				case 'px':
					return (float) $spacing->size / $basesize;
				case 'em':
					return (float) $spacing->size;
			}
		}

		return '';
	}

	/**
	 * Get theme list
	 */
	public function get_global_list() {
		$global_db = Database::instance()->theme_globals;
		$data      = $global_db->get_all_globals();

		foreach ( $data as &$global ) {
			if ( ! empty( $global['file'] ) ) {
				$global['file'] = maybe_unserialize( $global['file'] );
			}
		}

		return array(
			'data'   => $data,
			'active' => $this->get_active_global_id(),
		);
	}

	/**
	 * Get theme list Pagination
	 *
	 * @param object $request .
	 *
	 * @return object
	 */
	public function get_global_list_pagination( $request ) {
		$paged    = gutenverse_esc_data( $request->get_param( 'paged' ), 'int' );
		$paged    = empty( $paged ) ? 1 : $paged;
		$num_post = gutenverse_esc_data( $request->get_param( 'num_post' ), 'integer' );
		$num_post = empty( $num_post ) ? 10 : $num_post;
		$offset   = ( $paged - 1 ) * $num_post;

		$global_db = Database::instance()->theme_globals;
		$data      = $global_db->get_pagination_data( $offset, $num_post );
		foreach ( $data as &$global ) {
			if ( ! empty( $global['file'] ) ) {
				$global['file'] = maybe_unserialize( $global['file'] );
			}
		}
		$global_color = Misc::get_color_settings();
		$globals      = new Global_Variable();
		$global_font  = $globals->get_global_variable( 'font' );

		$max_page = ceil( $data['total_data'] / $num_post );
		return array(
			'active'       => $this->get_active_global_id(),
			'data'         => $data,
			'total_page'   => $max_page,
			'global_color' => $global_color,
			'global_font'  => $global_font,
		);
	}

	/**
	 * Get Active Global ID
	 *
	 * @return int|false
	 */
	public function get_active_global_id() {
		$theme_db = Database::instance()->theme_info;
		$theme_id = get_option( 'gtb_active_theme_id' );
		$theme    = $theme_db->get_theme_data( $theme_id );

		if ( ! empty( $theme ) ) {
			return $theme[0]['global_id'];
		}

		return false;
	}

	/**
	 * Create Global Styles
	 *
	 * @param object $request .
	 *
	 * @return array
	 */
	public function create_globalstyle( $request ) {
		$global_tb_check = $this->global_column_checker();
		if ( ! $global_tb_check['status'] ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => implode( ', ', $global_tb_check['messages'] ),
				),
				400
			);
		}
		$title     = gutenverse_esc_data( $request->get_param( 'title' ) );
		$filedata  = gutenverse_esc_data( $request->get_param( 'file' ), 'array' );
		$imported  = $this->global_style_import( $filedata );
		$global_db = Database::instance()->theme_globals;
		$data      = array(
			'title'  => $title,
			'file'   => maybe_serialize( $filedata ),
			'fonts'  => maybe_serialize( $imported['fonts'] ),
			'colors' => maybe_serialize( $imported['colors'] ),
		);

		$global_db->create_data( $data );

		return new WP_REST_Response(
			array(
				'status'  => 'success',
				'message' => esc_html__( 'Create Global Success', 'gutenverse-themes-builder' ),
				'data'    => $this->get_global_list_pagination( $request ),
			),
			200
		);
	}

	/**
	 * Edit Global Styles
	 *
	 * @param object $request .
	 *
	 * @return array
	 */
	public function update_globalstyle( $request ) {
		$global_tb_check = $this->global_column_checker();
		if ( ! $global_tb_check['status'] ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => implode( ', ', $global_tb_check['messages'] ),
				),
				400
			);
		}
		$id        = gutenverse_esc_data( $request->get_param( 'id' ) );
		$title     = gutenverse_esc_data( $request->get_param( 'title' ) );
		$filedata  = gutenverse_esc_data( $request->get_param( 'file' ), 'array' );
		$global_db = Database::instance()->theme_globals;
		$previous  = $global_db->get_data( $id );

		if ( ! empty( $previous ) ) {
			$decode   = maybe_unserialize( $previous[0]['file'] );
			$filedata = maybe_unserialize( $filedata );
			if ( ! empty( $decode ) && (int) $decode['id'] !== (int) $filedata['id'] ) {
				$replace  = (int) $this->get_active_global_id() === (int) $id;
				$imported = $this->global_style_import( $filedata, $replace );
			}
		}

		$where = array(
			'id' => $id,
		);
		$data  = array(
			'title' => $title,
			'file'  => maybe_serialize( $filedata ),
		);

		if ( ! empty( $imported ) ) {
			$data['fonts']  = maybe_serialize( $imported['fonts'] );
			$data['colors'] = maybe_serialize( $imported['colors'] );
		}

		$global_db->update_data( $data, $where );

		return new WP_REST_Response(
			array(
				'status'  => 'success',
				'message' => esc_html__( 'Update Global Success', 'gutenverse-themes-builder' ),
				'data'    => $this->get_global_list_pagination( $request ),
			),
			200
		);
	}

	/**
	 * Delete Global
	 *
	 * @param object $request .
	 */
	public function delete_globalstyle( $request ) {
		try {
			$global_db = Database::instance()->theme_globals;
			$id        = $request->get_param( 'id' );

			$global_db->delete_data(
				array( 'id' => $id )
			);

			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => esc_html__( 'Delete Global Success', 'gutenverse-themes-builder' ),
					'data'    => $this->get_global_list_pagination( $request ),
				),
				200
			);
		} catch ( \Throwable $th ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => $th->getMessage(),
				),
				400
			);
		}
	}

	/**
	 * Set active global
	 *
	 * @param object $request .
	 */
	public function set_active_global( $request ) {
		try {
			$global_tb_check = $this->global_column_checker();
			if ( ! $global_tb_check['status'] ) {
				return new WP_REST_Response(
					array(
						'status'  => 'failed',
						'message' => implode( ', ', $global_tb_check['messages'] ),
					),
					400
				);
			}
			$global_id = $request->get_param( 'global_id' );
			$theme_id  = get_option( 'gtb_active_theme_id' );
			$global_db = Database::instance()->theme_globals;
			$theme_db  = Database::instance()->theme_info;
			$globals   = new Global_Variable();

			// Saving current style.
			$current_id     = $this->get_active_global_id();
			$theme          = wp_get_theme();
			$themedata      = WP_Theme_Json_Resolver::get_user_data_from_wp_global_styles( $theme );
			$current_styles = json_decode( $themedata['post_content'] );
			$global_colors  = $current_styles->settings->color->palette->custom;
			$global_fonts   = $globals->get_global_variable( 'font' );

			$where = array(
				'id' => $current_id,
			);
			$data  = array(
				'fonts'  => maybe_serialize( $global_fonts ),
				'colors' => maybe_serialize( $global_colors ),
				'styles' => maybe_serialize( $current_styles ),
			);

			$global_db->update_data( $data, $where );

			// Switching to new one.
			$update = $global_db->get_data( $global_id );

			$google_fonts = array();
			$new_fonts    = maybe_unserialize( $update[0]['fonts'] );

			foreach ( $new_fonts as $font ) {
				if ( isset( $font['font'] ) && ! empty( $font['font'] ) && 'google' === $font['font']['font']['type'] ) {
					$google_fonts[] = array(
						'label'  => $font['font']['font']['label'],
						'type'   => $font['font']['font']['type'],
						'value'  => $font['font']['font']['value'],
						'weight' => $font['font']['weight'] ? $font['font']['weight'] : '',
					);
				}
			}

			$globals->set_global_variable(
				array(
					'fonts'      => maybe_unserialize( $update[0]['fonts'] ),
					'colors'     => maybe_unserialize( $update[0]['colors'] ),
					'googlefont' => $google_fonts,
				)
			);
			$update_colors = maybe_unserialize( $update[0]['colors'] );
			$update_styles = maybe_unserialize( $update[0]['styles'] );
			$update_fonts  = maybe_unserialize( $update[0]['fonts'] );
			$theme         = wp_get_theme();
			$themedata     = WP_Theme_Json_Resolver::get_user_data_from_wp_global_styles( $theme );
			if ( count( $themedata ) > 0 ) {
				wp_delete_post( $themedata['ID'], true );
			}
			if ( ! isset( $update_styles ) || empty( $update_styles ) ) {
				$update_styles = array(
					'settings'                    => array(
						'color' => array(
							'palette' => array(
								'custom' => $update_colors,
							),
						),
					),
					'isGlobalStylesUserThemeJSON' => true,
					'version'                     => 3,
				);
			}

			$post_id = wp_insert_post(
				array(
					'post_title'   => 'Custom Styles',
					'post_name'    => 'wp-global-styles-' . get_stylesheet(),
					'post_status'  => 'publish',
					'post_type'    => 'wp_global_styles',
					'post_content' => wp_json_encode( $update_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' );
			}

			$theme_db->update_data(
				array(
					'global_id' => $global_id,
				),
				$theme_id
			);

			$google_fonts = array();
			foreach ( $update_fonts as $font ) {
				if ( isset( $font['font'] ) && ! empty( $font['font'] ) && 'google' === $font['font']['font']['type'] ) {
					$google_fonts[] = array(
						'label'  => $font['font']['font']['label'],
						'type'   => $font['font']['font']['type'],
						'value'  => $font['font']['font']['value'],
						'weight' => $font['font']['weight'] ? $font['font']['weight'] : '',
					);
				}
			}

			$globals->set_global_variable(
				array(
					'fonts'      => isset( $update_fonts ) ? $update_fonts : array(),
					'colors'     => isset( $update_colors ) ? $update_colors : array(),
					'googlefont' => $google_fonts,
				)
			);
			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => 'Global ' . $update[0]['title'] . ' Activated',
					'data'    => $this->get_global_list_pagination( $request ),
				),
				200
			);
		} catch ( \Throwable $th ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => $th->getMessage(),
				),
				400
			);
		}
	}

	/**
	 * ==================================================================================================================================
	 * THEMES APIs
	 * ==================================================================================================================================
	 */

	/**
	 * Check for Active THeme
	 *
	 * @return WP_REST_Response
	 */
	public function get_active_theme_id() {
		$theme_db = Database::instance()->theme_info;
		$theme_id = get_option( 'gtb_active_theme_id' );
		$data     = $theme_db->get_theme_data( $theme_id );

		if ( ! empty( $theme_id ) ) {
			return new WP_REST_Response(
				array(
					'theme_id' => $theme_id,
					'mode'     => $data[0]['theme_mode'],
				),
				200
			);
		}
		return new WP_REST_Response(
			array(
				'theme_id' => null,
				'message'  => 'No Active Theme',
			),
			404
		);
	}

	/**
	 * Theme Details Check
	 *
	 * @param array $details .
	 *
	 * $return array.
	 */
	public function theme_details_check( $details ) {
		if ( empty( $details ) ) {
			return false;
		}

		$result    = true;
		$important = array(
			'slug'              => true,
			'title'             => true,
			'author_name'       => true,
			'theme_version'     => true,
			'wp_min_version'    => true,
			'wp_tested_version' => true,
			'php_version'       => true,
			'theme_mode'        => true,
		);

		foreach ( $important as $key => $value ) {
			if ( ! empty( $value ) && empty( $details[ $key ] ) ) {
				$result = false;
			}
		}

		return $result;
	}

	/**
	 * Start building theme from parameters
	 *
	 * @param object $request .
	 */
	public function create_theme( $request ) {
		$global_tb_check = $this->global_column_checker();
		if ( ! $global_tb_check['status'] ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => implode( ', ', $global_tb_check['messages'] ),
				),
				400
			);
		}
		$info_details = $request->get_param( 'info_details' );
		$theme_json   = $request->get_param( 'theme_json' );
		$other_data   = $request->get_param( 'other_data' );

		$data_check = $this->theme_details_check( $info_details );

		if ( ! $data_check ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => esc_html__( 'Please fill all the required field!', 'gutenverse-themes-builder' ),
				),
				400
			);
		}

		$theme_id              = $this->generate_uid();
		$import_library_option = $info_details['import_library_option'] ?? false;

		/**Get Current Global Data */
		$current_color    = Misc::get_color_settings();
		$current_font     = array();
		$wp_active_theme  = wp_get_theme();
		$current_style_wp = WP_Theme_Json_Resolver::get_user_data_from_wp_global_styles( $wp_active_theme );
		$current_style    = json_decode( $current_style_wp['post_content'] );

		/**If using library option replace the global styles */
		if ( $import_library_option ) {
			$current_globals = $this->create_update_default_global_colors();
			$current_style   = $current_globals['styles'];
			$current_color   = $current_globals['colors'];
			$current_font    = $this->create_update_default_global_fonts();
		}

		/**Create a global theme data for backup when changing theme/global */
		$global_db = Database::instance()->theme_globals;
		$data      = array(
			'title'  => $info_details['title'] ? $info_details['title'] : 'Global Theme',
			'file'   => '',
			'fonts'  => maybe_serialize( $current_font ),
			'colors' => maybe_serialize( $current_color ),
			'styles' => maybe_serialize( $current_style ),
		);

		$global_id = $global_db->create_data( $data );

		$info_db = Database::instance()->theme_info;
		$data    = array(
			'theme_id'   => $theme_id,
			'slug'       => $info_details['slug'],
			'theme_mode' => $info_details['theme_mode'],
			'theme_data' => maybe_serialize( $info_details ),
			'theme_json' => maybe_serialize( $theme_json ),
			'other'      => maybe_serialize( $other_data ),
			'global_id'  => $global_id,
		);

		$result = $info_db->create_data( $data );

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

		return new WP_REST_Response(
			array(
				'status'  => 'success',
				'message' => esc_html__( 'Create Theme Success', 'gutenverse-themes-builder' ),
			),
			200
		);
	}

	/**
	 * Update theme data
	 *
	 * @param object $request .
	 */
	public function update_theme( $request ) {
		$global_tb_check = $this->global_column_checker();
		if ( ! $global_tb_check['status'] ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => implode( ', ', $global_tb_check['messages'] ),
				),
				400
			);
		}

		$info_details = $request->get_param( 'info_details' );
		$theme_json   = $request->get_param( 'theme_json' );
		$theme_id     = $request->get_param( 'theme_id' );

		$data_check = $this->theme_details_check( $info_details );

		if ( ! $data_check ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => esc_html__( 'Please fill all the required field!', 'gutenverse-themes-builder' ),
				),
				400
			);
		}

		$info_db = Database::instance()->theme_info;
		$current = gutenverse_themes_builder_get_theme_mode( $theme_id );

		/**If theme mode changed, backup the data */
		if ( ! empty( $current ) && $info_details['theme_mode'] !== $current ) {
			$this->save_templates( $theme_id );
		}
		$active_theme_id = get_option( 'gtb_active_theme_id' );
		if ( $theme_id === $active_theme_id ) {
			/**Get Current Global Data */
			$current_color    = Misc::get_color_settings();
			$globals          = new Global_Variable();
			$current_font     = $globals->get_global_variable( 'font' );
			$wp_active_theme  = wp_get_theme();
			$current_style_wp = WP_Theme_Json_Resolver::get_user_data_from_wp_global_styles( $wp_active_theme );
			$current_style    = json_decode( $current_style_wp['post_content'] );
		}

		/**Check if have global id*/
		$theme_data = $info_db->get_theme_data( $theme_id );
		$data       = $theme_data[0];
		$theme_info = maybe_unserialize( $data['theme_data'] );
		$global_id  = $data['global_id'];

		/**Check if using  import library option*/
		$import_library_option = $info_details['import_library_option'] ?? false;
		if ( $import_library_option ) {
			$current_globals = $this->create_update_default_global_colors( $theme_id );
			$current_style   = $current_globals['styles'];
			$current_color   = $current_globals['colors'];
			$current_font    = $this->create_update_default_global_fonts( $theme_id );
		}

		if ( ! $global_id ) {
			$global_db = Database::instance()->theme_globals;
			$global_data      = array(
				'title'      => $theme_info['title'] ? $theme_info['title'] : 'Global Theme',
				'file'       => '',
				'fonts'      => maybe_serialize( $current_font ),
				'colors'     => maybe_serialize( $current_color ),
				'styles'     => maybe_serialize( $current_style ),
			);

			$global_id = $global_db->create_data( $global_data );
			$data      = array(
				'global_id' => $global_id,
			);

			$info_db->update_data( $data, $theme_id );
		}

		if ( $theme_id === $active_theme_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 );
			if ( count( $wp_active_theme_data ) > 0 ) {
				$post_id = wp_update_post(
					array(
						'ID'           => $wp_active_theme_data['ID'],
						'post_content' => wp_json_encode( $current_style ),
					)
				);
			} else {
				$post_id = wp_insert_post(
					array(
						'post_title'   => 'Custom Styles',
						'post_name'    => 'wp-global-styles-' . get_stylesheet(),
						'post_status'  => 'publish',
						'post_type'    => 'wp_global_styles',
						'post_content' => wp_json_encode( $current_style ),
					)
				);
			}
			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' );
			}

			$google_fonts = array();
			foreach ( $current_font as $font ) {
				if ( isset( $font['font'] ) && ! empty( $font['font'] ) && 'google' === $font['font']['font']['type'] ) {
					$google_fonts[] = array(
						'label'  => $font['font']['font']['label'],
						'type'   => $font['font']['font']['type'],
						'value'  => $font['font']['font']['value'],
						'weight' => $font['font']['weight'],
					);
				}
			}
			$globals = new Global_Variable();
			$globals->set_global_variable(
				array(
					'fonts'      => $current_font,
					'colors'     => $current_color,
					'googlefont' => $google_fonts,
				)
			);
		}

		$data = array(
			'slug'       => $info_details['slug'],
			'theme_data' => maybe_serialize( $info_details ),
			'theme_json' => maybe_serialize( $theme_json ),
			'theme_mode' => $info_details['theme_mode'],
		);

		$info_db->update_data( $data, $theme_id );

		return new WP_REST_Response(
			array(
				'status'  => 'success',
				'message' => esc_html__( 'Update Theme Success', 'gutenverse-themes-builder' ),
			),
			200
		);
	}

	/**
	 * Create/update default global color
	 *
	 * @param mixed $theme_id .
	 */
	private function create_update_default_global_colors( $theme_id = false ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		WP_Filesystem();
		global $wp_filesystem;

		$color_json_data   = $wp_filesystem->get_contents( GUTENVERSE_THEMES_BUILDER_DIR . '/includes/data/default-global-color.json' );
		$default_color_arr = json_decode( $color_json_data, true );
		$current_color     = $default_color_arr;
		$theme             = wp_get_theme();
		$themedata         = WP_Theme_Json_Resolver::get_user_data_from_wp_global_styles( $theme );
		$current_data      = json_decode( $themedata['post_content'] );

		/**Check if it's update process */
		if ( $theme_id ) {
			$active_theme_id = get_option( 'gtb_active_theme_id' );
			$info_db         = Database::instance()->theme_info;
			$theme_data      = $info_db->get_theme_data( $theme_id );
			$data            = $theme_data[0];

			/**If it updating non-active theme use the data from their saved global */
			if ( $active_theme_id !== $theme_id ) {
				$global_id    = $data['global_id'];
				$global_db    = Database::instance()->theme_globals;
				$saved_global = $global_db->get_data( $global_id );

				if ( ! empty( $saved_global ) ) {
					$current_color = maybe_unserialize( $saved_global[0]['colors'] );
					$current_data  = maybe_unserialize( $saved_global[0]['styles'] );
				}
			} else {
				// Active theme case → prefer Misc, fallback to defaults.
				$current_color = ! empty( Misc::get_color_settings() ) ? Misc::get_color_settings() : $default_color_arr;
			}
			/**Add default color if not exist */
			foreach ( $default_color_arr as $def_color ) {
				$slug_without_prefix = str_replace( 'gutenverse-', '', $def_color['slug'] );
				if ( ! in_array( $def_color['slug'], array_column( $current_color, 'slug' ), true ) && ! in_array( $slug_without_prefix, array_column( $current_color, 'slug' ), true ) ) {
					$current_color[] = $def_color;
				}
			}
		}

		/**Update the current data color */
		$palette_custom = $current_data->settings->color->palette->custom ?? null;
		if ( null !== $palette_custom ) {
			$current_data->settings->color->palette->custom = $current_color;
		} else {
			$current_data = array(
				'settings'                    => array(
					'color' => array(
						'palette' => array(
							'custom' => $current_color,
						),
					),
				),
				'isGlobalStylesUserThemeJSON' => true,
				'version'                     => 3,
			);
		}
		return array(
			'styles' => $current_data,
			'colors' => $current_color,
		);
	}

	/**
	 * Creating/update default global fonts
	 *
	 * @param mixed $theme_id .
	 */
	private function create_update_default_global_fonts( $theme_id = false ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		WP_Filesystem();
		global $wp_filesystem;

		$font_json_data   = $wp_filesystem->get_contents( GUTENVERSE_THEMES_BUILDER_DIR . '/includes/data/default-global-font.json' );
		$default_font_arr = json_decode( $font_json_data, true );
		$current_fonts    = $default_font_arr;
		if ( $theme_id ) {
			$active_theme_id = get_option( 'gtb_active_theme_id' );
			$info_db         = Database::instance()->theme_info;
			$theme_data      = $info_db->get_theme_data( $theme_id );
			$data            = $theme_data[0];
			$globals         = new Global_Variable();
			$current_fonts   = $globals->get_global_variable( 'font' ) ? $globals->get_global_variable( 'font' ) : array();

			if ( $active_theme_id !== $theme_id ) {
				$global_id    = $data['global_id'];
				$global_db    = Database::instance()->theme_globals;
				$saved_global = $global_db->get_data( $global_id );
				if ( ! empty( $saved_global ) ) {
					$current_fonts = maybe_unserialize( $saved_global[0]['fonts'] );
				}
			}
			foreach ( $default_font_arr as $def_font ) {
				$id_without_prefix = str_replace( 'gutenverse-', '', $def_font['id'] );
				if ( ! in_array( $def_font['id'], array_column( $current_fonts, 'id' ), true ) && ! in_array( $id_without_prefix, array_column( $current_fonts, 'id' ), true ) ) {
					$current_fonts[] = $def_font;
				}
			}
		}
		return $current_fonts;
	}

	/**
	 * Get theme list
	 */
	public function get_theme_list() {
		$info_db = Database::instance()->theme_info;
		$data    = $info_db->get_all_data();
		$active  = get_option( 'gtb_active_theme_id' );

		foreach ( $data as &$theme ) {
			if ( ! empty( $theme['theme_data'] ) ) {
				$theme['theme_data'] = maybe_unserialize( $theme['theme_data'] );
			}
		}

		return array(
			'active' => $active,
			'data'   => $data,
		);
	}

	/**
	 * Get theme list Pagination
	 *
	 * @param object $request .
	 */
	public function get_theme_list_pagination( $request ) {
		$paged    = gutenverse_esc_data( $request->get_param( 'paged' ), 'int' );
		$num_post = gutenverse_esc_data( $request->get_param( 'num_post' ), 'integer' );
		$offset   = ( $paged - 1 ) * $num_post;

		$info_db = Database::instance()->theme_info;
		$data    = $info_db->get_pagination_data( $offset, $num_post );
		$active  = get_option( 'gtb_active_theme_id' );

		foreach ( $data['list'] as &$theme ) {
			if ( ! empty( $theme['theme_data'] ) ) {
				$theme['theme_data'] = maybe_unserialize( $theme['theme_data'] );
			}
		}
		$max_page = ceil( $data['total_data'] / $num_post );
		return array(
			'active'     => $active,
			'data'       => $data,
			'total_page' => $max_page,
		);
	}

	/**
	 * Get theme data
	 *
	 * @param object $request .
	 */
	public function get_theme_data( $request ) {
		$theme_id = ! empty( $request->get_param( 'id' ) ) ? $request->get_param( 'id' ) : get_option( 'gtb_active_theme_id' );
		$info_db  = Database::instance()->theme_info;
		$data     = $info_db->get_theme_data( $theme_id );

		$theme_data = array();

		foreach ( $data as $key => $theme ) {
			if ( 0 === $key ) {
				$theme_data['info_details'] = array(
					'theme_id' => $theme['theme_id'],
					'slug'     => $theme['slug'],
				);

				$metadata                   = maybe_unserialize( $theme['theme_data'] );
				$theme_data['info_details'] = array_merge( $theme_data['info_details'], $metadata );
				$theme_data['other']        = maybe_unserialize( $theme['other'] );
			}
		}

		return $theme_data;
	}

	/**
	 * Update theme data
	 *
	 * @param object $request .
	 */
	public function update_theme_other_data( $request ) {
		global $wpdb;
		try {
			$wpdb->query( 'START TRANSACTION' );
			$key          = $request->get_param( 'key' );
			$data_request = $request->get_param( 'data' );
			$theme_id     = get_option( 'gtb_active_theme_id' );
			$info_db      = Database::instance()->theme_info;
			$previous     = $info_db->get_theme_data( $theme_id );
			if ( ! empty( $previous ) ) {
				$other_data = maybe_unserialize( $previous[0]['other'] );

				if ( empty( $other_data ) ) {
					$other_data = array();
				}

				$other_data[ $key ] = $data_request;

				$data = array(
					'other' => maybe_serialize( $other_data ),
				);

				$info_db->update_data( $data, $theme_id );
			}
			$new_data = $info_db->get_theme_data( $theme_id );

			if ( 'usedTemplateMode' === $key ) {
				$this->change_template_content( $data_request, $theme_id );
			}
			$wpdb->query( 'COMMIT' );
			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => esc_html__( 'Update Theme Other Data Success', 'gutenverse-themes-builder' ),
					'data'    => maybe_unserialize( $new_data[0]['other'] ),
				),
				200
			);
		} catch ( \Throwable $th ) {
			$wpdb->query( 'ROLLBACK' );
			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => $th->getMessage(),
				),
				400
			);
		}
	}

	/**
	 * Change template content based on used template mode
	 *
	 * @param string $type .
	 * @param string $theme_id .
	 */
	public function change_template_content( $type, $theme_id ) {
		$theme_name = get_stylesheet();
		if ( 'none' === $type ) {
			$core_template_slug = array(
				'404',
				'archive',
				'author',
				'category',
				'home',
				'index',
				'search',
				'single',
				'singular',
				'tag',
				'front-page',
				'date',
				'page',
			);
			foreach ( $core_template_slug as $template_slug ) {
				$existing_template = get_page_by_path( $template_slug, OBJECT, 'wp_template' );
				if ( $existing_template ) {
					/** Delete the template */
					wp_delete_post( $existing_template->ID, true );
				}
			}
		} else {
			$templates_db   = Database::instance()->theme_templates;
			$except_types   = array( 'header', 'footer', 'custom_template', 'template_part' );
			$templates_data = $templates_db->get_data_except_some_type( $theme_id, $except_types, $type );
			foreach ( $templates_data as $template ) {
				$existing_template = get_page_by_path( $template['template_type'], OBJECT, 'wp_template' );
				$used_template     = get_block_template( $theme_name . '//' . $type . '-' . $template['template_type'] );
				$empty_content     = '<!-- wp:paragraph --><p></p><!-- /wp:paragraph -->';
				if ( $existing_template && $used_template && ! empty( $used_template->content ) && $used_template->content !== $empty_content ) {
					/** Update with new content */
					wp_update_post(
						array(
							'ID'           => $existing_template->ID,
							'post_content' => $used_template->content,
						)
					);

				} elseif ( ! $existing_template && $used_template && ! empty( $used_template->content ) && $used_template->content !== $empty_content ) {
					/** Create new template */
					wp_insert_post(
						array(
							'post_title'   => ucwords( str_replace( '-', ' ', $template['template_type'] ) ),
							'post_name'    => $template['template_type'],
							'post_type'    => 'wp_template',
							'post_status'  => 'publish',
							'post_content' => $used_template->content,
							'tax_input'    => array(
								'wp_theme' => array( $theme_name ),
							),
						)
					);
				}
			}
			$core_template_slug = array(
				'404',
				'archive',
				'author',
				'category',
				'home',
				'index',
				'search',
				'single',
				'singular',
				'tag',
				'front-page',
				'date',
				'page',
			);
			foreach ( $core_template_slug as $template_slug ) {
				if ( ! in_array( $template_slug, array_column( $templates_data, 'template_type' ), true ) ) {
					$existing_template = get_page_by_path( $template_slug, OBJECT, 'wp_template' );
					if ( $existing_template ) {
						/**  Delete the template */
						wp_delete_post( $existing_template->ID, true );
					}
				}
			}
		}
	}

	/**
	 * Reset theme
	 *
	 * @param string $theme_id .
	 */
	private function reset_theme( $theme_id = null ) {
		$theme_id      = empty( $theme_id ) ? get_option( 'gtb_active_theme_id' ) : $theme_id;
		$templates_db  = Database::instance()->theme_templates;
		$template_list = $templates_db->get_data( $theme_id );

		if ( ! empty( $template_list ) ) {
			foreach ( $template_list as $template_data ) {
				$template_name = strtolower( $template_data['category'] . '-' . $template_data['name'] );
				$template_type = in_array( $template_data['template_type'], gutenverse_themes_builder_parts(), true ) ? 'wp_template_part' : 'wp_template';

				$posts = get_posts(
					array(
						'post_type' => $template_type,
						'name'      => $template_name,
					)
				);

				foreach ( $posts as $post ) {
					wp_delete_post( $post->ID, true );
				}
			}
		}
	}

	/**
	 * Delete theme data
	 *
	 * @param object $request .
	 */
	public function delete_theme( $request ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		WP_Filesystem();
		global $wp_filesystem, $wpdb;

		try {
			/**Start the transaction */
			$wpdb->query( 'START TRANSACTION' );

			$theme_id = $request->get_param( 'theme_id' );

			$active_id = get_option( 'gtb_active_theme_id' );

			$this->reset_theme( $active_id );

			$info_db = Database::instance()->theme_info;
			$info_db->delete_data( $theme_id );

			$args = array(
				'post_type'      => 'gutenverse-pattern',
				'meta_query'     => array(
					array(
						'key'   => '_pattern_theme_id',
						'value' => $theme_id,
					),
				),
				'posts_per_page' => -1,
				'fields'         => 'ids',
			);

			$query = new WP_Query( $args );

			/**Check if any posts are found */
			if ( $query->have_posts() ) {
				foreach ( $query->posts as $post_id ) {
					/** Delete the post */
					wp_delete_post( $post_id, true );
				}
			}

			/**  Query attachments with the specific meta key and value */
			$args = array(
				'post_type'      => 'attachment',
				'post_status'    => 'inherit',
				'meta_query'     => array(
					array(
						'key'   => '_img_theme_id',
						'value' => $theme_id,
					),
				),
				'posts_per_page' => -1,
				'fields'         => 'ids',
			);

			$query = new WP_Query( $args );

			/**  Check if any attachments are found */
			if ( $query->have_posts() ) {
				foreach ( $query->posts as $attachment_id ) {
					/** Delete the attachment  */
					wp_delete_attachment( $attachment_id, true );
				}
			}

			if ( $active_id === $theme_id ) {
				update_option( 'gtb_active_theme_id', null );
			}

			$theme_folder = gutenverse_themes_builder_theme_folder_path( $theme_id );

			if ( is_dir( $theme_folder ) ) {
				$wp_filesystem->rmdir( $theme_folder );
			}

			$wpdb->query( 'COMMIT' );
			wp_reset_postdata();
			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => 'Delete Theme Success',
				),
				200
			);
		} catch ( Exception $e ) {
			$wpdb->query( 'ROLLBACK' );
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => $e->getMessage(),
				),
				400
			);
		}
	}

	/**
	 * Set active theme
	 *
	 * @param object $request .
	 */
	public function set_active_theme( $request ) {
		try {
			$theme_id   = $request->get_param( 'theme_id' );
			$current_id = get_option( 'gtb_active_theme_id' );

			$this->set_active_theme_global_data( $current_id, $theme_id );
			$this->save_templates( $current_id );

			update_option( 'gtb_active_theme_id', $theme_id );

			$theme_id   = get_option( 'gtb_active_theme_id' );
			$info_db    = Database::instance()->theme_info;
			$theme_data = $info_db->get_theme_data( $theme_id );
			$data       = $theme_data[0];
			$other      = maybe_unserialize( $data['other'] );
			if ( isset( $other['usedTemplateMode'] ) && ! empty( $other['usedTemplateMode'] ) && 'none' !== $other['usedTemplateMode'] ) {
				$this->change_template_content( $other['usedTemplateMode'], $theme_id );
			}
			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => 'Theme ' . $theme_id . ' Activated',
				),
				200
			);
		} catch ( \Throwable $th ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => $th->getMessage(),
				),
				400
			);
		}
	}

	/**
	 * Set Active Theme Global Data
	 *
	 * @param integer/string $current_id .
	 * @param integer/string $theme_id .
	 */
	private function set_active_theme_global_data( $current_id, $theme_id ) {
		$info_db   = Database::instance()->theme_info;
		$global_db = Database::instance()->theme_globals;
		$globals   = new Global_Variable();
		/**Save Global Data to current theme info */

		if ( $current_id ) {
			$current_theme_data = $info_db->get_theme_data( $current_id );
			$current_data       = $current_theme_data[0];
			$current_theme_info = maybe_unserialize( $current_data['theme_data'] );
			$current_global_id  = $current_data['global_id'];

			$wp_global_fonts = $globals->get_global_variable( 'font' );

			$wp_active_theme      = wp_get_theme();
			$wp_active_theme_data = WP_Theme_Json_Resolver::get_user_data_from_wp_global_styles( $wp_active_theme );
			$wp_global_data       = json_decode( $wp_active_theme_data['post_content'] );

			/**Get Current Global Color */
			if ( count( $wp_active_theme_data ) > 0 ) {
				$wp_global_color = ! empty( $wp_global_data ) && isset( $wp_global_data->settings ) ? $wp_global_data->settings->color->palette->custom : array();
			}

			/**Create or update global data */

			if ( ! isset( $current_global_id ) ) {
				$current_global_data = array(
					'title'  => $current_theme_info['title'] ? $current_theme_info['title'] : 'Global Theme',
					'file'   => '',
					'fonts'  => maybe_serialize( $wp_global_fonts ),
					'colors' => maybe_serialize( $wp_global_color ),
					'styles' => maybe_serialize( $wp_global_data ),
				);
				$global_id           = $global_db->create_data( $current_global_data );
				$info_db->update_data(
					array(
						'global_id'  => $global_id,
						'theme_data' => maybe_serialize( $current_theme_info ),
					),
					$current_id
				);
			} else {
				$current_global_data = array(
					'fonts'  => maybe_serialize( $wp_global_fonts ),
					'colors' => maybe_serialize( $wp_global_color ),
					'styles' => maybe_serialize( $wp_global_data ),
				);
				$where               = array(
					'id' => $current_global_id,
				);
				$global_db->update_data( $current_global_data, $where );
				$info_db->update_data(
					array(
						'theme_data' => maybe_serialize( $current_theme_info ),
					),
					$current_id
				);
			}

			if ( count( $wp_active_theme_data ) > 0 ) {
				wp_delete_post( $wp_active_theme_data['ID'], true );
			}
		}

		/**Get Activated Theme Global Data and Fonts */
		$activated_theme_data = $info_db->get_theme_data( $theme_id );
		$activated_data       = $activated_theme_data[0];
		$activated_theme_info = maybe_unserialize( $activated_data['theme_data'] );
		$activated_global_id  = $activated_data['global_id'];

		$style_format = array(
			'settings'                    => array(
				'color' => array(
					'palette' => array(
						'custom' => array(),
					),
				),
			),
			'isGlobalStylesUserThemeJSON' => true,
			'version'                     => 3,
		);

		/**Check if theme have global style saved */
		if ( ! isset( $activated_global_id ) ) {
			/**If not create and update the data */
			$activated_styles      = isset( $activated_theme_info['global_color'] ) ? maybe_unserialize( $activated_theme_info['global_color'] ) : $style_format;
			$activated_fonts       = isset( $activated_theme_info['global_font'] ) ? maybe_unserialize( $activated_theme_info['global_font'] ) : array();
			$activated_colors      = ! empty( $activated_styles ) && isset( $activated_styles->settings->color->palette->custom ) ? $activated_styles->settings->color->palette->custom : array();
			$activated_global_data = array(
				'title'  => $activated_theme_info['title'] ? $activated_theme_info['title'] : 'Global Theme',
				'file'   => '',
				'fonts'  => maybe_serialize( $activated_fonts ),
				'colors' => maybe_serialize( $activated_colors ),
				'styles' => maybe_serialize( $activated_styles ),
			);
			$global_id             = $global_db->create_data( $activated_global_data );
			$info_db->update_data(
				array(
					'global_id' => $global_id,
				),
				$theme_id
			);
		} else {
			/**If exist get the data */
			$activated_global_data = $global_db->get_data( $activated_global_id );
			if ( ! empty( $activated_global_data ) ) {
				$activated_colors = maybe_unserialize( $activated_global_data[0]['colors'] );
				$activated_fonts  = maybe_unserialize( $activated_global_data[0]['fonts'] );
				$activated_styles = maybe_unserialize( $activated_global_data[0]['styles'] );
			} else {
				$activated_colors = array();
				$activated_fonts  = array();
				$activated_styles = $style_format;
			}
		}

		$post_id = wp_insert_post(
			array(
				'post_title'   => 'Custom Styles',
				'post_name'    => 'wp-global-styles-' . get_stylesheet(),
				'post_status'  => 'publish',
				'post_type'    => 'wp_global_styles',
				'post_content' => wp_json_encode( $activated_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' );
		}

		$google_fonts = array();
		foreach ( $activated_fonts as $font ) {
			if ( isset( $font['font'] ) && ! empty( $font['font'] ) && 'google' === $font['font']['font']['type'] ) {
				$google_fonts[] = array(
					'label'  => $font['font']['font']['label'],
					'type'   => $font['font']['font']['type'],
					'value'  => $font['font']['font']['value'],
					'weight' => $font['font']['weight'],
				);
			}
		}
		$globals->set_global_variable(
			array(
				'fonts'      => $activated_fonts,
				'colors'     => $activated_colors,
				'googlefont' => $google_fonts,
			)
		);
	}

	/**
	 * Export Theme
	 */
	public function export_theme() {
		$result = new Export_Theme();
		return new WP_REST_Response(
			array(
				'file'  => $result->fileresult['fileurl'],
				'child' => $result->fileresult['child']['fileurl'] ?? '',
			),
			200
		);
	}

	/**
	 * ==================================================================================================================================
	 * PATTERNS APIs
	 * ==================================================================================================================================
	 */

	/**
	 * Create Pattern
	 *
	 * @param object $request .
	 */
	public function create_pattern( $request ) {
		$theme_id = get_option( 'gtb_active_theme_id' );

		if ( $theme_id ) {
			$slug     = gutenverse_esc_data( $request->get_param( 'slug' ) );
			$category = gutenverse_esc_data( $request->get_param( 'category' ) );
			$name     = gutenverse_esc_data( $request->get_param( 'name' ) );
			$sync     = gutenverse_esc_data( $request->get_param( 'sync' ), 'bool' );

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

			if ( null === $post_exists ) {
				$post_id = wp_insert_post(
					array(
						'post_title'  => $name,
						'post_name'   => $slug,
						'post_status' => 'publish',
						'post_type'   => 'gutenverse-pattern',
					)
				);

				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 );

				return new WP_REST_Response(
					array(
						'status'  => 'success',
						'message' => 'Success Creating Pattern',
					),
					200
				);
			} else {
				return new WP_REST_Response(
					array(
						'status'  => 'success',
						'message' => esc_html__( 'Slug Already Exist', 'gutenverse-themes-builder' ),
					),
					400
				);
			}
		} else {
			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => esc_html__( 'Theme not defined', 'gutenverse-themes-builder' ),
				),
				400
			);
		}
	}

	/**
	 * Edit Pattern
	 *
	 * @param object $request .
	 */
	public function edit_pattern( $request ) {
		$theme_id = get_option( 'gtb_active_theme_id' );

		if ( $theme_id ) {
			$id       = gutenverse_esc_data( $request->get_param( 'id' ), 'int' );
			$slug     = gutenverse_esc_data( $request->get_param( 'slug' ) );
			$category = gutenverse_esc_data( $request->get_param( 'category' ) );
			$name     = gutenverse_esc_data( $request->get_param( 'name' ) );
			$sync     = gutenverse_esc_data( $request->get_param( 'sync' ), 'bool' );

			$post_exists = get_page_by_path( $slug, OBJECT, 'gutenverse-pattern' );
			if ( empty( $post_exists ) || $id === $post_exists->ID ) {
				$post_id = wp_update_post(
					array(
						'ID'          => $id,
						'post_title'  => $name,
						'post_name'   => $slug,
						'post_status' => 'publish',
						'post_type'   => 'gutenverse-pattern',

					)
				);

				update_post_meta( $post_id, '_pattern_category', $category );
				update_post_meta( $post_id, '_pattern_sync', $sync );

				return new WP_REST_Response(
					array(
						'status'  => 'success',
						'message' => 'Success Editing Pattern',
					),
					200
				);
			} else {
				return new WP_REST_Response(
					array(
						'status'  => 'success',
						'message' => esc_html__( 'Slug Already Exist', 'gutenverse-themes-builder' ),
					),
					400
				);
			}
		} else {
			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => esc_html__( 'Theme not defined', 'gutenverse-themes-builder' ),
				),
				400
			);
		}
	}

	/**
	 * Search Pattern.
	 *
	 * @param object $request Request Object.
	 *
	 * @return array
	 */
	public function search_pattern( $request ) {
		$theme_id = get_option( 'gtb_active_theme_id' );

		if ( $theme_id ) {
			$search = $request->get_param( 'search' );
			$paged  = $request->get_param( 'paged' );
			$result = array();

			add_filter(
				'posts_where',
				function ( $where ) use ( $search ) {
					global $wpdb;
					$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $wpdb->esc_like( $search ) ) . '%\'';
					return $where;
				}
			);

			$patterns = new \WP_Query(
				array(
					'post_type'      => 'gutenverse-pattern',
					'meta_query' => array( //phpcs:ignore
						array(
							'key'     => '_pattern_theme_id',
							'value'   => $theme_id,
							'compare' => '===',
						),
					),
					'posts_per_page' => 9,
					'paged'          => ! empty( $paged ) ? $paged : 1,
				)
			);

			foreach ( $patterns->posts as $post ) {
				$result[] = array(
					'value'   => $post->post_name,
					'label'   => $post->post_title,
					'content' => $post->post_content,
				);
			}

			return array(
				'list'  => $result,
				'total' => $patterns->max_num_pages,
			);
		}
	}

	/**
	 * Get Pattern Data.
	 *
	 * @param object $request Request Object.
	 *
	 * @return string
	 */
	public function get_pattern_data( $request ) {
		$id   = $request->get_param( 'id' );
		$post = get_post( $id );

		if ( $post ) {
			$pattern_category = get_post_meta( $id, '_pattern_category', true );
			$pattern_sync     = get_post_meta( $id, '_pattern_sync', true );
			return array(
				'slug'     => $post->post_name,
				'name'     => $post->post_title,
				'category' => $pattern_category,
				'sync'     => $pattern_sync,
			);
		} else {
			return false;
		}
	}

	/**
	 * Get Pattern.
	 *
	 * @param object $request Request Object.
	 *
	 * @return string
	 */
	public function get_pattern( $request ) {
		$slug = $request->get_param( 'slug' );
		$post = get_page_by_path( $slug, OBJECT, 'gutenverse-pattern' );

		if ( $post ) {
			return $post->post_content;
		} else {
			return false;
		}
	}

	/**
	 * Get Pattern List.
	 *
	 * @param object $request Request Object.
	 *
	 * @return string
	 */
	public function get_pattern_list( $request ) {
		$paged    = $request->get_param( 'paged' );
		$paged    = empty( $paged ) ? 1 : $paged;
		$theme_id = get_option( 'gtb_active_theme_id' );
		$patterns = new \WP_Query(
			array(
				'post_type'      => 'gutenverse-pattern',
				'paged'          => $paged,
				'posts_per_page' => -1,
				'meta_query' => array( //phpcs:ignore
					array(
						'key'     => '_pattern_theme_id',
						'value'   => $theme_id,
						'compare' => '===',
					),
				),
			)
		);

		return $patterns->posts;
	}

	/**
	 * Get Pattern List.
	 *
	 * @param object $request Request Object.
	 *
	 * @return object
	 */
	public function get_pattern_list_pagination( $request ) {
		$paged    = gutenverse_esc_data( $request->get_param( 'paged' ), 'int' );
		$paged    = empty( $paged ) ? 1 : $paged;
		$num_post = gutenverse_esc_data( $request->get_param( 'num_post' ), 'integer' );
		$num_post = empty( $num_post ) ? 10 : $num_post;
		$theme_id = get_option( 'gtb_active_theme_id' );
		$patterns = new \WP_Query(
			array(
				'post_type'      => 'gutenverse-pattern',
				'paged'          => $paged,
				'posts_per_page' => $num_post,
				'meta_query' => array( //phpcs:ignore
					array(
						'key'     => '_pattern_theme_id',
						'value'   => $theme_id,
						'compare' => '===',
					),
				),
			)
		);
		$posts    = array();
		if ( $patterns->have_posts() ) {
			foreach ( $patterns->posts as $pattern ) {
				$pattern->category = get_post_meta( $pattern->ID, '_pattern_category', true );
				$posts[]           = $pattern;
			}
		}
		return (object) array(
			'patterns'    => $posts,
			'total_page'  => $patterns->max_num_pages,
			'total_posts' => $patterns->found_posts,
		);
	}

	/**
	 * Delete Pattern
	 *
	 * @param object $request Request Object.
	 *
	 * @return array
	 */
	public function delete_pattern( $request ) {
		try {
			$pattern_id = $request->get_param( 'pattern_id' );

			if ( ! empty( $pattern_id ) ) {
				wp_delete_post( $pattern_id, true );
				return new WP_REST_Response(
					array(
						'status'  => 'success',
						'message' => 'Delete Pattern Success',
					),
					200
				);
			}
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => 'Could not Find Pattern',
				),
				404
			);
		} catch ( \Throwable $th ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => $th->getMessage(),
				),
				400
			);
		}
	}

	/**
	 * ==================================================================================================================================
	 * ASSETS APIs
	 * ==================================================================================================================================
	 */

	/**
	 * Get Asset List.
	 *
	 * @param object $request .
	 *
	 * @return object
	 */
	public function get_asset_list( $request ) {
		$paged    = gutenverse_esc_data( $request->get_param( 'paged' ), 'int' );
		$paged    = empty( $paged ) ? 1 : $paged;
		$num_post = gutenverse_esc_data( $request->get_param( 'num_post' ), 'integer' );
		$num_post = empty( $num_post ) ? 10 : $num_post;
		$offset   = ( $paged - 1 ) * $num_post;

		$assets_db = Database::instance()->theme_assets;
		$active    = get_option( 'gtb_active_theme_id' );
		$data      = $assets_db->get_pagination_data( $active, $offset, $num_post );

		$max_page = ceil( $data['total_data'] / $num_post );
		return array(
			'data'       => $data,
			'total_page' => $max_page,
		);
	}

	/**
	 * Update theme data
	 *
	 * @param object $request .
	 */
	public function update_asset( $request ) {
		$id      = $request->get_param( 'id' );
		$handler = $request->get_param( 'handler' );
		$type    = $request->get_param( 'type' );
		$enqueue = $request->get_param( 'enqueue' );

		if ( empty( $id ) || empty( $handler ) || empty( $type ) || empty( $enqueue ) ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => esc_html__( 'Please fill all the required field!', 'gutenverse-themes-builder' ),
				),
				400
			);
		}

		$preset     = $request->get_param( 'preset' );
		$media_type = $request->get_param( 'media_type' );
		$content    = $request->get_param( 'content' );
		$assets_db  = Database::instance()->theme_assets;

		$assets_db->update_data(
			array(
				'handler'    => $handler,
				'type'       => $type,
				'enqueue'    => $enqueue,
				'preset'     => $preset,
				'media_type' => $media_type,
				'content'    => $content,
			),
			array(
				'id' => $id,
			)
		);

		$this->write_asset( $media_type, $type, $handler, $content );
		return new WP_REST_Response(
			array(
				'status'  => 'success',
				'message' => esc_html__( 'Success Updating Asset', 'gutenverse-themes-builder' ),
				'data'    => $this->get_asset_list( $request ),
			),
			200
		);
	}

	/**
	 * Create Assets
	 *
	 * @param object $request .
	 */
	public function create_asset( $request ) {
		$handler = $request->get_param( 'handler' );
		$type    = $request->get_param( 'type' );
		$enqueue = $request->get_param( 'enqueue' );

		if ( empty( $handler ) || empty( $type ) || empty( $enqueue ) ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => esc_html__( 'Please fill all the required field!', 'gutenverse-themes-builder' ),
				),
				400
			);
		}

		$preset     = $request->get_param( 'preset' );
		$media_type = $request->get_param( 'media_type' );
		$content    = $request->get_param( 'content' );
		$active     = get_option( 'gtb_active_theme_id' );
		$assets_db  = Database::instance()->theme_assets;

		$result = $assets_db->create_data(
			array(
				'handler'    => $handler,
				'type'       => $type,
				'enqueue'    => $enqueue,
				'media_type' => $media_type,
				'content'    => $content,
				'preset'     => $preset,
				'theme_id'   => $active,
			)
		);

		if ( $result ) {
			$this->write_asset( $media_type, $type, $handler, $content );
			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => esc_html__( 'Success Creating Asset', 'gutenverse-themes-builder' ),
					'data'    => $this->get_asset_list( $request ),
				),
				200
			);
		} else {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => esc_html__( 'Failed Creating Asset', 'gutenverse-themes-builder' ),
				),
				400
			);
		}
	}

	/**
	 * Write File Directly.
	 *
	 * @param string $media_type Media Type.
	 * @param string $type Type.
	 * @param string $handler Handler.
	 * @param string $content Content.
	 */
	public function write_asset( $media_type, $type, $handler, $content ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		WP_Filesystem();
		global $wp_filesystem;

		if ( 'content' === $media_type ) {
			$folder = gutenverse_themes_builder_theme_folder_path() . '/assets/' . $type;
			$file   = $folder . '/' . $handler . '.' . $type;

			$this->check_directory( $folder );

			if ( 'css' === $type ) {
				$content = '.editor-styles-wrapper .wp-block.no-margin { margin-top: 0; margin-bottom: 0; } ' . $content;
			}

			$wp_filesystem->put_contents(
				$file,
				$content,
				FS_CHMOD_FILE
			);
		}
	}

	/**
	 * Delete Assets
	 *
	 * @param object $request .
	 */
	public function delete_asset( $request ) {
		try {
			$assets_db = Database::instance()->theme_assets;
			$id        = $request->get_param( 'id' );

			$assets_db->delete_data(
				array( 'id' => $id )
			);

			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => esc_html__( 'Success Deleting Asset', 'gutenverse-themes-builder' ),
					'data'    => $this->get_asset_list( $request ),
				),
				200
			);
		} catch ( \Throwable $th ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => $th->getMessage(),
				),
				400
			);
		}
	}


	/**
	 * ==================================================================================================================================
	 * TEMPLATES APIs
	 * ==================================================================================================================================
	 */

	/**
	 * Get template list
	 *
	 * @return array
	 */
	public function get_template_list() {
		$theme_id = get_option( 'gtb_active_theme_id' );

		if ( $theme_id ) {
			$templates_db       = Database::instance()->theme_templates;
			$templates_data     = $templates_db->get_data( $theme_id );
			$info_db            = Database::instance()->theme_info;
			$theme_data         = $info_db->get_theme_data( $theme_id );
			$data               = $theme_data[0];
			$other              = maybe_unserialize( $data['other'] );
			$used_template_mode = null;
			if ( isset( $other['usedTemplateMode'] ) ) {
				$used_template_mode = $other['usedTemplateMode'];
			}

			return array(
				'mode'               => gutenverse_themes_builder_get_theme_mode( $theme_id ),
				'data'               => $templates_data,
				'used_template_mode' => $used_template_mode,
			);
		}

		return false;
	}

	/**
	 * Get template list search
	 *
	 * @param object $request .
	 *
	 * @return array
	 */
	public function get_template_list_search( $request ) {
		$theme_id = get_option( 'gtb_active_theme_id' );
		$search   = gutenverse_esc_data( $request->get_param( 'search' ), 'string' );
		$category = gutenverse_esc_data( $request->get_param( 'category' ), 'string' );

		if ( $theme_id ) {
			$templates_db   = Database::instance()->theme_templates;
			$templates_data = $templates_db->get_data_on_search( $theme_id, $category, $search );
			return array(
				'data' => $templates_data,
			);
		}

		return false;
	}


	/**
	 * Create template
	 *
	 * @param object $request .
	 */
	public function create_template( $request ) {
		$template_data  = $request->get_param( 'template_data' );
		$theme_id       = get_option( 'gtb_active_theme_id' );
		$allow_template = gutenverse_themes_builder_check_theme_mode( $template_data['category'], $theme_id );

		if ( ! empty( $template_data ) && $theme_id && $allow_template ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
			WP_Filesystem();
			global $wp_filesystem;

			$theme_dir       = gutenverse_themes_builder_theme_folder_path();
			$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   = strtolower( str_replace( ' ', '-', $template_data['name'] ) );
			$file_path       = $category_folder . '/' . $template_type . '/' . $template_name . '.html';

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

			$empty_content = '<!-- wp:paragraph --><p></p><!-- /wp:paragraph -->';

			$wp_filesystem->put_contents(
				$file_path,
				$empty_content,
				FS_CHMOD_FILE
			);

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

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

			$templates_db->create_data( $data );
			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => esc_html__( 'Create Template Success', 'gutenverse-themes-builder' ),
					'data'    => $this->get_template_list(),
				),
				200
			);
		}

		return new WP_REST_Response(
			array(
				'status'  => 'failed',
				'message' => esc_html__( 'Failed Creating Template!', 'gutenverse-themes-builder' ),
			),
			400
		);
	}

	/**
	 * Reset theme
	 *
	 * @param string $theme_id .
	 */
	private function save_templates( $theme_id ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		WP_Filesystem();
		global $wp_filesystem;

		$templates_db      = Database::instance()->theme_templates;
		$templates_data    = $templates_db->get_data( $theme_id );
		$template_dir      = trailingslashit( wp_upload_dir()['basedir'] ) . '/gtb-' . $theme_id . '/';
		$html_content      = array();
		$templates_content = get_block_templates(array(), 'wp_template'); // phpcs:ignore
		$parts_content     = get_block_templates(array(), 'wp_template_part'); // phpcs:ignore

		foreach ( $templates_content as $template ) {
			$html_content[ $template->slug ] = $template->content;
		}

		foreach ( $parts_content as $part ) {
			$html_content[ $part->slug ] = $part->content;
		}

		foreach ( $templates_data as $template ) {
			$template_type = in_array( $template['template_type'], gutenverse_themes_builder_parts(), true ) ? 'parts' : 'templates';
			$template_name = strtolower( str_replace( ' ', '-', $template['name'] ) );
			$file_dir      = $template_dir . '/' . $template['category'] . '/' . $template_type . '/' . $template_name . '.html';

			if ( file_exists( $file_dir ) ) {

				$slug_key = strtolower( $template['category'] . '-' . $template_name );
				if ( ! empty( $html_content[ $slug_key ] ) ) {
					$content = $html_content[ $slug_key ];

					$wp_filesystem->put_contents(
						$file_dir,
						$content,
						FS_CHMOD_FILE
					);
				}
			}
		}

		$this->reset_theme();
	}

	/**
	 * Delete template
	 *
	 * @param object $request .
	 */
	public function delete_template( $request ) {
		$template_data = $request->get_param( 'template_data' );

		/**
		 * Create theme folder & files
		 */
		if ( ! empty( $template_data ) ) {
			$theme_dir       = gutenverse_themes_builder_theme_folder_path();
			$templates_db    = Database::instance()->theme_templates;
			$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   = strtolower( str_replace( ' ', '-', $template_data['name'] ) );
			$file_path       = $category_folder . '/' . $template_type . '/' . $template_name . '.html';
			if ( $template_data['id'] ) {
				$templates_db->delete_data(
					array( 'id' => $template_data['id'] )
				);

				if ( file_exists( $file_path ) ) {
					$post_type = in_array( $template_data['template_type'], gutenverse_themes_builder_parts(), true ) ? 'wp_template_part' : 'wp_template';
					$post_name = strtolower( $template_data['category'] . '-' . $template_data['name'] );

					$posts = get_posts(
						array(
							'post_type' => $post_type,
							'name'      => $post_name,
						)
					);

					foreach ( $posts as $post ) {
						wp_delete_post( $post->ID, true );
					}

					wp_delete_file( $file_path );
				}
			}

			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => esc_html__( 'Delete Template Success', 'gutenverse-themes-builder' ),
					'data'    => $this->get_template_list(),
				),
				200
			);
		}

		return new WP_REST_Response(
			array(
				'status'  => 'failed',
				'message' => esc_html__( 'Failed Deleting Template!', 'gutenverse-themes-builder' ),
			),
			400
		);
	}

	/**
	 * ==================================================================================================================================
	 * OTHERS
	 * ==================================================================================================================================
	 */

	/**
	 * Generarte UID
	 *
	 * @param int $length .
	 */
	private function generate_uid( $length = 5 ) {
		return bin2hex( random_bytes( $length ) );
	}

	/**
	 * Get JSON data from a file.
	 *
	 * @param int $id .
	 *
	 * @return object|array
	 */
	private function get_file_json_data( $id ) {
		if ( ! isset( $id ) ) {
			return array();
		}

		$filepath = wp_get_attachment_url( $id );
		$file     = wp_remote_get( $filepath );
		$content  = '';

		if ( ! is_wp_error( $file ) ) {
			$content = wp_remote_retrieve_body( $file );
		}

		return json_decode( $content );
	}

	/**
	 * 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 );
		}
	}

	/**
	 * Get Page List
	 *
	 * @param object $request .
	 *
	 * @return object
	 */
	public function get_page_list( $request ) {
		$paged    = gutenverse_esc_data( $request->get_param( 'paged' ), 'int' );
		$paged    = empty( $paged ) ? 1 : $paged;
		$num_post = gutenverse_esc_data( $request->get_param( 'num_post' ), 'integer' );
		$num_post = empty( $num_post ) ? 10 : $num_post;
		$theme_id = get_option( 'gtb_active_theme_id' );

		$pages = new \WP_Query(
			array(
				'post_type'      => 'page',
				'paged'          => $paged,
				'posts_per_page' => $num_post,
				'meta_query' => array( //phpcs:ignore
					array(
						'key'     => '_gtb_page_theme_id',
						'value'   => $theme_id,
						'compare' => '===',
					),
				),
				'meta_key'       => '_gtb_page_order',
				'orderby'        => 'meta_value_num',
				'order'          => 'ASC',
			)
		);

		$data = array();
		if ( $pages->have_posts() ) {
			foreach ( $pages->posts as $post ) {
				$template          = get_post_meta( $post->ID, '_wp_page_template', true );
				$page_preview      = get_post_meta( $post->ID, '_gtb_page_preview', true );
				$page_image_id     = get_post_meta( $post->ID, '_gtb_page_image', true );
				$is_homepage       = get_post_meta( $post->ID, '_gtb_page_is_homepage', true );
				$order             = get_post_meta( $post->ID, '_gtb_page_order', true );
				$page_image        = (object) array(
					'url' => wp_get_attachment_url( $page_image_id ),
					'id'  => $page_image_id,
				);
				$template_page_arr = explode( '-', $template );
				$template_page     = '';
				if ( 'gutenverse' === $template_page_arr[0] ) {
					$sliced_array  = array_slice( $template_page_arr, 1 );
					$template_page = implode( '-', $sliced_array );
				} else {
					$template_page = $template;
				}
				$data[] = array(
					'ID'           => $post->ID,
					'post_name'    => $post->post_name,
					'post_title'   => $post->post_title,
					'template'     => $template_page,
					'page_preview' => $page_preview ? $page_preview : '',
					'page_image'   => $page_image,
					'is_homepage'  => $is_homepage,
					'order'        => $order,
				);
			}
		}

		return (object) array(
			'pages'       => $data,
			'total_page'  => $pages->max_num_pages,
			'total_posts' => $pages->found_posts,
		);
	}

	/**
	 * Create Page
	 *
	 * @param object $request .
	 */
	public function create_pages( $request ) {
		$name        = gutenverse_esc_data( $request->get_param( 'name' ), 'string' );
		$template    = gutenverse_esc_data( $request->get_param( 'template' ), 'string' );
		$category    = gutenverse_esc_data( $request->get_param( 'category' ), 'string' );
		$preview     = gutenverse_esc_data( $request->get_param( 'pagePreview' ), 'string' );
		$image       = gutenverse_esc_data( $request->get_param( 'pageImage' ), 'int' );
		$is_homepage = gutenverse_esc_data( $request->get_param( 'isHomepage' ), 'boolean' );
		$order       = gutenverse_esc_data( $request->get_param( 'order' ), 'int' );
		$theme_id    = get_option( 'gtb_active_theme_id' );

		if ( empty( $name ) || empty( $preview ) || empty( $image ) ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => 'Creating Page Failed!',
				),
				400
			);
		}
		if ( $theme_id ) {
			$page    = array(
				'post_type'    => 'page',
				'post_title'   => $name,
				'post_content' => '',
				'post_status'  => 'publish',
				'post_author'  => get_current_user_id(),
				'meta_input'   => array(
					'_wp_page_template'     => $template,
					'_gtb_page_category'    => $category,
					'_gtb_page_theme_id'    => $theme_id,
					'_gtb_page_preview'     => $preview,
					'_gtb_page_image'       => $image,
					'_gtb_page_is_homepage' => $is_homepage,
					'_gtb_page_order'       => $order,
				),
			);
			$success = wp_insert_post( $page );
			if ( ! $success ) {
				return new WP_REST_Response(
					array(
						'status'  => 'failed',
						'message' => 'Creating Page Failed!',
					),
					400
				);
			}
			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => 'Creating Page Success!',
				),
				200
			);
		}
	}

	/**
	 * Delete Page
	 *
	 * @param object $request .
	 */
	public function delete_page( $request ) {
		$id         = gutenverse_esc_data( $request->get_param( 'id' ), 'string' );
		$is_deleted = wp_delete_post( $id, true );
		if ( ! $is_deleted ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => 'Deleting Page Failed!',
				),
				400
			);
		}
		return new WP_REST_Response(
			array(
				'status'  => 'success',
				'message' => 'Deleting Page Success!',
			),
			200
		);
	}
	/**
	 * Update Page
	 *
	 * @param object $request .
	 */
	public function update_page( $request ) {
		$name        = gutenverse_esc_data( $request->get_param( 'name' ), 'string' );
		$template    = gutenverse_esc_data( $request->get_param( 'template' ), 'string' );
		$category    = gutenverse_esc_data( $request->get_param( 'category' ), 'string' );
		$id          = gutenverse_esc_data( $request->get_param( 'id' ), 'string' );
		$preview     = gutenverse_esc_data( $request->get_param( 'pagePreview' ), 'string' );
		$image       = gutenverse_esc_data( $request->get_param( 'pageImage' ), 'int' );
		$is_homepage = gutenverse_esc_data( $request->get_param( 'isHomepage' ), 'boolean' );
		$order       = gutenverse_esc_data( $request->get_param( 'order' ), 'int' );
		$theme_id    = get_option( 'gtb_active_theme_id' );

		if ( empty( $name ) ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => 'Creating Page Failed!',
				),
				400
			);
		}
		if ( $theme_id ) {
			$page    = array(
				'ID'            => $id,
				'post_title'    => $name,
				'post_author'   => get_current_user_id(),
				'page_template' => $template,
				'meta_input'    => array(
					'_gtb_page_category'    => $category,
					'_gtb_page_preview'     => $preview,
					'_gtb_page_image'       => $image,
					'_gtb_page_is_homepage' => $is_homepage,
					'_gtb_page_order'       => $order,
				),
			);
			$success = wp_update_post( $page );
			if ( ! $success ) {
				return new WP_REST_Response(
					array(
						'status'  => 'failed',
						'message' => 'Creating Page Failed!',
					),
					400
				);
			}
			return new WP_REST_Response(
				array(
					'status'  => 'success',
					'message' => 'Creating Page Success!',
				),
				200
			);
		}
	}

	/**
	 * Essence Proxy
	 *
	 * @param object $request .
	 */
	public function essence_proxy( $request ) {
		$url      = gutenverse_esc_data( $request->get_param( 'url' ) );
		$body     = gutenverse_esc_data( (array) $request->get_param( 'body' ), 'array' );
		$method   = gutenverse_esc_data( $request->get_param( 'method' ) );
		$response = wp_remote_request(
			$url,
			array(
				'method'  => strtoupper( $method ),
				'body'    => $body ? json_encode( $body ) : $body,
				'headers' => array(
					'Content-Type' => 'application/json',
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return new WP_REST_Response(
				array(
					'active' => false,
					'status' => 'failed',
				),
				400
			);
		}

		$external_api_body = wp_remote_retrieve_body( $response );
		return rest_ensure_response( json_decode( $external_api_body ) );
	}

	/**
	 * Export Backup Data
	 */
	public function export_backup_data() {
		$result = new Export_Backup();
		return new WP_REST_Response(
			array(
				'file'  => $result->fileresult['fileurl'],
				'child' => $result->fileresult['child']['fileurl'] ?? '',
			),
			200
		);
	}

	/**
	 * Import Backup Data
	 *
	 * @param object $request .
	 */
	public function import_backup_data( $request ) {
		$file_id = gutenverse_esc_data( $request->get_param( 'file_id' ) );
		new Import_Backup( $file_id );

		return new WP_REST_Response(
			true,
			200
		);
	}

	/**
	 * Install Basic Theme Theme Builder
	 *
	 * @return WP_REST_Response
	 */
	public function basic_theme_install() {
		// 1️⃣ Call the API to get the theme download URL
		$api_url  = GUTENVERSE_FRAMEWORK_SERVER_URL . '/wp-json/gutenverse-server/v1/extra-component/detail';
		$response = wp_remote_post(
			$api_url,
			array(
				'timeout' => 30,
				'headers' => array(
					'Content-Type' => 'application/json',
				),
				'body'    => wp_json_encode(
					array(
						'slug' => 'gutenverse-basic',
					)
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => 'Failed to contact API',
				),
				400
			);
		}

		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );
		if ( empty( $data['data']['component_file'] ) ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => 'No download URL found in API response',
				),
				400
			);
		}

		$theme_zip_url = $data['data']['component_file'];

		// 2️⃣ Download and install the theme
		include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		include_once ABSPATH . 'wp-admin/includes/theme.php';
		include_once ABSPATH . 'wp-admin/includes/file.php';
		include_once ABSPATH . 'wp-admin/includes/misc.php';

		// Prepare filesystem.
		WP_Filesystem();
		$upgrader = new Theme_Upgrader( new Automatic_Upgrader_Skin() );

		// Get theme slug (theme folder name) from ZIP URL.
		$theme_slug = basename( $theme_zip_url, '.zip' );

		// Check if theme is already installed.
		$themes = wp_get_themes();
		if ( isset( $themes[ $theme_slug ] ) ) {
			// Already installed — just activate.
			switch_theme( $theme_slug );
			return "Theme '$theme_slug' activated.";
		}

		// Install new theme.
		$result = $upgrader->install( $theme_zip_url );

		if ( is_wp_error( $result ) || ! $result ) {
			return new WP_REST_Response(
				array(
					'status'  => 'failed',
					'message' => 'Theme installation failed.',
				),
				400
			);
		}

		// 3️⃣ After installation, get installed theme folder
		$theme_info = $upgrader->theme_info();
		if ( $theme_info ) {
			$theme_slug = $theme_info->get_stylesheet();
		}

		// 4️⃣ Activate the theme
		switch_theme( $theme_slug );

		return new WP_REST_Response(
			array(
				'status'  => 'success',
				'message' => "Theme '$theme_slug' installed and activated successfully.",
			),
			200
		);
	}
}
