settings = $settings; $this->progress = $progress ?? new SyncProgress(); } public function register(): void { \add_action( 'admin_init', [ $this, 'redirectAfterActivation' ] ); \add_action( 'admin_post_' . self::ACTION, [ $this, 'handleAction' ] ); } public function isActive(): bool { return \get_option( self::OPTION, '' ) === 'active'; } public function isPaused(): bool { return \get_option( self::OPTION, '' ) === 'paused'; } public function step(): int { if ( ! $this->settings->hasApiKey() ) { return 1; } return $this->settings->hasSelectedAgents() && $this->settings->selectedAgentEmbedToken() !== '' ? 3 : 2; } public function canFinish(): bool { $progress = $this->progress->current(); return $this->step() === 3 && ! $progress['running'] && $progress['phase'] === SyncProgress::PHASE_DONE; } public function settingsUrl(): string { return \add_query_arg( [ 'page' => SettingsPage::PAGE_SLUG ], \admin_url( 'admin.php' ) ); } public function redirectAfterActivation(): void { $userId = \get_transient( self::REDIRECT_TRANSIENT ); if ( ! $userId || (int) $userId !== \get_current_user_id() ) { return; } if ( ! \current_user_can( SettingsPage::CAPABILITY ) || \wp_doing_ajax() || \wp_doing_cron() || \is_network_admin() || ( \defined( 'WP_CLI' ) && \WP_CLI ) || ( $GLOBALS['pagenow'] ?? '' ) === 'admin-post.php' ) { return; } \delete_transient( self::REDIRECT_TRANSIENT ); if ( ! $this->isActive() ) { return; } \wp_safe_redirect( $this->settingsUrl() ); exit; } public function handleAction(): void { if ( ! \current_user_can( SettingsPage::CAPABILITY ) ) { \wp_die( \esc_html__( 'Permission denied.', 'agent001-support-assistant-for-woocommerce' ), '', [ 'response' => 403 ] ); } \check_admin_referer( self::ACTION, '_agent001_onboarding_nonce' ); $operation = isset( $_POST['operation'] ) && is_string( $_POST['operation'] ) ? \sanitize_key( \wp_unslash( $_POST['operation'] ) ) : ''; if ( ! \in_array( $operation, [ 'pause', 'resume', 'finish' ], true ) ) { \wp_die( \esc_html__( 'Invalid setup action.', 'agent001-support-assistant-for-woocommerce' ), '', [ 'response' => 400 ] ); } if ( $operation === 'finish' && ! $this->canFinish() ) { \wp_die( \esc_html__( 'Complete the first synchronization before finishing setup.', 'agent001-support-assistant-for-woocommerce' ), '', [ 'response' => 409 ] ); } \update_option( self::OPTION, $operation === 'pause' ? 'paused' : ( $operation === 'finish' ? 'complete' : 'active' ), false ); \wp_safe_redirect( $this->settingsUrl() ); exit; } }