<?php
/**
 * Setup Wizard.
 *
 * First-run onboarding. On activation a one-time flag is set; the next admin
 * page load redirects (once) to this welcome screen. The wizard:
 *   - Introduces Platform Helm and its modules.
 *   - Lets the user enable the modules they want with checkboxes.
 *   - Optionally runs a first Internal Link Health scan so the dashboard has
 *     real numbers immediately.
 *   - Marks setup complete so it never auto-shows again (re-activation during
 *     development won't nag).
 *
 * Registered as a hidden submenu (no menu item) so it has a real admin URL but
 * doesn't clutter the menu. Capability-gated and nonce-protected.
 *
 * @package Platform\Helm\Admin
 */

declare( strict_types = 1 );

namespace Platform\Helm\Admin;

use Platform\Helm\Core\ModuleRegistry;
use Platform\Helm\Core\Settings;

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

final class SetupWizard {

	public const PAGE_SLUG = 'platform-helm-setup';
	private const CAPABILITY = 'manage_options';
	private const COMPLETE_OPTION = 'platform_helm_setup_complete';
	private const REDIRECT_OPTION = 'platform_helm_do_setup_redirect';

	public function __construct(
		private Settings $settings,
		private ModuleRegistry $registry
	) {}

	public function register_hooks(): void {
		add_action( 'admin_menu', [ $this, 'register_hidden_page' ] );
		add_action( 'admin_init', [ $this, 'maybe_redirect' ] );
		add_action( 'admin_init', [ $this, 'maybe_handle_submit' ] );
	}

	public function register_hidden_page(): void {
		// Registered with null parent = reachable by URL, not shown in a menu.
		add_submenu_page(
			'',
			__( 'Welcome to Platform Helm', 'platform-helm' ),
			__( 'Setup', 'platform-helm' ),
			self::CAPABILITY,
			self::PAGE_SLUG,
			[ $this, 'render' ]
		);
	}

	/**
	 * One-time redirect to the wizard right after activation.
	 */
	public function maybe_redirect(): void {
		if ( ! get_option( self::REDIRECT_OPTION ) ) {
			return;
		}
		// Don't redirect on AJAX, bulk activation, or for users who can't manage.
		if ( wp_doing_ajax() || ! current_user_can( self::CAPABILITY ) ) {
			return;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( isset( $_GET['activate-multi'] ) ) {
			delete_option( self::REDIRECT_OPTION );
			return;
		}
		delete_option( self::REDIRECT_OPTION );
		wp_safe_redirect( admin_url( 'admin.php?page=' . self::PAGE_SLUG ) );
		exit;
	}

	public function maybe_handle_submit(): void {
		if ( ! isset( $_POST['platform_helm_setup_save'] ) ) {
			return;
		}
		if ( ! current_user_can( self::CAPABILITY ) ) {
			return;
		}
		check_admin_referer( 'platform_helm_setup', '_setup_nonce' );

		// Enable chosen modules.
		$chosen = isset( $_POST['enable_module'] ) && is_array( $_POST['enable_module'] )
			? array_map( 'sanitize_key', wp_unslash( $_POST['enable_module'] ) )
			: [];

		foreach ( $this->registry->all() as $module ) {
			$this->settings->set_module_enabled( $module->id(), in_array( $module->id(), $chosen, true ) );
		}

		// Optionally run a first scan.
		$run_scan = ! empty( $_POST['run_first_scan'] );
		if ( $run_scan && class_exists( '\Platform\Helm\Modules\Link_Health\HealthAnalyzer' ) ) {
			( new \Platform\Helm\Modules\Link_Health\HealthAnalyzer() )->get_report( true );
		}

		update_option( self::COMPLETE_OPTION, 1, false );

		wp_safe_redirect( admin_url( 'admin.php?page=' . DashboardPage::PAGE_SLUG . '&helm_welcome=1' ) );
		exit;
	}

	public function render(): void {
		if ( ! current_user_can( self::CAPABILITY ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'platform-helm' ) );
		}
		$modules = $this->registry->all();
		?>
		<div class="wrap ph-wrap">
			<style>
			.phelm-wiz{max-width:720px;margin:30px auto 0;background:#fff;border:1px solid #E5EAF2;border-radius:12px;padding:32px 36px;box-shadow:0 4px 20px rgba(15,26,51,.06);}
			.phelm-wiz-badge{display:inline-flex;align-items:center;justify-content:center;width:48px;height:48px;border-radius:12px;background:linear-gradient(135deg,#0047AB,#2C6BD9);color:#fff;font-size:24px;font-weight:700;margin-bottom:16px;}
			.phelm-wiz h1{font-size:26px;font-weight:700;letter-spacing:-.5px;margin:0 0 6px;color:#0F1A33;}
			.phelm-wiz .lede{font-size:14px;color:#5C6B82;margin:0 0 24px;line-height:1.6;}
			.phelm-wiz-mod{display:flex;gap:12px;align-items:flex-start;padding:14px;border:1px solid #E5EAF2;border-radius:9px;margin-bottom:10px;transition:border-color .14s,background .14s;cursor:pointer;}
			.phelm-wiz-mod:hover{border-color:#C9D8EF;background:#F7F9FC;}
			.phelm-wiz-mod input{margin-top:3px;}
			.phelm-wiz-mod-body{flex:1;}
			.phelm-wiz-mod-name{font-size:14px;font-weight:600;color:#0F1A33;}
			.phelm-wiz-mod-desc{font-size:12px;color:#5C6B82;margin-top:2px;line-height:1.5;}
			.phelm-wiz-rec{display:inline-block;font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.3px;color:#1F8A5A;background:#E4F7EE;border:1px solid #B5E8CE;border-radius:3px;padding:1px 6px;margin-left:6px;vertical-align:middle;}
			.phelm-wiz-foot{margin-top:24px;display:flex;align-items:center;gap:16px;}
			.phelm-wiz-scan{font-size:13px;color:#5C6B82;display:flex;align-items:center;gap:7px;}
			.phelm-wiz-skip{margin-left:auto;font-size:13px;}
			</style>

			<div class="phelm-wiz">
				<div class="phelm-wiz-badge">⎈</div>
				<h1><?php esc_html_e( 'Welcome to Platform Helm', 'platform-helm' ); ?></h1>
				<p class="lede"><?php esc_html_e( 'Your content-operations command center. Pick the modules you want to start with — you can change these any time under Helm → Modules. Each module is self-contained and adds zero overhead when off.', 'platform-helm' ); ?></p>

				<form method="post">
					<?php wp_nonce_field( 'platform_helm_setup', '_setup_nonce' ); ?>

					<?php foreach ( $modules as $module ) :
						$default_on = $module->default_enabled();
						?>
						<label class="phelm-wiz-mod">
							<input type="checkbox" name="enable_module[]" value="<?php echo esc_attr( $module->id() ); ?>" <?php checked( $default_on ); ?>>
							<span class="phelm-wiz-mod-body">
								<span class="phelm-wiz-mod-name">
									<?php echo esc_html( $module->name() ); ?>
									<?php if ( $default_on ) : ?><span class="phelm-wiz-rec"><?php esc_html_e( 'recommended', 'platform-helm' ); ?></span><?php endif; ?>
								</span>
								<span class="phelm-wiz-mod-desc"><?php echo esc_html( $module->description() ); ?></span>
							</span>
						</label>
					<?php endforeach; ?>

					<div class="phelm-wiz-foot">
						<button type="submit" name="platform_helm_setup_save" class="button button-primary button-hero"><?php esc_html_e( 'Finish setup', 'platform-helm' ); ?></button>
						<label class="phelm-wiz-scan">
							<input type="checkbox" name="run_first_scan" value="1" checked>
							<?php esc_html_e( 'Run a first link-health scan now', 'platform-helm' ); ?>
						</label>
						<a class="phelm-wiz-skip" href="<?php echo esc_url( admin_url( 'admin.php?page=' . DashboardPage::PAGE_SLUG ) ); ?>"><?php esc_html_e( 'Skip for now', 'platform-helm' ); ?></a>
					</div>
				</form>
			</div>
		</div>
		<?php
	}

	/**
	 * Whether the user has completed (or skipped) setup. Used by the dashboard
	 * checklist to know whether to show the "complete setup" nudge.
	 */
	public static function is_complete(): bool {
		return (bool) get_option( self::COMPLETE_OPTION, false );
	}
}
