<?php
/**
 * Admin notice suggesting the Wuppi Blocks companion plugin when it is not active.
 *
 * @package wuppi
 */

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

/**
 * Handle the dismiss request for the Wuppi Blocks companion notice.
 */
function wuppi_companion_notice_handle_dismiss() {
	if ( empty( $_GET['wuppi_dismiss'] ) || 'blocks_notice' !== $_GET['wuppi_dismiss'] ) {
		return;
	}
	check_admin_referer( 'wuppi_dismiss_blocks_notice' );
	update_user_meta( get_current_user_id(), 'wuppi_dismiss_blocks_notice', true );
	wp_safe_redirect( remove_query_arg( array( 'wuppi_dismiss', '_wpnonce' ) ) );
	exit;
}
add_action( 'admin_init', 'wuppi_companion_notice_handle_dismiss' );

/**
 * Render the admin notice suggesting Wuppi Blocks.
 */
function wuppi_companion_notice_blocks() {
	if ( ! current_user_can( 'install_plugins' ) ) {
		return;
	}

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

	if ( is_plugin_active( 'wuppi-blocks/wuppi-blocks.php' ) ) {
		return;
	}

	if ( get_user_meta( get_current_user_id(), 'wuppi_dismiss_blocks_notice', true ) ) {
		return;
	}

	$screen = get_current_screen();
	if ( ! $screen ) {
		return;
	}

	$allowed_screens = array( 'dashboard', 'themes', 'plugins', 'appearance_page_wuppi-settings', 'appearance_page_wuppi-help' );
	if ( ! in_array( $screen->id, $allowed_screens, true ) ) {
		return;
	}

	$dismiss_url = wp_nonce_url(
		add_query_arg( 'wuppi_dismiss', 'blocks_notice' ),
		'wuppi_dismiss_blocks_notice'
	);
	?>
	<div class="notice notice-info is-dismissible">
		<p>
			<strong><?php esc_html_e( 'Unlock more blocks for Wuppi', 'wuppi' ); ?></strong> &mdash;
			<?php esc_html_e( 'Install the free Wuppi Blocks companion plugin to add custom blocks and patterns to your site.', 'wuppi' ); ?>
			<a href="<?php echo esc_url( network_admin_url( 'plugin-install.php?s=wuppi-blocks&tab=search&type=term' ) ); ?>">
				<?php esc_html_e( 'Install Wuppi Blocks', 'wuppi' ); ?>
			</a>
			&nbsp;&middot;&nbsp;
			<a href="<?php echo esc_url( $dismiss_url ); ?>"><?php esc_html_e( 'Dismiss', 'wuppi' ); ?></a>
		</p>
	</div>
	<?php
}
add_action( 'admin_notices', 'wuppi_companion_notice_blocks' );
