<?php
/**
 * Email Delivery diagnostics (no secrets).
 *
 * @package EmailSmtp
 * @since 1.1.0
 */

namespace EmailSmtp\Includes;

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

final class DiagnosticsService {

	/**
	 * @return array<string, mixed>
	 */
	public static function collect(): array {
		$settings = EmailRouter::get_settings();
		$provider = ProviderRegistry::get( (string) ( $settings['provider'] ?? 'wordpress' ) );
		$bag      = $provider ? SettingsSchema::provider_bag( $settings, $provider->get_id() ) : [];

		$credential_sources = [];
		foreach ( CredentialManager::constant_map() as $key => $constant ) {
			if ( CredentialManager::is_from_constant( $constant ) ) {
				$credential_sources[ $key ] = 'constant:' . $constant;
			}
		}

		$wp_mail_overridden = false;
		if ( function_exists( 'wp_mail' ) ) {
			$reflection = new \ReflectionFunction( 'wp_mail' );
			$wp_mail_overridden = $reflection->getFileName()
				&& strpos( (string) $reflection->getFileName(), WP_PLUGIN_DIR ) !== false
				&& strpos( (string) $reflection->getFileName(), 'WP-Powersuite' ) === false
				&& strpos( (string) $reflection->getFileName(), 'wp-powersuite' ) === false;
		}

		$runtime = get_option( 'wp_powersuite_email_delivery_meta', [] );
		$runtime = is_array( $runtime ) ? $runtime : [];

		return [
			'active_provider'       => $provider ? $provider->get_id() : 'wordpress',
			'provider_name'         => $provider ? $provider->get_name() : '',
			'connection_status'     => $provider ? $provider->get_connection_status( $bag ) : 'not_configured',
			'last_success_at'       => (string) ( $runtime['last_success_at'] ?? $settings['last_success_at'] ?? '' ),
			'last_failure_at'       => (string) ( $runtime['last_failure_at'] ?? $settings['last_failure_at'] ?? '' ),
			'last_failure_message'  => ErrorNormalizer::redact( (string) ( $runtime['last_failure_message'] ?? $settings['last_failure_message'] ?? '' ) ),
			'mail_override_active'  => $provider && ( $provider->uses_phpmailer_smtp() || $provider->uses_api_transport() ),
			'php_version'           => PHP_VERSION,
			'wp_version'            => get_bloginfo( 'version' ),
			'openssl'               => extension_loaded( 'openssl' ),
			'curl'                  => function_exists( 'curl_version' ) || function_exists( 'curl_init' ),
			'sockets'               => function_exists( 'fsockopen' ),
			'credential_sources'    => $credential_sources,
			'conflicting_plugins'   => SmtpSettingsHelper::detectConflictingPlugins(),
			'wp_mail_replaced'      => $wp_mail_overridden,
			'provider_endpoint'     => $provider && $provider->get_id() === 'smtp'
				? (string) ( $bag['smtp_host'] ?? '' ) . ':' . (string) ( $bag['smtp_port'] ?? '' )
				: '',
			'multisite'             => is_multisite(),
			'network_activated'     => \WP_PowerSuite\Core\NetworkScope::isNetworkActivated(),
		];
	}
}
