<?php
/**
 * First-run onboarding / setup wizard.
 *
 * @package SHC4WC
 */

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

class SHC4WC_Onboarding {
	const OPTION_COMPLETED      = 'shc4wc_onboarding_completed';
	const ACTIVATION_TRANSIENT  = 'shc4wc_activation_redirect';
	const PAGE_SLUG             = 'payments-square-connect-onboarding';

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

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public static function is_completed() {
		return (bool) get_option( self::OPTION_COMPLETED, false );
	}

	public static function mark_completed() {
		update_option( self::OPTION_COMPLETED, true, false );
	}

	/**
	 * @param string $status Optional shc4wc_status query arg after OAuth.
	 * @return string
	 */
	public static function page_url( $status = '' ) {
		$args = array();
		if ( $status ) {
			$args['shc4wc_status'] = $status;
		}
		return SHC4WC_Admin_Menu::page_url( self::PAGE_SLUG, $args );
	}

	private function __construct() {
		add_action( 'init', array( $this, 'maybe_redirect_onboarding_url' ), 1 );
		add_action( 'admin_menu', array( $this, 'register_menu' ), 11 );
		add_action( 'admin_init', array( $this, 'maybe_activation_redirect' ) );
		add_action( 'admin_init', array( $this, 'maybe_handle_save' ) );
		add_action( 'admin_post_shc4wc_onboarding_complete', array( $this, 'handle_complete' ) );
		add_action( 'admin_post_shc4wc_onboarding_skip', array( $this, 'handle_skip' ) );
		add_action( 'wp_ajax_shc4wc_onboarding_enable_gateway', array( $this, 'ajax_enable_gateway' ) );
		add_action( 'admin_notices', array( $this, 'setup_notice' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	public static function activation_redirect() {
		if ( wp_doing_ajax() || wp_doing_cron() || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
			return;
		}
		set_transient( self::ACTIVATION_TRANSIENT, 1, MINUTE_IN_SECONDS );
	}

	public function maybe_redirect_onboarding_url() {
		if ( empty( $_SERVER['REQUEST_URI'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			return;
		}

		$uri = sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		if ( ! preg_match( '#/wp-admin/payments-square-connect-onboarding/?(\?.*)?$#i', $uri ) ) {
			return;
		}

		if ( ! is_user_logged_in() ) {
			auth_redirect();
		}

		wp_safe_redirect( self::page_url() );
		exit;
	}

	public function maybe_activation_redirect() {
		if ( ! current_user_can( 'manage_options' ) || self::is_completed() ) {
			return;
		}

		if ( ! get_transient( self::ACTIVATION_TRANSIENT ) ) {
			return;
		}

		delete_transient( self::ACTIVATION_TRANSIENT );

		if ( isset( $_GET['activate-multi'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return;
		}

		wp_safe_redirect( self::page_url() );
		exit;
	}

	public function register_menu() {
		$title = self::is_completed()
			? __( 'Setup guide', 'payments-connect-square' )
			: __( 'Get started', 'payments-connect-square' );

		add_submenu_page(
			SHC4WC_Admin_Menu::MENU_SLUG,
			__( 'Payments Square Connect — Setup', 'payments-connect-square' ),
			$title,
			'manage_options',
			self::PAGE_SLUG,
			array( $this, 'render_page' )
		);
	}

	public function maybe_handle_save() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( self::PAGE_SLUG !== $page ) {
			return;
		}

		if ( empty( $_POST['shc4wc_onboarding_save'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
			return;
		}

		check_admin_referer( 'shc4wc_onboarding_save' );

		$current = SHC4WC_Plugin::get_raw_settings();
		$merged  = is_array( $current ) ? $current : array();

		if ( isset( $_POST['environment'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
			$env = sanitize_text_field( wp_unslash( $_POST['environment'] ) );
			$new_env = ( 'live' === $env ) ? 'live' : 'sandbox';
			$old_env = ( isset( $current['environment'] ) && 'live' === $current['environment'] ) ? 'live' : 'sandbox';
			$merged['environment'] = $new_env;
			if ( $old_env !== $new_env ) {
				if ( ! isset( $merged['location_ids'] ) || ! is_array( $merged['location_ids'] ) ) {
					$merged['location_ids'] = array();
				}
				if ( ! empty( $current['location_id'] ) ) {
					$merged['location_ids'][ $old_env ] = sanitize_text_field( (string) $current['location_id'] );
				}
				$merged['location_id'] = ! empty( $merged['location_ids'][ $new_env ] )
					? sanitize_text_field( (string) $merged['location_ids'][ $new_env ] )
					: '';
			}
		}

		if ( isset( $_POST['location_id'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
			$merged['location_id'] = sanitize_text_field( wp_unslash( $_POST['location_id'] ) );
			$active_env = ( isset( $merged['environment'] ) && 'live' === $merged['environment'] ) ? 'live' : 'sandbox';
			if ( ! isset( $merged['location_ids'] ) || ! is_array( $merged['location_ids'] ) ) {
				$merged['location_ids'] = array();
			}
			if ( '' !== $merged['location_id'] ) {
				$merged['location_ids'][ $active_env ] = $merged['location_id'];
			}
		}

		update_option( 'woocommerce_shc4wc_settings', SHC4WC_Plugin::normalize_settings( $merged ), false );

		wp_safe_redirect( add_query_arg( 'shc4wc_saved', '1', self::page_url() ) );
		exit;
	}

	public function handle_complete() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Unauthorized', 'payments-connect-square' ), 403 );
		}

		check_admin_referer( 'shc4wc_onboarding_complete' );
		self::mark_completed();

		wp_safe_redirect( SHC4WC_Connection_Settings::page_url( 'connected' ) );
		exit;
	}

	public function handle_skip() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Unauthorized', 'payments-connect-square' ), 403 );
		}

		check_admin_referer( 'shc4wc_onboarding_skip' );
		self::mark_completed();

		wp_safe_redirect( SHC4WC_Connection_Settings::page_url() );
		exit;
	}

	public function ajax_enable_gateway() {
		check_ajax_referer( 'shc4wc_onboarding', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Unauthorized', 'payments-connect-square' ) ), 403 );
		}

		if ( ! class_exists( 'WooCommerce' ) ) {
			wp_send_json_error( array( 'message' => __( 'WooCommerce is not active.', 'payments-connect-square' ) ), 400 );
		}

		$settings = get_option( 'woocommerce_shc4wc_settings', array() );
		if ( ! is_array( $settings ) ) {
			$settings = array();
		}

		$settings['enabled'] = 'yes';
		if ( empty( $settings['title'] ) ) {
			$settings['title'] = __( 'Pay with Square', 'payments-connect-square' );
		}
		if ( empty( $settings['description'] ) ) {
			$settings['description'] = __( 'You will be redirected to Square secure hosted checkout.', 'payments-connect-square' );
		}

		update_option( 'woocommerce_shc4wc_settings', $settings, false );

		wp_send_json_success(
			array(
				'message' => __( 'WooCommerce gateway enabled.', 'payments-connect-square' ),
			)
		);
	}

	public function setup_notice() {
		if ( ! current_user_can( 'manage_options' ) || self::is_completed() || SHC4WC_Plugin::is_connected() ) {
			return;
		}

		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( $screen && self::PAGE_SLUG === $screen->id ) {
			return;
		}

		printf(
			'<div class="notice notice-info is-dismissible"><p>%1$s <a href="%2$s" class="button button-primary" style="margin-left:8px;">%3$s</a></p></div>',
			esc_html__( 'Payments Square Connect is almost ready — complete the quick setup to accept payments.', 'payments-connect-square' ),
			esc_url( self::page_url() ),
			esc_html__( 'Get started', 'payments-connect-square' )
		);
	}

	public function enqueue_assets( $hook ) {
		if ( 'payments-square-connect_page_' . self::PAGE_SLUG !== $hook ) {
			return;
		}

		wp_enqueue_style(
			'shc4wc-onboarding',
			SHC4WC_PLUGIN_URL . 'assets/css/onboarding.css',
			array(),
			SHC4WC_VERSION
		);

		wp_enqueue_script(
			'shc4wc-onboarding',
			SHC4WC_PLUGIN_URL . 'assets/js/onboarding.js',
			array( 'jquery' ),
			SHC4WC_VERSION,
			true
		);

		wp_localize_script(
			'shc4wc-onboarding',
			'shc4wcOnboarding',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'shc4wc_onboarding' ),
				'aiNonce' => wp_create_nonce( 'shc4wc_ai_troubleshoot' ),
				'oauthStatus' => isset( $_GET['shc4wc_status'] ) ? sanitize_text_field( wp_unslash( $_GET['shc4wc_status'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				'i18n'    => array(
					'enabling'  => __( 'Enabling…', 'payments-connect-square' ),
					'enabled'   => __( 'Gateway enabled', 'payments-connect-square' ),
					'failed'    => __( 'Could not enable gateway. Try WooCommerce → Settings → Payments.', 'payments-connect-square' ),
					'aiLoading' => __( 'Asking AI…', 'payments-connect-square' ),
					'aiFailed'  => __( 'Could not get AI help. Check your OpenAI API key.', 'payments-connect-square' ),
				),
			)
		);
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$settings         = SHC4WC_Plugin::get_settings();
		$environment      = ( isset( $settings['environment'] ) && 'live' === $settings['environment'] ) ? 'live' : 'sandbox';
		$has_oauth        = SHC4WC_Plugin::has_oauth_connection();
		$is_connected     = SHC4WC_Plugin::is_connected();
		$gateway_enabled  = $this->is_gateway_enabled();
		$has_woocommerce  = class_exists( 'WooCommerce' );
		$location_options = $this->get_location_options();
		$location_id      = isset( $settings['location_id'] ) ? (string) $settings['location_id'] : '';
		$shop_url         = $has_woocommerce && function_exists( 'wc_get_page_permalink' ) ? wc_get_page_permalink( 'shop' ) : '';
		$checkout_url     = $has_woocommerce && function_exists( 'wc_get_checkout_url' ) ? wc_get_checkout_url() : '';
		$saved            = isset( $_GET['shc4wc_saved'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$status           = isset( $_GET['shc4wc_status'] ) ? sanitize_text_field( wp_unslash( $_GET['shc4wc_status'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$completed        = self::is_completed();
		$progress         = $this->calculate_progress( $has_oauth, $is_connected, $gateway_enabled, $has_woocommerce );

		$connect_url = wp_nonce_url( admin_url( 'admin-post.php?action=shc4wc_oauth_start' ), 'shc4wc_oauth_start' );
		$revoke_url  = wp_nonce_url( admin_url( 'admin-post.php?action=shc4wc_oauth_revoke' ), 'shc4wc_oauth_revoke' );
		?>
		<div class="wrap shc4wc-onboarding-wrap">
			<h1><?php esc_html_e( 'Welcome to Payments Square Connect', 'payments-connect-square' ); ?></h1>
			<p class="shc4wc-onboarding-intro">
				<?php esc_html_e( 'Follow these steps to connect Square and start accepting payments on Square Hosted Checkout.', 'payments-connect-square' ); ?>
			</p>

			<?php if ( $saved ) : ?>
				<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Settings saved.', 'payments-connect-square' ); ?></p></div>
			<?php endif; ?>

			<?php if ( 'connected' === $status ) : ?>
				<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Square connected successfully.', 'payments-connect-square' ); ?></p></div>
			<?php elseif ( in_array( $status, array( 'oauth_denied', 'oauth_state_error', 'oauth_exchange_failed', 'oauth_claim_failed' ), true ) ) : ?>
				<div class="notice notice-error is-dismissible"><p><?php esc_html_e( 'Square connection failed. Try again or enable Debug Log under advanced connection settings.', 'payments-connect-square' ); ?></p></div>
			<?php endif; ?>

			<div class="shc4wc-onboarding-progress" role="progressbar" aria-valuenow="<?php echo esc_attr( (string) $progress ); ?>" aria-valuemin="0" aria-valuemax="100">
				<div class="shc4wc-onboarding-progress__bar" style="width:<?php echo esc_attr( (string) $progress ); ?>%;"></div>
			</div>
			<p class="shc4wc-onboarding-progress-label">
				<?php
				printf(
					/* translators: %d: setup progress percentage. */
					esc_html__( 'Setup progress: %d%%', 'payments-connect-square' ),
					(int) $progress
				);
				?>
			</p>

			<div class="shc4wc-onboarding-steps">
				<?php $this->render_step_card(
					1,
					$environment && $has_oauth ? 'complete' : ( $environment ? 'current' : 'current' ),
					__( 'Choose environment', 'payments-connect-square' ),
					__( 'Start in Sandbox to test without real charges. Switch to Live when you are ready.', 'payments-connect-square' ),
					function () use ( $environment, $location_id, $location_options ) {
						?>
						<form method="post" action="">
							<?php wp_nonce_field( 'shc4wc_onboarding_save' ); ?>
							<input type="hidden" name="shc4wc_onboarding_save" value="1" />
							<input type="hidden" name="location_id" value="<?php echo esc_attr( $location_id ); ?>" />
							<fieldset>
								<label>
									<input type="radio" name="environment" value="sandbox" <?php checked( 'sandbox', $environment ); ?> />
									<?php esc_html_e( 'Sandbox (recommended for testing)', 'payments-connect-square' ); ?>
								</label>
								<br />
								<label>
									<input type="radio" name="environment" value="live" <?php checked( 'live', $environment ); ?> />
									<?php esc_html_e( 'Live (real payments)', 'payments-connect-square' ); ?>
								</label>
							</fieldset>
							<?php submit_button( __( 'Save environment', 'payments-connect-square' ), 'secondary', 'submit', false ); ?>
						</form>
						<?php
					}
				); ?>

				<?php $this->render_step_card(
					2,
					$has_oauth ? 'complete' : 'current',
					__( 'Connect Square', 'payments-connect-square' ),
					__( 'Sign in with your Square account. Tokens renew automatically in the background.', 'payments-connect-square' ),
					function () use ( $has_oauth, $connect_url, $revoke_url, $environment ) {
						if ( $has_oauth ) {
							$connected_label = ( 'live' === $environment )
								? __( 'Square Live account connected.', 'payments-connect-square' )
								: __( 'Square Sandbox account connected.', 'payments-connect-square' );
							echo '<p class="shc4wc-onboarding-status-ok">' . esc_html( $connected_label ) . '</p>';
							$disconnect_label = ( 'live' === $environment )
								? __( 'Disconnect Square for Live', 'payments-connect-square' )
								: __( 'Disconnect Square for Sandbox', 'payments-connect-square' );
							echo '<a class="button" href="' . esc_url( $revoke_url ) . '">' . esc_html( $disconnect_label ) . '</a>';
							return;
						}

						$connect_label = ( 'live' === $environment )
							? __( 'Connect Square for Live', 'payments-connect-square' )
							: __( 'Connect Square for Sandbox', 'payments-connect-square' );
						echo '<a class="button button-primary button-hero" href="' . esc_url( $connect_url ) . '">' . esc_html( $connect_label ) . '</a>';

						if ( 'sandbox' === $environment ) {
							echo SHC4WC_Connection_Settings::get_sandbox_connect_hint_html(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						}
					}
				); ?>

				<?php $this->render_step_card(
					3,
					$is_connected ? 'complete' : ( $has_oauth ? 'current' : 'pending' ),
					__( 'Select Square location', 'payments-connect-square' ),
					__( 'Choose the location that receives payments from this site.', 'payments-connect-square' ),
					function () use ( $has_oauth, $environment, $location_id, $location_options ) {
						if ( ! $has_oauth ) {
							echo '<p class="description">' . esc_html__( 'Connect Square first to load locations.', 'payments-connect-square' ) . '</p>';
							return;
						}
						?>
						<form method="post" action="">
							<?php wp_nonce_field( 'shc4wc_onboarding_save' ); ?>
							<input type="hidden" name="shc4wc_onboarding_save" value="1" />
							<input type="hidden" name="environment" value="<?php echo esc_attr( $environment ); ?>" />
							<p>
								<label for="shc4wc_onboarding_location" class="screen-reader-text"><?php esc_html_e( 'Square Location', 'payments-connect-square' ); ?></label>
								<select name="location_id" id="shc4wc_onboarding_location" class="regular-text">
									<?php foreach ( $location_options as $opt_key => $label ) : ?>
										<option value="<?php echo esc_attr( $opt_key ); ?>" <?php selected( $location_id, (string) $opt_key ); ?>><?php echo esc_html( $label ); ?></option>
									<?php endforeach; ?>
								</select>
							</p>
							<?php submit_button( __( 'Save location', 'payments-connect-square' ), 'secondary', 'submit', false ); ?>
						</form>
						<?php
					}
				); ?>

				<?php if ( $has_woocommerce ) : ?>
					<?php $this->render_step_card(
						4,
						$gateway_enabled ? 'complete' : ( $is_connected ? 'current' : 'pending' ),
						__( 'Enable WooCommerce checkout', 'payments-connect-square' ),
						__( 'Turn on Payments Square Connect as a payment method at checkout.', 'payments-connect-square' ),
						function () use ( $is_connected, $gateway_enabled ) {
							if ( ! $is_connected ) {
								echo '<p class="description">' . esc_html__( 'Finish Square connection and location first.', 'payments-connect-square' ) . '</p>';
								return;
							}
							if ( $gateway_enabled ) {
								echo '<p class="shc4wc-onboarding-status-ok">' . esc_html__( 'Gateway is enabled.', 'payments-connect-square' ) . '</p>';
								echo '<a class="button" href="' . esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=shc4wc' ) ) . '">' . esc_html__( 'Gateway settings', 'payments-connect-square' ) . '</a>';
							} else {
								echo '<button type="button" class="button button-primary shc4wc-onboarding-enable-gateway">' . esc_html__( 'Enable gateway now', 'payments-connect-square' ) . '</button>';
								echo ' <a class="button" href="' . esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=shc4wc' ) ) . '">' . esc_html__( 'Open payment settings', 'payments-connect-square' ) . '</a>';
								echo '<p class="shc4wc-onboarding-gateway-notice" aria-live="polite"></p>';
							}
						}
					); ?>

					<?php $this->render_step_card(
						5,
						$completed ? 'complete' : ( $gateway_enabled && $is_connected ? 'current' : 'pending' ),
						__( 'Place a test order', 'payments-connect-square' ),
						__( 'Add a product to the cart and pay on Square Hosted Checkout. Orders stay Pending until Square confirms payment.', 'payments-connect-square' ),
						function () use ( $is_connected, $gateway_enabled, $shop_url, $checkout_url ) {
							if ( ! $is_connected || ! $gateway_enabled ) {
								echo '<p class="description">' . esc_html__( 'Enable the gateway above, then run a test checkout.', 'payments-connect-square' ) . '</p>';
								return;
							}
							if ( $shop_url ) {
								echo '<a class="button button-primary" href="' . esc_url( $shop_url ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Visit shop', 'payments-connect-square' ) . '</a> ';
							}
							if ( $checkout_url ) {
								echo '<a class="button" href="' . esc_url( $checkout_url ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Go to checkout', 'payments-connect-square' ) . '</a>';
							}
						}
					); ?>
				<?php else : ?>
					<?php $this->render_step_card(
						4,
						$is_connected ? 'complete' : 'pending',
						__( 'Optional: WooCommerce', 'payments-connect-square' ),
						__( 'Install WooCommerce if you want a store checkout. You can also use payment link buttons, Contact Form 7, WPForms, or Fluent Forms.', 'payments-connect-square' ),
						function () {
							echo '<a class="button" href="' . esc_url( admin_url( 'plugin-install.php?s=woocommerce&tab=search&type=term' ) ) . '">' . esc_html__( 'Install WooCommerce', 'payments-connect-square' ) . '</a>';
						}
					); ?>
				<?php endif; ?>
			</div>

			<?php
			if ( class_exists( 'SHC4WC_AI_Assistant' ) ) {
				SHC4WC_AI_Assistant::render_onboarding_panel( $status );
			}
			?>

			<div class="shc4wc-onboarding-footer">
				<?php if ( $is_connected ) : ?>
					<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="shc4wc-onboarding-finish-form">
						<input type="hidden" name="action" value="shc4wc_onboarding_complete" />
						<?php wp_nonce_field( 'shc4wc_onboarding_complete' ); ?>
						<?php submit_button( __( 'Finish setup', 'payments-connect-square' ), 'primary', 'submit', false ); ?>
					</form>
				<?php endif; ?>

				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="shc4wc-onboarding-skip-form">
					<input type="hidden" name="action" value="shc4wc_onboarding_skip" />
					<?php wp_nonce_field( 'shc4wc_onboarding_skip' ); ?>
					<button type="submit" class="button-link"><?php esc_html_e( 'Skip setup for now', 'payments-connect-square' ); ?></button>
				</form>

				<p class="description">
					<a href="<?php echo esc_url( SHC4WC_Admin_Menu::page_url() ); ?>"><?php esc_html_e( 'Advanced connection settings', 'payments-connect-square' ); ?></a>
					|
					<a href="<?php echo esc_url( SHC4WC_Admin_Menu::page_url( SHC4WC_Admin_Menu::SUPPORT_SLUG ) ); ?>"><?php esc_html_e( 'Need help?', 'payments-connect-square' ); ?></a>
				</p>
			</div>
		</div>
		<?php
	}

	/**
	 * @param int      $number  Step number.
	 * @param string   $state   complete|current|pending.
	 * @param string   $title   Step title.
	 * @param string   $desc    Step description.
	 * @param callable $content Step body callback.
	 */
	private function render_step_card( $number, $state, $title, $desc, $content ) {
		$state = in_array( $state, array( 'complete', 'current', 'pending' ), true ) ? $state : 'pending';
		?>
		<div class="shc4wc-onboarding-step shc4wc-onboarding-step--<?php echo esc_attr( $state ); ?>">
			<div class="shc4wc-onboarding-step__badge" aria-hidden="true">
				<?php if ( 'complete' === $state ) : ?>
					<span class="dashicons dashicons-yes-alt"></span>
				<?php else : ?>
					<span><?php echo esc_html( (string) $number ); ?></span>
				<?php endif; ?>
			</div>
			<div class="shc4wc-onboarding-step__body">
				<h2><?php echo esc_html( $title ); ?></h2>
				<p class="description"><?php echo esc_html( $desc ); ?></p>
				<div class="shc4wc-onboarding-step__content">
					<?php
					if ( is_callable( $content ) ) {
						call_user_func( $content );
					}
					?>
				</div>
			</div>
		</div>
		<?php
	}

	private function is_gateway_enabled() {
		if ( ! class_exists( 'WooCommerce' ) ) {
			return true;
		}
		$settings = get_option( 'woocommerce_shc4wc_settings', array() );
		return is_array( $settings ) && isset( $settings['enabled'] ) && 'yes' === $settings['enabled'];
	}

	private function get_location_options() {
		$locations = SHC4WC_Plugin::get_locations();
		if ( empty( $locations ) ) {
			return array(
				'' => __( 'Connect Square to load locations', 'payments-connect-square' ),
			);
		}

		$options = array( '' => __( 'Select a location', 'payments-connect-square' ) );
		foreach ( $locations as $location ) {
			if ( empty( $location['id'] ) ) {
				continue;
			}
			$name                       = ! empty( $location['name'] ) ? $location['name'] : $location['id'];
			$options[ $location['id'] ] = sprintf( '%s (%s)', $name, $location['id'] );
		}
		return $options;
	}

	/**
	 * @param bool $has_oauth       OAuth connected.
	 * @param bool $is_connected    Full connection with location.
	 * @param bool $gateway_enabled Gateway on.
	 * @param bool $has_woocommerce WC active.
	 * @return int 0-100
	 */
	private function calculate_progress( $has_oauth, $is_connected, $gateway_enabled, $has_woocommerce ) {
		$steps   = array();
		$steps[] = true; // environment always chosen (default sandbox).
		$steps[] = $has_oauth;
		$steps[] = $is_connected;
		if ( $has_woocommerce ) {
			$steps[] = $gateway_enabled;
			$steps[] = self::is_completed();
		} else {
			$steps[] = $is_connected;
		}

		$done  = count( array_filter( $steps ) );
		$total = count( $steps );

		return $total > 0 ? (int) round( ( $done / $total ) * 100 ) : 0;
	}
}
