<?php
/**
 * Changeloger Setup Wizard
 *
 * Provides a step-by-step onboarding experience for new users.
 * Handles product creation, brand color setup, and demo import.
 *
 * @package Changeloger
 * @since   1.7.0
 */

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

/**
 * Class Changeloger_Setup_Wizard
 *
 * Multi-step setup wizard for first-time plugin users.
 */
class Changeloger_Setup_Wizard {

	/**
	 * Option key to track wizard completion.
	 *
	 * @var string
	 */
	const OPTION_WIZARD_COMPLETED = 'changeloger_wizard_completed';

	/**
	 * Singleton instance.
	 *
	 * @var self|null
	 */
	private static $instance = null;

	/**
	 * Get class instance.
	 *
	 * @return self
	 */
	public static function get_instance(): self {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	private function __construct() {
		add_action( 'admin_menu', [ $this, 'add_wizard_page' ], 20 );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_wizard_assets' ] );
		add_action( 'admin_init', [ $this, 'maybe_redirect_to_wizard' ] );
		add_action( 'rest_api_init', [ $this, 'register_rest_routes' ] );
	}

	/**
	 * Check if the wizard has been completed.
	 *
	 * @return bool
	 */
	public static function is_completed(): bool {
		return (bool) get_option( self::OPTION_WIZARD_COMPLETED, false );
	}

	/**
	 * Mark the wizard as completed.
	 *
	 * @return void
	 */
	public static function mark_completed(): void {
		update_option( self::OPTION_WIZARD_COMPLETED, true );
	}

	/**
	 * Redirect to wizard on first activation.
	 *
	 * Checks a transient set during plugin activation to trigger the redirect.
	 *
	 * @return void
	 */
	public function maybe_redirect_to_wizard(): void {
		// Only redirect if the activation transient is set.
		if ( ! get_transient( 'changeloger_activation_redirect' ) ) {
			return;
		}

		// Wait for Freemius opt-in decision
		if ( function_exists( 'cha_fs' ) && ! cha_fs()->is_registered() ) {
			return;
		}

		// Delete the transient so it only redirects once.
		delete_transient( 'changeloger_activation_redirect' );

		// Don't redirect on multisite bulk activation.
		if ( is_network_admin() || isset( $_GET['activate-multi'] ) ) {
			return;
		}

		// Don't redirect if wizard already completed.
		if ( self::is_completed() ) {
			return;
		}

		// Don't redirect if doing AJAX or REST request.
		if ( wp_doing_ajax() || defined( 'REST_REQUEST' ) ) {
			return;
		}

		wp_safe_redirect( admin_url( 'admin.php?page=changeloger-setup' ) );
		exit;
	}

	/**
	 * Add wizard page to admin menu.
	 *
	 * @return void
	 */
	public function add_wizard_page(): void {
		add_submenu_page(
			'changeloger',
			__( 'Changeloger Setup', 'changeloger' ),
			__( 'Setup Wizard', 'changeloger' ),
			'manage_options',
			'changeloger-setup',
			[ $this, 'render_wizard_page' ]
		);
	}

	/**
	 * Enqueue wizard CSS and JS.
	 *
	 * @param string $hook Current admin page hook.
	 * @return void
	 */
	public function enqueue_wizard_assets( string $hook ): void {
		if ( strpos( $hook, 'changeloger-setup' ) === false ) {
			return;
		}

		// Hide admin notices on wizard page.
		remove_all_actions( 'admin_notices' );
		remove_all_actions( 'all_admin_notices' );

		wp_enqueue_style(
			'cha-setup-wizard',
			plugins_url( 'assets/css/setup-wizard.css', dirname( __FILE__ ) ),
			[],
			defined( 'CHANGELOGER_VERSION' ) ? CHANGELOGER_VERSION : '1.7.0'
		);

		wp_enqueue_script(
			'cha-setup-wizard',
			plugins_url( 'assets/js/setup-wizard.js', dirname( __FILE__ ) ),
			[ 'wp-api-fetch' ],
			defined( 'CHANGELOGER_VERSION' ) ? CHANGELOGER_VERSION : '1.7.0',
			true
		);

		wp_localize_script( 'cha-setup-wizard', 'chaSetupWizard', [
			'nonce'        => wp_create_nonce( 'wp_rest' ),
			'restBase'     => rest_url( 'changeloger/v1/' ),
			'adminUrl'     => admin_url(),
			'dashboardUrl' => admin_url( 'admin.php?page=changeloger' ),
			'releasesUrl'  => admin_url( 'admin.php?page=changeloger-releases' ),
			'settingsUrl'  => admin_url( 'admin.php?page=changeloger-settings' ),
			'pluginUrl'    => plugins_url( '', dirname( __FILE__ ) ),
			'isPremium'    => function_exists( 'cha_is_premium' ) && cha_is_premium(),
			'i18n'         => [
				'welcome_title'       => __( 'Welcome to Changeloger!', 'changeloger' ),
				'welcome_subtitle'    => __( 'Let\'s set up your changelog in just a few steps.', 'changeloger' ),
				'product_title'       => __( 'Create Your Product', 'changeloger' ),
				'product_subtitle'    => __( 'Give your software or product a name to start tracking releases.', 'changeloger' ),
				'branding_title'      => __( 'Customize Your Brand', 'changeloger' ),
				'branding_subtitle'   => __( 'Set a brand color to personalize your changelog\'s appearance.', 'changeloger' ),
				'import_title'        => __( 'Import Sample Data', 'changeloger' ),
				'import_subtitle'     => __( 'Want to see how Changeloger works? Import sample data to explore the features.', 'changeloger' ),
				'done_title'          => __( 'You\'re All Set!', 'changeloger' ),
				'done_subtitle'       => __( 'Your changelog is ready. Here are some next steps to get started.', 'changeloger' ),
				'btn_get_started'     => __( 'Get Started', 'changeloger' ),
				'btn_next'            => __( 'Continue', 'changeloger' ),
				'btn_skip'            => __( 'Skip', 'changeloger' ),
				'btn_back'            => __( 'Back', 'changeloger' ),
				'btn_finish'          => __( 'Go to Dashboard', 'changeloger' ),
				'btn_import'          => __( 'Import Sample Data', 'changeloger' ),
				'btn_skip_import'     => __( 'Skip, I\'ll start from scratch', 'changeloger' ),
				'product_label'       => __( 'Product Name', 'changeloger' ),
				'product_placeholder' => __( 'e.g. My Awesome Plugin', 'changeloger' ),
				'product_help'        => __( 'This is the product you want to track changelogs for.', 'changeloger' ),
				'color_label'         => __( 'Primary Brand Color', 'changeloger' ),
				'color_help'          => __( 'This color will be used for buttons, highlights, and accents throughout your changelog.', 'changeloger' ),
				'importing'           => __( 'Importing sample data...', 'changeloger' ),
				'import_success'      => __( 'Sample data imported successfully!', 'changeloger' ),
				'import_error'        => __( 'Failed to import sample data. You can try again later from the Dashboard.', 'changeloger' ),
				'creating_product'    => __( 'Creating product...', 'changeloger' ),
				'product_created'     => __( 'Product created successfully!', 'changeloger' ),
				'product_error'       => __( 'Failed to create product. Please try again.', 'changeloger' ),
				'saving_settings'     => __( 'Saving settings...', 'changeloger' ),
				'settings_saved'      => __( 'Settings saved!', 'changeloger' ),
				'next_create_release' => __( 'Create Your First Release', 'changeloger' ),
				'next_settings'       => __( 'Configure Settings', 'changeloger' ),
				'next_docs'           => __( 'Read Documentation', 'changeloger' ),
			],
		] );
	}

	/**
	 * Register REST API routes for the wizard.
	 *
	 * @return void
	 */
	public function register_rest_routes(): void {
		register_rest_route( 'changeloger/v1', '/setup/complete', [
			'methods'             => 'POST',
			'callback'            => [ $this, 'rest_complete_wizard' ],
			'permission_callback' => function () {
				return current_user_can( 'manage_options' );
			},
		] );

		register_rest_route( 'changeloger/v1', '/setup/save-settings', [
			'methods'             => 'POST',
			'callback'            => [ $this, 'rest_save_settings' ],
			'permission_callback' => function () {
				return current_user_can( 'manage_options' );
			},
		] );
	}

	/**
	 * REST callback to mark wizard complete.
	 *
	 * @return WP_REST_Response
	 */
	public function rest_complete_wizard(): WP_REST_Response {
		self::mark_completed();
		return rest_ensure_response( [ 'success' => true ] );
	}

	/**
	 * REST callback to save brand color setting.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function rest_save_settings( WP_REST_Request $request ): WP_REST_Response {
		$data     = $request->get_json_params();
		$settings = get_option( 'changeloger_settings', [] );

		if ( isset( $data['brand_color'] ) ) {
			$settings['brand_color'] = sanitize_hex_color( $data['brand_color'] );
		}

		update_option( 'changeloger_settings', $settings );

		return rest_ensure_response( [ 'success' => true ] );
	}

	/**
	 * Render the wizard page.
	 *
	 * @return void
	 */
	public function render_wizard_page(): void {
		?>
		<div id="cha-setup-wizard" class="cha-setup-wizard">
			<!-- Wizard content rendered by JavaScript -->
			<div class="cha-wizard-loading">
				<div class="cha-wizard-spinner"></div>
			</div>
		</div>
		<?php
	}
}
