<?php
/**
 * Welcome Notice
 * This file is loaded at after_setup_theme@10
 */

/**
 * Whether to load notice
 */
function maglume_load_notices() {
	global $pagenow;
	$subpage = isset( $_GET['page'] ) ? $_GET['page'] : 'subpage';
	$slug = maglume_abouttag( 'slug' );
	$dashslug = hoot_dashboard( 'slug' );
	return (
		$slug && is_string( $slug )
		&& ! get_option( "{$slug}-dismiss-welcome" )
		&& (
			in_array( $pagenow, array( 'themes.php', 'plugins.php', 'upload.php' ) )
			|| ( $pagenow === 'edit.php' && ( empty( $_GET['post_type'] ) || $_GET['post_type'] === 'page' ) )
		)
		&& ! in_array( $subpage, array( $dashslug, 'hootkit', 'hoot-import' ) )
	);
}

/**
 * Add a welcome notice if not already dismissed
 */
function maglume_welcome_notice() {
	$slug = maglume_abouttag( 'slug' );
	$hootkitactive = function_exists( 'hootkit' );
	$hootkitrequired = hoot_hootkit_version_required();
	$hootkitcompat = $hootkitactive ? version_compare( hootkit()->version, $hootkitrequired, '>=' ) : true;
	$hootkitdismissed = get_option( "{$slug}-dismiss-hkcompat" );
	$noticefn = '';
	if ( $hootkitactive && ! $hootkitcompat && !$hootkitdismissed )
		$noticefn = 'maglume_add_hootkit_version_notice';
	elseif ( maglume_load_notices() )
		$noticefn = 'maglume_add_welcome_notice';
	if ( !empty( $noticefn ) )
		add_action( 'admin_notices', $noticefn );
	if ( !empty( $_GET['hoot-noticereset'] ) ) {
		update_option( "{$slug}-dismiss-welcome", 0 );
		update_option( "{$slug}-dismiss-hkcompat", 0 );
	}
}
add_action( 'admin_head', 'maglume_welcome_notice' );

/**
 * Enqueue CSS
 *
 * @since 1.0
 * @access public
 * @return void
 */
function maglume_admin_enqueue_notice_styles( $hook ) {
	if ( maglume_load_notices() || $hook === hoot_dashboard( 'screen' ) ) {
		wp_enqueue_style( 'hoot-admin-notice', hoot_data()->incuri . 'admin/css/notice.css', array(),  hoot_data()->hoot_version );
		wp_enqueue_script( 'hoot-admin-notice', hoot_data()->incuri . 'admin/js/notice.js', array( 'jquery' ),  hoot_data()->hoot_version, true );
		wp_localize_script( 'hoot-admin-notice', 'hoot_admin_notice', array(
							'ajax_url' => esc_url( admin_url( 'admin-ajax.php' ) ),
							'nonce' => wp_create_nonce( 'hoottheme-welcome-action' ),
							'dismiss_action' => 'maglume_dismiss_welcome_notice',
							'hoot_processplugin_action' => 'maglume_processplugin',
							'hoot_processplugin_btntext' => esc_html__( 'Please Wait. This may take a while...', 'magazine-lume' ),
						) );
	}
}
add_action( 'admin_enqueue_scripts', 'maglume_admin_enqueue_notice_styles' );

/**
 * Display admin notice
 */
function maglume_add_hootkit_version_notice() {
	$themename = maglume_abouttag( 'name' );
	?><div id="hoot-hkcompat-msg" class="hoot-hkcompat-msg notice notice-error is-dismissible" data-hootmsg="hkcompat">
		<div class="hoot-welcome-content">
			<p><?php
				/* Translators: 1 is the theme name */
				printf( esc_html__( 'Your current HootKit plugin is outdated. Please %1$supdate to the latest version%2$s to ensure compatibility with %3$s theme.', 'magazine-lume' ), '<a href="' . esc_url( admin_url( 'update-core.php' ) ) . '">', '</a>', $themename );
			?></p>
		</div>
	</div><?php
}
function maglume_add_welcome_notice() {
	$themename = maglume_abouttag( 'name' );
	$imgshot = maglume_abouttag( 'fullshot', true );
	$issmall = false;
	if ( ! $imgshot ) {
		$imgshot = maglume_abouttag( 'multishot' );
		$issmall = 0;
	}
	if ( ! $imgshot ) {
		$imgshot = maglume_abouttag( 'shot' );
		$issmall = true;
	}
	$urldemo = maglume_abouttag('urldemo');
	?>
	<div id="hoot-welcome-msg" class="hoot-welcome-msg notice is-dismissible">
		<div class="hoot-welcome-content">
			<?php if ( $imgshot ) : ?>
				<a class="hoot-welcome-img <?php echo ( $issmall ? 'hoot-welcome-img--ss': ( $issmall === false ? 'hoot-welcome-img--large' : 'hoot-welcome-img--large hoot-welcome-multiimg' ) ); ?>" href="<?php echo esc_url( $urldemo ); ?>" target="_blank">
					<img class="hoot-welcome-screenshot <?php if ( $issmall === false ) { echo 'hoot-welcome-scrollableimg'; } ?>" src="<?php echo esc_url( $imgshot ); ?>" alt="<?php echo esc_attr( $themename ); ?>" />
				</a>
			<?php endif; ?>
			<div class="hoot-welcome-text">
				<h1><?php
					/* Translators: 1 is the theme name 2 and 3 are span tags */
					printf( esc_html__( 'Thank you for choosing %2$s%1$s!%3$s', 'magazine-lume' ), $themename, '<span>', '</span>' );
				?></h1>
				<p>
					<?php
					/* Translators: 1 is the link start markup, 2 is link markup end 3 is line break 4 is the theme name */
					printf( esc_html__( 'To get started and fully take advantage of our theme, please visit your %1$sTheme Dashboard%2$s.%3$sWe hope you enjoy using %4$s', 'magazine-lume' ), '<a href="' . esc_url( hoot_dashboard( 'url', array( 'tab' => 'qstart' ) ) ) . '" style="display: inline-block;">', '</a>', '<br />', $themename );
				?></p>
				<p class="hoot-welcome-actions">
					<a class="button button-primary hoot-welcome-btn" href="<?php echo esc_url( hoot_dashboard( 'url', array( 'tab' => 'qstart' ) ) ); ?>"><?php esc_html_e( 'Quick Start', 'magazine-lume' ); ?></a>
					<?php $processclass = class_exists( 'HootKit' ) ? '' : 'hoot-btn-processplugin'; /*
					*/ ?>
					<a class="button button-secondary hoot-welcome-btn <?php echo sanitize_html_class( $processclass ); ?>" href="<?php echo esc_url( hoot_dashboard( 'url', array( 'tab' => 'demoimport' ) ) ); ?>" data-plugin="hootkit" data-redirectdashtab="demoimport"><?php esc_html_e( 'Import Pre-built Website', 'magazine-lume' ); ?></a>
				</p>
				<?php if ( ! class_exists( 'HootKit' ) ) : ?>
					<p class="hoot-welcome-note">
						<?php _e( "* Clicking the 'Import Website' button above will install the 'HootKit' plugin.", 'magazine-lume' ); ?>
					</p>
				<?php endif; ?>
			</div>
		</div>
	</div>
	<?php
}

/**
 * Ajax callback to set dismissable notice
 */
function maglume_dismiss_welcome_notice() {
	check_ajax_referer( 'hoottheme-welcome-action', 'nonce' );
	$slug = maglume_abouttag( 'slug' );
	update_option( "{$slug}-dismiss-welcome", 1 );
	wp_die();
}
add_action( 'wp_ajax_maglume_dismiss_welcome_notice', 'maglume_dismiss_welcome_notice' );

/**
 * Ajax callback to import and activate Hoot Import plugin
 */
function maglume_processplugin() {
	check_ajax_referer( 'hoottheme-welcome-action', 'nonce' );
	$slug = maglume_abouttag( 'slug' );
	$state = '';
	$alreadyexists = false;
	$response = array();
	$plugin = isset( $_POST['plugin'] ) && in_array( $_POST['plugin'], array( 'hoot-import', 'hootkit' ) ) ? $_POST['plugin'] : '';
	$redirectdashtab = isset( $_POST['redirectdashtab'] ) ? sanitize_text_field( wp_unslash( $_POST['redirectdashtab'] ) ) : '';
	if (
		( $plugin === 'hoot-import' && class_exists( 'HootImport' ) ) ||
		( $plugin === 'hootkit' && class_exists( 'HootKit' ) )
	 ) {
		$state = 'activated';
		$alreadyexists = true;
	} elseif ( file_exists( WP_PLUGIN_DIR . "/{$plugin}/{$plugin}.php" ) ) {
		$state = 'installed';
	} else {
		/** Install plugin. **/
		wp_enqueue_style( 'plugin-install' );
		wp_enqueue_script( 'plugin-install' );
		include_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
		include_once( ABSPATH . 'wp-admin/includes/plugin-install.php' );
		include_once( ABSPATH . 'wp-admin/includes/class-wp-ajax-upgrader-skin.php' );
		include_once( ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php' );
		$api = plugins_api(
			'plugin_information',
			array(
				'slug'   => sanitize_key( wp_unslash( $plugin ) ),
				'fields' => array(
					'short_description' => false,
					'sections' => false,
					'requires' => false,
					'rating' => false,
					'ratings' => false,
					'downloaded' => false,
					'last_updated' => false,
					'added' => false,
					'tags' => false,
					'compatibility' => false,
					'homepage' => false,
					'donate_link' => false,
				),
			)
		);
		if ( is_wp_error( $api ) ) {
			$response['errorInstall'] = $api->get_error_message();
		} else {
			$skin     = new WP_Ajax_Upgrader_Skin();
			$upgrader = new Plugin_Upgrader( $skin );
			$result   = $upgrader->install( $api->download_link );
			if ( $result ) {
				$state = 'installed';
			} else {
				$pluginname = ucwords( str_replace( '-', ' ', $plugin ) );
				/* Translators: 1 is line break, 2 is the link start markup, 3 is link markup end, 4 is the plugin name, 5 and 6 are strong tags */
				$errormsg = sprintf( esc_html__( 'WordPress encountered an unexpected error during the plugin installation.%1$sPlease %2$sclick this link%3$s to install the %5$s%4$s plugin%6$s directly.', 'magazine-lume' ), '<br />', '<a href="' . esc_url( admin_url( "plugin-install.php?s={$plugin}&tab=search&type=term" ) ) . '">', '</a>', $pluginname, '<strong>', '</strong>' );
				$response['errorInstall'] = $errormsg;
			}
		}
	}

	if ( 'installed' === $state ) {
		if ( current_user_can( 'activate_plugin' ) ) {
			$result = activate_plugin( "{$plugin}/{$plugin}.php" );
			if ( ! is_wp_error( $result ) ) {
				$state = 'activated';
			} else {
				$response['errorCode']    = $result->get_error_code();
				$response['errorMessage'] = $result->get_error_message();
			}
		}
	}
	if ( 'activated' === $state ) {
		if ( $plugin === 'hoot-import' ) {
			$response['redirect'] = admin_url( 'themes.php?page=hoot-import' );
		} elseif ( $plugin === 'hootkit' ) {
			if ( ! $alreadyexists ) {
				$args = array( $slug.'_hkinstalled' => 'true' );
				if ( $redirectdashtab ) $args['tab'] = $redirectdashtab;
				$response['redirect'] = add_query_arg( $args, admin_url( 'plugins.php' ) );
			} else {
				$args = array();
				if ( $redirectdashtab ) $args['tab'] = $redirectdashtab;
				$response['redirect'] = hoot_dashboard( 'url', $args );
			}
		}
	}

	wp_send_json( $response );
	exit();
}
add_action( 'wp_ajax_maglume_processplugin', 'maglume_processplugin' );
/**
 * Redirect if HootKit was just installed
 */
function maglume_installed_hootkit() {
	$slug = maglume_abouttag( 'slug' );
	if ( isset( $_GET[$slug.'_hkinstalled'] ) && $_GET[$slug.'_hkinstalled'] === 'true' ) {
		$args = isset( $_GET['tab'] ) ? array( 'tab' => sanitize_text_field( wp_unslash( $_GET['tab'] ) ) ) : array();
		if ( wp_safe_redirect( hoot_dashboard( 'url', $args ) ) ) {
			exit;
		}
	}
}
add_action( 'admin_init', 'maglume_installed_hootkit' );
