<?php
/**
 * Helper to check if the AKD Demo Importer plugin is installed and active.
 */
function hostiko_is_akd_demo_importer_active() {
	if ( ! function_exists( 'is_plugin_active' ) ) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}

	return is_plugin_active( 'akd-demo-importer/akd-demo-importer.php' );
}

/**
 * Add menu page under Appearance when AKD Demo Importer is not active.
 */
add_action( 'admin_menu', 'akd_hostiko_about_menu_page' );

function akd_hostiko_about_menu_page() {
	// Only show the welcome/setup page when the AKD Demo Importer plugin is not active.
	if ( ! hostiko_is_akd_demo_importer_active() ) {
		$activated_theme = wp_get_theme();
		$theme_name      = $activated_theme->get( 'Name' );

		// Create the page title and menu title using sprintf for translation.
		$page_title = sprintf( __( 'Welcome to %s', 'hostiko' ), $theme_name );
		$menu_title = sprintf( __( 'Welcome to %s', 'hostiko' ), $theme_name );

		add_theme_page(
			$page_title,
			$menu_title,
			'edit_theme_options',
			str_replace( ' ', '-', strtolower( $theme_name ) ),
			'akd_menu_page_content'
		);
	}
}

/**
 * Define content for akd menu page
 */
function akd_menu_page_content() {
	$activated_theme = wp_get_theme();
	$plugin_slug     = 'akd-demo-importer';
	$plugin_file     = 'akd-demo-importer/akd-demo-importer.php';

	$plugin_installed = file_exists( WP_PLUGIN_DIR . '/' . $plugin_file );
	$plugin_active    = hostiko_is_akd_demo_importer_active();

	// Decide button state.
	$button_class      = '';
	$button_label      = '';
	$button_processing = '';

	if ( ! $plugin_active ) {
		if ( $plugin_installed ) {
			$button_class      = 'activate-akd-framework';
			$button_label      = __( 'Activate', 'hostiko' );
			$button_processing = __( 'Activating ...', 'hostiko' );
		} else {
			$button_class      = 'install-akd-framework';
			$button_label      = __( 'Install', 'hostiko' );
			$button_processing = __( 'Installing ...', 'hostiko' );
		}
	}
	?>
	<div class="akd-about-menu-page">
	<?php  ?>

		<div class="akd-logo">
			<img src="<?php _e(get_template_directory_uri() . '/assets/img/logo/logo.png', 'hostiko') ?>">
		</div>
		<h1 class="akd-menu-page-title" style="width:30%;">
			<?php 
				$theme_name = $activated_theme->get('Name');
				$theme_version = $activated_theme->get('Version');
				// Create the message with placeholders and escape the dynamic parts
				$welcome_message = sprintf(
					esc_html__('Introducing %1$s %2$s Your Ultimate Hosting Solution', 'hostiko'), 
					esc_html($theme_name), 
					esc_html($theme_version)
				);
				// Echo the translated and formatted message
				echo esc_html($welcome_message);
			?>			
		</h1>
		<div class="akd-menu-page-desc" style="width:30%;">
			<p>
				<?php
					printf(
						wp_kses(
							/* translators: %s: support URL */
							__( 'This theme is designed & developed by Designing Media. In case of any issues, please contact us through our support channel at <a href="%s" target="_blank" rel="nofollow">Support</a>.', 'hostiko' ),
							array(
								'a' => array(
									'href' => array(),
									'target' => array(),
									'rel' => array(),
								)
							)
						),
						esc_url( 'https://designingmedia.com/support/' )
					);
					?>

				

			</p>
			<p>
				<?php
				if ( ! $plugin_active ) {
					if ( $plugin_installed ) {
						/* translators: %s: plugin name */
						printf(
							esc_html__( 'In order to continue, please click the activate button to activate: %s', 'hostiko' ),
							'<b>' . esc_html__( 'AKD Demo Importer', 'hostiko' ) . '</b>'
						);
					} else {
						/* translators: %s: plugin name */
						printf(
							esc_html__( 'In order to continue, please click the install button to install and activate: %s', 'hostiko' ),
							'<b>' . esc_html__( 'AKD Demo Importer', 'hostiko' ) . '</b>'
						);
					}
				} else {
					esc_html_e( 'AKD Demo Importer is already installed and active.', 'hostiko' );
				}
				?>
			</p>
		</div>
		<?php if ( ! $plugin_active && $button_class && $button_label ) : ?>
			<div class="akd-menu-page-btn">
				<a
					class="<?php echo esc_attr( $button_class ); ?>"
					href=""
					data-slug="<?php echo esc_attr( $plugin_slug ); ?>"
					data-name="<?php echo esc_attr( $plugin_slug ); ?>"
					data-processing="<?php echo esc_attr( $button_processing ); ?>"
					aria-label="<?php echo esc_attr( $button_label ); ?>"
				>
					<?php echo esc_html( $button_label ); ?>
				</a>
			</div>
		<?php endif; ?>
	</div>
	<?php
}

/**
 * Redirect to hostiko menu page on theme activation when AKD Demo Importer is not active.
 */
add_action('admin_init', 'akd_redirect_on_theme_activation');

function akd_redirect_on_theme_activation() {
	if ( isset( $_GET['activated'] ) && is_admin() ) {
		// If AKD Demo Importer is not active at the time of theme activation, redirect to the welcome screen.
		if ( ! hostiko_is_akd_demo_importer_active() ) {
			$activated_theme = wp_get_theme();
			wp_redirect( admin_url( 'themes.php?page='.str_replace( ' ', '-', strtolower( $activated_theme ) ).'') );
			exit;
		}
	}

	$protocol = ( ! empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ) ? "https://" : "http://";

	/**
	 * Get the host (domain name)
	 */
	$host = $_SERVER['HTTP_HOST'];

	/**
	 * Get the URI (path and query string)
	 */
	$uri = $_SERVER['REQUEST_URI'];

	/**
	 * Combine them to get the current URL
	 */
	$current_url = $protocol . $host . $uri;

	if ( isset( $_GET['page'] ) && 'merlin' === $_GET['page'] ) {
		wp_safe_redirect( admin_url() );
		exit;
	}
}

function check_url_for_themes_merlin( $url ) {

	/**
	 * Parse the URL
	 */
	$parsed_url = parse_url( $url );

	/**
	 * Check if the path contains 'themes.php'
	 */
	$path_contains_themes_php = isset($parsed_url['path']) && strpos($parsed_url['path'], 'themes.php') !== false;

	/**
	 * Parse query parameters
	 */
	$query_contains_page_merlin = false;
	if (isset($parsed_url['query'])) {
		parse_str($parsed_url['query'], $query_params);
		$query_contains_page_merlin = isset($query_params['page']) && $query_params['page'] === 'merlin';
	}

	/**
	 * Return true if both conditions are met
	 */
	return $path_contains_themes_php && $query_contains_page_merlin;
}

add_action('wp_ajax_install_plugin', 'akd_required_plugin_callback');

function akd_required_plugin_callback() {
	// Only admins with plugin install capability should be able to run this.
	if ( ! current_user_can( 'install_plugins' ) ) {
		wp_send_json_error( 'Unauthorized' );
	}

	check_ajax_referer( 'akd_install_plugin', 'nonce' );

	$plugin_slug = isset( $_POST['plugin_slug'] ) ? sanitize_text_field( wp_unslash( $_POST['plugin_slug'] ) ) : '';
	$plugin_name = isset( $_POST['plugin_name'] ) ? sanitize_text_field( wp_unslash( $_POST['plugin_name'] ) ) : '';
	$plugin      = $plugin_slug . '/' . $plugin_slug . '.php';

	include_once( ABSPATH . 'wp-admin/includes/plugin-install.php' );
	include_once( ABSPATH . 'wp-admin/includes/file.php' );
	include_once( ABSPATH . 'wp-admin/includes/misc.php' );
	include_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
	require_once(ABSPATH . 'wp-admin/includes/plugin.php');

	/**
	 * Plugin slug (directory name)
	 */
	$plugin_slug = 'akd-demo-importer';

	/**
	 * Check if the plugin is active
	 */
	$active_plugins = get_option('active_plugins');
	if (in_array($plugin_slug . '/akd-demo-importer.php', $active_plugins)) {
		/**
		 * Deactivate the plugin
		 */
		deactivate_plugins($plugin_slug . '/akd-demo-importer.php');
	}

	/**
	 * Attempt to delete the plugin
	 */
	$result = delete_plugins(array($plugin_slug . '/akd-demo-importer.php'));
	$arr = [];
	$plugin_zip_path = get_template_directory() . '/plugins/akd-demo-importer.zip';
	$plugin_dir = WP_PLUGIN_DIR . '/akd-demo-importer';

	/**
	 * Check if the plugin directory already exists
	 */
	if (!file_exists($plugin_dir)) {
		/**
		 * Create the plugin directory
		 */
		wp_mkdir_p($plugin_dir);

		/**
		 * Unzip the plugin file to the plugins directory
		 */
		WP_Filesystem();
		$result = unzip_file($plugin_zip_path, $plugin_dir, false);

		/**
		 * Check if the plugin was unzipped successfully
		 */
		if (!is_wp_error($result)) {
			activate_plugin('akd-demo-importer/akd-demo-importer.php');
			$arr = [
				'required_akd_plugin' => true,
				'required_akd_plugin_notice' => true
			];
			update_option('_hostiko_requied_akd_plugin', $arr);
		} else {
			wp_send_json_error( 'Error installing the plugin.' );
		}
	}
	
	wp_die();
}

add_action( 'wp_ajax_activate_plugin', 'akd_activate_plugin_callback' );
function akd_activate_plugin_callback() {
	if ( ! current_user_can( 'activate_plugins' ) ) {
		wp_send_json_error( 'Unauthorized' );
	}

	check_ajax_referer( 'akd_install_plugin', 'nonce' );

	$plugin_slug = isset( $_POST['plugin_slug'] ) ? sanitize_text_field( wp_unslash( $_POST['plugin_slug'] ) ) : '';
	$plugin      = 'akd-demo-importer' . '/' . 'akd-demo-importer' . '.php';

	$activate = activate_plugin($plugin);
	$arr = [];
	if ( $activate !== null ) {
		$arr = array(
			'required_akd_plugin' => true,
			'required_akd_plugin_notice' => true
		);
		update_option( '_hostiko_requied_akd_plugin', $arr );
		wp_send_json_success( 'Plugin activated successfully.' );
	} else {
		wp_send_json_error( 'Error activating the plugin.' );
	}

	wp_die();
}

add_action( 'admin_enqueue_scripts', 'enqueue_custom_script' );

function enqueue_custom_script() {
	wp_enqueue_style( 'custom-style', get_template_directory_uri() . '/assets/css/custom-style.css', array(), '1.0' );
	$activated_theme = wp_get_theme();

	wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/assets/js/custom-script.js', array( 'jquery' ), '1.0', true );
	wp_localize_script( 'custom-script', 'urls', array(
		'ajaxUrl'       => admin_url( 'admin-ajax.php' ),
		'adminUrl'      => admin_url(),
		'themeTemplate' => $activated_theme->get_template(),
		'nonce'         => wp_create_nonce( 'akd_install_plugin' ),
	));
}
add_action( 'admin_notices', 'akd_show_activation_notice' );

/**
 * Method to show plugin activation and installation notices
 */
function akd_show_activation_notice() {
	global $pagenow;
	$activated_theme = wp_get_theme();

	/**
	 * Activate AKD framework if activation form is submitted
	 */
	activate_akd_framework_plugin();

	/**
	 * Check if the current page is the custom menu page with the slug '{theme-name}'
	 */
	if ( $pagenow !== 'themes.php' || ! isset( $_GET['page'] ) || $_GET['page'] !== str_replace( ' ', '-', strtolower( $activated_theme ) ) ) {
		$theme_name     = $activated_theme->get( 'Name' );
		$theme_version  = $activated_theme->get( 'Version' );
		$screenshot_url = get_template_directory_uri() . '/screenshot.png';
		$message = '';

		/**
		 * Plugin slug (directory name)
		 */
		$plugin_slug = 'akd-demo-importer';
		/**
		 * Check if the plugin is active
		 */
		$active_plugins = get_option( 'active_plugins' );
		if ( file_exists( WP_PLUGIN_DIR . '/'. $plugin_slug . '/akd-demo-importer.php' ) && ! in_array( $plugin_slug . '/akd-demo-importer.php', $active_plugins ) ) {
			$message .= sprintf(
				'<div class="notice notice-info is-dismissible">
					<div class="akd-theme-screenshot">
						<img src="%1$s" alt="%2$s">
						<h6>%2$s</h6>
					</div>
					<div class="akd-theme-info">
						<h2>%3$s %4$s</h2>
						<p>%5$s</p>
						<hr>
						<p><strong>%6$s</strong> %7$s</p>
						<form method="post">
							<button class="button-primary" type="submit" name="activate_akd_framework">%8$s</button>
						</form>
					</div>
				</div>',
				esc_url( $screenshot_url ),
				esc_html( $theme_name ),
				__( '', 'hostiko' ),
				esc_html( $theme_name ) . ' ' . esc_html( $theme_version ),
				__( 'Meet Hostiko, your ultimate solution for building digital products, brands, and experiences.', 'hostiko' ),
				__( 'Important!', 'hostiko'),
				__( 'To proceed, you must install and activate the "AKD Demo Importer" plugin.', 'hostiko' ),
				__( 'Activate AKD Importer Plugin', 'hostiko' )
			);
		}
		elseif ( ! get_option( '_hostiko_requied_akd_plugin' ) && ! in_array( $plugin_slug . '/akd-demo-importer.php', $active_plugins ) ) {
			$message .= sprintf(
				'<div class="notice notice-info is-dismissible">
					<div class="akd-theme-screenshot">
						<img src="%1$s" alt="%2$s">
						<h6>%2$s</h6>
					</div>
					<div class="akd-theme-info">
						<h2>%3$s %4$s</h2>
						<p>%5$s</p>
						<p class="akd-label"><strong>%6$s</strong> %7$s</p>
						<div class="plugin-btn">
							<a href="%8$s" class="button-primary">%9$s</a>
						</div>
					</div>
				</div>',
				esc_url( $screenshot_url ),
				esc_html( $theme_name ),
				__( '', 'hostiko' ),
				esc_html( $theme_name ) . ' ' . esc_html( $theme_version ),
				__( 'Meet Hostiko, your ultimate solution for building digital products, brands, and experiences.', 'hostiko' ),
				__( 'Important!', 'hostiko' ),
				__( 'To proceed, you must install  the "AKD Demo Importer" plugin.', 'hostiko' ),
				esc_url( admin_url( "themes.php?page=" . str_replace( ' ', '-', strtolower( $theme_name ) ) ) ),
				__( 'Install plugin "AKD Demo Importer"', 'hostiko')
			);

		} else if ( in_array( $plugin_slug . '/akd-demo-importer.php', $active_plugins ) && file_exists( $plugin_slug . '/akd-demo-importer.php' ) ) {
		   
			$message .= sprintf(
				'<div class="notice notice-info is-dismissible">
					<div class="akd-theme-screenshot">
						<img src="%1$s" alt="%2$s">
						<h6>%2$s</h6>
					</div>
					<div class="akd-theme-info">
						<h2>%3$s %4$s</h2>
						<p>%5$s</p>
						<hr>
						<p><strong>%6$s</strong> %7$s</p>
						<form method="post">
							<button class="button-primary" type="submit" name="activate_akd_framework">%8$s</button>
						</form>
					</div>
				</div>',
				esc_url( $screenshot_url ),
				esc_html( $theme_name ),
				__( '', 'hostiko' ),
				esc_html( $theme_name ) . ' ' . esc_html( $theme_version ),
				__( 'Meet Hostiko, your ultimate solution for building digital products, brands, and experiences.', 'hostiko' ),
				__( 'Important!', 'hostiko' ),
				__( 'To proceed, you must install and activate the "AKD Demo Importer" plugin.', 'hostiko' ),
				__( 'Activate AKD Importer Plugin', 'hostiko' )
			);
		}

		/**
		 * Output the message safely
		 */
		echo wp_kses_post($message);
	}
}

/**
 * Method to activate theme's required plugin
 */
function activate_akd_framework_plugin() {
	if ( isset( $_POST['activate_akd_framework'] ) ) {
		/**
		 * Retrieve active plugins
		 */
		$active_plugins = get_option( 'active_plugins' );

		/**
		 * Define plugin slug and path
		 */
		$plugin_slug = 'akd-demo-importer';
		$plugin_path = "{$plugin_slug}/akd-demo-importer.php";

		/**
		 * Check if the plugin is not already activated
		 */
		if ( ! in_array( $plugin_path, $active_plugins, true ) ) {
			/**
			 * Activate the plugin
			 */
			activate_plugin( $plugin_path );
		}
	}
}

/**
 * Function to track plugin deletion
 */
function akd_track_required_plugin_deletion( $plugin ) {
	if ( strpos( $plugin, 'akd-demo-importer/akd-demo-importer.php' ) !== false ) {
		delete_option( '_hostiko_requied_akd_plugin' );
	}
}
add_action( 'deleted_plugin', 'akd_track_required_plugin_deletion' );

/**
 * Method to check if the plugin is present or not
 */
function akd_check_akd_demo_importer_plugin() {
	$plugin_file = 'akd-demo-importer/akd-demo-importer.php';
	if ( ! file_exists( WP_PLUGIN_DIR . '/' . $plugin_file ) ) {
		delete_option( '_akd_requied_plugin_inst' );
	}
}
add_action( 'admin_init', 'akd_check_akd_demo_importer_plugin' );