<?php
/**
 * Export Init
 *
 * @author Jegstudio
 * @since 1.0.0
 * @package gutenverse-themes-builder
 */

namespace Gutenverse_Themes_Builder\Export;

use Gutenverse_Themes_Builder\Builder_Page;
use Gutenverse_Themes_Builder\Database\Database;

/**
 * Class Export Init
 *
 * @package gutenverse-themes-builder
 */
class Export_Init {
	/**
	 * Create class-init.php File
	 *
	 * @param object  $system .
	 * @param array   $data .
	 * @param string  $theme_id .
	 * @param boolean $include_global_import .
	 */
	public static function create_init_php( $system, $data, $theme_id, $include_global_import ) {
		$instance       = new self();
		$theme_data     = maybe_unserialize( $data['theme_data'] );
		$templates_db   = Database::instance()->theme_templates;
		$templates_data = $templates_db->get_data( $theme_id );
		$class_dir      = gutenverse_themes_builder_theme_built_path() . 'inc/class';

		if ( ! is_dir( $class_dir ) ) {
			wp_mkdir_p( $class_dir );
		}

		if ( ! is_dir( gutenverse_themes_builder_theme_built_path() . 'assets/img' ) ) {
			wp_mkdir_p( gutenverse_themes_builder_theme_built_path() . 'assets/img' );
		}

		// Take which placeholder.
		$placeholder = $system->get_contents( GUTENVERSE_THEMES_BUILDER_DIR . '/includes/data/init-default.txt' );
		$placeholder = str_replace( '{{namespace}}', Misc::get_namespace( $theme_data['slug'] ), $placeholder );
		$placeholder = str_replace( '{{slug}}', $theme_data['slug'], $placeholder );
		$placeholder = str_replace( '{{title}}', $theme_data['title'], $placeholder );
		$placeholder = str_replace( '{{description}}', isset( $theme_data['description'] ) ? str_replace( "'", "\'", $theme_data['description'] ) : '', $placeholder );
		$placeholder = str_replace( '{{author_name}}', $theme_data['author_name'], $placeholder );
		$placeholder = str_replace( '{{constant}}', Misc::get_constant_name( $theme_data['slug'] ), $placeholder );

		$other                           = maybe_unserialize( $data['other'] );
		$config                          = array();
		$additional_filter               = array();
		$additional_admin_enqueue_script = array();
		if ( 'gutenverse-only' === $data['theme_mode'] ) {
			$config[]            = "'isThemeforest' => true,";
			$additional_filter[] = "add_filter( 'gutenverse_show_theme_list', '__return_false' );";
		}
		if ( $include_global_import ) {
			$additional_filter[] = "add_filter( 'gutenverse_themes_support_section_global_style', '__return_true' );";
		}

		// Build dashboard.
		$placeholder  = $instance->build_dashboard( $placeholder );
		$required     = $instance->get_required_plugin( $other );
		$placeholder  = str_replace( '{{plugins_required}}', join( ",\n\t\t\t\t", $required ), $placeholder );
		$add_class    = array();
		$assigns      = array();
		$data_page    = array();
		$theme_logo   = 'false';
		$docs_link    = isset( $other['dashboard']['docs_link'] ) ? $other['dashboard']['docs_link'] : '';
		$support_link = isset( $other['dashboard']['support_link'] ) ? $other['dashboard']['support_link'] : '';

		if ( 'gutenverse-only' === $data['theme_mode'] ) {
			if ( isset( $other['dashboard']['logo'] ) ) {
				$image_data = wp_remote_get( $other['dashboard']['logo']['url'], array( 'sslverify' => true ) );
				$thumbnail  = gutenverse_themes_builder_theme_built_path() . 'assets/img/' . $other['dashboard']['logo']['filename'];
				$theme_logo = "trailingslashit( get_template_directory_uri() ) . 'assets/img/" . $other['dashboard']['logo']['filename'] . "'";
				if ( ! is_wp_error( $image_data ) ) {
					$system->put_contents(
						$thumbnail,
						$image_data['body'],
						FS_CHMOD_FILE
					);
				}
			}

			$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' => '===',
						),
					),
				)
			);
			if ( $pages->have_posts() ) {
				foreach ( $pages->posts as $post ) {
					$image_id   = get_post_meta( $post->ID, '_gtb_page_image', true );
					$image_url  = wp_get_attachment_url( $image_id );
					$image_data = wp_remote_get( $image_url, array( 'sslverify' => true ) );
					$file_path  = get_post_meta( $image_id, '_wp_attached_file', true );
					$filename   = basename( $file_path );
					$thumbnail  = gutenverse_themes_builder_theme_built_path() . 'assets/img/' . $filename;
					$thumb_url  = "trailingslashit( get_template_directory_uri() ) . 'assets/img/" . $filename . "'";
					$post_demo  = get_post_meta( $post->ID, '_gtb_page_preview', true );
					$template   = get_post_meta( $post->ID, '_wp_page_template', true );
					$order      = get_post_meta( $post->ID, '_gtb_page_order', true );
					$parts      = explode( '-', $template );
					array_shift( $parts );
					$template_slug = implode( '-', $parts );
					if ( ! is_wp_error( $image_data ) ) {
						$system->put_contents(
							$thumbnail,
							$image_data['body'],
							FS_CHMOD_FILE
						);
						$data_page[] = (object) array(
							'title' => $post->post_title,
							'page'  => $post->post_title,
							'demo'  => $post_demo,
							'slug'  => $template_slug,
							'thumb' => $thumb_url,
							'order' => $order,
						);
					}
				}

				usort(
					$data_page,
					function ( $a, $b ) {
						if ( 'string' === gettype( $a->order ) ) {
							$a->order = (int) $a->order;
						}
						if ( 'string' === gettype( $b->order ) ) {
							$b->order = (int) $b->order;
						}
						return $a->order - $b->order;
					}
				);

				foreach ( $data_page as $dt ) {
					$assigns[] = "array(
						'title' => '{$dt->title}',
						'page'  => '{$dt->page}',
						'demo'  => '{$dt->demo}',
						'slug'  => '{$dt->slug}',
						'thumb' => {$dt->thumb},
					)";
				}
			}
			$plugin_notice_placeholder = $system->get_contents( GUTENVERSE_THEMES_BUILDER_DIR . '/includes/data/plugin-notice.txt' );
			$plugin_notice_placeholder = $instance->add_plugin_notice_gutenverse_theme( $plugin_notice_placeholder, $theme_data, $required, $other );
			$add_class[]               = 'new Plugin_Notice();';
			$system->put_contents(
				$class_dir . '/class-plugin-notice.php',
				$plugin_notice_placeholder,
				FS_CHMOD_FILE
			);
		} else {
			$plugin_notice_placeholder = $system->get_contents( GUTENVERSE_THEMES_BUILDER_DIR . '/includes/data/plugin-notice.txt' );
			$plugin_notice_placeholder = $instance->add_plugin_notice( $plugin_notice_placeholder, $theme_data, $required, $other );
			$add_class[]               = 'new Plugin_Notice();';
			$system->put_contents(
				$class_dir . '/class-plugin-notice.php',
				$plugin_notice_placeholder,
				FS_CHMOD_FILE
			);
		}

		if ( gutenverse_themes_builder_check_themeforest_mode() ) {
			$dir_string          = Misc::get_constant_name( $theme_data['slug'] ) . '_DIR';
			$additional_filter[] = "add_filter( 'gutenverse_companion_essential_assets_directory', function () { return $dir_string . 'assets'; });";
			$additional_filter[] = "add_filter( 'gutenverse_companion_essential_assets_url', function () { return trailingslashit( get_template_directory_uri() ) . 'assets'; } );";
			$additional_filter[] = "add_filter( 'gutenverse_companion_essential_mode_on', '__return_false' );";
			$instance->add_essential();
		}

		$placeholder = str_replace( '{{theme_logo}}', $theme_logo, $placeholder );
		$placeholder = str_replace( '{{docs_link}}', $docs_link, $placeholder );
		$placeholder = str_replace( '{{support_link}}', $support_link, $placeholder );
		$placeholder = str_replace( '{{assign_templates}}', join( ",\n\t\t\t\t", $assigns ), $placeholder );
		$placeholder = str_replace( '{{additional_class}}', join( "\n\t\t\t\t", $add_class ), $placeholder );
		$placeholder = str_replace( '{{additional_filter}}', join( "\n\t\t", $additional_filter ), $placeholder );
		$placeholder = str_replace( '{{additional_config}}', join( "\n\t\t\t", $config ), $placeholder );
		$placeholder = str_replace( '{{additional_admin_enqueue_script}}', join( "\n\t\t", $additional_admin_enqueue_script ), $placeholder );
		$placeholder = $instance->add_screenshot_page_list( $placeholder, $other, $theme_data, $system );
		$placeholder = $instance->add_custom_template( $placeholder, $templates_data );
		$placeholder = $instance->generate_init_fonts( $placeholder );

		$system->put_contents(
			$class_dir . '/class-init.php',
			$placeholder,
			FS_CHMOD_FILE
		);
		$system->put_contents(
			gutenverse_themes_builder_theme_built_path() . '/index.php',
			$system->get_contents( GUTENVERSE_THEMES_BUILDER_DIR . '/includes/data/index.txt' ),
			FS_CHMOD_FILE
		);
	}

	/**
	 * Add Essential Functionality
	 */
	private function add_essential() {
		/**Copy Essential Js Dir */
		Misc::copy_dir( GUTENVERSE_THEMES_BUILDER_DIR . '/assets/js/essential', gutenverse_themes_builder_theme_built_path() . 'assets/js/essential', array( 'chunk-gsap-scroll-trigger.js.map', 'chunk-gsap.js.map', 'frontend.js.map', 'profrontend.js.map', 'filter.js.map', 'filter-client.js.map', 'filter.js', 'chunk-gsap.js.LICENSE.txt', 'chunk-gsap-scroll-trigger.js.LICENSE.txt' ) );
		/**Copy Essential Css Dir */
		Misc::copy_dir( GUTENVERSE_THEMES_BUILDER_DIR . '/assets/css/essential', gutenverse_themes_builder_theme_built_path() . 'assets/css/essential' );
		/**Copy Essential Dependencies Dir */
		Misc::copy_dir( GUTENVERSE_THEMES_BUILDER_DIR . '/lib/dependencies/essential', gutenverse_themes_builder_theme_built_path() . 'assets/dependencies/essential' );
		/**Copy Essential Blocks Dir */
		Misc::copy_dir( GUTENVERSE_THEMES_BUILDER_DIR . '/block', gutenverse_themes_builder_theme_built_path() . 'assets/block', array( 'pattern-wrapper' ) );
	}

	/**
	 * Build Dashboard
	 *
	 * @param string $placeholder .
	 *
	 * @return string
	 */
	private function build_dashboard( $placeholder ) {
		if ( ! is_dir( gutenverse_themes_builder_theme_built_path() . 'assets/js' ) ) {
			wp_mkdir_p( gutenverse_themes_builder_theme_built_path() . 'assets/js' );
		}

		if ( ! is_dir( gutenverse_themes_builder_theme_built_path() . 'assets/css' ) ) {
			wp_mkdir_p( gutenverse_themes_builder_theme_built_path() . 'assets/css' );
		}

		if ( ! is_dir( gutenverse_themes_builder_theme_built_path() . 'assets/img' ) ) {
			wp_mkdir_p( gutenverse_themes_builder_theme_built_path() . 'assets/img' );
		}

		$theme_mode = gutenverse_themes_builder_get_theme_mode();
		if ( 'gutenverse-only' === $theme_mode ) {
			copy( GUTENVERSE_THEMES_BUILDER_DIR . '/includes/data/assets/img/background-banner.png', gutenverse_themes_builder_theme_built_path() . 'assets/img/background-banner.png' );
			copy( GUTENVERSE_THEMES_BUILDER_DIR . '/includes/data/assets/img/banner-install-gutenverse.png', gutenverse_themes_builder_theme_built_path() . 'assets/img/banner-install-gutenverse.png' );
		}
		copy( GUTENVERSE_THEMES_BUILDER_DIR . '/includes/data/assets/img/icon-loading.svg', gutenverse_themes_builder_theme_built_path() . 'assets/img/icon-loading.svg' );

		$dashboard_data_string = '';
		$placeholder           = str_replace( '{{dashboard_data}}', $dashboard_data_string, $placeholder );
		return $placeholder;
	}

	/**
	 * Get Required Plugin
	 *
	 * @param array $other .
	 * @param array $required .
	 *
	 * @return array
	 */
	private function get_required_plugin( $other, $required = array() ) {
		if ( ! empty( $other['plugins'] ) ) {
			$req_plugin        = $other['plugins'];
			$mandatory_plugin  = array( 'gutenverse', 'gutenverse-companion' );
			$recomended_plugin = Builder_Page::get_recomended_plugin_gutenverse();
			$theme_mode        = gutenverse_themes_builder_get_theme_mode();
			if ( 'gutenverse-only' === $theme_mode ) {
				foreach ( $mandatory_plugin as $mandatory ) {
					// Check if the mandatory plugin already exists in $req_plugin.
					$found = false;
					foreach ( $req_plugin as $plugin ) {
						if ( isset( $plugin['value'] ) && $plugin['value'] === $mandatory ) {
							$found = true;
							break;
						}
					}

					// If not found, add it from the recommended list.
					if ( ! $found ) {
						$detail_plugin = array_find(
							$recomended_plugin,
							function ( $el ) use ( $mandatory ) {
								return isset( $el['value'] ) && $el['value'] === $mandatory;
							}
						);

						if ( $detail_plugin ) {
							$req_plugin[] = array(
								'label'   => $detail_plugin['name'] ?? ucfirst( $mandatory ),
								'value'   => $detail_plugin['value'] ?? $mandatory,
								'version' => $detail_plugin['version'] ?? '',
								'type'    => 'wporg',
							);
						}
					}
				}
			}

			require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
			foreach ( $req_plugin as $plugin ) {
				$url        = '';
				$icons      = null;
				$short_desc = '';

				$result      = plugins_api(
					'plugin_information',
					array(
						'slug'   => $plugin['value'],
						'locale' => 'en_US',
						'fields' => array(
							'icons' => true,
						),
					)
				);
				$icons       = var_export( $result->icons, true );
				$description = $result->sections['description'];
				$short_desc  = '';
				if ( preg_match( '/<p[^>]*>(.*?)<\/p>/', $description, $matches ) ) {
					$short_desc = wp_strip_all_tags( $matches[1] );
				}
				$icons      = isset( $icons ) ? $icons : 'null';
				$required[] = "array(
					'slug'       		=> '{$plugin['value']}',
					'title'      		=> '{$plugin['label']}',
					'short_desc' 		=> '{$short_desc}',
					'active'    		=> in_array( '{$plugin['value']}', \$plugins, true ),
					'installed'  		=> \$this->is_installed( '{$plugin['value']}' ),
					'icons'      		=> {$icons},
					'download_url'      => '{$url}',
				)";
			}
		}
		return $required;
	}

	/**
	 * Add Pages List
	 *
	 * @param string $placeholder .
	 * @param array  $other .
	 * @param array  $theme_data .
	 * @param object $system .
	 * @return string
	 */
	private function add_screenshot_page_list( $placeholder, $other, $theme_data, $system ) {
		$pages = array();
		if ( ! empty( $other['screenshots'] ) && ! empty( $other['screenshots']['dashboard'] ) ) {
			if ( ! is_dir( gutenverse_themes_builder_theme_built_path() . 'assets/img' ) ) {
				wp_mkdir_p( gutenverse_themes_builder_theme_built_path() . 'assets/img' );
			}

			foreach ( $other['screenshots']['dashboard'] as $key => $dashboard ) {
				$image_data = wp_remote_get( $dashboard['url'], array( 'sslverify' => true ) );

				if ( ! is_wp_error( $image_data ) ) {
					$system->put_contents(
						gutenverse_themes_builder_theme_built_path() . 'assets/img/' . $dashboard['filename'],
						$image_data['body'],
						FS_CHMOD_FILE
					);
				}

				$pages[] = "'page-{$key}' => get_template_directory_uri() . '/assets/img/{$dashboard['filename']}'";
			}
		}

		$placeholder = str_replace( '{{page_list}}', join( ",\n\t\t\t\t", $pages ), $placeholder );
		return $placeholder;
	}

	/**
	 * Generate Init Fonts
	 *
	 * @param string $placeholder .
	 * @return string
	 */
	private function generate_init_fonts( $placeholder ) {
		$global_fonts = get_option( 'gutenverse-global-variable-font-' . get_stylesheet(), false );
		$fonts        = '';

		if ( $global_fonts ) {
			foreach ( $global_fonts as $font ) {
				$fonts .= var_export( $font, true ) . ','; //phpcs:ignore
			}
		}

		$placeholder = str_replace( '{{theme_fonts}}', $fonts, $placeholder );
		return $placeholder;
	}

	/**
	 * Add Custom Template
	 *
	 * @param string $placeholder .
	 * @param array  $templates_data .
	 *
	 * @return string
	 */
	private function add_custom_template( $placeholder, $templates_data ) {
		$custom_template = '';
		$theme_id        = get_option( 'gtb_active_theme_id' );
		foreach ( $templates_data as $template ) {
			if ( ! gutenverse_themes_builder_check_theme_mode( $template['category'], $theme_id ) ) {
				continue;
			}
			if ( in_array( $template['category'], array( 'gutenverse', 'pro' ), true ) ) {
				if ( 'custom_template' === $template['template_type'] ) {
					$template_name    = strtolower( str_replace( ' ', '-', $template['name'] ) );
					$custom_template .= var_export( $template_name, true ) . ','; //phpcs:ignore
				}
			}
		}
		$placeholder = str_replace( '{{custom_template_list}}', $custom_template, $placeholder );
		return $placeholder;
	}

	/**
	 * Add Plugin Notice for Gutenverse Theme (ThemeForest)
	 *
	 * @param string $plugin_notice_placeholder .
	 * @param array  $theme_data .
	 * @param array  $required .
	 * @param array  $other .
	 * @return string
	 */
	private function add_plugin_notice_gutenverse_theme( $plugin_notice_placeholder, $theme_data, $required, $other ) {
		$plugin_notice_placeholder = str_replace( '{{namespace}}', Misc::get_namespace( $theme_data['slug'] ), $plugin_notice_placeholder );
		$plugin_notice_placeholder = str_replace( '{{slug}}', $theme_data['slug'], $plugin_notice_placeholder );
		$plugin_notice_placeholder = str_replace( '{{author_name}}', $theme_data['author_name'], $plugin_notice_placeholder );
		$plugin_notice_placeholder = str_replace( '{{plugins_required}}', join( ",\n\t\t\t\t", $required ), $plugin_notice_placeholder );
		$plugin_notice_placeholder = str_replace( '{{constant}}', Misc::get_constant_name( $theme_data['slug'] ), $plugin_notice_placeholder );

		$style  = '<style>
            .install-gutenverse-plugin-notice {
                border: 1px solid #E6E6EF;
                position: relative;
                overflow: hidden;
                padding: 0 !important;
                margin-bottom: 30px !important;
                background: url( <?php echo esc_url( get_template_directory_uri() . \'/assets/img/background-banner.png\' ); ?> );
                background-size: cover;
                background-position: center;
            }

            .install-gutenverse-plugin-notice .gutenverse-notice-content {
                display: flex;
                align-items: center;
                position: relative;
            }

            .gutenverse-notice-text, .gutenverse-notice-image {
                width: 50%;
            }

            .gutenverse-notice-text {
                padding: 40px 0 40px 40px;
                position: relative;
                z-index: 2;
            }

            .install-gutenverse-plugin-notice img {
                max-height: 100%;
                display: flex;
                position: absolute;
                top: 0;
                right: 0;
                bottom: 0;
            }

            .install-gutenverse-plugin-notice:after {
                content: "";
                position: absolute;
                left: 0;
                top: 0;
                height: 100%;
                width: 5px;
                display: block;
                background: linear-gradient(to bottom, #68E4F4, #4569FF, #F045FF);
            }

            .install-gutenverse-plugin-notice .notice-dismiss {
                top: 20px;
                right: 20px;
                padding: 0;
                background: white;
                border-radius: 6px;
            }

            .install-gutenverse-plugin-notice .notice-dismiss:before {
                content: "\f335";
                font-size: 17px;
                width: 25px;
                height: 25px;
                line-height: 25px;
                border: 1px solid #E6E6EF;
                border-radius: 3px;
            }

            .install-gutenverse-plugin-notice h3 {
                margin-top: 5px;
                margin-bottom: 15px;
                font-weight: 600;
                font-size: 25px;
                line-height: 1.4em;
            }

            .install-gutenverse-plugin-notice h3 span {
                font-weight: 700;
                background-clip: text !important;
                -webkit-text-fill-color: transparent;
                background: linear-gradient(80deg, rgba(208, 77, 255, 1) 0%,rgba(69, 105, 255, 1) 48.8%,rgba(104, 228, 244, 1) 100%);
            }

            .install-gutenverse-plugin-notice p {
                font-size: 13px;
                font-weight: 400;
                margin: 5px 100px 20px 0 !important;
            }

            .install-gutenverse-plugin-notice .gutenverse-bottom {
                display: flex;
                align-items: center;
                margin-top: 30px;
            }

            .install-gutenverse-plugin-notice a {
                text-decoration: none;
                margin-right: 20px;
            }

            .install-gutenverse-plugin-notice a.gutenverse-button {
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", serif;
                text-decoration: none;
                cursor: pointer;
                font-size: 12px;
                line-height: 18px;
                border-radius: 5px;
                background: #3B57F7;
                color: #fff;
                padding: 10px 15px;
                font-weight: 500;
                background: linear-gradient(to left, #68E4F4, #4569FF, #F045FF);
                transition: transform 0.5s ease, color 0.5s ease;
				width: 100px;
				text-align: center;
            }

			.install-gutenverse-plugin-notice .gutenverse-bottom .installing-indicator {
				margin: 0 !important;
				max-width: 50%;
			}

            .install-gutenverse-plugin-notice a.gutenverse-button:hover {
                color: hsla(0, 0%, 100%, .749);
                transform: scale(.94);
            }

            #gutenverse-install-plugin.loader:after {
                display: block;
                content: url(<?php echo esc_url( get_template_directory_uri() . \'/assets/img/icon-loading.svg\' ); ?>);
				border-radius: 50%;
				width: 100%;
				height: 100%;
                -webkit-animation: spin 2s linear infinite;
                animation: spin 2s linear infinite;
            }

            @-webkit-keyframes spin {
                0% {
                    -webkit-transform: rotate(0deg);
                }
                100% {
                    -webkit-transform: rotate(360deg);
                }
            }

            @keyframes spin {
                0% {
                    transform: rotate(0deg);
                }
                100% {
                    transform: rotate(360deg);
                }
            }

            @media screen and (max-width: 1024px) {
                .gutenverse-notice-text {
                    width: 100%;
                }

                .gutenverse-notice-image {
                    display: none;
                }
            }
        </style>';
		$notice = '<div class="notice install-gutenverse-plugin-notice">
            <div class="gutenverse-notice-inner">
                <div class="gutenverse-notice-content">
                    <div class="gutenverse-notice-text">
                        <h3><?php esc_html_e( \'Complete setup to activate all \', \'' . $theme_data['slug'] . '\' ); ?> <span>' . $theme_data['title'] . ' features!</span></h3> 
                        <p><?php esc_html_e( \'Complete the setup to unlock all features. The prepare wizard will install mandatory plugins and redirect you to the wizard page, to help you maximize your ' . $theme_data['title'] . ' theme.\' , \'' . $theme_data['slug'] . '\' ); ?></p>
                        <div class="gutenverse-bottom">
                            <a class="gutenverse-button" id="gutenverse-install-plugin" href="#">
                                <?php echo esc_html( __( \'Continue Setup\', \'' . $theme_data['slug'] . '\' ) ); ?>
                            </a>
                        </div>
                    </div>
                    <div class="gutenverse-notice-image">
                        <img src="<?php echo esc_url( trailingslashit( get_template_directory_uri() ) ) . \'/assets/img/banner-install-gutenverse.png\'; ?>"/>
                    </div>
                </div>
            </div>
        </div>';

		$redirect_url = "window.location.href = site_url + '/themes.php?page=theme-wizard'";

		$script                    = "<script>
        var promises = [];
        var actions = <?php echo wp_json_encode( \$actions ); ?>;
        let site_url = '<?php echo admin_url(); ?>';

        function sequenceInstall (plugin, index, total) {
            return new Promise((resolve, reject) => {
				const buttonWrapper = document.querySelector('.notice.install-gutenverse-plugin-notice .gutenverse-bottom');
				const checkIndicator = buttonWrapper.querySelector('.installing-indicator');
				if (checkIndicator) {
					checkIndicator.remove();
				}
				if (buttonWrapper) {
					const p = document.createElement('p');
					p.className = 'installing-indicator';
					p.textContent = index + 1 + '/' + total + ' Installing ' + plugin.title;
					buttonWrapper.appendChild(p);
				}
				if (!plugin) return resolve();

				const slug = plugin.slug;
				const path = `\${slug}/\${slug}`;

				let request;

				switch (actions[slug]) {
					case 'active':
						// Already active – nothing to do
						return resolve();

					case 'inactive':
						request = wp.apiFetch({
							path: `wp/v2/plugins/plugin?plugin=\${path}`,
							method: 'POST',
							data: {
								status: 'active'
							}
						});
						break;

					default:
						request = wp.apiFetch({
							path: 'wp/v2/plugins',
							method: 'POST',
							data: {
								slug: slug,
								status: 'active'
							}
						});
						break;
				}

				request
					.then(() => 
						setTimeout(() => {
							resolve()
						}, 500)
					)
					.catch((error) => {
						console.error(`Failed to install/activate \${slug}:`, error);
						resolve(); // Continue with the sequence even if one fails
					});
			});
        };

        document.addEventListener('DOMContentLoaded', function () {
			const button = document.getElementById('gutenverse-install-plugin');

			if (!button) return;

			button.addEventListener('click', function (e) {
				const hasFinishClass = button.classList.contains('finished');
				const hasLoaderClass = button.classList.contains('loader');

				if (!hasFinishClass) {
					e.preventDefault(); // stop navigation
				}

				if (!hasLoaderClass && !hasFinishClass) {
					const plugins = <?php echo wp_json_encode( \$plugins_required ); ?>;
					button.classList.add('loader');
					button.textContent = '';

					let sequence = Promise.resolve();

					plugins.forEach((plugin, index) => {
						sequence = sequence.then(() => sequenceInstall(plugin, index, plugins.length));
					});

					sequence.then(() => {
						" . $redirect_url . '
					});
				}
			});
		});
        </script>';
		$plugin_notice_placeholder = str_replace( '{{dashboard_style}}', $style, $plugin_notice_placeholder );
		$plugin_notice_placeholder = str_replace( '{{dashboard_script}}', $script, $plugin_notice_placeholder );
		$plugin_notice_placeholder = str_replace( '{{dashboard_notice}}', $notice, $plugin_notice_placeholder );
		return $plugin_notice_placeholder;
	}

	/**
	 * Add Plugin Notice
	 *
	 * @param string $plugin_notice_placeholder .
	 * @param array  $theme_data .
	 * @param array  $required .
	 * @param array  $other .
	 * @return string
	 */
	private function add_plugin_notice( $plugin_notice_placeholder, $theme_data, $required, $other ) {
		$plugin_notice_placeholder = str_replace( '{{namespace}}', Misc::get_namespace( $theme_data['slug'] ), $plugin_notice_placeholder );
		$plugin_notice_placeholder = str_replace( '{{slug}}', $theme_data['slug'], $plugin_notice_placeholder );
		$plugin_notice_placeholder = str_replace( '{{author_name}}', $theme_data['author_name'], $plugin_notice_placeholder );
		$plugin_notice_placeholder = str_replace( '{{plugins_required}}', join( ",\n\t\t\t\t", $required ), $plugin_notice_placeholder );
		$plugin_notice_placeholder = str_replace( '{{constant}}', Misc::get_constant_name( $theme_data['slug'] ), $plugin_notice_placeholder );

		$style       = '<style>
			.update-php .wrap{
				width: 100% !important;
			}
            .install-gutenverse-plugin-notice {
                border: 1px solid #E6E6EF;
                position: relative;
                overflow: hidden;
                padding: 0 !important;
                margin-bottom: 30px !important;
            }

            .gutenverse-notice-text {
                padding: 20px 40px 20px 40px;
                position: relative;
                z-index: 2;
				display: flex;
				flex-direction: column;
				gap: 10px;
            }

            .install-gutenverse-plugin-notice:after {
                content: "";
                position: absolute;
                left: 0;
                top: 0;
                height: 100%;
                width: 5px;
                display: block;
                background: #1B67A5;
            }

            .install-gutenverse-plugin-notice .notice-dismiss {
                top: 10px;
                right: 10px;
                padding: 0;
				cursor: pointer;
				z-index: 9;
            }

            .install-gutenverse-plugin-notice .notice-dismiss:before {
                content: "\f335";
                font-size: 12px;
                width: 20px;
                height: 20px;
                line-height: 20px;
				
            }

            .install-gutenverse-plugin-notice h3 {
                font-weight: 600;
                font-size: 17px;
				color: #011627;
				margin: 0;
            }

            .install-gutenverse-plugin-notice p {
                font-size: 13px;
                font-weight: 400;
				color: #3C434A;
				margin: 0;
            }

            .install-gutenverse-plugin-notice a {
                text-decoration: none;
                margin-right: 20px;
            }

            .install-gutenverse-plugin-notice .gutenverse-button {
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", serif;
                cursor: pointer;
                font-size: 13px;
                border-radius: 5px;
                color: #fff;
                padding: 11px 14px;
                font-weight: 400;
                background: #1B67A5;
                transition: transform 0.5s ease, color 0.5s ease;
				width: fit-content;
            }

            .install-gutenverse-plugin-notice a.gutenverse-button:hover {
                color: hsla(0, 0%, 100%, .749);
                transform: scale(.94);
            }

            #gutenverse-install-plugin.loader:after {
                display: block;
                content: "";
                border: 5px solid white;
                border-radius: 50%;
                border-top: 5px solid rgba(255, 255, 255, 0);
                width: 10px;
                height: 10px;
                -webkit-animation: spin 2s linear infinite;
                animation: spin 2s linear infinite;
            }

            @-webkit-keyframes spin {
                0% {
                    -webkit-transform: rotate(0deg);
                }
                100% {
                    -webkit-transform: rotate(360deg);
                }
            }

            @keyframes spin {
                0% {
                    transform: rotate(0deg);
                }
                100% {
                    transform: rotate(360deg);
                }
            }

            @media screen and (max-width: 1024px) {
                .gutenverse-notice-text {
                    width: 100%;
                }

                .gutenverse-notice-image {
                    display: none;
                }
            }
        </style>';
		$notice      = '<div class="notice install-gutenverse-plugin-notice">
            <div class="gutenverse-notice-inner">
                <div class="gutenverse-notice-content">
                    <div class="gutenverse-notice-text">
                        <h3><?php esc_html_e( "Let\'s Get Your Theme Ready!",  \'' . $theme_data['slug'] . '\' ); ?></h3> 
                        <p><?php esc_html_e( "Install the recommended plugins to unlock all the features and make your site look just like the demo.",  \'' . $theme_data['slug'] . '\' ); ?></p>
                        <div class="gutenverse-bottom">
                            <div class="gutenverse-button" id="gutenverse-install-plugin">
                                <?php echo esc_html( __( "Install Required Plugins",  \'' . $theme_data['slug'] . '\' ) ); ?>
							</div>
                        </div>
                    </div>
                </div>
			<div class="notice-dismiss"></div>
            </div>
        </div>';
		$script_done = "
			window.location.reload();
            $(this).removeClass('loader').addClass('finished').text('All is Done!');
		";

		$script                    = "<script>
        var promises = [];
        var actions = <?php echo wp_json_encode( \$actions ); ?>;
        let site_url = '<?php echo admin_url(); ?>';

        function sequenceInstall (plugin) {
            return new Promise((resolve, reject) => {
				if (!plugin) return resolve();

				const slug = plugin.slug;
				const path = `\${slug}/\${slug}`;

				let request;

				switch (actions[slug]) {
					case 'active':
						// Already active – nothing to do
						return resolve();

					case 'inactive':
						request = wp.apiFetch({
							path: `wp/v2/plugins/plugin?plugin=\${path}`,
							method: 'POST',
							data: {
								status: 'active'
							}
						});
						break;

					default:
						request = wp.apiFetch({
							path: 'wp/v2/plugins',
							method: 'POST',
							data: {
								slug: slug,
								status: 'active'
							}
						});
						break;
				}

				request
					.then(() => resolve())
					.catch((error) => {
						console.error(`Failed to install/activate \${slug}:`, error);
						resolve(); // Continue with the sequence even if one fails
					});
			});
        };
		document.addEventListener('DOMContentLoaded', function () {
			const notice = document.querySelector('div.notice.install-gutenverse-plugin-notice');
			if (notice) {
				notice.addEventListener('click', function (event) {
					if (event.target && event.target.classList.contains('notice-dismiss')) {
						event.preventDefault();

						const xhr = new XMLHttpRequest();
						const params = new URLSearchParams();
						params.append('action', '" . $theme_data['slug'] . "_set_admin_notice_viewed');
						params.append('nonce', '<?php echo esc_html( wp_create_nonce( '" . $theme_data['slug'] . "_admin_notice' ) ); ?>');

						xhr.open('POST', ajaxurl, true);
						xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xhr.send(params.toString());
						window.location.reload();
					}
				});
			}
		});
        document.addEventListener('DOMContentLoaded', function () {
			const button = document.getElementById('gutenverse-install-plugin');

			if (!button) return;

			button.addEventListener('click', function (e) {
				const hasFinishClass = button.classList.contains('finished');
				const hasLoaderClass = button.classList.contains('loader');

				if (!hasFinishClass) {
					e.preventDefault(); // stop navigation
				}

				if (!hasLoaderClass && !hasFinishClass) {
					const plugins = <?php echo wp_json_encode( \$plugins_required ); ?>;
					button.classList.add('loader');
					button.textContent = '';

					let sequence = Promise.resolve();

					plugins.forEach(plugin => {
						sequence = sequence.then(() => sequenceInstall(plugin));
					});

					sequence.then(() => {
						$script_done
					});
				}
			});
		});
        </script>";
		$plugin_notice_placeholder = str_replace( '{{dashboard_style}}', $style, $plugin_notice_placeholder );
		$plugin_notice_placeholder = str_replace( '{{dashboard_script}}', $script, $plugin_notice_placeholder );
		$plugin_notice_placeholder = str_replace( '{{dashboard_notice}}', $notice, $plugin_notice_placeholder );
		return $plugin_notice_placeholder;
	}
}
