<?php
/**
 * Detect and import mail settings from other active/configured email plugins.
 *
 * @package EmailSmtp
 */

namespace EmailSmtp\Includes;

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

final class SettingsImporter {

	public const DISMISS_OPTION = 'wpps_ed_import_dismissed';

	/**
	 * Sources that may hold importable mail settings (plugin file => source id).
	 *
	 * @return array<string, string>
	 */
	private static function plugin_map(): array {
		return [
			'fluent-smtp/fluent-smtp.php'   => 'fluentmail',
			'post-smtp/postman-smtp.php'    => 'postman',
			'suremails/suremails.php'       => 'suremails',
			'wp-mail-smtp/wp_mail_smtp.php' => 'wp_mail_smtp',
			'easy-wp-smtp/easy-wp-smtp.php' => 'easy_wp_smtp',
		];
	}

	/**
	 * @return list<array{id:string, label:string, count:int, plugin_file:string}>
	 */
	public static function discover(): array {
		$found = [];

		foreach ( self::plugin_map() as $plugin_file => $source_id ) {
			$connections = self::extract_connections( $source_id );
			if ( $connections === [] ) {
				continue;
			}
			$found[] = [
				'id'          => $source_id,
				'label'       => self::plugin_label( $plugin_file ),
				'count'       => count( $connections ),
				'plugin_file' => $plugin_file,
			];
		}

		return $found;
	}

	/**
	 * Sources to show in the import banner (respects dismiss).
	 *
	 * @return list<array{id:string, label:string, count:int, plugin_file:string}>
	 */
	public static function banner_sources(): array {
		$dismissed = get_option( self::DISMISS_OPTION, [] );
		$dismissed = is_array( $dismissed ) ? $dismissed : [];
		$out       = [];

		foreach ( self::discover() as $source ) {
			if ( ! empty( $dismissed[ $source['id'] ] ) ) {
				continue;
			}
			$out[] = $source;
		}

		return $out;
	}

	public static function dismiss( string $source_id ): void {
		$source_id = sanitize_key( $source_id );
		$dismissed = get_option( self::DISMISS_OPTION, [] );
		$dismissed = is_array( $dismissed ) ? $dismissed : [];
		$dismissed[ $source_id ] = time();
		update_option( self::DISMISS_OPTION, $dismissed, false );
	}

	/**
	 * Import connections from a source into Email Delivery settings.
	 *
	 * @param array<string, mixed> $settings
	 * @return array{settings: array<string, mixed>, imported: int, skipped: int}|\WP_Error
	 */
	public static function import( string $source_id, array $settings ) {
		$source_id = sanitize_key( $source_id );
		$incoming  = self::extract_connections( $source_id );
		if ( $incoming === [] ) {
			return new \WP_Error( 'nothing_to_import', __( 'No importable mail settings were found.', 'wp-powersuite' ) );
		}

		$settings    = ConnectionStore::ensure( $settings );
		$connections = is_array( $settings['connections'] ?? null ) ? $settings['connections'] : [];
		$imported    = 0;
		$skipped     = 0;
		$default_id  = sanitize_key( (string) ( $settings['default_connection_id'] ?? '' ) );

		foreach ( $incoming as $row ) {
			$settings['connections'] = $connections;
			$from = sanitize_email( (string) ( $row['from_email'] ?? '' ) );
			if ( ! is_email( $from ) ) {
				++$skipped;
				continue;
			}
			if ( ConnectionStore::from_email_in_use( $settings, $from, '' ) ) {
				++$skipped;
				continue;
			}

			$provider = sanitize_key( (string) ( $row['provider'] ?? 'smtp' ) );
			if ( ! in_array( $provider, ProviderRegistry::ids(), true ) ) {
				++$skipped;
				continue;
			}

			$id = ConnectionStore::new_id();
			$conn = array_merge(
				$row,
				[
					'id'               => $id,
					'name'             => sanitize_text_field( (string) ( $row['name'] ?? '' ) ),
					'provider'         => $provider,
					'from_email'       => $from,
					'from_name'        => sanitize_text_field( (string) ( $row['from_name'] ?? get_option( 'blogname' ) ) ),
					'force_from_email' => ! empty( $row['force_from_email'] ) && (string) $row['force_from_email'] !== '0' ? '1' : '0',
					'force_from_name'  => ! empty( $row['force_from_name'] ) && (string) $row['force_from_name'] !== '0' ? '1' : '0',
					'set_return_path'  => ! isset( $row['set_return_path'] ) || ( ! empty( $row['set_return_path'] ) && (string) $row['set_return_path'] !== '0' ) ? '1' : '0',
					'override_from'    => ! empty( $row['force_from_email'] ) && (string) $row['force_from_email'] !== '0' ? '1' : '0',
					'transport'        => sanitize_key( (string) ( $row['transport'] ?? ( $provider === 'smtp' ? 'smtp' : 'api' ) ) ),
				]
			);
			if ( $conn['name'] === '' ) {
				$conn['name'] = ProviderRegistry::get( $provider )?->get_name() ?? $provider;
			}

			foreach ( CredentialManager::secret_keys() as $secret_key ) {
				$plain = (string) ( $conn[ $secret_key ] ?? '' );
				if ( $plain !== '' && ! CredentialManager::is_encrypted( $plain ) ) {
					$conn[ $secret_key ] = CredentialManager::encrypt( $plain );
				}
			}

			$connections[ $id ] = $conn;
			$settings['connections'] = $connections;
			++$imported;

			if ( $default_id === '' || ! isset( $connections[ $default_id ] ) ) {
				$default_id = $id;
			}
		}

		if ( $imported === 0 ) {
			return new \WP_Error(
				'nothing_imported',
				__( 'Nothing was imported. Matching From emails may already exist, or credentials could not be read.', 'wp-powersuite' )
			);
		}

		$settings['connections']           = $connections;
		$settings['default_connection_id'] = $default_id;
		$settings['migration_version']     = SettingsSchema::MIGRATION_VERSION;
		$settings                          = ConnectionStore::ensure( $settings );

		self::dismiss( $source_id );

		return [
			'settings' => $settings,
			'imported' => $imported,
			'skipped'  => $skipped,
		];
	}

	/**
	 * @return list<array<string, mixed>>
	 */
	private static function extract_connections( string $source_id ): array {
		switch ( $source_id ) {
			case 'fluentmail':
				return self::from_fluentmail();
			case 'postman':
				return self::from_postman();
			case 'suremails':
				return self::from_suremails();
			case 'wp_mail_smtp':
				return self::from_wp_mail_smtp();
			case 'easy_wp_smtp':
				return self::from_easy_wp_smtp();
			default:
				return [];
		}
	}

	private static function plugin_label( string $plugin_file ): string {
		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		$plugins = get_plugins();
		if ( isset( $plugins[ $plugin_file ]['Name'] ) && is_string( $plugins[ $plugin_file ]['Name'] ) ) {
			return $plugins[ $plugin_file ]['Name'];
		}

		return __( 'another email plugin', 'wp-powersuite' );
	}

	/**
	 * @return list<array<string, mixed>>
	 */
	private static function from_fluentmail(): array {
		$raw = get_option( 'fluentmail-settings' );
		if ( ! is_array( $raw ) || empty( $raw['connections'] ) || ! is_array( $raw['connections'] ) ) {
			return [];
		}

		$out = [];
		foreach ( $raw['connections'] as $conn ) {
			if ( ! is_array( $conn ) ) {
				continue;
			}
			$ps = isset( $conn['provider_settings'] ) && is_array( $conn['provider_settings'] )
				? $conn['provider_settings']
				: $conn;
			$provider_key = sanitize_key( (string) ( $ps['provider'] ?? '' ) );
			$mapped       = self::map_provider_alias( $provider_key );
			if ( $mapped === '' ) {
				continue;
			}

			$row = [
				'name'             => (string) ( $conn['title'] ?? '' ),
				'provider'         => $mapped,
				'from_email'       => (string) ( $ps['sender_email'] ?? '' ),
				'from_name'        => (string) ( $ps['sender_name'] ?? '' ),
				'force_from_email' => self::yes_no( $ps['force_from_email'] ?? '' ) ? '1' : '0',
				'force_from_name'  => self::yes_no( $ps['force_from_name'] ?? '' ) ? '1' : '0',
				// Source plugins store return_path as yes/no (not an email).
				'set_return_path'  => self::yes_no( $ps['return_path'] ?? 'yes' ) ? '1' : '0',
				'transport'        => $mapped === 'smtp' ? 'smtp' : 'api',
			];

			$row = array_merge( $row, self::fluent_provider_fields( $mapped, $ps ) );
			if ( self::row_has_credentials( $row ) || $mapped === 'wordpress' ) {
				$out[] = $row;
			}
		}

		return $out;
	}

	/**
	 * @param array<string, mixed> $ps
	 * @return array<string, mixed>
	 */
	private static function fluent_provider_fields( string $provider, array $ps ): array {
		switch ( $provider ) {
			case 'smtp':
				return [
					'smtp_host'       => (string) ( $ps['host'] ?? '' ),
					'smtp_port'       => (string) ( $ps['port'] ?? '587' ),
					'smtp_encryption' => self::norm_enc( (string) ( $ps['encryption'] ?? 'tls' ) ),
					'smtp_auth'       => self::yes_no( $ps['auth'] ?? 'yes' ) ? '1' : '0',
					'smtp_username'   => (string) ( $ps['username'] ?? '' ),
					'smtp_password'   => self::fluent_decrypt( (string) ( $ps['password'] ?? '' ) ),
					'smtp_autotls'    => self::yes_no( $ps['auto_tls'] ?? 'yes' ) ? '1' : '0',
				];
			case 'amazon-ses':
				return [
					'aws_access_key_id'     => (string) ( $ps['access_key'] ?? '' ),
					'aws_secret_access_key' => self::fluent_decrypt( (string) ( $ps['secret_key'] ?? '' ) ),
					'aws_region'            => (string) ( $ps['region'] ?? 'us-east-1' ),
				];
			case 'mailgun':
				return [
					'mailgun_api_key' => self::fluent_decrypt( (string) ( $ps['api_key'] ?? '' ) ),
					'mailgun_domain'  => (string) ( $ps['domain_name'] ?? $ps['domain'] ?? '' ),
					'mailgun_region'  => strtolower( (string) ( $ps['region'] ?? 'us' ) ) === 'eu' ? 'eu' : 'us',
				];
			case 'sendgrid':
				return [ 'sendgrid_api_key' => self::fluent_decrypt( (string) ( $ps['api_key'] ?? '' ) ) ];
			case 'brevo':
				return [ 'brevo_api_key' => self::fluent_decrypt( (string) ( $ps['api_key'] ?? '' ) ) ];
			case 'sparkpost':
				return [ 'sparkpost_api_key' => self::fluent_decrypt( (string) ( $ps['api_key'] ?? '' ) ) ];
			case 'postmark':
				return [
					'postmark_server_token'   => self::fluent_decrypt( (string) ( $ps['api_key'] ?? '' ) ),
					'postmark_message_stream' => (string) ( $ps['message_stream'] ?? 'outbound' ),
				];
			case 'elastic-email':
				return [ 'elastic_email_api_key' => self::fluent_decrypt( (string) ( $ps['api_key'] ?? '' ) ) ];
			case 'smtp2go':
				return [ 'smtp2go_api_key' => self::fluent_decrypt( (string) ( $ps['api_key'] ?? '' ) ) ];
			case 'netcore':
				return [ 'netcore_api_key' => self::fluent_decrypt( (string) ( $ps['api_key'] ?? '' ) ) ];
			case 'google':
				return [
					'google_client_id'     => (string) ( $ps['client_id'] ?? '' ),
					'google_client_secret' => self::fluent_decrypt( (string) ( $ps['client_secret'] ?? '' ) ),
				];
			case 'microsoft':
				return [
					'microsoft_client_id'     => (string) ( $ps['client_id'] ?? '' ),
					'microsoft_client_secret' => self::fluent_decrypt( (string) ( $ps['client_secret'] ?? '' ) ),
				];
			default:
				return [];
		}
	}

	private static function fluent_decrypt( string $value ): string {
		if ( $value === '' ) {
			return '';
		}
		if ( function_exists( 'fluentMailEncryptDecrypt' ) ) {
			$dec = fluentMailEncryptDecrypt( $value, 'd' );
			if ( is_string( $dec ) && $dec !== '' ) {
				return $dec;
			}
		}
		return $value;
	}

	/**
	 * @return list<array<string, mixed>>
	 */
	private static function from_postman(): array {
		$raw = get_option( 'postman_options' );
		if ( ! is_array( $raw ) ) {
			return [];
		}

		$transport = sanitize_key( (string) ( $raw['transport_type'] ?? 'smtp' ) );
		$mapped    = self::map_provider_alias( $transport );
		if ( $mapped === '' ) {
			return [];
		}

		$row = [
			'name'             => __( 'Imported connection', 'wp-powersuite' ),
			'provider'         => $mapped,
			'from_email'       => (string) ( $raw['sender_email'] ?? '' ),
			'from_name'        => (string) ( $raw['sender_name'] ?? '' ),
			'force_from_email' => ! empty( $raw['prevent_sender_email_override'] ) ? '1' : '0',
			'force_from_name'  => ! empty( $raw['prevent_sender_name_override'] ) ? '1' : '0',
			'transport'        => $mapped === 'smtp' ? 'smtp' : 'api',
		];

		if ( $mapped === 'smtp' ) {
			$row['smtp_host']       = (string) ( $raw['hostname'] ?? '' );
			$row['smtp_port']       = (string) ( $raw['port'] ?? '587' );
			$row['smtp_encryption'] = self::norm_enc( (string) ( $raw['enc_type'] ?? 'tls' ) );
			$row['smtp_auth']       = ( sanitize_key( (string) ( $raw['auth_type'] ?? 'none' ) ) !== 'none' ) ? '1' : '0';
			$row['smtp_username']   = (string) ( $raw['basic_auth_username'] ?? '' );
			$row['smtp_password']   = self::b64( (string) ( $raw['basic_auth_password'] ?? '' ) );
		} else {
			$row = array_merge( $row, self::postman_api_fields( $mapped, $raw ) );
		}

		if ( ! self::row_has_credentials( $row ) && $mapped !== 'wordpress' ) {
			return [];
		}

		return [ $row ];
	}

	/**
	 * @param array<string, mixed> $raw
	 * @return array<string, mixed>
	 */
	private static function postman_api_fields( string $provider, array $raw ): array {
		switch ( $provider ) {
			case 'sendgrid':
				return [ 'sendgrid_api_key' => self::b64( (string) ( $raw['sendgrid_api_key'] ?? '' ) ) ];
			case 'mailgun':
				return [
					'mailgun_api_key' => self::b64( (string) ( $raw['mailgun_api_key'] ?? '' ) ),
					'mailgun_domain'  => (string) ( $raw['mailgun_domain_name'] ?? '' ),
					'mailgun_region'  => strtolower( (string) ( $raw['mailgun_region'] ?? 'us' ) ) === 'eu' ? 'eu' : 'us',
				];
			case 'brevo':
				return [ 'brevo_api_key' => self::b64( (string) ( $raw['sendinblue_api_key'] ?? $raw['brevo_api_key'] ?? '' ) ) ];
			case 'postmark':
				return [ 'postmark_server_token' => self::b64( (string) ( $raw['postmark_api_key'] ?? '' ) ) ];
			case 'mailersend':
				return [ 'mailersend_api_token' => self::b64( (string) ( $raw['mailersend_api_key'] ?? '' ) ) ];
			case 'resend':
				return [ 'resend_api_key' => self::b64( (string) ( $raw['resend_api_key'] ?? '' ) ) ];
			case 'sparkpost':
				return [ 'sparkpost_api_key' => self::b64( (string) ( $raw['sparkpost_api_key'] ?? '' ) ) ];
			case 'elastic-email':
				return [ 'elastic_email_api_key' => self::b64( (string) ( $raw['elasticemail_api_key'] ?? '' ) ) ];
			case 'smtp2go':
				return [ 'smtp2go_api_key' => self::b64( (string) ( $raw['smtp2go_api_key'] ?? '' ) ) ];
			case 'mailjet':
				return [
					'mailjet_api_key'    => self::b64( (string) ( $raw['mailjet_api_key'] ?? '' ) ),
					'mailjet_secret_key' => self::b64( (string) ( $raw['mailjet_secret_key'] ?? '' ) ),
				];
			case 'mandrill':
				return [ 'mandrill_api_key' => self::b64( (string) ( $raw['mandrill_api_key'] ?? '' ) ) ];
			case 'emailit':
				return [ 'emailit_api_key' => self::b64( (string) ( $raw['emailit_api_key'] ?? '' ) ) ];
			case 'maileroo':
				return [ 'maileroo_api_key' => self::b64( (string) ( $raw['maileroo_api_key'] ?? '' ) ) ];
			case 'google':
				return [
					'google_client_id'     => (string) ( $raw['oauth_client_id'] ?? '' ),
					'google_client_secret' => self::b64( (string) ( $raw['oauth_client_secret'] ?? '' ) ),
				];
			case 'microsoft':
				return [
					'microsoft_client_id'     => (string) ( $raw['office365_app_id'] ?? $raw['oauth_client_id'] ?? '' ),
					'microsoft_client_secret' => self::b64( (string) ( $raw['office365_app_password'] ?? $raw['oauth_client_secret'] ?? '' ) ),
				];
			case 'amazon-ses':
				return [
					'aws_access_key_id'     => self::b64( (string) ( $raw['ses_access_key_id'] ?? $raw['access_key_id'] ?? '' ) ),
					'aws_secret_access_key' => self::b64( (string) ( $raw['ses_secret_access_key'] ?? $raw['secret_access_key'] ?? '' ) ),
					'aws_region'            => (string) ( $raw['ses_region'] ?? $raw['region'] ?? 'us-east-1' ),
				];
			default:
				return [];
		}
	}

	/**
	 * @return list<array<string, mixed>>
	 */
	private static function from_suremails(): array {
		$raw = get_option( 'suremails_connections' );
		if ( ! is_array( $raw ) || empty( $raw['connections'] ) || ! is_array( $raw['connections'] ) ) {
			return [];
		}

		$out = [];
		foreach ( $raw['connections'] as $conn ) {
			if ( ! is_array( $conn ) ) {
				continue;
			}
			$type   = strtoupper( (string) ( $conn['type'] ?? '' ) );
			$mapped = self::map_provider_alias( $type );
			if ( $mapped === '' ) {
				continue;
			}

			$row = [
				'name'             => (string) ( $conn['connection_title'] ?? '' ),
				'provider'         => $mapped,
				'from_email'       => (string) ( $conn['from_email'] ?? '' ),
				'from_name'        => (string) ( $conn['from_name'] ?? '' ),
				'force_from_email' => ! empty( $conn['force_from_email'] ) ? '1' : '0',
				'force_from_name'  => ! empty( $conn['force_from_name'] ) ? '1' : '0',
				'transport'        => $mapped === 'smtp' ? 'smtp' : 'api',
			];

			if ( $mapped === 'smtp' ) {
				$row['smtp_host']       = (string) ( $conn['host'] ?? '' );
				$row['smtp_port']       = (string) ( $conn['port'] ?? '587' );
				$row['smtp_encryption'] = self::norm_enc( (string) ( $conn['encryption'] ?? 'tls' ) );
				$row['smtp_username']   = (string) ( $conn['username'] ?? '' );
				$row['smtp_password']   = self::suremails_decrypt( (string) ( $conn['password'] ?? '' ) );
				$row['smtp_auth']       = '1';
				$row['smtp_autotls']    = ! empty( $conn['auto_tls'] ) ? '1' : '0';
			} else {
				$row = array_merge( $row, self::suremails_api_fields( $mapped, $conn ) );
			}

			if ( self::row_has_credentials( $row ) || $mapped === 'wordpress' ) {
				$out[] = $row;
			}
		}

		return $out;
	}

	/**
	 * @param array<string, mixed> $conn
	 * @return array<string, mixed>
	 */
	private static function suremails_api_fields( string $provider, array $conn ): array {
		$api = self::suremails_decrypt( (string) ( $conn['api_key'] ?? '' ) );
		switch ( $provider ) {
			case 'sendgrid':
				return [ 'sendgrid_api_key' => $api ];
			case 'mailgun':
				return [
					'mailgun_api_key' => $api,
					'mailgun_domain'  => (string) ( $conn['domain'] ?? '' ),
					'mailgun_region'  => strtolower( (string) ( $conn['region'] ?? 'us' ) ) === 'eu' ? 'eu' : 'us',
				];
			case 'brevo':
				return [ 'brevo_api_key' => $api ];
			case 'postmark':
				return [
					'postmark_server_token'   => self::suremails_decrypt( (string) ( $conn['server_token'] ?? $conn['api_key'] ?? '' ) ),
					'postmark_message_stream' => (string) ( $conn['message_stream'] ?? 'outbound' ),
				];
			case 'mailersend':
				return [ 'mailersend_api_token' => $api ];
			case 'sparkpost':
				return [ 'sparkpost_api_key' => $api ];
			case 'elastic-email':
				return [ 'elastic_email_api_key' => $api ];
			case 'smtp2go':
				return [ 'smtp2go_api_key' => $api ];
			case 'mailjet':
				return [
					'mailjet_api_key'    => $api,
					'mailjet_secret_key' => self::suremails_decrypt( (string) ( $conn['secret_key'] ?? '' ) ),
				];
			case 'amazon-ses':
				return [
					'aws_access_key_id'     => (string) ( $conn['username'] ?? $conn['access_key'] ?? '' ),
					'aws_secret_access_key' => self::suremails_decrypt( (string) ( $conn['password'] ?? $conn['secret_key'] ?? '' ) ),
					'aws_region'            => (string) ( $conn['region'] ?? 'us-east-1' ),
				];
			case 'google':
				return [
					'google_client_id'     => (string) ( $conn['client_id'] ?? '' ),
					'google_client_secret' => self::suremails_decrypt( (string) ( $conn['client_secret'] ?? '' ) ),
				];
			case 'microsoft':
				return [
					'microsoft_client_id'     => (string) ( $conn['client_id'] ?? '' ),
					'microsoft_client_secret' => self::suremails_decrypt( (string) ( $conn['client_secret'] ?? '' ) ),
				];
			case 'netcore':
				return [ 'netcore_api_key' => $api ];
			case 'emailit':
				return [ 'emailit_api_key' => $api ];
			default:
				return [];
		}
	}

	private static function suremails_decrypt( string $value ): string {
		if ( $value === '' ) {
			return '';
		}
		if ( class_exists( '\SureMails\Inc\Settings' ) && method_exists( '\SureMails\Inc\Settings', 'decrypt' ) ) {
			try {
				$dec = \SureMails\Inc\Settings::decrypt( $value );
				if ( is_string( $dec ) && $dec !== '' ) {
					return $dec;
				}
			} catch ( \Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
			}
		}
		$decoded = base64_decode( $value, true );
		return ( is_string( $decoded ) && $decoded !== '' ) ? $decoded : $value;
	}

	/**
	 * @param array<string, mixed>|null $raw Optional preloaded option blob.
	 * @return list<array<string, mixed>>
	 */
	private static function from_wp_mail_smtp( ?array $raw = null ): array {
		if ( $raw === null ) {
			$raw = get_option( 'wp_mail_smtp' );
		}
		if ( ! is_array( $raw ) || empty( $raw['mail'] ) || ! is_array( $raw['mail'] ) ) {
			return [];
		}

		$mailer = sanitize_key( (string) ( $raw['mail']['mailer'] ?? 'smtp' ) );
		$mapped = self::map_provider_alias( $mailer );
		if ( $mapped === '' ) {
			return [];
		}

		$row = [
			'name'             => __( 'Imported connection', 'wp-powersuite' ),
			'provider'         => $mapped,
			'from_email'       => (string) ( $raw['mail']['from_email'] ?? '' ),
			'from_name'        => (string) ( $raw['mail']['from_name'] ?? '' ),
			'force_from_email' => ! empty( $raw['mail']['from_email_force'] ) ? '1' : '0',
			'force_from_name'  => ! empty( $raw['mail']['from_name_force'] ) ? '1' : '0',
			'transport'        => $mapped === 'smtp' ? 'smtp' : 'api',
		];

		if ( $mapped === 'smtp' && isset( $raw['smtp'] ) && is_array( $raw['smtp'] ) ) {
			$smtp = $raw['smtp'];
			$row['smtp_host']       = (string) ( $smtp['host'] ?? '' );
			$row['smtp_port']       = (string) ( $smtp['port'] ?? '587' );
			$row['smtp_encryption'] = self::norm_enc( (string) ( $smtp['encryption'] ?? 'tls' ) );
			$row['smtp_auth']       = ! empty( $smtp['auth'] ) ? '1' : '0';
			$row['smtp_username']   = (string) ( $smtp['user'] ?? '' );
			$row['smtp_password']   = self::wpms_decrypt( (string) ( $smtp['pass'] ?? '' ) );
			$row['smtp_autotls']    = ! isset( $smtp['autotls'] ) || ! empty( $smtp['autotls'] ) ? '1' : '0';
		} elseif ( $mapped === 'mailgun' && isset( $raw['mailgun'] ) && is_array( $raw['mailgun'] ) ) {
			$row['mailgun_api_key'] = (string) ( $raw['mailgun']['api_key'] ?? '' );
			$row['mailgun_domain']  = (string) ( $raw['mailgun']['domain'] ?? '' );
			$row['mailgun_region']  = strtolower( (string) ( $raw['mailgun']['region'] ?? 'us' ) ) === 'eu' ? 'eu' : 'us';
		} elseif ( $mapped === 'sendgrid' && isset( $raw['sendgrid'] ) && is_array( $raw['sendgrid'] ) ) {
			$row['sendgrid_api_key'] = (string) ( $raw['sendgrid']['api_key'] ?? '' );
		} elseif ( $mapped === 'brevo' && ( isset( $raw['sendinblue'] ) || isset( $raw['brevo'] ) ) ) {
			$bag = is_array( $raw['brevo'] ?? null ) ? $raw['brevo'] : (array) ( $raw['sendinblue'] ?? [] );
			$row['brevo_api_key'] = (string) ( $bag['api_key'] ?? '' );
		} elseif ( $mapped === 'smtp2go' && isset( $raw['smtp2go'] ) && is_array( $raw['smtp2go'] ) ) {
			$row['smtp2go_api_key'] = (string) ( $raw['smtp2go']['api_key'] ?? '' );
		} elseif ( $mapped === 'amazon-ses' && isset( $raw['amazonses'] ) && is_array( $raw['amazonses'] ) ) {
			$row['aws_access_key_id']     = (string) ( $raw['amazonses']['client_id'] ?? '' );
			$row['aws_secret_access_key'] = (string) ( $raw['amazonses']['client_secret'] ?? '' );
			$row['aws_region']            = (string) ( $raw['amazonses']['region'] ?? 'us-east-1' );
		} elseif ( $mapped === 'netcore' && isset( $raw['pepipostapi'] ) && is_array( $raw['pepipostapi'] ) ) {
			$row['netcore_api_key'] = (string) ( $raw['pepipostapi']['api_key'] ?? '' );
		}

		if ( ! self::row_has_credentials( $row ) && $mapped !== 'wordpress' ) {
			return [];
		}

		return [ $row ];
	}

	private static function wpms_decrypt( string $value ): string {
		if ( $value === '' ) {
			return '';
		}
		// Best-effort: many installs store plaintext or already-decrypted values in exports.
		if ( defined( 'WPMS_SMTP_PASS' ) && is_string( WPMS_SMTP_PASS ) && WPMS_SMTP_PASS !== '' ) {
			return (string) WPMS_SMTP_PASS;
		}
		return $value;
	}

	/**
	 * @return list<array<string, mixed>>
	 */
	private static function from_easy_wp_smtp(): array {
		$raw = get_option( 'swpsmtp_options' );
		if ( ! is_array( $raw ) ) {
			// Newer Easy WP SMTP may store a WP Mail SMTP-compatible blob.
			$alt = get_option( 'easy_wp_smtp' );
			if ( is_array( $alt ) && ! empty( $alt['mail'] ) ) {
				return self::from_wp_mail_smtp( $alt );
			}
			return [];
		}

		$smtp = isset( $raw['smtp_settings'] ) && is_array( $raw['smtp_settings'] ) ? $raw['smtp_settings'] : [];
		$row  = [
			'name'             => __( 'Imported connection', 'wp-powersuite' ),
			'provider'         => 'smtp',
			'from_email'       => (string) ( $raw['from_email_field'] ?? '' ),
			'from_name'        => (string) ( $raw['from_name_field'] ?? '' ),
			'force_from_name'  => ! empty( $raw['force_from_name_replace'] ) ? '1' : '0',
			'force_from_email' => '1',
			'transport'        => 'smtp',
			'smtp_host'        => (string) ( $smtp['host'] ?? '' ),
			'smtp_port'        => (string) ( $smtp['port'] ?? '587' ),
			'smtp_encryption'  => self::norm_enc( (string) ( $smtp['type_encryption'] ?? 'tls' ) ),
			'smtp_auth'        => ! empty( $smtp['autentication'] ) || ! empty( $smtp['authentication'] ) ? '1' : '0',
			'smtp_username'    => (string) ( $smtp['username'] ?? '' ),
			'smtp_password'    => (string) ( $smtp['password'] ?? '' ),
		];

		if ( ! self::row_has_credentials( $row ) ) {
			return [];
		}

		return [ $row ];
	}

	private static function map_provider_alias( string $key ): string {
		$key = strtolower( str_replace( [ '-', ' ' ], '_', $key ) );
		$map = [
			'smtp'            => 'smtp',
			'default'         => 'wordpress',
			'mail'            => 'wordpress',
			'phpmail'         => 'wordpress',
			'wordpress'       => 'wordpress',
			'sendgrid'        => 'sendgrid',
			'sendgrid_api'    => 'sendgrid',
			'mailgun'         => 'mailgun',
			'mailgun_api'     => 'mailgun',
			'sendinblue'      => 'brevo',
			'sendinblue_api'  => 'brevo',
			'brevo'           => 'brevo',
			'postmark'        => 'postmark',
			'postmark_api'    => 'postmark',
			'mailersend'      => 'mailersend',
			'mailersend_api'  => 'mailersend',
			'resend'          => 'resend',
			'resend_api'      => 'resend',
			'sparkpost'       => 'sparkpost',
			'sparkpost_api'   => 'sparkpost',
			'elasticemail'    => 'elastic-email',
			'elasticemail_api'=> 'elastic-email',
			'elasticmail'     => 'elastic-email',
			'elastic'         => 'elastic-email',
			'smtp2go'         => 'smtp2go',
			'smtp2go_api'     => 'smtp2go',
			'mailjet'         => 'mailjet',
			'mailjet_api'     => 'mailjet',
			'mandrill'        => 'mandrill',
			'mandrill_api'    => 'mandrill',
			'ses'             => 'amazon-ses',
			'amazonses'       => 'amazon-ses',
			'aws'             => 'amazon-ses',
			'aws_ses_api'     => 'amazon-ses',
			'gmail'           => 'google',
			'gmail_api'       => 'google',
			'google'          => 'google',
			'outlook'         => 'microsoft',
			'office365_api'   => 'microsoft',
			'microsoft'       => 'microsoft',
			'pepipost'        => 'netcore',
			'pepipostapi'     => 'netcore',
			'netcore'         => 'netcore',
			'emailit'         => 'emailit',
			'emailit_api'     => 'emailit',
			'maileroo'        => 'maileroo',
			'maileroo_api'    => 'maileroo',
		];

		$mapped = $map[ $key ] ?? '';
		if ( $mapped !== '' && in_array( $mapped, ProviderRegistry::ids(), true ) ) {
			return $mapped;
		}
		return '';
	}

	/**
	 * @param array<string, mixed> $row
	 */
	private static function row_has_credentials( array $row ): bool {
		$provider = (string) ( $row['provider'] ?? '' );
		if ( $provider === 'wordpress' ) {
			return true;
		}
		if ( $provider === 'smtp' ) {
			return trim( (string) ( $row['smtp_host'] ?? '' ) ) !== '';
		}
		foreach ( CredentialManager::secret_keys() as $key ) {
			if ( trim( (string) ( $row[ $key ] ?? '' ) ) !== '' ) {
				return true;
			}
		}
		foreach ( [ 'aws_access_key_id', 'google_client_id', 'microsoft_client_id', 'smtp_username' ] as $key ) {
			if ( trim( (string) ( $row[ $key ] ?? '' ) ) !== '' ) {
				return true;
			}
		}
		return false;
	}

	private static function yes_no( $value ): bool {
		if ( is_bool( $value ) ) {
			return $value;
		}
		$v = strtolower( trim( (string) $value ) );
		return in_array( $v, [ '1', 'yes', 'true', 'on' ], true );
	}

	private static function norm_enc( string $enc ): string {
		$enc = strtolower( trim( $enc ) );
		if ( in_array( $enc, [ 'ssl', 'tls' ], true ) ) {
			return $enc;
		}
		return $enc === 'none' || $enc === '' ? '' : 'tls';
	}

	private static function b64( string $value ): string {
		if ( $value === '' ) {
			return '';
		}
		$decoded = base64_decode( $value, true );
		if ( is_string( $decoded ) && $decoded !== '' && base64_encode( $decoded ) === $value ) {
			return $decoded;
		}
		// Postman often stores without strict padding checks.
		$decoded = base64_decode( $value );
		return is_string( $decoded ) && $decoded !== '' ? $decoded : $value;
	}
}
