<?php
/**
 * First-run welcome wizard.
 *
 * After activation, sets a transient that triggers a redirect to the
 * welcome page on the next admin page load. Network-activated multisite
 * activations are not redirected.
 *
 * @package WPLens
 */

namespace WPLens\Admin;

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

final class Welcome {

	public const REDIRECT_TRANSIENT = 'wplens_welcome_redirect';

	public function register(): void {
		add_action( 'admin_init', array( $this, 'maybe_redirect' ) );
	}

	public static function arm_redirect(): void {
		set_transient( self::REDIRECT_TRANSIENT, 1, MINUTE_IN_SECONDS * 5 );
	}

	public function maybe_redirect(): void {
		if ( ! get_transient( self::REDIRECT_TRANSIENT ) ) {
			return;
		}
		if ( wp_doing_ajax() || wp_doing_cron() ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		// Bail on network activation; just leave the welcome page accessible.
		if ( is_network_admin() ) {
			return;
		}
		// Don't redirect when already on the welcome page or doing a bulk plugin update.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
		if ( 'lens-welcome' === $page ) {
			delete_transient( self::REDIRECT_TRANSIENT );
			return;
		}

		delete_transient( self::REDIRECT_TRANSIENT );
		wp_safe_redirect( admin_url( 'admin.php?page=lens-welcome' ) );
		exit;
	}
}
