<?php
/**
 * System Summary Module
 *
 * Dashboard widget: environment, site health, performance, security, database,
 * updates, storage, quick actions, and WP PowerSuite status.
 *
 * @package SystemSummary
 * @since 1.0.0
 */

namespace SystemSummary;

use WP_PowerSuite\Core\Contracts\DataLocationsInterface;
use WP_PowerSuite\Core\AbstractModule;
use WP_PowerSuite\Core\ModuleRegistry;
use WP_PowerSuite\Core\NetworkScope;
class Module extends AbstractModule implements DataLocationsInterface {

	private const MODULE_ID = 'system-summary';
	private const MODULE_VERSION = '1.0.0';
	private const CACHE_KEY = 'wpps_system_summary_widget';
	private const CACHE_EXPIRY = 300; // 5 minutes

	private const STATUS_OK     = 'ok';
	private const STATUS_WARN   = 'warning';
	private const STATUS_ERROR  = 'error';

public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'System Summary', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'At-a-glance site health, environment, updates, and storage on the dashboard—expand what you need.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return [ 'admin' ];
	}

	public function getDependencies(): array {
		return [];
	}

	private function isLicenseActive(): bool {
		return function_exists( 'wp_powersuite_is_license_valid' ) && wp_powersuite_is_license_valid();
	}


	protected function registerHooks(): void {
		if ( ! $this->isLicenseActive() ) {
			return;
		}

		if ( ! is_admin() ) {
			return;
		}
		add_action( 'wp_dashboard_setup', [ $this, 'addDashboardWidget' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueueAssets' ] );
		add_action( 'wp_powersuite_module_settings_saved', [ $this, 'clearWidgetCache' ], 10, 2 );
	}


	/**
	 * {@inheritdoc}
	 */
	public function getDataLocations(): array {
		return [
			'option_store_keys' => [ self::MODULE_ID ],
		];
	}

	/**
	 * Clear widget cache when settings are saved.
	 */
	public function clearWidgetCache( string $module_id, array $settings ): void {
		if ( $module_id === self::MODULE_ID ) {
			delete_transient( self::CACHE_KEY );
		}
	}

	public function enqueueAssets( string $hook ): void {
		if ( $hook !== 'index.php' ) {
			return;
		}
		add_action( 'admin_head', [ $this, 'outputWidgetStyles' ] );
		add_action( 'admin_footer', [ $this, 'outputWidgetScripts' ] );
	}

	public function addDashboardWidget(): void {
		if ( ! current_user_can( NetworkScope::adminCapability() ) ) {
			return;
		}
		wp_add_dashboard_widget(
			'wpps_system_summary',
			__( 'System Summary', 'wp-powersuite' ),
			[ $this, 'renderDashboardWidget' ]
		);
	}

	public function renderDashboardWidget(): void {
		$settings = $this->getSettings();
		$sections = $settings['sections'] ?? $this->getDefaultSections();
		$sections = is_array( $sections ) ? $sections : [];
		$compact  = ! empty( $settings['compact_mode'] );

		$cached = get_transient( self::CACHE_KEY );
		if ( $cached !== false && is_string( $cached ) ) {
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Cached HTML built from escaped data
			echo $cached;
			return;
		}

		$env      = ! empty( $sections['environment'] ) ? $this->getEnvironmentData() : [];
		$health   = ! empty( $sections['site_health'] ) ? $this->getSiteHealthData() : [];
		$perf     = ! empty( $sections['performance'] ) ? $this->getPerformanceData() : [];
		$security = ! empty( $sections['security'] ) ? $this->getSecurityData() : [];
		$db       = ! empty( $sections['database'] ) ? $this->getDatabaseData() : [];
		$updates  = ! empty( $sections['updates'] ) ? $this->getUpdatesData() : [];
		$suite    = ! empty( $sections['powersuite'] ) ? $this->getPowerSuiteData() : [];

		ob_start();
		$compact_class = $compact ? ' wpps-ss-compact' : '';
		?>
		<div class="wpps-system-summary<?php echo esc_attr( $compact_class ); ?>">
			<?php if ( ! empty( $sections['environment'] ) ) : ?>
			<details class="wpps-ss-section">
				<summary class="wpps-ss-section-title"><span class="dashicons dashicons-admin-tools"></span> <?php esc_html_e( 'Environment', 'wp-powersuite' ); ?></summary>
				<div class="wpps-ss-section-body">
					<?php $this->renderEnvironment( $env ); ?>
				</div>
			</details>
			<?php endif; ?>

			<?php if ( ! empty( $sections['site_health'] ) ) : ?>
			<details class="wpps-ss-section">
				<summary class="wpps-ss-section-title"><span class="dashicons dashicons-heart"></span> <?php esc_html_e( 'Site Health', 'wp-powersuite' ); ?></summary>
				<div class="wpps-ss-section-body">
					<?php $this->renderSiteHealth( $health ); ?>
				</div>
			</details>
			<?php endif; ?>

			<?php if ( ! empty( $sections['performance'] ) ) : ?>
			<details class="wpps-ss-section">
				<summary class="wpps-ss-section-title"><span class="dashicons dashicons-performance"></span> <?php esc_html_e( 'Performance', 'wp-powersuite' ); ?></summary>
				<div class="wpps-ss-section-body">
					<?php $this->renderPerformance( $perf ); ?>
				</div>
			</details>
			<?php endif; ?>

			<?php if ( ! empty( $sections['security'] ) ) : ?>
			<details class="wpps-ss-section">
				<summary class="wpps-ss-section-title"><span class="dashicons dashicons-shield"></span> <?php esc_html_e( 'Security', 'wp-powersuite' ); ?></summary>
				<div class="wpps-ss-section-body">
					<?php $this->renderSecurity( $security ); ?>
				</div>
			</details>
			<?php endif; ?>

			<?php if ( ! empty( $sections['database'] ) ) : ?>
			<details class="wpps-ss-section">
				<summary class="wpps-ss-section-title"><span class="dashicons dashicons-database"></span> <?php esc_html_e( 'Database', 'wp-powersuite' ); ?></summary>
				<div class="wpps-ss-section-body">
					<?php $this->renderDatabase( $db ); ?>
				</div>
			</details>
			<?php endif; ?>

			<?php if ( ! empty( $sections['updates'] ) ) : ?>
			<details class="wpps-ss-section">
				<summary class="wpps-ss-section-title"><span class="dashicons dashicons-update"></span> <?php esc_html_e( 'Updates', 'wp-powersuite' ); ?></summary>
				<div class="wpps-ss-section-body">
					<?php $this->renderUpdates( $updates ); ?>
				</div>
			</details>
			<?php endif; ?>

			<?php if ( ! empty( $sections['powersuite'] ) ) : ?>
			<details class="wpps-ss-section">
				<summary class="wpps-ss-section-title"><span class="dashicons dashicons-admin-plugins"></span> <?php esc_html_e( 'WP PowerSuite', 'wp-powersuite' ); ?></summary>
				<div class="wpps-ss-section-body">
					<?php $this->renderPowerSuite( $suite ); ?>
				</div>
			</details>
			<?php endif; ?>
			<p class="wpps-ss-privacy-note description"><?php esc_html_e( 'This summary is for administrators only. Avoid sharing screenshots publicly—they may reveal environment and security details.', 'wp-powersuite' ); ?></p>
		</div>
		<?php
		$html = ob_get_clean();
		set_transient( self::CACHE_KEY, $html, self::CACHE_EXPIRY );
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Built from escaped data
		echo $html;
	}

	private function getSettings(): array {
$default_sections = $this->getDefaultSections();
		$section_keys     = array_keys( $default_sections );
		$saved            = $this->moduleSettings()->all( [] );
		$saved            = is_array( $saved ) ? $saved : [];

		// Build sections from flat keys (section_environment, etc.) or legacy nested format
		$sections = [];
		foreach ( $section_keys as $key ) {
			if ( isset( $saved[ 'section_' . $key ] ) ) {
				$val = $saved[ 'section_' . $key ];
			} elseif ( isset( $saved['sections'][ $key ] ) ) {
				$val = $saved['sections'][ $key ];
			} else {
				$val = $default_sections[ $key ];
			}
			$sections[ $key ] = ( $val === true || $val === 1 || $val === '1' );
		}

		return [
			'sections'     => $sections,
			'compact_mode' => ! empty( $saved['compact_mode'] ),
		];
	}

	private function getDefaultSections(): array {
		return [
			'environment'   => true,
			'site_health'   => true,
			'performance'   => true,
			'security'      => true,
			'database'      => true,
			'updates'       => true,
			'powersuite'    => true,
		];
	}

	private function getEnvironmentData(): array {
		global $wpdb;
		$php_version     = PHP_VERSION;
		$php_outdated    = version_compare( $php_version, '8.1', '<' );
		$memory_limit    = ini_get( 'memory_limit' );
		$memory_bytes    = wp_convert_hr_to_bytes( $memory_limit );
		$memory_low      = $memory_bytes > 0 && $memory_bytes < 128 * 1024 * 1024; // < 128M
		$max_upload      = wp_max_upload_size();
		$max_post        = ini_get( 'post_max_size' ) ?: __( 'Unknown', 'wp-powersuite' );
		$max_execution   = ini_get( 'max_execution_time' );
		$max_execution   = $max_execution === false || $max_execution === '' ? __( 'Unknown', 'wp-powersuite' ) : ( (int) $max_execution === 0 ? __( 'Unlimited', 'wp-powersuite' ) : ( (int) $max_execution . 's' ) );
		$server_software = isset( $_SERVER['SERVER_SOFTWARE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : __( 'Unknown', 'wp-powersuite' );
		$db_version      = ! empty( $wpdb->db_version() ) ? $wpdb->db_version() : __( 'Unknown', 'wp-powersuite' );
		$timezone        = wp_timezone_string();
		$ssl             = is_ssl();
		$multisite       = is_multisite();
		$environment     = function_exists( 'wp_get_environment_type' ) ? wp_get_environment_type() : 'production';

		return [
			'php_version'      => $php_version,
			'php_outdated'     => $php_outdated,
			'wp_version'       => get_bloginfo( 'version' ),
			'server'          => $server_software,
			'db_version'       => $db_version,
			'memory_limit'     => $memory_limit,
			'memory_low'      => $memory_low,
			'max_upload'      => size_format( $max_upload, 2 ),
			'max_post'        => $max_post,
			'max_execution'   => $max_execution,
			'timezone'        => $timezone ?: __( 'UTC', 'wp-powersuite' ),
			'ssl'             => $ssl,
			'ssl_warning'     => ! $ssl,
			'multisite'       => $multisite,
			'environment'     => $environment,
		];
	}

	private function getSiteHealthData(): array {
		$blog_public   = (int) get_option( 'blog_public', 1 );
		$debug         = defined( 'WP_DEBUG' ) && WP_DEBUG;
		$cron_disabled = defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON;
		$permalink     = get_option( 'permalink_structure' );

		$rest_ok   = true;
		$rest_label = __( 'REST API available', 'wp-powersuite' );
if ( \WP_PowerSuite\Core\OptionStoreModuleSettingsRepository::isModuleEnabled( 'disable-rest-api' ) ) {
			$rest_settings = \WP_PowerSuite\Core\OptionStoreModuleSettingsRepository::forModule( 'disable-rest-api' )->all( [] );
			$rest_mode     = $rest_settings['mode'] ?? 'disable_public';
			$rest_ok       = false;
			$rest_label    = $rest_mode === 'disable_completely'
				? __( 'REST API disabled', 'wp-powersuite' )
				: __( 'REST API restricted (public)', 'wp-powersuite' );
		} elseif ( function_exists( 'rest_url' ) && rest_url( 'wp/v2' ) ) {
			$rest_ok    = true;
			$rest_label = __( 'REST API available', 'wp-powersuite' );
		} else {
			$rest_ok    = false;
			$rest_label = __( 'REST API issue', 'wp-powersuite' );
		}

		return [
			'search_visibility' => $blog_public === 1 ? self::STATUS_OK : self::STATUS_WARN,
			'search_label'      => $blog_public === 1 ? __( 'Visible to search engines', 'wp-powersuite' ) : __( 'Discouraging search engines', 'wp-powersuite' ),
			'debug_mode'        => $debug ? self::STATUS_WARN : self::STATUS_OK,
			'debug_label'      => $debug ? __( 'Debug mode is on', 'wp-powersuite' ) : __( 'Debug mode off', 'wp-powersuite' ),
			'cron_status'       => $cron_disabled ? self::STATUS_WARN : self::STATUS_OK,
			'cron_label'        => $cron_disabled ? __( 'WP-Cron disabled', 'wp-powersuite' ) : __( 'WP-Cron active', 'wp-powersuite' ),
			'permalink_status'  => ! empty( $permalink ) ? self::STATUS_OK : self::STATUS_ERROR,
			'permalink_label'  => ! empty( $permalink ) ? __( 'Pretty permalinks', 'wp-powersuite' ) : __( 'Plain permalinks', 'wp-powersuite' ),
			'rest_status'       => $rest_ok ? self::STATUS_OK : self::STATUS_ERROR,
			'rest_label'        => $rest_label,
		];
	}

	private function getPerformanceData(): array {
		$wp_reports_object_cache = wp_using_ext_object_cache();
		$object_cache = $wp_reports_object_cache && $this->hasRealObjectCache();
		$page_cache     = false;
		if ( defined( 'LSCACHE_ADV_CACHE' ) && LSCACHE_ADV_CACHE ) {
			$page_cache = true;
		}
		if ( defined( 'W3TC' ) && W3TC ) {
			$page_cache = true;
		}
		if ( defined( 'WP_CACHE' ) && WP_CACHE ) {
			$page_cache = true;
		}
		$cdn = false;
		if ( defined( 'CDN_ENABLED' ) && CDN_ENABLED ) {
			$cdn = true;
		}
		$theme  = wp_get_theme();
		$theme_name = $theme->get( 'Name' ) ?: __( 'Unknown', 'wp-powersuite' );
		$plugins = get_plugins();
		$active  = 0;
		foreach ( $plugins as $path => $p ) {
			if ( is_plugin_active( $path ) ) {
				++$active;
			}
		}
		global $wpdb;
		$autoload_size = (int) $wpdb->get_var( "SELECT SUM(LENGTH(option_value)) FROM $wpdb->options WHERE autoload = 'yes'" );
		$autoload_mb   = round( $autoload_size / 1024 / 1024, 2 );
		$autoload_warn = $autoload_mb > 1;

		return [
			'page_cache'     => $page_cache,
			'object_cache'  => $object_cache,
			'cdn'            => $cdn,
			'theme'          => $theme_name,
			'plugins_count'  => $active,
			'autoload_mb'    => $autoload_mb,
			'autoload_warn'  => $autoload_warn,
		];
	}

	/**
	 * Whether a persistent object cache (Redis, Memcached, etc.) is likely in use.
	 * wp_using_ext_object_cache() can be true on some hosts without a real backend.
	 *
	 * @return bool
	 */
	private function hasRealObjectCache(): bool {
		if ( defined( 'WP_REDIS_HOST' ) && WP_REDIS_HOST ) {
			return true;
		}
		if ( defined( 'MEMCACHED_SERVERS' ) && MEMCACHED_SERVERS ) {
			return true;
		}
		if ( file_exists( WP_CONTENT_DIR . '/object-cache.php' ) ) {
			return true;
		}
		return false;
	}

	private function getSecurityData(): array {
		$admin_user = false;
		$users      = get_users( [ 'role' => 'administrator', 'login__in' => [ 'admin' ], 'number' => 1 ] );
		if ( ! empty( $users ) ) {
			$admin_user = true;
		}
		$file_edit = defined( 'DISALLOW_FILE_EDIT' ) && DISALLOW_FILE_EDIT;
if ( ! $file_edit && \WP_PowerSuite\Core\OptionStoreModuleSettingsRepository::isModuleEnabled( 'disable-file-editing' ) ) {
			$file_settings = \WP_PowerSuite\Core\OptionStoreModuleSettingsRepository::forModule( 'disable-file-editing' )->all( [] );
			$file_edit     = ! empty( $file_settings['disable_theme_editor'] ) || ! empty( $file_settings['disable_plugin_editor'] );
		}
		$limit_login = \WP_PowerSuite\Core\OptionStoreModuleSettingsRepository::isModuleEnabled( 'limit-login-attempts' );
		$xmlrpc_disabled = \WP_PowerSuite\Core\OptionStoreModuleSettingsRepository::isModuleEnabled( 'disable-xmlrpc' )
			|| apply_filters( 'xmlrpc_enabled', true ) === false;
		$login_url_changed = \WP_PowerSuite\Core\OptionStoreModuleSettingsRepository::isModuleEnabled( 'change-login-url' );

		return [
			'admin_username_safe' => ! $admin_user,
			'file_edit_disabled' => $file_edit,
			'limit_login_active' => $limit_login,
			'xmlrpc_disabled'    => $xmlrpc_disabled,
			'login_url_changed'  => $login_url_changed,
		];
	}

	private function getDatabaseData(): array {
		global $wpdb;
		$db_size = $this->getDatabaseSizeMb();
		$posts    = (int) wp_count_posts( 'post' )->publish + (int) wp_count_posts( 'post' )->draft + (int) wp_count_posts( 'post' )->pending + (int) wp_count_posts( 'post' )->future;
		$pages    = (int) wp_count_posts( 'page' )->publish + (int) wp_count_posts( 'page' )->draft + (int) wp_count_posts( 'page' )->pending;
		$users    = (int) count_users()['total_users'];
		$comments = (int) wp_count_comments()->approved + (int) wp_count_comments()->moderated;
		$autoload = (int) $wpdb->get_var( "SELECT SUM(LENGTH(option_value)) FROM $wpdb->options WHERE autoload = 'yes'" );
		$revisions = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'revision'" );
		$revisions_warn = $revisions > 500;

		return [
			'db_size_mb'     => round( $db_size, 2 ),
			'posts'          => $posts,
			'pages'          => $pages,
			'users'          => $users,
			'comments'       => $comments,
			'autoload_mb'    => round( $autoload / 1024 / 1024, 2 ),
			'revisions'      => $revisions,
			'revisions_warn' => $revisions_warn,
		];
	}

	private function getUpdatesData(): array {
		$core = get_site_transient( 'update_core' );
		$core_avail = false;
		if ( is_object( $core ) && ! empty( $core->updates ) ) {
			foreach ( $core->updates as $u ) {
				if ( isset( $u->response ) && $u->response === 'upgrade' ) {
					$core_avail = true;
					break;
				}
			}
		}
		$plugins = get_site_transient( 'update_plugins' );
		$plugin_count = 0;
		if ( is_object( $plugins ) && ! empty( $plugins->response ) ) {
			$plugin_count = count( $plugins->response );
		}
		$themes = get_site_transient( 'update_themes' );
		$theme_count = 0;
		if ( is_object( $themes ) && ! empty( $themes->response ) ) {
			$theme_count = count( $themes->response );
		}
		return [
			'core_available'  => $core_avail,
			'plugin_count'    => $plugin_count,
			'theme_count'     => $theme_count,
		];
	}

	private function getPowerSuiteData(): array {
$enabled = $this->optionStore()->getEnabledModules();
		$enabled = is_array( $enabled ) ? $enabled : [];
		$count   = count( $enabled );

		$registry   = ModuleRegistry::getInstance();
		$perf_active = 0;
		$sec_active  = 0;
		foreach ( $enabled as $module_id ) {
			$meta = $registry->getModuleMetadata( $module_id );
			if ( empty( $meta['category'] ) ) {
				continue;
			}
			$cat = (string) $meta['category'];
			if ( strtolower( $cat ) === 'speed' ) {
				++$perf_active;
			}
			if ( $cat === 'Security' ) {
				++$sec_active;
			}
		}

		return [
			'enabled_count'   => $count,
			'perf_active'    => $perf_active,
			'sec_active'     => $sec_active,
		];
	}

	/**
	 * Database size in megabytes with information_schema fallback.
	 */
	private function getDatabaseSizeMb(): float {
		global $wpdb;

		$db_size = 0.0;
		$result  = $wpdb->get_results(
			"SELECT ROUND(((data_length + index_length) / 1024 / 1024), 2) AS size_mb FROM information_schema.TABLES WHERE table_schema = '" . esc_sql( $wpdb->dbname ) . "'",
			ARRAY_A
		);
		if ( is_array( $result ) && $result !== [] ) {
			foreach ( $result as $row ) {
				$db_size += (float) ( $row['size_mb'] ?? 0 );
			}
			return round( $db_size, 2 );
		}

		$status_rows = $wpdb->get_results( 'SHOW TABLE STATUS', ARRAY_A );
		if ( is_array( $status_rows ) ) {
			foreach ( $status_rows as $row ) {
				$data  = (float) ( $row['Data_length'] ?? 0 );
				$index = (float) ( $row['Index_length'] ?? 0 );
				$db_size += ( $data + $index ) / 1024 / 1024;
			}
		}

		return round( $db_size, 2 );
	}

	/**
	 * Render a status dot with screen-reader text.
	 */
	private function renderStatusDot( string $status, string $label ): void {
		?>
		<span class="wpps-ss-status wpps-ss-<?php echo esc_attr( $status ); ?>" aria-hidden="true"></span>
		<span class="screen-reader-text"><?php echo esc_html( $label ); ?></span>
		<?php
	}

	private function renderEnvironment( array $env ): void {
		if ( empty( $env ) ) {
			return;
		}
		?>
		<ul class="wpps-ss-list">
			<li><span class="wpps-ss-label"><?php esc_html_e( 'PHP', 'wp-powersuite' ); ?></span> <span class="<?php echo ! empty( $env['php_outdated'] ) ? 'wpps-ss-warning' : ''; ?>"><?php echo esc_html( $env['php_version'] ?? '' ); ?></span><?php if ( ! empty( $env['php_outdated'] ) ) { echo ' <span class="wpps-ss-badge wpps-ss-warn">' . esc_html__( 'Outdated', 'wp-powersuite' ) . '</span>'; } ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'WordPress', 'wp-powersuite' ); ?></span> <?php echo esc_html( $env['wp_version'] ?? '' ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Multisite', 'wp-powersuite' ); ?></span> <?php echo ! empty( $env['multisite'] ) ? esc_html__( 'Yes', 'wp-powersuite' ) : esc_html__( 'No', 'wp-powersuite' ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Environment', 'wp-powersuite' ); ?></span> <?php echo esc_html( (string) ( $env['environment'] ?? 'production' ) ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Server', 'wp-powersuite' ); ?></span> <?php echo esc_html( $env['server'] ?? '' ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'MySQL/MariaDB', 'wp-powersuite' ); ?></span> <?php echo esc_html( $env['db_version'] ?? '' ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Memory limit', 'wp-powersuite' ); ?></span> <span class="<?php echo ! empty( $env['memory_low'] ) ? 'wpps-ss-warning' : ''; ?>"><?php echo esc_html( $env['memory_limit'] ?? '' ); ?></span></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Max upload', 'wp-powersuite' ); ?></span> <?php echo esc_html( $env['max_upload'] ?? '' ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Max post size', 'wp-powersuite' ); ?></span> <?php echo esc_html( $env['max_post'] ?? '' ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Max execution time', 'wp-powersuite' ); ?></span> <?php echo esc_html( $env['max_execution'] ?? '' ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Timezone', 'wp-powersuite' ); ?></span> <?php echo esc_html( $env['timezone'] ?? '' ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'SSL', 'wp-powersuite' ); ?></span> <?php $this->renderStatusDot( ! empty( $env['ssl'] ) ? 'ok' : 'error', ! empty( $env['ssl'] ) ? __( 'SSL enabled', 'wp-powersuite' ) : __( 'SSL missing', 'wp-powersuite' ) ); ?><span class="wpps-ss-value"><?php echo ! empty( $env['ssl'] ) ? esc_html__( 'Yes', 'wp-powersuite' ) : esc_html__( 'No', 'wp-powersuite' ); ?></span><?php if ( ! empty( $env['ssl_warning'] ) ) { echo ' <span class="wpps-ss-badge wpps-ss-error">' . esc_html__( 'Missing SSL', 'wp-powersuite' ) . '</span>'; } ?></li>
		</ul>
		<?php
	}

	private function renderSiteHealth( array $h ): void {
		?>
		<ul class="wpps-ss-list">
			<li><?php $this->renderStatusDot( $h['search_visibility'], (string) $h['search_label'] ); ?> <?php echo esc_html( $h['search_label'] ); ?></li>
			<li><?php $this->renderStatusDot( $h['debug_mode'], (string) $h['debug_label'] ); ?> <?php echo esc_html( $h['debug_label'] ); ?></li>
			<li><?php $this->renderStatusDot( $h['cron_status'], (string) $h['cron_label'] ); ?> <?php echo esc_html( $h['cron_label'] ); ?></li>
			<li><?php $this->renderStatusDot( $h['permalink_status'], (string) $h['permalink_label'] ); ?> <?php echo esc_html( $h['permalink_label'] ); ?></li>
			<li><?php $this->renderStatusDot( $h['rest_status'], (string) $h['rest_label'] ); ?> <?php echo esc_html( $h['rest_label'] ); ?></li>
		</ul>
		<?php
	}

	private function renderPerformance( array $p ): void {
		if ( empty( $p ) ) {
			return;
		}
		?>
		<ul class="wpps-ss-list">
			<li><?php $this->renderStatusDot( ! empty( $p['page_cache'] ) ? 'ok' : 'warn', ! empty( $p['page_cache'] ) ? __( 'Page cache active', 'wp-powersuite' ) : __( 'Page cache not detected', 'wp-powersuite' ) ); ?> <?php esc_html_e( 'Page cache', 'wp-powersuite' ); ?>: <?php echo ! empty( $p['page_cache'] ) ? esc_html__( 'Active', 'wp-powersuite' ) : esc_html__( 'Not detected', 'wp-powersuite' ); ?></li>
			<li><?php $this->renderStatusDot( ! empty( $p['object_cache'] ) ? 'ok' : 'warn', ! empty( $p['object_cache'] ) ? __( 'Object cache active', 'wp-powersuite' ) : __( 'Object cache not detected', 'wp-powersuite' ) ); ?> <?php esc_html_e( 'Object cache', 'wp-powersuite' ); ?>: <?php echo ! empty( $p['object_cache'] ) ? esc_html__( 'Active', 'wp-powersuite' ) : esc_html__( 'Not detected', 'wp-powersuite' ); ?></li>
			<li><?php $this->renderStatusDot( ! empty( $p['cdn'] ) ? 'ok' : 'warn', ! empty( $p['cdn'] ) ? __( 'CDN detected', 'wp-powersuite' ) : __( 'CDN not detected', 'wp-powersuite' ) ); ?> <?php esc_html_e( 'CDN', 'wp-powersuite' ); ?>: <?php echo ! empty( $p['cdn'] ) ? esc_html__( 'Detected', 'wp-powersuite' ) : esc_html__( 'Not detected', 'wp-powersuite' ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Theme', 'wp-powersuite' ); ?></span> <?php echo esc_html( $p['theme'] ?? '' ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Active plugins', 'wp-powersuite' ); ?></span> <?php echo (int) ( $p['plugins_count'] ?? 0 ); ?></li>
			<?php if ( ! empty( $p['autoload_warn'] ) ) : ?>
			<li><?php $this->renderStatusDot( 'warn', __( 'Autoload options size warning', 'wp-powersuite' ) ); ?> <?php printf( esc_html__( 'Autoload options: %s MB (consider reducing)', 'wp-powersuite' ), esc_html( (string) ( $p['autoload_mb'] ?? 0 ) ) ); ?></li>
			<?php endif; ?>
		</ul>
		<?php
	}

	private function renderSecurity( array $s ): void {
		if ( empty( $s ) ) {
			return;
		}
		?>
		<ul class="wpps-ss-list">
			<li><?php $this->renderStatusDot( ! empty( $s['admin_username_safe'] ) ? 'ok' : 'error', ! empty( $s['admin_username_safe'] ) ? __( 'Admin username safe', 'wp-powersuite' ) : __( 'Admin username unsafe', 'wp-powersuite' ) ); ?> <?php esc_html_e( 'Admin username safe', 'wp-powersuite' ); ?>: <?php echo ! empty( $s['admin_username_safe'] ) ? esc_html__( 'Yes', 'wp-powersuite' ) : esc_html__( 'No (avoid "admin")', 'wp-powersuite' ); ?></li>
			<li><?php $this->renderStatusDot( ! empty( $s['file_edit_disabled'] ) ? 'ok' : 'warn', ! empty( $s['file_edit_disabled'] ) ? __( 'File editing disabled', 'wp-powersuite' ) : __( 'File editing enabled', 'wp-powersuite' ) ); ?> <?php esc_html_e( 'File editing disabled', 'wp-powersuite' ); ?>: <?php echo ! empty( $s['file_edit_disabled'] ) ? esc_html__( 'Yes', 'wp-powersuite' ) : esc_html__( 'No', 'wp-powersuite' ); ?></li>
			<li><?php $this->renderStatusDot( ! empty( $s['limit_login_active'] ) ? 'ok' : 'warn', ! empty( $s['limit_login_active'] ) ? __( 'Login attempts protection active', 'wp-powersuite' ) : __( 'Login attempts protection inactive', 'wp-powersuite' ) ); ?> <?php esc_html_e( 'Login attempts protection', 'wp-powersuite' ); ?>: <?php echo ! empty( $s['limit_login_active'] ) ? esc_html__( 'Active', 'wp-powersuite' ) : esc_html__( 'Not active', 'wp-powersuite' ); ?></li>
			<li><?php $this->renderStatusDot( ! empty( $s['xmlrpc_disabled'] ) ? 'ok' : 'warn', ! empty( $s['xmlrpc_disabled'] ) ? __( 'XML-RPC disabled', 'wp-powersuite' ) : __( 'XML-RPC enabled', 'wp-powersuite' ) ); ?> <?php esc_html_e( 'XML-RPC', 'wp-powersuite' ); ?>: <?php echo ! empty( $s['xmlrpc_disabled'] ) ? esc_html__( 'Disabled', 'wp-powersuite' ) : esc_html__( 'Enabled', 'wp-powersuite' ); ?></li>
			<li><?php $this->renderStatusDot( ! empty( $s['login_url_changed'] ) ? 'ok' : 'warn', ! empty( $s['login_url_changed'] ) ? __( 'Login URL changed', 'wp-powersuite' ) : __( 'Login URL unchanged', 'wp-powersuite' ) ); ?> <?php esc_html_e( 'Login URL changed', 'wp-powersuite' ); ?>: <?php echo ! empty( $s['login_url_changed'] ) ? esc_html__( 'Yes', 'wp-powersuite' ) : esc_html__( 'No', 'wp-powersuite' ); ?></li>
		</ul>
		<?php
	}

	private function renderDatabase( array $db ): void {
		if ( empty( $db ) ) {
			return;
		}
		$db_size_mb = (float) ( $db['db_size_mb'] ?? 0 );
		?>
		<ul class="wpps-ss-list">
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Database size', 'wp-powersuite' ); ?></span> <?php echo esc_html( size_format( $db_size_mb * 1024 * 1024, 2 ) ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Posts', 'wp-powersuite' ); ?></span> <?php echo (int) ( $db['posts'] ?? 0 ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Pages', 'wp-powersuite' ); ?></span> <?php echo (int) ( $db['pages'] ?? 0 ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Users', 'wp-powersuite' ); ?></span> <?php echo (int) ( $db['users'] ?? 0 ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Comments', 'wp-powersuite' ); ?></span> <?php echo (int) ( $db['comments'] ?? 0 ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Autoload options', 'wp-powersuite' ); ?></span> <?php echo esc_html( (string) ( $db['autoload_mb'] ?? 0 ) ); ?> MB</li>
			<?php if ( ! empty( $db['revisions_warn'] ) ) : ?>
			<li><?php $this->renderStatusDot( 'warn', __( 'High revision count', 'wp-powersuite' ) ); ?> <?php printf( esc_html__( 'Revisions: %s (consider cleanup)', 'wp-powersuite' ), esc_html( number_format_i18n( (int) ( $db['revisions'] ?? 0 ) ) ) ); ?></li>
			<?php else : ?>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Revisions', 'wp-powersuite' ); ?></span> <?php echo esc_html( number_format_i18n( (int) ( $db['revisions'] ?? 0 ) ) ); ?></li>
			<?php endif; ?>
		</ul>
		<?php
	}

	private function renderUpdates( array $u ): void {
		if ( empty( $u ) ) {
			return;
		}
		?>
		<ul class="wpps-ss-list">
			<li><?php $this->renderStatusDot( ! empty( $u['core_available'] ) ? 'error' : 'ok', ! empty( $u['core_available'] ) ? __( 'WordPress update available', 'wp-powersuite' ) : __( 'WordPress up to date', 'wp-powersuite' ) ); ?> <?php esc_html_e( 'WordPress', 'wp-powersuite' ); ?>: <?php echo ! empty( $u['core_available'] ) ? esc_html__( 'Update available', 'wp-powersuite' ) : esc_html__( 'Up to date', 'wp-powersuite' ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Plugins', 'wp-powersuite' ); ?></span> <?php echo (int) ( $u['plugin_count'] ?? 0 ); ?> <?php esc_html_e( 'updates', 'wp-powersuite' ); ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Themes', 'wp-powersuite' ); ?></span> <?php echo (int) ( $u['theme_count'] ?? 0 ); ?> <?php esc_html_e( 'updates', 'wp-powersuite' ); ?></li>
		</ul>
		<p class="wpps-ss-actions">
			<a href="<?php echo esc_url( admin_url( 'update-core.php' ) ); ?>" class="button button-small"><?php esc_html_e( 'Open updates', 'wp-powersuite' ); ?></a>
		</p>
		<?php
	}

	private function renderPowerSuite( array $suite ): void {
		?>
		<ul class="wpps-ss-list">
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Enabled modules', 'wp-powersuite' ); ?></span> <?php echo (int) $suite['enabled_count']; ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Performance-related', 'wp-powersuite' ); ?></span> <?php echo (int) $suite['perf_active']; ?></li>
			<li><span class="wpps-ss-label"><?php esc_html_e( 'Security-related', 'wp-powersuite' ); ?></span> <?php echo (int) $suite['sec_active']; ?></li>
		</ul>
		<p class="wpps-ss-actions">
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite' ) ); ?>" class="button button-small"><?php esc_html_e( 'Open Modules', 'wp-powersuite' ); ?></a>
		</p>
		<?php
	}

	public function outputWidgetStyles(): void {
		?>
		<style type="text/css">
			#wpps_system_summary .inside { padding: 0 12px 12px; }
			.wpps-system-summary { padding: 0; }
			.wpps-ss-section { border: 1px solid #c3c4c7; border-radius: 4px; margin-bottom: 8px; }
			.wpps-ss-section summary { padding: 8px 12px; cursor: pointer; font-weight: 600; font-size: 13px; list-style: none; }
			.wpps-ss-section summary::-webkit-details-marker { display: none; }
			.wpps-ss-section summary::before { content: '\25b6'; margin-right: 6px; font-size: 10px; }
			.wpps-ss-section[open] summary::before { content: '\25bc'; }
			.wpps-ss-section-title .dashicons { font-size: 16px; width: 16px; height: 16px; margin-right: 4px; vertical-align: middle; color: #646970; }
			.wpps-ss-section-body { padding: 8px 12px 12px; border-top: 1px solid #f0f0f1; }
			.wpps-ss-list { margin: 0; padding: 0; list-style: none; }
			.wpps-ss-list li { padding: 4px 0; font-size: 13px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
			.wpps-ss-label { color: #646970; min-width: 120px; }
			.wpps-ss-status { display: inline-block; width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; margin-right: 6px; }
			.wpps-ss-status.wpps-ss-ok { background: #00a32a; }
			.wpps-ss-status.wpps-ss-warn { background: #dba617; }
			.wpps-ss-status.wpps-ss-warning { background: #dba617; }
			.wpps-ss-status.wpps-ss-error { background: #d63638; }
			.wpps-ss-badge { font-size: 10px; padding: 2px 6px; border-radius: 3px; }
			.wpps-ss-badge.wpps-ss-warn { background: #fcf0e3; color: #94660c; }
			.wpps-ss-badge.wpps-ss-error { background: #fcebef; color: #b32d2e; }
			.wpps-ss-warning { color: #dba617; }
			.wpps-ss-actions { margin: 10px 0 0; }
			.wpps-ss-privacy-note { margin: 12px 0 0; font-size: 12px; color: #646970; }
			.wpps-ss-compact .wpps-ss-section-body { padding: 6px 10px 10px; }
			.wpps-ss-compact .wpps-ss-list li { padding: 2px 0; font-size: 12px; }
			#wpps_system_summary .postbox-header { display: flex; align-items: center; flex-wrap: wrap; gap: 4px; }
			#wpps_system_summary .postbox-header .hndle { margin: 0; flex: 0 0 auto; }
			#wpps_system_summary .postbox-header .handle-actions { margin-left: auto; }
					</style>
		<?php
	}

	public function outputWidgetScripts(): void {
		?>
		<script>
		(function() {
			function init() {
				var box = document.getElementById('wpps_system_summary');
				if (!box) return;
				var sections = box.querySelectorAll('.wpps-ss-section');
				sections.forEach(function(d) { d.removeAttribute('open'); });
				sections.forEach(function(details) {
					details.addEventListener('toggle', function() {
						if (details.open) {
							sections.forEach(function(other) {
								if (other !== details) other.open = false;
							});
						}
					});
				});
			}
			if (document.readyState === 'loading') {
				document.addEventListener('DOMContentLoaded', init);
			} else {
				init();
			}
		})();
		</script>
		<?php
	}

}
