<?php
/**
 * FoodOrd Setup Wizard.
 *
 * @package FoodOrd
 */

defined('ABSPATH') || exit;

require_once FOODORD_DIR . 'includes/class-foodord-demo-importer.php';

/**
 * Class Foodord_Setup_Wizard
 */
class Foodord_Setup_Wizard
{
	private const PAGE_SLUG = 'foodord-setup';
	private const OPTION_COMPLETE = 'foodord_onboarding_complete';
	private const OPTION_REDIRECT = 'foodord_onboarding_redirect';
	private const OPTION_ORDER_PAGE_ID = 'foodord_onboarding_order_page_id';
	private const OPTION_RESERVATION_PAGE_ID = 'foodord_onboarding_reservation_page_id';
	private const OPTION_IMPORT_SUMMARY = 'foodord_onboarding_import_summary';
	private const OPTION_ALLOW_TRACKING = 'foodord_allow_tracking';
	private const TRANSIENT_ERROR = 'foodord_setup_wizard_error';
	private const TRANSIENT_NOTICE = 'foodord_setup_wizard_notice';

	/**
	 * Register wizard hooks.
	 */
	public function init(): void
	{
		add_action('admin_menu', array($this, 'register_page'));
		add_action('admin_init', array($this, 'handle_actions'), 1);
		add_action('admin_init', array($this, 'maybe_redirect'));
		add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
		add_filter('woocommerce_prevent_automatic_wizard_redirect', array($this, 'prevent_woocommerce_wizard_redirect'), 10, 1);
	}

	/**
	 * Handle wizard actions early so redirects don't trigger "headers already sent" warnings.
	 */
	public function handle_actions(): void
	{
		if (!is_admin() || !current_user_can('manage_options')) {
			return;
		}

		if (function_exists('wp_doing_ajax') && wp_doing_ajax()) {
			return;
		}

		if (!$this->is_wizard_request()) {
			return;
		}

		if ('yes' !== get_option(self::OPTION_COMPLETE)) {
			$this->cleanup_woocommerce_wizard_redirect();
		}

		$request_method = isset($_SERVER['REQUEST_METHOD']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD'])) : '';
		if ('POST' !== $request_method) {
			return;
		}

		$nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
		if ('' === $nonce) {
			return;
		}

		$setup_action = isset($_POST['foodord_setup_action']) ? sanitize_key(wp_unslash($_POST['foodord_setup_action'])) : '';

		if ('skip' === $setup_action && wp_verify_nonce($nonce, 'foodord_setup_skip')) {
			$this->handle_skip();
			return;
		}

		if ('import' === $setup_action && wp_verify_nonce($nonce, 'foodord_setup_import')) {
			$this->handle_import();
			return;
		}

		if ('setup_woocommerce' === $setup_action && wp_verify_nonce($nonce, 'foodord_setup_woocommerce')) {
			$this->handle_woocommerce_setup();
			return;
		}

		if ('save_diagnostics' === $setup_action && wp_verify_nonce($nonce, 'foodord_setup_diagnostics')) {
			$this->handle_diagnostics_preferences();
			return;
		}

		// Backward compatibility for forms that post only nonce.
		if (wp_verify_nonce($nonce, 'foodord_setup_skip')) {
			$this->handle_skip();
			return;
		}

		if (wp_verify_nonce($nonce, 'foodord_setup_import')) {
			$this->handle_import();
			return;
		}

		if (wp_verify_nonce($nonce, 'foodord_setup_woocommerce')) {
			$this->handle_woocommerce_setup();
			return;
		}

		if (wp_verify_nonce($nonce, 'foodord_setup_diagnostics')) {
			$this->handle_diagnostics_preferences();
			return;
		}
	}

	/**
	 * Prevent WooCommerce from hijacking FoodOrd onboarding by redirecting to its own setup wizard.
	 *
	 * @param bool $prevent Current filter value.
	 * @return bool
	 */
	public function prevent_woocommerce_wizard_redirect($prevent): bool
	{
		if ('yes' === get_option(self::OPTION_COMPLETE)) {
			return (bool) $prevent;
		}

		return true;
	}

	/**
	 * Determine whether the current request is for the FoodOrd setup wizard.
	 */
	private function is_wizard_request(): bool
	{
		$page_raw = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		$page = is_string($page_raw) ? sanitize_key($page_raw) : '';
		return self::PAGE_SLUG === $page;
	}

	/**
	 * Remove WooCommerce activation redirect flags so FoodOrd wizard can continue.
	 */
	private function cleanup_woocommerce_wizard_redirect(): void
	{
		delete_transient('_wc_activation_redirect');
		delete_transient('woocommerce_activation_redirect');
		delete_transient('_woocommerce_activation_redirect');
	}

	/**
	 * Store a one-time error message.
	 */
	private function set_error(string $message): void
	{
		if ('' === trim($message)) {
			return;
		}
		set_transient(self::TRANSIENT_ERROR, $message, 60);
	}

	/**
	 * Store a one-time notice message.
	 */
	private function set_notice(string $message): void
	{
		if ('' === trim($message)) {
			return;
		}
		set_transient(self::TRANSIENT_NOTICE, $message, 60);
	}

	/**
	 * Pop and clear a one-time message.
	 */
	private function pop_transient_message(string $key): string
	{
		$value = get_transient($key);
		delete_transient($key);
		return is_string($value) ? $value : '';
	}

	/**
	 * Redirect to a wizard step.
	 */
	private function redirect_to_step(string $step, array $args = array()): void
	{
		$args = array_merge(
			array(
				'page' => self::PAGE_SLUG,
				'step' => $step,
			),
			$args
		);

		wp_safe_redirect(add_query_arg($args, admin_url('admin.php')));
		exit;
	}

	/**
	 * Redirect to the wizard after activation.
	 */
	public function maybe_redirect(): void
	{
		if (!is_admin() || !current_user_can('manage_options')) {
			return;
		}

		if (function_exists('wp_doing_ajax') && wp_doing_ajax()) {
			return;
		}

		if (is_network_admin()) {
			return;
		}

		$activate_multi = filter_input(INPUT_GET, 'activate-multi', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		if (null !== $activate_multi) {
			return;
		}

		if ('yes' === get_option(self::OPTION_COMPLETE)) {
			delete_option(self::OPTION_REDIRECT);
			return;
		}

		if ('1' !== get_option(self::OPTION_REDIRECT)) {
			return;
		}

		$page_raw = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		if (is_string($page_raw) && self::PAGE_SLUG === sanitize_key($page_raw)) {
			return;
		}

		delete_option(self::OPTION_REDIRECT);

		wp_safe_redirect(admin_url('admin.php?page=' . self::PAGE_SLUG));
		exit;
	}

	/**
	 * Register hidden wizard page.
	 */
	public function register_page(): void
	{
		add_submenu_page(
			null,
			__('FoodOrd Setup', 'foodord'),
			__('FoodOrd Setup', 'foodord'),
			'manage_options',
			self::PAGE_SLUG,
			array($this, 'render')
		);
	}

	/**
	 * Enqueue assets for wizard page.
	 *
	 * @param string $hook Current admin hook.
	 */
	public function enqueue_assets($hook): void
	{
		if ('admin_page_' . self::PAGE_SLUG !== $hook) {
			return;
		}

		wp_enqueue_style(
			'foodord-setup-wizard',
			FOODORD_URL . 'admin/css/foodord-setup-wizard.css',
			array(),
			FOODORD_VERSION,
			'all'
		);

		wp_enqueue_script(
			'foodord-setup-wizard',
			FOODORD_URL . 'admin/js/foodord-setup-wizard.js',
			array(),
			FOODORD_VERSION,
			true
		);

		wp_localize_script(
			'foodord-setup-wizard',
			'foodord_wizard_data',
			array(
				'loading_text' => __('Processing...', 'foodord'),
			)
		);
	}

	/**
	 * Render wizard UI.
	 */
	public function render(): void
	{
		if (!current_user_can('manage_options')) {
			wp_die(esc_html__('You do not have permission to access this page.', 'foodord'));
		}

		$step_raw = filter_input(INPUT_GET, 'step', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		$step = is_string($step_raw) ? sanitize_key($step_raw) : 'welcome';
		$allowed_steps = array('welcome', 'checks', 'import', 'done');
		if (!in_array($step, $allowed_steps, true)) {
			$step = 'welcome';
		}

		$this->render_layout_start($step);

		switch ($step) {
			case 'checks':
				$this->render_checks_step();
				break;
			case 'import':
				$this->render_import_step();
				break;
			case 'done':
				$this->render_done_step();
				break;
			case 'welcome':
			default:
				$this->render_welcome_step();
				break;
		}

		$this->render_layout_end();
	}

	/**
	 * Render layout header.
	 *
	 * @param string $step Current step.
	 */
	private function render_layout_start(string $step): void
	{
		$steps = array(
			'welcome' => __('Welcome', 'foodord'),
			'checks' => __('Prerequisites', 'foodord'),
			'import' => __('Demo Import', 'foodord'),
			'done' => __('Done', 'foodord'),
		);

		?>
		<div class="foodord-setup-wizard">
			<div class="foodord-setup-wizard__header">
				<div class="foodord-setup-wizard__brand"><?php esc_html_e('FoodOrd', 'foodord'); ?></div>
				<ol class="foodord-setup-wizard__steps">
					<?php foreach ($steps as $key => $label): ?>
						<?php $class = ($key === $step) ? 'foodord-setup-wizard__step is-active' : 'foodord-setup-wizard__step'; ?>
						<li class="<?php echo esc_attr($class); ?>"><?php echo esc_html($label); ?></li>
					<?php endforeach; ?>
				</ol>
			</div>
			<div class="foodord-setup-wizard__content">
				<?php
	}

	/**
	 * Render layout footer.
	 */
	private function render_layout_end(): void
	{
		?>
			</div>
			<form class="foodord-setup-wizard__skip" method="post" action="<?php echo esc_url(admin_url('admin.php?page=' . self::PAGE_SLUG)); ?>">
				<?php wp_nonce_field('foodord_setup_skip'); ?>
				<input class="foodord-setup-wizard__input" type="hidden" name="foodord_setup_action" value="skip" />
				<button type="submit"
					class="foodord-setup-wizard__skip-btn"><?php esc_html_e('Skip setup', 'foodord'); ?></button>
			</form>
		</div>
		<?php
	}

	/**
	 * Render welcome step.
	 */
	private function render_welcome_step(): void
	{
		echo '<h1 class="foodord-setup-wizard__title">' . esc_html__('Welcome to FoodOrd', 'foodord') . '</h1>';
		echo '<p class="foodord-setup-wizard__text">' . esc_html__('This short setup will import demo products, settings, and create Order and Reservations pages for you.', 'foodord') . '</p>';
		echo '<p class="foodord-setup-wizard__text">' . esc_html__('You can skip this at any time and set things up manually.', 'foodord') . '</p>';

		$this->render_next_button('checks', __('Start setup', 'foodord'));
	}

	/**
	 * Render prerequisites step.
	 */
	private function render_checks_step(): void
	{
		$notice_message = $this->pop_transient_message(self::TRANSIENT_NOTICE);
		$error_message = $this->pop_transient_message(self::TRANSIENT_ERROR);

		$checks = $this->get_prerequisites();
		$all_ok = true;
		foreach ($checks as $check) {
			if (empty($check['ok'])) {
				$all_ok = false;
				break;
			}
		}

		echo '<h1 class="foodord-setup-wizard__title">' . esc_html__('Prerequisites', 'foodord') . '</h1>';
		echo '<p class="foodord-setup-wizard__text">' . esc_html__('Make sure the following requirements are met before importing the demo.', 'foodord') . '</p>';

		if ('' !== $error_message) {
			echo '<div class="foodord-setup-wizard__notice is-error">' . esc_html($error_message) . '</div>';
		} elseif ('' !== $notice_message) {
			echo '<div class="foodord-setup-wizard__notice">' . esc_html($notice_message) . '</div>';
		}
		?>
		<ul class="foodord-setup-wizard__checks">
			<?php foreach ($checks as $check): ?>
				<?php
				$status = !empty($check['ok']) ? esc_html__('OK', 'foodord') : esc_html__('Not ready', 'foodord');
				$class = !empty($check['ok']) ? 'is-ok' : 'is-fail';
				?>
				<li class="foodord-setup-wizard__check <?php echo esc_attr($class); ?>">
					<div class="foodord-setup-wizard__check-title"><?php echo esc_html((string) $check['label']); ?></div>
					<div class="foodord-setup-wizard__check-status"><?php echo esc_html($status); ?></div>
					<?php if (!empty($check['message'])): ?>
						<div class="foodord-setup-wizard__check-message"><?php echo esc_html((string) $check['message']); ?></div>
					<?php endif; ?>
				</li>
			<?php endforeach; ?>
		</ul>
		<?php

		$this->render_diagnostics_opt_in();

		if (empty($checks['woocommerce']['ok'])) {
			$plugin_file = 'woocommerce/woocommerce.php';
			$label = file_exists(WP_PLUGIN_DIR . '/' . $plugin_file) ? __('Activate WooCommerce', 'foodord') : __('Install WooCommerce', 'foodord');
			?>
			<form method="post" class="foodord-setup-wizard__form">
				<?php wp_nonce_field('foodord_setup_woocommerce'); ?>
				<input class="foodord-setup-wizard__input" type="hidden" name="foodord_setup_action" value="setup_woocommerce" />
				<button type="submit" class="foodord-setup-wizard__primary-btn"><?php echo esc_html($label); ?></button>
			</form>
			<?php
		}

		if ($all_ok) {
			$this->render_diagnostics_continue_button(__('Continue to demo import', 'foodord'));
		} else {
			?>
			<div class="foodord-setup-wizard__alert is-warning">
				<div class="foodord-setup-wizard__alert-content">
					<span class="foodord-setup-wizard__alert-icon">!</span>
					<div class="foodord-setup-wizard__alert-text">
						<?php esc_html_e('One or more requirements are not met. Please fix the items above and refresh the page to continue.', 'foodord'); ?>
					</div>
				</div>
			</div>
			<?php
		}
	}

	/**
	 * Render diagnostic data consent on the prerequisites step.
	 */
	private function render_diagnostics_opt_in(): void
	{
		$allow_tracking = 'no' !== (string) get_option(self::OPTION_ALLOW_TRACKING, 'yes');
		?>
		<div class="foodord-setup-wizard__diagnostics">
			<label class="foodord-setup-wizard__diagnostics-label" for="foodord-setup-diagnostics">
				<span class="foodord-setup-wizard__diagnostics-content">
					<strong><?php esc_html_e('Share diagnostic data', 'foodord'); ?></strong>
					<small><?php esc_html_e('Help us improve FoodOrd by sharing technical environment and compatibility data.', 'foodord'); ?></small>
					<small><?php esc_html_e('No customer, order, payment, product, or personal customer data is collected.', 'foodord'); ?></small>
					<small><?php esc_html_e('Note: You can disable this later from the FoodOrd Help tab.', 'foodord'); ?></small>
				</span>
				<span class="foodord-setup-wizard__diagnostics-toggle">
					<input id="foodord-setup-diagnostics" class="foodord-setup-wizard__diagnostics-checkbox" type="checkbox" name="foodord_allow_tracking" value="yes" form="foodord-setup-diagnostics-form" <?php checked($allow_tracking); ?> />
					<span class="foodord-setup-wizard__diagnostics-toggle-control" aria-hidden="true"></span>
				</span>
			</label>
		</div>
		<?php
	}

	/**
	 * Render import step.
	 *
	 * @param string $error_message Error message.
	 */
	private function render_import_step(): void
	{
		$notice_message = $this->pop_transient_message(self::TRANSIENT_NOTICE);
		$error_message = $this->pop_transient_message(self::TRANSIENT_ERROR);

		echo '<h1 class="foodord-setup-wizard__title">' . esc_html__('Import demo content', 'foodord') . '</h1>';
		echo '<p class="foodord-setup-wizard__text">' . esc_html__('This will overwrite existing demo items by slug (products and categories).', 'foodord') . '</p>';
		echo '<p class="foodord-setup-wizard__text">' . esc_html__('It will also create an "Order Page" with the FoodOrd products and cart shortcodes, create a Reservations page, and set the Order Page as the homepage.', 'foodord') . '</p>';

		if ('' !== $error_message) {
			echo '<div class="foodord-setup-wizard__notice is-error">' . esc_html($error_message) . '</div>';
		} elseif ('' !== $notice_message) {
			echo '<div class="foodord-setup-wizard__notice">' . esc_html($notice_message) . '</div>';
		}

		?>
		<form method="post" class="foodord-setup-wizard__form">
			<?php wp_nonce_field('foodord_setup_import'); ?>
			<input class="foodord-setup-wizard__input" type="hidden" name="foodord_setup_action" value="import" />
			<button type="submit"
				class="foodord-setup-wizard__primary-btn"><?php esc_html_e('Run demo import', 'foodord'); ?></button>
		</form>
		<?php
	}

	/**
	 * Render done step.
	 */
	private function render_done_step(): void
	{
		$order_page_id = (int) get_option(self::OPTION_ORDER_PAGE_ID, 0);
		$reservation_page_id = (int) get_option(self::OPTION_RESERVATION_PAGE_ID, 0);
		$summary = get_option(self::OPTION_IMPORT_SUMMARY, array());
		$summary = is_array($summary) ? $summary : array();
		$skipped_raw = filter_input(INPUT_GET, 'skipped', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		$skipped = is_string($skipped_raw) && '1' === sanitize_text_field($skipped_raw);
		$settings_page = function_exists('foodord_get_settings_page_slug') ? foodord_get_settings_page_slug('dashboard') : 'foodord-dashboard';
		$settings_url = admin_url('admin.php?page=' . $settings_page);

		?>
		<h1 class="foodord-setup-wizard__title"><?php esc_html_e('Setup complete', 'foodord'); ?></h1>

		<?php if ($skipped): ?>
			<p class="foodord-setup-wizard__text">
				<?php esc_html_e('You skipped the demo import. You can configure FoodOrd from the settings pages.', 'foodord'); ?>
			</p>
		<?php else: ?>
			<p class="foodord-setup-wizard__text"><?php esc_html_e('Your demo content has been imported.', 'foodord'); ?></p>
			<?php if (!empty($summary['counts']) && is_array($summary['counts'])): ?>
				<ul class="foodord-setup-wizard__summary">
					<?php foreach ($summary['counts'] as $key => $value): ?>
						<?php
						if (!is_scalar($value)) {
							continue;
						}
						?>
						<li><?php echo esc_html(ucfirst((string) $key) . ': ' . (string) $value); ?></li>
					<?php endforeach; ?>
				</ul>
			<?php endif; ?>

			<?php
			$order_page_url = $order_page_id > 0 ? get_permalink($order_page_id) : '';
			$reservation_page_url = $reservation_page_id > 0 ? get_permalink($reservation_page_id) : '';
			?>
			<div class="foodord-setup-wizard__actions">
				<?php if ($order_page_url): ?>
					<a class="foodord-setup-wizard__link" href="<?php echo esc_url($order_page_url); ?>" target="_blank"
						rel="noopener noreferrer"><?php esc_html_e('Visit Order Page', 'foodord'); ?></a>
				<?php endif; ?>
				<?php if ($reservation_page_url): ?>
					<a class="foodord-setup-wizard__link" href="<?php echo esc_url($reservation_page_url); ?>" target="_blank"
						rel="noopener noreferrer"><?php esc_html_e('Visit Reservations Page', 'foodord'); ?></a>
				<?php endif; ?>
				<a class="foodord-setup-wizard__link"
					href="<?php echo esc_url($settings_url); ?>"><?php esc_html_e('Go to FoodOrd settings', 'foodord'); ?></a>
			</div>
		<?php endif; ?>

		<?php if ($skipped): ?>
			<div class="foodord-setup-wizard__actions">
				<a class="foodord-setup-wizard__link"
					href="<?php echo esc_url($settings_url); ?>"><?php esc_html_e('Go to FoodOrd settings', 'foodord'); ?></a>
			</div>
		<?php endif; ?>
		<?php $this->render_optional_theme_panel(); ?>
	<?php
	}

	/**
	 * Render the optional FoodOrd Theme download panel.
	 */
	private function render_optional_theme_panel(): void
	{
		if (defined('FOODORD_THEME_ACTIVE') && FOODORD_THEME_ACTIVE) {
			return;
		}

		$theme_download_url = function_exists('foodord_get_theme_download_url')
			? foodord_get_theme_download_url()
			: 'https://www.foodord.com/downloads/';
		?>
		<div class="foodord-setup-wizard__theme-card">
			<div class="foodord-setup-wizard__theme-copy">
				<h2 class="foodord-setup-wizard__theme-title"><?php esc_html_e('FoodOrd Theme is optional', 'foodord'); ?></h2>
				<p class="foodord-setup-wizard__theme-text">
					<?php esc_html_e('Install the FoodOrd Theme for the full storefront layout with the sidebar cart, home banner, and theme-specific admin pages.', 'foodord'); ?>
				</p>
				<p class="foodord-setup-wizard__theme-text">
					<?php esc_html_e('Download the theme zip, then upload it in Appearance > Themes > Add New > Upload Theme.', 'foodord'); ?>
				</p>
			</div>
			<div class="foodord-setup-wizard__theme-actions">
				<a class="foodord-setup-wizard__primary-btn foodord-setup-wizard__primary-btn--inline" href="<?php echo esc_url($theme_download_url); ?>" target="_blank" rel="noopener noreferrer">
					<?php esc_html_e('Download Theme', 'foodord'); ?>
				</a>
			</div>
		</div>
		<?php
	}

	/**
	 * Render a next-step button.
	 *
	 * @param string $step Target step.
	 * @param string $label Button label.
	 */
	private function render_next_button(string $step, string $label): void
	{
		?>
		<form method="get" class="foodord-setup-wizard__form">
			<input type="hidden" name="page" value="<?php echo esc_attr(self::PAGE_SLUG); ?>" />
			<input type="hidden" name="step" value="<?php echo esc_attr($step); ?>" />
			<button type="submit" class="foodord-setup-wizard__primary-btn"><?php echo esc_html($label); ?></button>
		</form>
		<?php
	}

	/**
	 * Render the prerequisites continue form that persists diagnostic preferences.
	 *
	 * @param string $label Button label.
	 */
	private function render_diagnostics_continue_button(string $label): void
	{
		?>
		<form id="foodord-setup-diagnostics-form" method="post" class="foodord-setup-wizard__form">
			<?php wp_nonce_field('foodord_setup_diagnostics'); ?>
			<input class="foodord-setup-wizard__input" type="hidden" name="foodord_setup_action" value="save_diagnostics" />
			<button id="foodord-setup-diagnostics-submit" type="submit" class="foodord-setup-wizard__primary-btn"><?php echo esc_html($label); ?></button>
		</form>
		<?php
	}

	/**
	 * Handle skip action.
	 */
	private function handle_skip(): void
	{
		update_option(self::OPTION_COMPLETE, 'yes');
		delete_option(self::OPTION_REDIRECT);
		wp_safe_redirect(admin_url('index.php'));
		exit;
	}

	/**
	 * Persist diagnostic preferences before continuing to import.
	 */
	private function handle_diagnostics_preferences(): void
	{
		$tracking_value = filter_input(INPUT_POST, 'foodord_allow_tracking', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		$tracking_value = is_string($tracking_value) ? sanitize_text_field(wp_unslash($tracking_value)) : '';
		$allow_tracking = 'yes' === $tracking_value;
		if (class_exists('Foodord_Diagnostics')) {
			Foodord_Diagnostics::update_preference($allow_tracking);
		} else {
			update_option(self::OPTION_ALLOW_TRACKING, $allow_tracking ? 'yes' : 'no');
		}

		$this->redirect_to_step('import');
	}

	/**
	 * Handle demo import.
	 */
	private function handle_import(): void
	{
		if (!(class_exists('WooCommerce') || function_exists('wc'))) {
			$this->set_error(__('WooCommerce must be installed and active before importing the demo.', 'foodord'));
			$this->redirect_to_step('checks');
		}

		$demo_dir = FOODORD_DIR . 'assets/demo';
		$importer = new Foodord_Demo_Importer($demo_dir);
		$result = $importer->import();

		if (empty($result['success'])) {
			$this->set_error(isset($result['message']) ? (string) $result['message'] : __('Demo import failed.', 'foodord'));
			$this->redirect_to_step('import');
		}

		$order_page_id = isset($result['order_page_id']) ? (int) $result['order_page_id'] : 0;
		$reservation_page_id = isset($result['reservation_page_id']) ? (int) $result['reservation_page_id'] : 0;
		update_option(self::OPTION_ORDER_PAGE_ID, $order_page_id);
		update_option(self::OPTION_RESERVATION_PAGE_ID, $reservation_page_id);
		update_option(self::OPTION_IMPORT_SUMMARY, $result);
		update_option(self::OPTION_COMPLETE, 'yes');
		delete_option(self::OPTION_REDIRECT);

		$this->redirect_to_step('done');
	}

	/**
	 * Install or activate WooCommerce and return to FoodOrd wizard.
	 */
	private function handle_woocommerce_setup(): void
	{
		if (class_exists('WooCommerce') || function_exists('wc')) {
			$this->set_notice(__('WooCommerce is already active.', 'foodord'));
			$this->redirect_to_step('checks');
		}

		$plugin_file = 'woocommerce/woocommerce.php';

		if (file_exists(WP_PLUGIN_DIR . '/' . $plugin_file)) {
			if (!current_user_can('activate_plugins')) {
				$this->set_error(__('You do not have permission to activate plugins.', 'foodord'));
				$this->redirect_to_step('checks');
			}

			$result = activate_plugin($plugin_file);
			if (is_wp_error($result)) {
				$this->set_error($result->get_error_message());
				$this->redirect_to_step('checks');
			}

			$this->cleanup_woocommerce_wizard_redirect();
			$this->set_notice(__('WooCommerce activated.', 'foodord'));
			$this->redirect_to_step('checks');
		}

		if (!current_user_can('install_plugins')) {
			$this->set_error(__('You do not have permission to install plugins.', 'foodord'));
			$this->redirect_to_step('checks');
		}

		$installed = $this->install_woocommerce();
		if (is_wp_error($installed)) {
			$this->set_error($installed->get_error_message());
			$this->redirect_to_step('checks');
		}

		if (!file_exists(WP_PLUGIN_DIR . '/' . $plugin_file)) {
			$this->set_error(__('WooCommerce was installed but could not be found on disk.', 'foodord'));
			$this->redirect_to_step('checks');
		}

		if (!current_user_can('activate_plugins')) {
			$this->cleanup_woocommerce_wizard_redirect();
			$this->set_notice(__('WooCommerce installed. Activate it to continue.', 'foodord'));
			$this->redirect_to_step('checks');
		}

		$result = activate_plugin($plugin_file);
		if (is_wp_error($result)) {
			$this->set_error($result->get_error_message());
			$this->redirect_to_step('checks');
		}

		$this->cleanup_woocommerce_wizard_redirect();
		$this->set_notice(__('WooCommerce installed and activated.', 'foodord'));
		$this->redirect_to_step('checks');
	}

	/**
	 * Install WooCommerce from WordPress.org.
	 *
	 * @return true|WP_Error
	 */
	private function install_woocommerce()
	{
		require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
		require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		require_once ABSPATH . 'wp-admin/includes/file.php';

		$api = plugins_api(
			'plugin_information',
			array(
				'slug' => 'woocommerce',
				'fields' => array(
					'sections' => false,
				),
			)
		);

		if (is_wp_error($api)) {
			return new WP_Error(
				'foodord_wc_plugins_api_failed',
				sprintf(
					/* translators: %s: Error message returned by WordPress.org API. */
					__('Could not reach WordPress.org to download WooCommerce. Please check your server connection and try again. (%s)', 'foodord'),
					$api->get_error_message()
				)
			);
		}

		$download_link = isset($api->download_link) ? (string) $api->download_link : '';
		if ('' === $download_link) {
			return new WP_Error('foodord_wc_download_link_missing', __('WooCommerce download link is missing.', 'foodord'));
		}

		$skin = new Automatic_Upgrader_Skin();
		$upgrader = new Plugin_Upgrader($skin);

		ob_start();
		$result = $upgrader->install($download_link);
		ob_end_clean();

		if (is_wp_error($result)) {
			return $result;
		}

		if (!$result) {
			return new WP_Error('foodord_wc_install_failed', __('WooCommerce installation failed.', 'foodord'));
		}

		return true;
	}

	/**
	 * Build prerequisites list.
	 *
	 * @return array<string,array{label:string,ok:bool,message:string,action_url?:string,action_label?:string}>
	 */
	private function get_prerequisites(): array
	{
		$checks = array();

		$wp_ok = defined('FOODORD_MIN_WP') ? version_compare(get_bloginfo('version'), FOODORD_MIN_WP, '>=') : true;
		$checks['wp'] = array(
			'label' => __('WordPress version', 'foodord'),
			'ok' => $wp_ok,
			/* translators: %s: Minimum required WordPress version. */
			'message' => $wp_ok ? '' : sprintf(__('Requires WordPress %s or newer.', 'foodord'), defined('FOODORD_MIN_WP') ? FOODORD_MIN_WP : ''),
		);

		$php_ok = defined('FOODORD_MIN_PHP') ? version_compare(PHP_VERSION, FOODORD_MIN_PHP, '>=') : true;
		$checks['php'] = array(
			'label' => __('PHP version', 'foodord'),
			'ok' => $php_ok,
			/* translators: %s: Minimum required PHP version. */
			'message' => $php_ok ? '' : sprintf(__('Requires PHP %s or newer.', 'foodord'), defined('FOODORD_MIN_PHP') ? FOODORD_MIN_PHP : ''),
		);

		$wc_active = class_exists('WooCommerce') || function_exists('wc');
		$checks['woocommerce'] = array(
			'label' => __('WooCommerce active', 'foodord'),
			'ok' => $wc_active,
			'message' => $wc_active ? '' : __('Install and activate WooCommerce to continue.', 'foodord'),
		);

		$demo_zip_ok = file_exists(FOODORD_DIR . 'assets/demo/demo-data.json')
			&& is_dir(FOODORD_DIR . 'assets/demo/images');
		$checks['demo'] = array(
			'label' => __('Embedded demo package', 'foodord'),
			'ok' => $demo_zip_ok,
			'message' => $demo_zip_ok ? '' : __('Demo content is missing from the plugin.', 'foodord'),
		);

		$upload_dir = wp_upload_dir();
		$uploads_ok = isset($upload_dir['basedir']) && is_string($upload_dir['basedir']) && is_dir($upload_dir['basedir']) && wp_is_writable($upload_dir['basedir']);
		$checks['uploads'] = array(
			'label' => __('Uploads folder writable', 'foodord'),
			'ok' => $uploads_ok,
			'message' => $uploads_ok ? '' : __('Uploads directory is not writable.', 'foodord'),
		);

		return $checks;
	}
}
