<?php

namespace NeurogenesisTheme\QuickSetup\Steps;

use NeurogenesisTheme\Helpers\RecommendedPlugin;
use NeurogenesisTheme\QuickSetup\QuickSetup;
use NeurogenesisTheme\QuickSetup\Step;

defined( 'ABSPATH' ) || exit;

final class InstallCompanionPlugin extends Step {

	public function id(): string {
		return 'companion';
	}

	public function label(): string {
		return __( 'Install & activate Neurogenesis Styler plugin', 'thinko' );
	}

	public function url(): string {
		return '';
	}

	public function action(): string {
		if ( $this->completed() ) {
			return '';
		}

		return 'install_recommended_plugin';
	}

	public function completed(): bool {
		$filtered = $this->filtered_completed( 'neurogenesis_theme_quick_setup_companion_completed' );
		if ( null !== $filtered ) {
			return $filtered;
		}

		return 'active' === RecommendedPlugin::get_status()
			|| self::is_plugin_active( QuickSetup::companion_slug() )
			|| null !== RecommendedPlugin::get_plugin_basename();
	}

	private static function is_plugin_active( string $slug ): bool {
		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		$folder = sanitize_title( $slug ) . '/';

		foreach ( array_keys( get_plugins() ) as $file ) {
			if ( ! str_starts_with( $file, $folder ) ) {
				continue;
			}

			return is_plugin_active( $file );
		}

		return false;
	}
}
