<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

final class TMSMTP_Plugin {
	const OPTION = 'titanium_mail_smtp';
	const WP_MAIL_SMTP_MIGRATION_OPTION = 'titanium_mail_smtp_wp_mail_smtp_migration_version';
	const WP_MAIL_SMTP_MIGRATION_VERSION = 2;
	const WP_MAIL_SMTP_MIGRATION_STATE_OPTION = 'titanium_mail_smtp_wp_mail_smtp_migration_state';
	const PRICING_OPT_IN_OPTION = 'tmsmtp_pricing_opt_in';
	const SECRET_MASK = '••••••••••••';
	private static $instance;
	private $current_mail_args = array();
	private $sending_alert = false;
	private $captured_error = null;
	private $bypass_provider = false;

	public static function instance() {
		if ( null === self::$instance ) { self::$instance = new self(); }
		return self::$instance;
	}

	private function __construct() {
		add_action( 'admin_menu', array( $this, 'admin_menu' ) );
		add_action( 'admin_head', array( $this, 'hide_more_plugins_submenu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'print_upgrade_menu_css' ) );
		add_action( 'wp_ajax_tmsmtp_get_freemius_pricing', array( $this, 'ajax_get_freemius_pricing' ) );
		add_action( 'admin_init', array( __CLASS__, 'migrate_wp_mail_smtp' ), 5 );
		add_action( 'admin_init', array( $this, 'handle_pricing_consent' ) );
		add_action( 'admin_post_tmsmtp_save', array( $this, 'process_save' ) );
		add_action( 'admin_post_tmsmtp_test', array( $this, 'process_test' ) );
		add_filter( 'wp_mail', array( $this, 'capture_mail' ), PHP_INT_MAX );
		add_filter( 'pre_wp_mail', array( $this, 'maybe_send_api_mail' ), PHP_INT_MAX, 2 );

		add_filter( 'wp_mail_from', array( $this, 'filter_default_from_email' ), PHP_INT_MAX ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		add_filter( 'wp_mail_from_name', array( $this, 'filter_default_from_name' ), PHP_INT_MAX ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		add_action( 'phpmailer_init', array( $this, 'configure_smtp' ), PHP_INT_MAX );
		add_action( 'wp_mail_failed', array( $this, 'mail_failed' ) ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
	}

	public static function activate() {
		if ( ! self::ensure_settings_option() ) {
			return false;
		}

		self::migrate_wp_mail_smtp();
		return true;
	}

	private static function ensure_settings_option() {
		$current = get_option( self::OPTION, null );
		if ( is_array( $current ) ) {
			return true;
		}
		$defaults = self::defaults();
		update_option( self::OPTION, $defaults, false );
		return $defaults === get_option( self::OPTION, null );
	}

	public static function uninstall( $preserve_shared_settings = false ) {
		$settings = get_option( self::OPTION, array() );
		if (
			$preserve_shared_settings
			|| empty( $settings['delete_on_uninstall'] )
		) {
			return;
		}

		delete_option( self::OPTION );
		if ( null === get_option( self::OPTION, null ) ) {
			delete_option( self::WP_MAIL_SMTP_MIGRATION_OPTION );
			delete_option( self::WP_MAIL_SMTP_MIGRATION_STATE_OPTION );
			delete_option( 'titanium_mail_smtp_migration' );
			delete_option( 'titanium_mail_smtp_schema_version' );
			delete_transient( 'tmsmtp_public_pricing_payload_v3' );
			delete_option( 'tmsmtp_public_pricing_cache_v3' );
			delete_option( self::PRICING_OPT_IN_OPTION );
		}
	}

	private static function defaults() {
		return array(
			'connection' => array(
				'name' => 'Primary Connection', 'mailer' => 'default',
				'from_email' => get_option( 'admin_email' ), 'from_name' => get_bloginfo( 'name' ),
				'force_from_email' => 1, 'force_from_name' => 1,
				'postmark_token' => '', 'message_stream' => 'outbound',
				'sendgrid_api_key' => '', 'mailgun_api_key' => '', 'mailgun_domain' => '', 'mailgun_region' => 'US',
				'brevo_api_key' => '', 'ses_access_key' => '', 'ses_secret_key' => '', 'ses_session_token' => '', 'ses_region' => 'us-east-1',
				'smtp_host' => '', 'smtp_port' => 587, 'smtp_encryption' => 'tls', 'smtp_autotls' => 1, 'smtp_auth' => 1,
				'smtp_user' => '', 'smtp_pass' => '',
			),
			'alerts_enabled' => 0,
			'alert_recipient' => get_option( 'admin_email' ),
			'delete_on_uninstall' => 0,
		);
	}

	private function settings() {
		$stored   = get_option( self::OPTION, array() );
		$defaults = self::defaults();
		$settings = wp_parse_args( is_array( $stored ) ? $stored : array(), $defaults );
		$settings['connection'] = $this->normalize_connection(
			isset( $settings['connection'] ) && is_array( $settings['connection'] ) ? $settings['connection'] : array()
		);
		$settings['alerts_enabled']    = empty( $settings['alerts_enabled'] ) ? 0 : 1;
		$settings['alert_recipient']   = sanitize_email( is_scalar( $settings['alert_recipient'] ?? '' ) ? (string) $settings['alert_recipient'] : '' );
		$settings['delete_on_uninstall'] = empty( $settings['delete_on_uninstall'] ) ? 0 : 1;
		return $settings;
	}

	private function normalize_connection( $connection ) {
		$defaults   = self::defaults()['connection'];
		$connection = wp_parse_args( is_array( $connection ) ? $connection : array(), $defaults );
		$scalar     = static function ( $value, $fallback = '' ) {
			return is_scalar( $value ) ? (string) $value : (string) $fallback;
		};
		$allowed_mailers = array( 'default', 'postmark', 'amazonses', 'sendgrid', 'mailgun', 'brevo', 'smtp' );
		$mailer          = sanitize_key( $scalar( $connection['mailer'] ?? '', 'default' ) );
		$encryption      = sanitize_key( $scalar( $connection['smtp_encryption'] ?? '', 'tls' ) );
		$region          = strtoupper( $scalar( $connection['mailgun_region'] ?? '', 'US' ) );

		$normalized = array(
			'name'              => sanitize_text_field( $scalar( $connection['name'] ?? '', 'Primary Connection' ) ),
			'mailer'            => in_array( $mailer, $allowed_mailers, true ) ? $mailer : 'default',
			'from_email'        => sanitize_email( $scalar( $connection['from_email'] ?? '' ) ),
			'from_name'         => sanitize_text_field( $scalar( $connection['from_name'] ?? '' ) ),
			'force_from_email'  => empty( $connection['force_from_email'] ) ? 0 : 1,
			'force_from_name'   => empty( $connection['force_from_name'] ) ? 0 : 1,
			'postmark_token'    => $scalar( $connection['postmark_token'] ?? '' ),
			'message_stream'    => sanitize_text_field( $scalar( $connection['message_stream'] ?? '', 'outbound' ) ),
			'sendgrid_api_key'  => $scalar( $connection['sendgrid_api_key'] ?? '' ),
			'mailgun_api_key'   => $scalar( $connection['mailgun_api_key'] ?? '' ),
			'mailgun_domain'    => sanitize_text_field( $scalar( $connection['mailgun_domain'] ?? '' ) ),
			'mailgun_region'    => in_array( $region, array( 'US', 'EU' ), true ) ? $region : 'US',
			'brevo_api_key'     => $scalar( $connection['brevo_api_key'] ?? '' ),
			'ses_access_key'    => $scalar( $connection['ses_access_key'] ?? '' ),
			'ses_secret_key'    => $scalar( $connection['ses_secret_key'] ?? '' ),
			'ses_session_token' => $scalar( $connection['ses_session_token'] ?? '' ),
			'ses_region'        => sanitize_key( $scalar( $connection['ses_region'] ?? '', 'us-east-1' ) ),
			'smtp_host'         => sanitize_text_field( $scalar( $connection['smtp_host'] ?? '' ) ),
			'smtp_port'         => min( 65535, max( 1, absint( $connection['smtp_port'] ?? 587 ) ) ),
			'smtp_encryption'   => in_array( $encryption, array( 'none', 'ssl', 'tls' ), true ) ? $encryption : 'tls',
			'smtp_autotls'      => empty( $connection['smtp_autotls'] ) ? 0 : 1,
			'smtp_auth'         => empty( $connection['smtp_auth'] ) ? 0 : 1,
			'smtp_user'         => sanitize_text_field( $scalar( $connection['smtp_user'] ?? '' ) ),
			'smtp_pass'         => $scalar( $connection['smtp_pass'] ?? '' ),
		);

		return array_merge( $connection, $normalized );
	}

	private function save_settings( $settings ) {
		$settings = is_array( $settings ) ? $settings : self::defaults();
		update_option( self::OPTION, $settings, false );
		return $settings === get_option( self::OPTION, null );
	}

	private function apply_constants( $connection ) {
		$connection = $this->normalize_connection( $connection );
		$map = array(
			'postmark_token'    => array( 'TMSMTP_POSTMARK_PRIMARY_TOKEN', 'TMS_POSTMARK_PRIMARY_TOKEN' ),
			'sendgrid_api_key'  => array( 'TMSMTP_SENDGRID_PRIMARY_API_KEY', 'TMS_SENDGRID_PRIMARY_API_KEY' ),
			'mailgun_api_key'   => array( 'TMSMTP_MAILGUN_PRIMARY_API_KEY', 'TMS_MAILGUN_PRIMARY_API_KEY' ),
			'brevo_api_key'     => array( 'TMSMTP_BREVO_PRIMARY_API_KEY', 'TMS_BREVO_PRIMARY_API_KEY' ),
			'ses_access_key'    => array( 'TMSMTP_SES_PRIMARY_ACCESS_KEY', 'TMS_SES_PRIMARY_ACCESS_KEY' ),
			'ses_secret_key'    => array( 'TMSMTP_SES_PRIMARY_SECRET_KEY', 'TMS_SES_PRIMARY_SECRET_KEY' ),
			'ses_session_token' => array( 'TMSMTP_SES_PRIMARY_SESSION_TOKEN', 'TMS_SES_PRIMARY_SESSION_TOKEN' ),
			'smtp_pass'         => array( 'TMSMTP_SMTP_PRIMARY_PASSWORD', 'TMS_SMTP_PRIMARY_PASSWORD' ),
		);

		foreach ( $map as $key => $constants ) {
			foreach ( $constants as $constant_name ) {
				if ( defined( $constant_name ) ) {
					$value = constant( $constant_name );
					$connection[ $key ] = is_scalar( $value ) ? (string) $value : '';
					break;
				}
			}
		}

		return $connection;
	}

	public static function migrate_wp_mail_smtp() {
		$previous_version = (int) get_option( self::WP_MAIL_SMTP_MIGRATION_OPTION, 0 );
		$legacy_completed = 1 === (int) get_option( 'titanium_mail_smtp_migration', 0 );
		if ( self::WP_MAIL_SMTP_MIGRATION_VERSION <= $previous_version ) {
			return true;
		}

		if ( self::should_defer_wp_mail_smtp_migration() ) {
			return false;
		}

		if ( ! self::ensure_settings_option() ) {
			return false;
		}

		$stored = get_option( self::OPTION, null );
		if ( ! is_array( $stored ) ) {
			return false;
		}

		$current = isset( $stored['connection'] ) && is_array( $stored['connection'] )
			? wp_parse_args( $stored['connection'], self::defaults()['connection'] )
			: self::defaults()['connection'];

		if ( ! self::is_pristine_connection( $current ) ) {
			return self::complete_wp_mail_smtp_migration();
		}

		$source_bundle = self::get_wp_mail_smtp_options();
		$source        = $source_bundle['options'];
		$raw_source    = $source_bundle['raw'];

		if ( empty( $source ) && ! defined( 'WPMS_MAILER' ) ) {
			if ( 0 < $previous_version || $legacy_completed ) {
				return self::complete_wp_mail_smtp_migration();
			}
			self::record_wp_mail_smtp_migration_state( 'no_source', '', HOUR_IN_SECONDS );
			return false;
		}

		$source_mailer = sanitize_key( self::wp_mail_smtp_value( $source, 'mail', 'mailer', array( 'WPMS_MAILER' ), '' ) );
		if ( '' === $source_mailer ) {
			self::record_wp_mail_smtp_migration_state( 'invalid_source', '', HOUR_IN_SECONDS );
			return false;
		}

		$aliases = array(
			'mail'       => 'default',
			'none'       => 'default',
			'default'    => 'default',
			'smtp'       => 'smtp',
			'postmark'   => 'postmark',
			'sendgrid'   => 'sendgrid',
			'mailgun'    => 'mailgun',
			'sendinblue' => 'brevo',
			'brevo'      => 'brevo',
			'amazonses'  => 'amazonses',
		);

		if ( ! isset( $aliases[ $source_mailer ] ) ) {
			self::record_wp_mail_smtp_migration_state( 'unsupported_provider', $source_mailer, HOUR_IN_SECONDS );
			return false;
		}

		$imported   = $current;
		$from_email = sanitize_email(
			self::wp_mail_smtp_value( $source, 'mail', 'from_email', array( 'WPMS_MAIL_FROM' ), $current['from_email'] )
		);
		$from_name = sanitize_text_field(
			self::wp_mail_smtp_value( $source, 'mail', 'from_name', array( 'WPMS_MAIL_FROM_NAME' ), $current['from_name'] )
		);
		$imported['from_email'] = is_email( $from_email ) ? $from_email : $current['from_email'];
		$imported['from_name'] = '' !== $from_name ? $from_name : $current['from_name'];
		$imported['force_from_email'] = self::wp_mail_smtp_bool(
			self::wp_mail_smtp_value( $source, 'mail', 'from_email_force', array( 'WPMS_MAIL_FROM_FORCE' ), $current['force_from_email'] )
		);
		$imported['force_from_name'] = self::wp_mail_smtp_bool(
			self::wp_mail_smtp_value( $source, 'mail', 'from_name_force', array( 'WPMS_MAIL_FROM_NAME_FORCE' ), $current['force_from_name'] )
		);
		$imported['mailer'] = $aliases[ $source_mailer ];

		switch ( $imported['mailer'] ) {
			case 'postmark':
				$secret = self::wp_mail_smtp_secret_from_source( $source_bundle, 'postmark', 'server_api_token', array( 'WPMS_POSTMARK_SERVER_API_TOKEN' ) );
				if ( empty( $secret['success'] ) ) {
					self::record_wp_mail_smtp_migration_state( 'credential_unavailable', $source_mailer, 15 * MINUTE_IN_SECONDS );
					return false;
				}
				$imported['postmark_token'] = $secret['value'];
				$imported['message_stream'] = sanitize_text_field(
					self::wp_mail_smtp_value( $source, 'postmark', 'message_stream', array( 'WPMS_POSTMARK_MESSAGE_STREAM' ), 'outbound' )
				);
				break;

			case 'sendgrid':
				$secret = self::wp_mail_smtp_secret_from_source( $source_bundle, 'sendgrid', 'api_key', array( 'WPMS_SENDGRID_API_KEY' ) );
				if ( empty( $secret['success'] ) ) {
					self::record_wp_mail_smtp_migration_state( 'credential_unavailable', $source_mailer, 15 * MINUTE_IN_SECONDS );
					return false;
				}
				$imported['sendgrid_api_key'] = $secret['value'];
				break;

			case 'mailgun':
				$secret = self::wp_mail_smtp_secret_from_source( $source_bundle, 'mailgun', 'api_key', array( 'WPMS_MAILGUN_API_KEY' ) );
				if ( empty( $secret['success'] ) ) {
					self::record_wp_mail_smtp_migration_state( 'credential_unavailable', $source_mailer, 15 * MINUTE_IN_SECONDS );
					return false;
				}
				$imported['mailgun_api_key'] = $secret['value'];
				$imported['mailgun_domain'] = sanitize_text_field(
					self::wp_mail_smtp_value( $source, 'mailgun', 'domain', array( 'WPMS_MAILGUN_DOMAIN' ), '' )
				);
				$region = strtoupper( self::wp_mail_smtp_value( $source, 'mailgun', 'region', array( 'WPMS_MAILGUN_REGION' ), 'US' ) );
				$imported['mailgun_region'] = in_array( $region, array( 'US', 'EU' ), true ) ? $region : 'US';
				break;

			case 'brevo':
				$brevo_group = isset( $source['brevo'] ) && is_array( $source['brevo'] ) ? 'brevo' : 'sendinblue';
				$secret = self::wp_mail_smtp_secret_from_source( $source_bundle, $brevo_group, 'api_key', array( 'WPMS_SENDINBLUE_API_KEY' ) );
				if ( empty( $secret['success'] ) ) {
					self::record_wp_mail_smtp_migration_state( 'credential_unavailable', $source_mailer, 15 * MINUTE_IN_SECONDS );
					return false;
				}
				$imported['brevo_api_key'] = $secret['value'];
				break;

			case 'amazonses':
				$access = self::wp_mail_smtp_secret_from_source( $source_bundle, 'amazonses', 'client_id', array( 'WPMS_AMAZONSES_CLIENT_ID' ) );
				$secret = self::wp_mail_smtp_secret_from_source( $source_bundle, 'amazonses', 'client_secret', array( 'WPMS_AMAZONSES_CLIENT_SECRET' ) );
				if ( empty( $access['success'] ) || empty( $secret['success'] ) ) {
					self::record_wp_mail_smtp_migration_state( 'credential_unavailable', $source_mailer, 15 * MINUTE_IN_SECONDS );
					return false;
				}
				$imported['ses_access_key'] = $access['value'];
				$imported['ses_secret_key'] = $secret['value'];
				$imported['ses_region'] = sanitize_key(
					self::wp_mail_smtp_value( $source, 'amazonses', 'region', array( 'WPMS_AMAZONSES_REGION' ), 'us-east-1' )
				);
				break;

			case 'smtp':
				$imported['smtp_host'] = sanitize_text_field(
					self::wp_mail_smtp_value( $source, 'smtp', 'host', array( 'WPMS_SMTP_HOST' ), '' )
				);
				$imported['smtp_port'] = min( 65535, max( 1, absint(
					self::wp_mail_smtp_value( $source, 'smtp', 'port', array( 'WPMS_SMTP_PORT' ), 587 )
				) ) );
				$encryption = sanitize_key(
					self::wp_mail_smtp_value( $source, 'smtp', 'encryption', array( 'WPMS_SSL' ), 'tls' )
				);
				$imported['smtp_encryption'] = in_array( $encryption, array( 'ssl', 'tls' ), true ) ? $encryption : 'none';
				$imported['smtp_autotls'] = self::wp_mail_smtp_bool(
					self::wp_mail_smtp_value( $source, 'smtp', 'autotls', array( 'WPMS_SMTP_AUTOTLS' ), 1 )
				);
				$imported['smtp_auth'] = self::wp_mail_smtp_bool(
					self::wp_mail_smtp_value( $source, 'smtp', 'auth', array( 'WPMS_SMTP_AUTH' ), 1 )
				);
				$imported['smtp_user'] = sanitize_text_field(
					self::wp_mail_smtp_value( $source, 'smtp', 'user', array( 'WPMS_SMTP_USER' ), '' )
				);

				if ( $imported['smtp_auth'] ) {
					if ( defined( 'WPMS_SMTP_PASS' ) ) {
						$password_result = self::resolve_wp_mail_smtp_secret( (string) constant( 'WPMS_SMTP_PASS' ), true );
					} else {
						$resolved_password = self::wp_mail_smtp_value( $source, 'smtp', 'pass', array(), '' );
						$raw_password      = self::wp_mail_smtp_value( $raw_source, 'smtp', 'pass', array(), '' );
						$already_resolved  = ! empty( $source_bundle['resolved'] )
							&& ( $resolved_password !== $raw_password || ! self::looks_like_wp_mail_smtp_encrypted_secret( $resolved_password ) );
						$password_result = self::resolve_wp_mail_smtp_secret( $resolved_password, $already_resolved );
					}

					if ( empty( $password_result['success'] ) ) {
						self::record_wp_mail_smtp_migration_state( 'credential_unavailable', $source_mailer, 15 * MINUTE_IN_SECONDS );
						return false;
					}
					$imported['smtp_pass'] = $password_result['value'];
				} else {
					$imported['smtp_pass'] = '';
				}
				break;
		}

		if ( ! self::is_imported_connection_usable( $imported ) ) {
			self::record_wp_mail_smtp_migration_state( 'incomplete_source', $source_mailer, 15 * MINUTE_IN_SECONDS );
			return false;
		}

		$stored['connection'] = array_merge(
			isset( $stored['connection'] ) && is_array( $stored['connection'] ) ? $stored['connection'] : array(),
			$imported
		);
		update_option( self::OPTION, $stored, false );
		if ( $stored !== get_option( self::OPTION, null ) ) {
			return false;
		}

		return self::complete_wp_mail_smtp_migration();
	}

	private static function get_wp_mail_smtp_options() {
		$raw_source = get_option( 'wp_mail_smtp', array() );
		$raw_source = is_array( $raw_source ) ? $raw_source : array();
		$source     = $raw_source;
		$resolved   = false;

		if ( class_exists( '\\WPMailSMTP\\Options' ) && is_callable( array( '\\WPMailSMTP\\Options', 'init' ) ) ) {
			try {
				$options = \WPMailSMTP\Options::init();
				if ( is_object( $options ) && is_callable( array( $options, 'get_all' ) ) ) {
					$resolved_options = $options->get_all();
					if ( is_array( $resolved_options ) ) {
						$source   = array_replace_recursive( $source, $resolved_options );
						$resolved = true;
					}
				}
			} catch ( Throwable $exception ) {
				 
			}
		}

		return array(
			'options'  => $source,
			'raw'      => $raw_source,
			'resolved' => $resolved,
		);
	}

	private static function wp_mail_smtp_value( $source, $group, $key, $constants = array(), $fallback = '' ) {
		foreach ( $constants as $constant_name ) {
			if ( defined( $constant_name ) ) {
				$value = constant( $constant_name );
				return is_scalar( $value ) ? (string) $value : (string) $fallback;
			}
		}

		if ( isset( $source[ $group ] ) && is_array( $source[ $group ] ) && array_key_exists( $key, $source[ $group ] ) && is_scalar( $source[ $group ][ $key ] ) ) {
			return (string) $source[ $group ][ $key ];
		}

		return is_scalar( $fallback ) ? (string) $fallback : '';
	}

	private static function wp_mail_smtp_bool( $value ) {
		if ( is_bool( $value ) ) {
			return $value ? 1 : 0;
		}
		if ( is_numeric( $value ) ) {
			return 0 === (int) $value ? 0 : 1;
		}
		$value = strtolower( trim( is_scalar( $value ) ? (string) $value : '' ) );
		return in_array( $value, array( '1', 'true', 'yes', 'on' ), true ) ? 1 : 0;
	}

	private static function is_pristine_connection( $connection ) {
		$defaults   = self::defaults()['connection'];
		$connection = wp_parse_args( is_array( $connection ) ? $connection : array(), $defaults );

		foreach ( $defaults as $key => $default ) {
			$current = $connection[ $key ] ?? null;
			if ( is_int( $default ) ) {
				if ( (int) $current !== $default ) {
					return false;
				}
			} elseif ( (string) $current !== (string) $default ) {
				return false;
			}
		}

		return true;
	}

	private static function is_imported_connection_usable( $connection ) {
		$mailer = isset( $connection['mailer'] ) && is_scalar( $connection['mailer'] ) ? sanitize_key( (string) $connection['mailer'] ) : 'default';
		if ( 'default' === $mailer ) {
			return true;
		}
		if ( ! is_email( $connection['from_email'] ?? '' ) ) {
			return false;
		}

		switch ( $mailer ) {
			case 'postmark':
				return '' !== trim( (string) ( $connection['postmark_token'] ?? '' ) );
			case 'sendgrid':
				return '' !== trim( (string) ( $connection['sendgrid_api_key'] ?? '' ) );
			case 'mailgun':
				return '' !== trim( (string) ( $connection['mailgun_api_key'] ?? '' ) ) && '' !== trim( (string) ( $connection['mailgun_domain'] ?? '' ) );
			case 'brevo':
				return '' !== trim( (string) ( $connection['brevo_api_key'] ?? '' ) );
			case 'amazonses':
				return '' !== trim( (string) ( $connection['ses_access_key'] ?? '' ) ) && '' !== trim( (string) ( $connection['ses_secret_key'] ?? '' ) );
			case 'smtp':
				if ( '' === trim( (string) ( $connection['smtp_host'] ?? '' ) ) ) {
					return false;
				}
				if ( ! empty( $connection['smtp_auth'] ) ) {
					return '' !== trim( (string) ( $connection['smtp_user'] ?? '' ) ) && '' !== (string) ( $connection['smtp_pass'] ?? '' );
				}
				return true;
		}

		return false;
	}

	private static function complete_wp_mail_smtp_migration() {
		update_option( self::WP_MAIL_SMTP_MIGRATION_OPTION, self::WP_MAIL_SMTP_MIGRATION_VERSION, false );
		$complete = self::WP_MAIL_SMTP_MIGRATION_VERSION === (int) get_option( self::WP_MAIL_SMTP_MIGRATION_OPTION, 0 );
		if ( $complete ) {
			delete_option( self::WP_MAIL_SMTP_MIGRATION_STATE_OPTION );
		}
		return $complete;
	}

	private static function should_defer_wp_mail_smtp_migration() {
		$state = get_option( self::WP_MAIL_SMTP_MIGRATION_STATE_OPTION, array() );
		return is_array( $state )
			&& self::WP_MAIL_SMTP_MIGRATION_VERSION === (int) ( $state['version'] ?? 0 )
			&& time() < (int) ( $state['retry_after'] ?? 0 );
	}

	private static function record_wp_mail_smtp_migration_state( $status, $source_mailer, $retry_delay ) {
		$state = array(
			'version'       => self::WP_MAIL_SMTP_MIGRATION_VERSION,
			'status'        => sanitize_key( (string) $status ),
			'source_mailer' => sanitize_key( (string) $source_mailer ),
			'checked_at'    => time(),
			'retry_after'   => time() + max( MINUTE_IN_SECONDS, absint( $retry_delay ) ),
		);
		update_option( self::WP_MAIL_SMTP_MIGRATION_STATE_OPTION, $state, false );
		return $state === get_option( self::WP_MAIL_SMTP_MIGRATION_STATE_OPTION, null );
	}

	private static function wp_mail_smtp_secret_from_source( $source_bundle, $group, $key, $constants = array() ) {
		foreach ( $constants as $constant_name ) {
			if ( defined( $constant_name ) ) {
				$value = constant( $constant_name );
				return self::resolve_wp_mail_smtp_secret( is_scalar( $value ) ? (string) $value : '', true );
			}
		}

		$source    = isset( $source_bundle['options'] ) && is_array( $source_bundle['options'] ) ? $source_bundle['options'] : array();
		$raw    = isset( $source_bundle['raw'] ) && is_array( $source_bundle['raw'] ) ? $source_bundle['raw'] : array();
		$value     = self::wp_mail_smtp_value( $source, $group, $key, array(), '' );
		$raw_value = self::wp_mail_smtp_value( $raw, $group, $key, array(), '' );
		$already_resolved = ! empty( $source_bundle['resolved'] )
			&& ( $value !== $raw_value || ! self::looks_like_wp_mail_smtp_encrypted_secret( $value ) );

		return self::resolve_wp_mail_smtp_secret( $value, $already_resolved );
	}

	private static function resolve_wp_mail_smtp_secret( $value, $already_resolved = false ) {
		$value = (string) $value;
		if ( '' === $value ) {
			return array( 'success' => true, 'value' => '', 'status' => 'empty' );
		}

		if ( $already_resolved ) {
			return array( 'success' => true, 'value' => $value, 'status' => 'resolved' );
		}

		if ( class_exists( '\\WPMailSMTP\\Helpers\\Crypto' ) && is_callable( array( '\\WPMailSMTP\\Helpers\\Crypto', 'decrypt' ) ) ) {
			try {
				$plain = \WPMailSMTP\Helpers\Crypto::decrypt( $value );
				if ( is_scalar( $plain ) ) {
					$plain = (string) $plain;
					if ( '' !== $plain && ( $plain !== $value || ! self::looks_like_wp_mail_smtp_encrypted_secret( $value ) ) ) {
						return array( 'success' => true, 'value' => $plain, 'status' => 'decrypted' );
					}
				}
			} catch ( Throwable $exception ) {
				 
			}
		}

		if ( ! self::looks_like_wp_mail_smtp_encrypted_secret( $value ) ) {
			return array( 'success' => true, 'value' => $value, 'status' => 'plaintext' );
		}

		if ( ! function_exists( 'sodium_crypto_secretbox_open' ) ) {
			return array( 'success' => false, 'value' => '', 'status' => 'sodium_unavailable' );
		}

		$key = defined( 'WPMS_CRYPTO_KEY' ) ? constant( 'WPMS_CRYPTO_KEY' ) : '';
		if ( ! is_string( $key ) || '' === $key ) {
			$encoded_key = get_option( 'wp_mail_smtp_mail_key', false );
			$key         = is_string( $encoded_key ) ? self::decode_wp_mail_smtp_key( $encoded_key ) : '';
		} else {
			$key = self::decode_wp_mail_smtp_key( $key );
		}

		$decoded     = base64_decode( $value, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
		$nonce_bytes = defined( 'SODIUM_CRYPTO_SECRETBOX_NONCEBYTES' ) ? SODIUM_CRYPTO_SECRETBOX_NONCEBYTES : 24;
		$mac_bytes   = defined( 'SODIUM_CRYPTO_SECRETBOX_MACBYTES' ) ? SODIUM_CRYPTO_SECRETBOX_MACBYTES : 16;
		$key_bytes   = defined( 'SODIUM_CRYPTO_SECRETBOX_KEYBYTES' ) ? SODIUM_CRYPTO_SECRETBOX_KEYBYTES : 32;

		if ( ! is_string( $key ) || $key_bytes !== strlen( $key ) || ! is_string( $decoded ) || strlen( $decoded ) < ( $nonce_bytes + $mac_bytes ) ) {
			return array( 'success' => false, 'value' => '', 'status' => 'key_unavailable' );
		}

		$nonce      = substr( $decoded, 0, $nonce_bytes );
		$ciphertext = substr( $decoded, $nonce_bytes );
		try {
			$plain = sodium_crypto_secretbox_open( $ciphertext, $nonce, $key );
		} catch ( Throwable $exception ) {
			$plain = false;
		}

		return false === $plain
			? array( 'success' => false, 'value' => '', 'status' => 'decrypt_failed' )
			: array( 'success' => true, 'value' => (string) $plain, 'status' => 'decrypted' );
	}

	private static function looks_like_wp_mail_smtp_encrypted_secret( $value ) {
		$value = trim( (string) $value );
		if ( strlen( $value ) < 40 || 1 !== preg_match( '/^[A-Za-z0-9+\\/]+={0,2}$/', $value ) ) {
			return false;
		}

		$decoded     = base64_decode( $value, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
		if ( ! is_string( $decoded ) || strlen( $decoded ) < 40 ) {
			return false;
		}

		return rtrim( base64_encode( $decoded ), '=' ) === rtrim( $value, '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
	}

	private static function decode_wp_mail_smtp_key( $key ) {
		$key       = (string) $key;
		$key_bytes = defined( 'SODIUM_CRYPTO_SECRETBOX_KEYBYTES' ) ? SODIUM_CRYPTO_SECRETBOX_KEYBYTES : 32;
		if ( $key_bytes === strlen( $key ) ) {
			return $key;
		}

		$decoded     = base64_decode( $key, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
		return is_string( $decoded ) && $key_bytes === strlen( $decoded ) ? $decoded : '';
	}

	public function capture_mail( $args ) {
		$this->current_mail_args = is_array( $args ) ? $args : array();
		return $args;
	}

	private function connection() {
		$settings   = $this->settings();
		$connection = $this->apply_constants( $settings['connection'] );
		return apply_filters( 'tmsmtp_runtime_connection', $connection );
	}

	public function get_connection_status( $connection = null ) {
		return $this->connection_status( $connection );
	}

	private function connection_status( $connection = null ) {
		$connection = is_array( $connection ) ? $this->normalize_connection( $connection ) : $this->connection();
		$mailer     = $connection['mailer'];

		if ( 'default' === $mailer ) {
			return array(
				'configured' => true,
				'default'    => true,
				'message'    => __( 'WordPress default mail is active. Titanium Mail SMTP is not replacing the site mailer.', 'titanium-mail-smtp' ),
			);
		}
		if ( ! is_email( $connection['from_email'] ) ) {
			return array( 'configured' => false, 'default' => false, 'message' => __( 'A valid From Email address is required for the selected provider.', 'titanium-mail-smtp' ) );
		}
		if ( 'postmark' === $mailer && '' === trim( $connection['postmark_token'] ) ) {
			return array( 'configured' => false, 'default' => false, 'message' => __( 'Postmark is selected, but the Postmark server token is missing.', 'titanium-mail-smtp' ) );
		}
		if ( 'sendgrid' === $mailer && '' === trim( $connection['sendgrid_api_key'] ) ) {
			return array( 'configured' => false, 'default' => false, 'message' => __( 'SendGrid is selected, but the SendGrid API key is missing.', 'titanium-mail-smtp' ) );
		}
		if ( 'mailgun' === $mailer && ( '' === trim( $connection['mailgun_api_key'] ) || ! TMSMTP_API_Mailers::valid_mailgun_domain( $connection['mailgun_domain'] ) ) ) {
			return array( 'configured' => false, 'default' => false, 'message' => __( 'Mailgun is selected, but a valid API key or sending domain is missing.', 'titanium-mail-smtp' ) );
		}
		if ( 'brevo' === $mailer && '' === trim( $connection['brevo_api_key'] ) ) {
			return array( 'configured' => false, 'default' => false, 'message' => __( 'Brevo is selected, but the Brevo API key is missing.', 'titanium-mail-smtp' ) );
		}
		if ( 'amazonses' === $mailer && ( '' === trim( $connection['ses_access_key'] ) || '' === trim( $connection['ses_secret_key'] ) || ! preg_match( '/^[a-z]{2}(?:-gov)?-[a-z0-9-]+-\d$/', $connection['ses_region'] ) ) ) {
			return array( 'configured' => false, 'default' => false, 'message' => __( 'Amazon SES is selected, but the access key, secret key, or region is missing or invalid.', 'titanium-mail-smtp' ) );
		}
		if ( 'smtp' === $mailer ) {
			if ( '' === trim( $connection['smtp_host'] ) || empty( $connection['smtp_port'] ) ) {
				return array( 'configured' => false, 'default' => false, 'message' => __( 'Other SMTP is selected, but the SMTP host or port is missing.', 'titanium-mail-smtp' ) );
			}
			if ( ! empty( $connection['smtp_auth'] ) && ( '' === trim( $connection['smtp_user'] ) || '' === trim( $connection['smtp_pass'] ) ) ) {
				return array( 'configured' => false, 'default' => false, 'message' => __( 'SMTP authentication is enabled, but the username or password is missing.', 'titanium-mail-smtp' ) );
			}
		}
		if ( ! in_array( $mailer, array( 'postmark', 'sendgrid', 'mailgun', 'brevo', 'amazonses', 'smtp' ), true ) ) {
			return array( 'configured' => false, 'default' => false, 'message' => __( 'The selected mailer is not supported.', 'titanium-mail-smtp' ) );
		}
		return array( 'configured' => true, 'default' => false, 'message' => __( 'The selected provider has the required configuration.', 'titanium-mail-smtp' ) );
	}

	public function filter_default_from_email( $email ) {
		$c = $this->connection();
		$status = $this->connection_status( $c );
		if ( ( ! empty( $status['default'] ) || empty( $status['configured'] ) ) && ! empty( $c['force_from_email'] ) && is_email( $c['from_email'] ) ) { return $c['from_email']; }
		return $email;
	}

	public function filter_default_from_name( $name ) {
		$c = $this->connection();
		$status = $this->connection_status( $c );
		if ( ( ! empty( $status['default'] ) || empty( $status['configured'] ) ) && ! empty( $c['force_from_name'] ) && '' !== trim( (string) $c['from_name'] ) ) { return $c['from_name']; }
		return $name;
	}

	public function maybe_send_api_mail( $return, $atts ) {
		$this->current_mail_args = is_array( $atts ) ? $atts : array();
		if ( null !== $return || $this->bypass_provider ) {
			return $return;
		}

		if ( apply_filters( 'tmsmtp_defer_core_delivery', false, $atts ) ) {
			return $return;
		}

		$connection = $this->connection();
		$status     = $this->connection_status( $connection );
		if ( ! empty( $status['default'] ) || empty( $status['configured'] ) || 'smtp' === $connection['mailer'] ) {
			return null;
		}

		$result = 'postmark' === $connection['mailer']
			? $this->send_postmark( $connection, $atts )
			: TMSMTP_API_Mailers::send( $connection, $atts );
		if ( is_wp_error( $result ) ) {
			$this->captured_error = $result;
			do_action( 'wp_mail_failed', $result ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
			return false;
		}

		do_action( 'wp_mail_succeeded', $atts ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		return true;
	}

	public static function is_empty_file_reference( $value ) {
		if ( null === $value || false === $value ) {
			return true;
		}
		if ( ! is_scalar( $value ) ) {
			return false;
		}
		$value = trim( (string) $value );
		return '' === $value || ( in_array( strtolower( $value ), array( 'none', 'null', 'false' ), true ) && ! is_file( $value ) );
	}

	private function validated_attachments( $attachments, $atts, $inline = false ) {
		$files = array();
		foreach ( (array) $attachments as $key => $path ) {
			if ( self::is_empty_file_reference( $path ) ) {
				continue;
			}
			if ( ! is_scalar( $path ) ) {
				return new WP_Error( 'tmsmtp_attachment_invalid', __( 'An email attachment path is invalid.', 'titanium-mail-smtp' ), $atts );
			}
			$args = array( 'path' => (string) $path, 'cid' => $inline ? (string) $key : '', 'name' => basename( (string) $path ), 'encoding' => 'base64', 'type' => '', 'disposition' => $inline ? 'inline' : 'attachment' );
			if ( $inline ) {
				$args = apply_filters( 'wp_mail_embed_args', $args ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
			}
			if ( ! is_array( $args ) || ! isset( $args['path'] ) || ! is_scalar( $args['path'] ) ) {
				return new WP_Error( 'tmsmtp_attachment_invalid', __( 'An email attachment path is invalid.', 'titanium-mail-smtp' ), $atts );
			}
			if ( self::is_empty_file_reference( $args['path'] ) ) {
				continue;
			}
			$path = trim( (string) $args['path'] );
			$size = '' !== $path && is_file( $path ) && is_readable( $path ) ? filesize( $path ) : false;
			if ( false === $size ) {
				return new WP_Error( 'tmsmtp_attachment_unreadable', sprintf( /* translators: %s: attachment file name. */ __( 'The email attachment could not be read: %s', 'titanium-mail-smtp' ), sanitize_file_name( basename( $path ) ) ), $atts );
			}
			$filetype = wp_check_filetype( $path );
			$files[] = array(
				'path' => $path,
				'name' => sanitize_file_name( isset( $args['name'] ) && is_scalar( $args['name'] ) ? (string) $args['name'] : basename( $path ) ),
				'type' => sanitize_mime_type( isset( $args['type'] ) && is_scalar( $args['type'] ) ? (string) $args['type'] : ( $filetype['type'] ?? '' ) ) ?: 'application/octet-stream',
				'size' => (int) $size,
				'cid'  => $inline && isset( $args['cid'] ) && is_scalar( $args['cid'] ) ? preg_replace( '/[\r\n]+/', '', (string) $args['cid'] ) : '',
			);
		}
		return $files;
	}

	private function send_postmark( $connection, $atts ) {
		$token = trim( (string) $connection['postmark_token'] );
		if ( '' === $token ) {
			return new WP_Error( 'tmsmtp_postmark_config', __( 'The Postmark server token is missing.', 'titanium-mail-smtp' ), $atts );
		}

		$headers = $this->parse_headers( $atts['headers'] ?? array() );
		$host    = wp_parse_url( network_home_url(), PHP_URL_HOST );
		$host    = is_string( $host ) ? preg_replace( '/^www\./i', '', $host ) : '';
		$host    = $host ? $host : 'localhost.localdomain';
		$original_from_email = ! empty( $headers['from_email'] ) ? $headers['from_email'] : 'wordpress@' . $host;
		$original_from_name  = ! empty( $headers['from_name'] ) ? $headers['from_name'] : 'WordPress';
		$original_from_email = apply_filters( 'wp_mail_from', $original_from_email ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		$original_from_name  = apply_filters( 'wp_mail_from_name', $original_from_name ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		$from_email = ! empty( $connection['force_from_email'] ) ? $connection['from_email'] : $original_from_email;
		$from_name  = ! empty( $connection['force_from_name'] ) ? $connection['from_name'] : $original_from_name;
		if ( ! is_email( $from_email ) ) {
			return new WP_Error( 'tmsmtp_postmark_from', __( 'The configured From Email is invalid.', 'titanium-mail-smtp' ), $atts );
		}

		$to = $this->valid_recipient_strings( $atts['to'] ?? array() );
		$cc = $this->valid_recipient_strings( $headers['cc'] ?? array() );
		$bcc = $this->valid_recipient_strings( $headers['bcc'] ?? array() );
		if ( empty( $to ) ) {
			return new WP_Error( 'tmsmtp_postmark_recipients', __( 'Postmark requires at least one valid To recipient.', 'titanium-mail-smtp' ), $atts );
		}

		$message      = isset( $atts['message'] ) && is_scalar( $atts['message'] ) ? (string) $atts['message'] : '';
		$content_type = ! empty( $headers['content-type'] ) ? implode( ' ', (array) $headers['content-type'] ) : 'text/plain';
		if ( empty( $headers['content-type'] ) ) {
			$content_type = (string) apply_filters( 'wp_mail_content_type', $content_type ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		}
		$has_html_markup = (bool) preg_match( '/<(?:!doctype\s+html|html|body|table|div|p|br|img|a)(?:\s|>)/i', $message );
		$is_html         = false !== stripos( $content_type, 'text/html' ) || $has_html_markup;

		$body = array(
			'From'          => $from_name ? sprintf( '"%s" <%s>', addcslashes( $from_name, '"' ), $from_email ) : $from_email,
			'To'            => implode( ', ', $to ),
			'Subject'       => isset( $atts['subject'] ) && is_scalar( $atts['subject'] ) ? (string) $atts['subject'] : '',
			'MessageStream' => sanitize_text_field( $connection['message_stream'] ?: 'outbound' ),
		);
		if ( $is_html ) {
			$body['HtmlBody'] = $has_html_markup ? $message : nl2br( make_clickable( esc_html( $message ) ) );
			$body['TextBody'] = $has_html_markup ? $this->html_to_text( $message ) : $message;
		} else {
			$body['TextBody'] = $message;
		}
		if ( $cc ) {
			$body['Cc'] = implode( ', ', $cc );
		}
		if ( $bcc ) {
			$body['Bcc'] = implode( ', ', $bcc );
		}

		$reply_to = ! empty( $headers['reply-to'] ) ? implode( ', ', $this->valid_recipient_strings( $headers['reply-to'] ) ) : '';
		if ( '' === $reply_to && ! empty( $connection['force_from_email'] ) && is_email( $original_from_email ) && strtolower( $original_from_email ) !== strtolower( $from_email ) ) {
			$reply_to = $original_from_email;
		}
		if ( '' !== $reply_to ) {
			$body['ReplyTo'] = $reply_to;
		}

		$custom_headers = array();
		foreach ( $headers as $name => $values ) {
			if ( in_array( $name, array( 'from_email', 'from_name', 'from', 'content-type', 'cc', 'bcc', 'reply-to', 'mime-version' ), true ) || ! preg_match( '/^[A-Za-z0-9!#$%&\'*+.^_`|~-]+$/', $name ) ) {
				continue;
			}
			foreach ( (array) $values as $value ) {
				$value = str_replace( array( "\r", "\n" ), '', (string) $value );
				if ( '' !== $value ) {
					$custom_headers[] = array( 'Name' => $name, 'Value' => $value );
				}
			}
		}
		if ( $custom_headers ) {
			$body['Headers'] = $custom_headers;
		}

		$files = $this->validated_attachments( $atts['attachments'] ?? array(), $atts );
		if ( ! is_wp_error( $files ) ) {
			$embeds = $this->validated_attachments( $atts['embeds'] ?? array(), $atts, true );
			$files  = is_wp_error( $embeds ) ? $embeds : array_merge( $files, $embeds );
		}
		if ( is_wp_error( $files ) ) {
			return $files;
		}
		foreach ( array( 'HtmlBody', 'TextBody' ) as $field ) {
			if ( isset( $body[ $field ] ) && strlen( $body[ $field ] ) > 5 * MB_IN_BYTES ) {
				return new WP_Error( 'tmsmtp_postmark_body_too_large', __( 'The email body exceeds Postmark’s 5 MB body limit.', 'titanium-mail-smtp' ), $atts );
			}
		}
		$estimate = strlen( (string) wp_json_encode( $body ) );
		foreach ( $files as $file ) {
			$estimate += (int) ( 4 * ceil( $file['size'] / 3 ) ) + strlen( $file['name'] . $file['type'] . $file['cid'] ) + 128;
		}
		if ( $estimate > 10 * MB_IN_BYTES ) {
			return new WP_Error( 'tmsmtp_postmark_message_too_large', __( 'The email exceeds Postmark’s 10 MB encoded message limit.', 'titanium-mail-smtp' ), $atts );
		}

		$attachments = array();
		foreach ( $files as $file ) {
			$content = file_get_contents( $file['path'] ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
			if ( false === $content ) {
				return new WP_Error( 'tmsmtp_attachment_read_failed', sprintf( /* translators: %s: attachment file name. */ __( 'The email attachment could not be read: %s', 'titanium-mail-smtp' ), $file['name'] ), $atts );
			}
			$item = array( 'Name' => $file['name'], 'Content' => base64_encode( $content ), 'ContentType' => $file['type'] );
			if ( '' !== $file['cid'] ) { $item['ContentID'] = 'cid:' . preg_replace( '/^cid:/i', '', $file['cid'] ); }
			$attachments[] = $item;
		}
		if ( $attachments ) { $body['Attachments'] = $attachments; }

		$json = wp_json_encode( $body );
		if ( false === $json ) {
			return new WP_Error( 'tmsmtp_postmark_json', __( 'The Postmark request could not be encoded.', 'titanium-mail-smtp' ), $atts );
		}
		if ( strlen( $json ) > 10 * MB_IN_BYTES ) {
			return new WP_Error( 'tmsmtp_postmark_message_too_large', __( 'The email exceeds Postmark’s 10 MB encoded message limit.', 'titanium-mail-smtp' ), $atts );
		}
		$response = wp_remote_post(
			'https://api.postmarkapp.com/email',
			array(
				'timeout'             => 30,
				'redirection'         => 0,
				'limit_response_size' => 262144,
				'headers'             => array(
					'Accept'                  => 'application/json',
					'Content-Type'            => 'application/json',
					'X-Postmark-Server-Token' => $token,
				),
				'body'    => $json,
			)
		);
		if ( is_wp_error( $response ) ) {
			return new WP_Error( $response->get_error_code(), $response->get_error_message(), $atts );
		}
		$code = wp_remote_retrieve_response_code( $response );
		if ( $code < 200 || $code >= 300 ) {
			return new WP_Error(
				'tmsmtp_postmark',
				sprintf(
					/* translators: 1: HTTP status code, 2: response message. */
					__( 'Postmark returned HTTP %1$d: %2$s', 'titanium-mail-smtp' ),
					$code,
					wp_strip_all_tags( wp_remote_retrieve_body( $response ) )
				),
				$atts
			);
		}
		return true;
	}

	private function html_to_text( $html ) {
		$text = preg_replace( '/<\s*br\s*\/?\s*>/i', "\n", (string) $html );
		$text = preg_replace( '/<\/(?:p|div|li|tr|h[1-6])\s*>/i', "\n", $text );
		return trim( html_entity_decode( wp_strip_all_tags( $text, true ), ENT_QUOTES | ENT_HTML5, get_bloginfo( 'charset' ) ?: 'UTF-8' ) );
	}
	private function parse_headers( $headers ) {
		$out = array( 'cc' => array(), 'bcc' => array(), 'reply-to' => array() );
		if ( is_string( $headers ) ) { $headers = preg_split( '/\r\n|\r|\n/', $headers ); }
		foreach ( (array) $headers as $name => $value ) {
			foreach ( (array) $value as $line ) {
				if ( ! is_scalar( $line ) ) { continue; }
				$line = is_string( $name ) && ! ctype_digit( $name ) ? $name . ': ' . $line : (string) $line;
				foreach ( preg_split( '/\r\n|\r|\n/', $line ) as $header ) {
					if ( false === strpos( $header, ':' ) ) { continue; }
					list( $header_name, $header_value ) = array_map( 'trim', explode( ':', $header, 2 ) );
					$key = strtolower( $header_name );
					if ( 'from' === $key && preg_match( '/^(.*)<([^>]+)>$/', $header_value, $match ) ) {
						$out['from_name']  = sanitize_text_field( trim( $match[1], " \t\n\r\0\x0B\"'" ) );
						$out['from_email'] = sanitize_email( trim( $match[2] ) );
					} elseif ( 'from' === $key ) {
						$out['from_email'] = sanitize_email( $header_value );
					} elseif ( in_array( $key, array( 'cc', 'bcc', 'reply-to' ), true ) ) {
						$out[ $key ] = array_merge( $out[ $key ], preg_split( '/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/', $header_value ) );
					} else {
						$out[ $key ][] = $header_value;
					}
				}
			}
		}
		return $out;
	}

	private function valid_recipient_strings( $values ) {
		$out = array();
		foreach ( (array) $values as $value ) {
			if ( ! is_scalar( $value ) ) {
				continue;
			}
			foreach ( preg_split( '/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/', (string) $value ) as $item ) {
				$item = trim( $item );
				$name = '';
				if ( preg_match( '/^(.*)<([^>]+)>$/', $item, $matches ) ) {
					$name  = sanitize_text_field( trim( trim( $matches[1] ), " \t\n\r\0\x0B\"'" ) );
					$email = sanitize_email( trim( $matches[2] ) );
				} else {
					$email = sanitize_email( $item );
				}
				if ( is_email( $email ) ) {
					$out[] = '' !== $name ? sprintf( '"%s" <%s>', addcslashes( $name, '"' ), $email ) : $email;
				}
			}
		}
		return $out;
	}

	public function configure_smtp( $phpmailer ) {
		if ( $this->bypass_provider ) {
			return;
		}
		$connection = $this->connection();
		$status     = $this->connection_status( $connection );
		if ( 'smtp' !== $connection['mailer'] || empty( $status['configured'] ) ) {
			return;
		}

		$phpmailer->isSMTP();
		$phpmailer->Host        = (string) $connection['smtp_host'];
		$phpmailer->Port        = absint( $connection['smtp_port'] );
		$phpmailer->SMTPAuth    = ! empty( $connection['smtp_auth'] );
		$phpmailer->Username    = (string) $connection['smtp_user'];
		$phpmailer->Password    = (string) $connection['smtp_pass'];
		$phpmailer->SMTPAutoTLS = ! empty( $connection['smtp_autotls'] );
		$phpmailer->Timeout     = 30;
		$phpmailer->SMTPSecure  = 'none' === $connection['smtp_encryption'] ? '' : (string) $connection['smtp_encryption'];

		if ( ! empty( $connection['force_from_email'] ) && is_email( $connection['from_email'] ) ) {
			$original_from = $phpmailer->From;
			if ( is_email( $original_from ) && strtolower( $original_from ) !== strtolower( $connection['from_email'] ) && empty( $phpmailer->getReplyToAddresses() ) ) {
				$phpmailer->addReplyTo( $original_from, $phpmailer->FromName );
			}
			$phpmailer->setFrom( $connection['from_email'], ! empty( $connection['force_from_name'] ) ? $connection['from_name'] : $phpmailer->FromName, false );
		} elseif ( ! empty( $connection['force_from_name'] ) ) {
			$phpmailer->FromName = $connection['from_name'];
		}
	}

	public function mail_failed( $error ) {
		if ( apply_filters( 'tmsmtp_pro_failure_handled', false, $error, $this->current_mail_args ) ) { return; }
		if ( ! is_wp_error( $error ) ) {
			return;
		}
		if ( ! $this->sending_alert ) {
			$this->captured_error = $error;
		}
		if ( $this->sending_alert ) {
			return;
		}

		$settings = $this->settings();
		if ( empty( $settings['alerts_enabled'] ) || ! is_email( $settings['alert_recipient'] ) ) {
			return;
		}

		$this->sending_alert  = true;
		$this->bypass_provider = true;
		try {
			$recipient = is_array( $this->current_mail_args['to'] ?? '' ) ? implode( ', ', $this->current_mail_args['to'] ) : (string) ( $this->current_mail_args['to'] ?? '' );
			$message = __( 'Titanium Mail SMTP detected a failed email.', 'titanium-mail-smtp' ) . "\n\n";
			$message .= __( 'Error:', 'titanium-mail-smtp' ) . ' ' . $error->get_error_message() . "\n";
			$message .= __( 'Subject:', 'titanium-mail-smtp' ) . ' ' . sanitize_text_field( $this->current_mail_args['subject'] ?? '' ) . "\n";
			$message .= __( 'Recipient:', 'titanium-mail-smtp' ) . ' ' . sanitize_text_field( $recipient );
			wp_mail( $settings['alert_recipient'], __( 'Titanium Mail SMTP delivery failure', 'titanium-mail-smtp' ), $message );
		} finally {
			$this->bypass_provider = false;
			$this->sending_alert   = false;
			$this->captured_error  = $error;
		}
	}

	public function admin_menu() {
		add_menu_page(
			__( 'Titanium Mail SMTP', 'titanium-mail-smtp' ),
			__( 'Titanium Mail SMTP', 'titanium-mail-smtp' ),
			'manage_options',
			'titanium-mail-smtp',
			array( $this, 'render_settings_admin' ),
			'dashicons-email-alt',
			58
		);
		add_submenu_page(
			'titanium-mail-smtp',
			__( 'Titanium Mail SMTP Settings', 'titanium-mail-smtp' ),
			__( 'Settings', 'titanium-mail-smtp' ),
			'manage_options',
			'titanium-mail-smtp-settings',
			array( $this, 'render_settings_admin' )
		);
		add_submenu_page(
			'titanium-mail-smtp',
			__( 'Titanium Mail SMTP Tools', 'titanium-mail-smtp' ),
			__( 'Tools', 'titanium-mail-smtp' ),
			'manage_options',
			'titanium-mail-smtp-tools',
			array( $this, 'render_tools_admin' )
		);
		add_submenu_page(
			'titanium-mail-smtp',
			__( 'Titanium Mail SMTP Pro', 'titanium-mail-smtp' ),
			$this->premium_available() ? __( 'License & Plans', 'titanium-mail-smtp' ) : __( 'Upgrade to Pro', 'titanium-mail-smtp' ),
			'manage_options',
			'titanium-mail-smtp-pro',
			array( $this, 'render_pro_admin' )
		);
		add_submenu_page(
			'titanium-mail-smtp',
			__( 'More Plugins', 'titanium-mail-smtp' ),
			__( 'More Plugins', 'titanium-mail-smtp' ),
			'manage_options',
			'titanium-mail-smtp-more-plugins-settings',
			array( $this, 'render_more_plugins_settings_admin' )
		);
		add_submenu_page(
			'titanium-mail-smtp',
			__( 'More Plugins', 'titanium-mail-smtp' ),
			__( 'More Plugins', 'titanium-mail-smtp' ),
			'manage_options',
			'titanium-mail-smtp-more-plugins-tools',
			array( $this, 'render_more_plugins_tools_admin' )
		);

		remove_submenu_page( 'titanium-mail-smtp', 'titanium-mail-smtp' );
	}

	public function hide_more_plugins_submenu() {
		remove_submenu_page( 'titanium-mail-smtp', 'titanium-mail-smtp-more-plugins-settings' );
		remove_submenu_page( 'titanium-mail-smtp', 'titanium-mail-smtp-more-plugins-tools' );
	}

	public function process_save() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You are not allowed to manage these settings.', 'titanium-mail-smtp' ) );
		}
		check_admin_referer( 'tmsmtp_save' );

		$tab = sanitize_key( wp_unslash( $_POST['tmsmtp_tab'] ?? 'connections' ) );
		if ( ! in_array( $tab, array( 'connections', 'alerts', 'misc' ), true ) ) {
			wp_die( esc_html__( 'The submitted settings section is invalid.', 'titanium-mail-smtp' ) );
		}

		$settings = $this->settings();
		if ( isset( $_POST['tmsmtp'] ) && is_array( $_POST['tmsmtp'] ) ) {
			$posted = wp_unslash( $_POST['tmsmtp'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		} elseif ( isset( $_POST['tms'] ) && is_array( $_POST['tms'] ) ) {
			$posted = wp_unslash( $_POST['tms'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		} else {
			$posted = array();
		}

		$validation = true;
		if ( 'connections' === $tab ) {
			if ( ! isset( $posted['connection'] ) || ! is_array( $posted['connection'] ) ) {
				wp_die( esc_html__( 'The submitted connection settings are invalid.', 'titanium-mail-smtp' ) );
			}
			$connection = $this->sanitize_connection_submission( $posted['connection'], $settings['connection'] );
			$validation = $this->validate_connection_submission( $posted['connection'], $connection );
			if ( ! is_wp_error( $validation ) ) {
				$settings['connection'] = $connection;
			}
		} elseif ( 'alerts' === $tab ) {
			$enabled       = empty( $posted['alerts_enabled'] ) ? 0 : 1;
			$raw_recipient = is_scalar( $posted['alert_recipient'] ?? '' ) ? trim( (string) $posted['alert_recipient'] ) : '';
			$recipient     = sanitize_email( $raw_recipient );
			$validation    = $this->validate_alert_submission( $enabled, $raw_recipient, $recipient );
			if ( ! is_wp_error( $validation ) ) {
				$settings['alerts_enabled']  = $enabled;
				$settings['alert_recipient'] = $recipient;
			}
		} elseif ( 'misc' === $tab ) {
			$settings['delete_on_uninstall'] = empty( $posted['delete_on_uninstall'] ) ? 0 : 1;
		}

		if ( is_wp_error( $validation ) ) {
			set_transient( 'tmsmtp_settings_error_' . get_current_user_id(), $validation->get_error_message(), MINUTE_IN_SECONDS * 5 );
			wp_safe_redirect(
				add_query_arg(
					array(
						'page'                    => 'titanium-mail-smtp-settings',
						'tab'                     => $tab,
						'tmsmtp_validation_error' => 1,
					),
					admin_url( 'admin.php' )
				)
			);
			exit;
		}

		$saved = $this->save_settings( $settings );
		wp_safe_redirect(
			add_query_arg(
				array(
					'page'              => 'titanium-mail-smtp-settings',
					'tab'               => $tab,
					'tmsmtp_saved'      => $saved ? 1 : 0,
					'tmsmtp_save_error' => $saved ? 0 : 1,
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	private function sanitize_connection_submission( $submitted, $saved ) {
		$submitted = is_array( $submitted ) ? $submitted : array();
		$saved     = $this->normalize_connection( $saved );
		$scalar    = static function ( $value, $fallback = '' ) {
			return is_scalar( $value ) ? (string) $value : (string) $fallback;
		};
		$allowed        = array( 'default', 'postmark', 'amazonses', 'sendgrid', 'mailgun', 'brevo', 'smtp' );
		$mailer         = sanitize_key( $scalar( $submitted['mailer'] ?? '', 'default' ) );
		$encryption     = sanitize_key( $scalar( $submitted['smtp_encryption'] ?? '', 'tls' ) );
		$mailgun_region = strtoupper( $scalar( $submitted['mailgun_region'] ?? '', 'US' ) );

		$connection = array_merge(
			$saved,
			array(
			'name'               => 'Primary Connection',
			'mailer'             => in_array( $mailer, $allowed, true ) ? $mailer : 'default',
			'from_email'         => sanitize_email( $scalar( $submitted['from_email'] ?? '' ) ),
			'from_name'          => sanitize_text_field( $scalar( $submitted['from_name'] ?? '' ) ),
			'force_from_email'   => empty( $submitted['force_from_email'] ) ? 0 : 1,
			'force_from_name'    => empty( $submitted['force_from_name'] ) ? 0 : 1,
			'postmark_token'     => $this->sanitize_secret_value( $submitted['postmark_token'] ?? null, $saved['postmark_token'], array_key_exists( 'postmark_token', $submitted ) ),
			'message_stream'     => sanitize_text_field( $scalar( $submitted['message_stream'] ?? '', 'outbound' ) ),
			'sendgrid_api_key'   => $this->sanitize_secret_value( $submitted['sendgrid_api_key'] ?? null, $saved['sendgrid_api_key'], array_key_exists( 'sendgrid_api_key', $submitted ) ),
			'mailgun_api_key'    => $this->sanitize_secret_value( $submitted['mailgun_api_key'] ?? null, $saved['mailgun_api_key'], array_key_exists( 'mailgun_api_key', $submitted ) ),
			'mailgun_domain'     => sanitize_text_field( $scalar( $submitted['mailgun_domain'] ?? '' ) ),
			'mailgun_region'     => in_array( $mailgun_region, array( 'US', 'EU' ), true ) ? $mailgun_region : 'US',
			'brevo_api_key'      => $this->sanitize_secret_value( $submitted['brevo_api_key'] ?? null, $saved['brevo_api_key'], array_key_exists( 'brevo_api_key', $submitted ) ),
			'ses_access_key'     => $this->sanitize_secret_value( $submitted['ses_access_key'] ?? null, $saved['ses_access_key'], array_key_exists( 'ses_access_key', $submitted ) ),
			'ses_secret_key'     => $this->sanitize_secret_value( $submitted['ses_secret_key'] ?? null, $saved['ses_secret_key'], array_key_exists( 'ses_secret_key', $submitted ) ),
			'ses_session_token'  => $this->sanitize_secret_value( $submitted['ses_session_token'] ?? null, $saved['ses_session_token'], array_key_exists( 'ses_session_token', $submitted ) ),
			'ses_region'         => sanitize_key( $scalar( $submitted['ses_region'] ?? '', 'us-east-1' ) ),
			'smtp_host'          => sanitize_text_field( $scalar( $submitted['smtp_host'] ?? '' ) ),
			'smtp_port'          => min( 65535, max( 1, absint( $submitted['smtp_port'] ?? 587 ) ) ),
			'smtp_encryption'    => in_array( $encryption, array( 'none', 'ssl', 'tls' ), true ) ? $encryption : 'tls',
			'smtp_autotls'       => empty( $submitted['smtp_autotls'] ) ? 0 : 1,
			'smtp_auth'          => empty( $submitted['smtp_auth'] ) ? 0 : 1,
			'smtp_user'          => sanitize_text_field( $scalar( $submitted['smtp_user'] ?? '' ) ),
			'smtp_pass'          => $this->sanitize_secret_value( $submitted['smtp_pass'] ?? null, $saved['smtp_pass'], array_key_exists( 'smtp_pass', $submitted ) ),
			)
		);
		return $this->normalize_connection( $connection );
	}

	private function validate_connection_submission( $submitted, $connection ) {
		$submitted       = is_array( $submitted ) ? $submitted : array();
		$connection      = $this->normalize_connection( $connection );
		$allowed_mailers = array( 'default', 'postmark', 'amazonses', 'sendgrid', 'mailgun', 'brevo', 'smtp' );
		$raw_mailer      = is_scalar( $submitted['mailer'] ?? '' ) ? sanitize_key( (string) $submitted['mailer'] ) : '';
		if ( ! in_array( $raw_mailer, $allowed_mailers, true ) ) {
			return new WP_Error( 'tmsmtp_invalid_mailer', __( 'The selected mailer is invalid.', 'titanium-mail-smtp' ) );
		}

		$effective      = $this->apply_constants( $connection );
		$raw_from_email = is_scalar( $submitted['from_email'] ?? '' ) ? trim( (string) $submitted['from_email'] ) : '';
		if ( ( '' !== $raw_from_email && ! is_email( $effective['from_email'] ) ) || ( ( 'default' !== $effective['mailer'] || ! empty( $effective['force_from_email'] ) ) && ! is_email( $effective['from_email'] ) ) ) {
			return new WP_Error( 'tmsmtp_invalid_from_email', __( 'Enter a valid From Email address before saving this connection.', 'titanium-mail-smtp' ) );
		}

		if ( 'mailgun' === $effective['mailer'] ) {
			$raw_region = is_scalar( $submitted['mailgun_region'] ?? '' ) ? strtoupper( trim( (string) $submitted['mailgun_region'] ) ) : '';
			if ( ! in_array( $raw_region, array( 'US', 'EU' ), true ) ) {
				return new WP_Error( 'tmsmtp_invalid_mailgun_region', __( 'Select a valid Mailgun region.', 'titanium-mail-smtp' ) );
			}
		}

		if ( 'amazonses' === $effective['mailer'] ) {
			$raw_region = is_scalar( $submitted['ses_region'] ?? '' ) ? trim( (string) $submitted['ses_region'] ) : '';
			if ( 1 !== preg_match( '/^[a-z]{2}(?:-gov)?-[a-z0-9-]+-\d$/', $raw_region ) ) {
				return new WP_Error( 'tmsmtp_invalid_ses_region', __( 'Enter a valid Amazon SES region, for example us-east-1.', 'titanium-mail-smtp' ) );
			}
		}

		if ( 'smtp' === $effective['mailer'] ) {
			$raw_port = is_scalar( $submitted['smtp_port'] ?? null ) ? trim( (string) $submitted['smtp_port'] ) : '';
			$valid_port = false !== filter_var(
				$raw_port,
				FILTER_VALIDATE_INT,
				array( 'options' => array( 'min_range' => 1, 'max_range' => 65535 ) )
			);
			if ( ! $valid_port ) {
				return new WP_Error( 'tmsmtp_invalid_smtp_port', __( 'SMTP port must be a whole number between 1 and 65535.', 'titanium-mail-smtp' ) );
			}

			$raw_encryption = is_scalar( $submitted['smtp_encryption'] ?? '' ) ? sanitize_key( (string) $submitted['smtp_encryption'] ) : '';
			if ( ! in_array( $raw_encryption, array( 'none', 'ssl', 'tls' ), true ) ) {
				return new WP_Error( 'tmsmtp_invalid_smtp_encryption', __( 'Select a valid SMTP encryption method.', 'titanium-mail-smtp' ) );
			}
			if ( ! $this->valid_smtp_host( $effective['smtp_host'] ) ) {
				return new WP_Error( 'tmsmtp_invalid_smtp_host', __( 'Enter a valid SMTP host without a URL path or protocol.', 'titanium-mail-smtp' ) );
			}
		}

		$status = $this->connection_status( $effective );
		if ( empty( $status['configured'] ) ) {
			return new WP_Error( 'tmsmtp_incomplete_connection', $status['message'] );
		}

		return true;
	}

	private function validate_alert_submission( $enabled, $raw_recipient, $recipient ) {
		if ( '' !== $raw_recipient && ! is_email( $recipient ) ) {
			return new WP_Error( 'tmsmtp_invalid_alert_recipient', __( 'Enter a valid alert recipient email address.', 'titanium-mail-smtp' ) );
		}
		if ( $enabled && ! is_email( $recipient ) ) {
			return new WP_Error( 'tmsmtp_missing_alert_recipient', __( 'A valid alert recipient is required while email alerts are enabled.', 'titanium-mail-smtp' ) );
		}
		return true;
	}

	private function valid_smtp_host( $host ) {
		$host = trim( is_scalar( $host ) ? (string) $host : '' );
		if ( '' === $host || strlen( $host ) > 253 || false !== strpos( $host, '://' ) || preg_match( '/[\s\/?#]/', $host ) ) {
			return false;
		}
		if ( '[' === substr( $host, 0, 1 ) && ']' === substr( $host, -1 ) ) {
			return false !== filter_var( substr( $host, 1, -1 ), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 );
		}
		if ( false !== filter_var( $host, FILTER_VALIDATE_IP ) ) {
			return true;
		}
		return 1 === preg_match( '/^(?=.{1,253}\.?$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.?$/i', $host );
	}

	public function process_test() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You are not allowed to send test emails.', 'titanium-mail-smtp' ) );
		}
		check_admin_referer( 'tmsmtp_test' );
		$to = sanitize_email( wp_unslash( $_POST['test_to'] ?? '' ) );
		$ok = false;
		$this->captured_error = null;
		$c = $this->connection();
		$status = $this->connection_status( $c );
		if ( ! is_email( $to ) ) {
			$this->captured_error = new WP_Error( 'tmsmtp_invalid_test_recipient', __( 'The test recipient email address is invalid.', 'titanium-mail-smtp' ) );
		} elseif ( empty( $status['configured'] ) ) {
			$this->captured_error = new WP_Error( 'tmsmtp_incomplete_connection', $status['message'] . ' ' . __( 'Normal website emails continue through WordPress default mail until the provider is configured.', 'titanium-mail-smtp' ) );
		} else {
			$subject = __( 'Titanium Mail SMTP test —', 'titanium-mail-smtp' ) . ' ' . wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
			$message = '<!doctype html><html><body style="margin:0;background:#eef2f7;font-family:Arial,sans-serif"><table width="100%" role="presentation" style="padding:30px"><tr><td align="center"><table width="100%" role="presentation" style="max-width:620px;background:#fff;border:1px solid #d9e2ef;border-radius:16px"><tr><td style="padding:24px;background:#245edb;color:#fff;font-size:24px;font-weight:700">Titanium Mail SMTP</td></tr><tr><td style="padding:28px;color:#334155;line-height:1.7"><strong>' . esc_html__( 'Test email sent successfully.', 'titanium-mail-smtp' ) . '</strong><br>' . esc_html__( 'This confirms that your selected mailer is working.', 'titanium-mail-smtp' ) . '</td></tr></table></td></tr></table></body></html>';
			$ok = wp_mail( $to, $subject, $message, array( 'Content-Type: text/html; charset=UTF-8' ) );
		}
		$message = $ok ? '' : ( $this->captured_error instanceof WP_Error ? $this->captured_error->get_error_message() : __( 'WordPress could not send the test email. Check the selected provider credentials and From Email settings.', 'titanium-mail-smtp' ) );
		if ( $ok && ! empty( $status['default'] ) ) { $message = __( 'The test email was handed to WordPress default mail. No external provider is configured.', 'titanium-mail-smtp' ); }
		set_transient( 'tmsmtp_test_result_' . get_current_user_id(), array( 'status' => $ok ? 'success' : 'failed', 'message' => $message, 'recipient' => $to ), MINUTE_IN_SECONDS * 5 );
		wp_safe_redirect( add_query_arg( array( 'page' => 'titanium-mail-smtp-tools', 'tab' => 'test-email', 'tmsmtp_test_result' => $ok ? 'success' : 'failed' ), admin_url( 'admin.php' ) ) );
		exit;
	}

	public function render_settings_admin() {
		$this->render_admin_shell( 'settings' );
	}

	public function render_tools_admin() {
		$this->render_admin_shell( 'tools' );
	}

	public function render_more_plugins_settings_admin() {
		$this->render_more_plugins_admin( 'settings' );
	}

	public function render_more_plugins_tools_admin() {
		$this->render_more_plugins_admin( 'tools' );
	}

	private function render_more_plugins_admin( $section ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$section = 'tools' === $section ? 'tools' : 'settings';
		if ( 'tools' === $section ) {
			$page_slug = 'titanium-mail-smtp-tools';
			$tabs      = array( 'test-email' => __( 'Test Email', 'titanium-mail-smtp' ) );
			if ( $this->premium_available() ) {
				$tabs['dns-check'] = __( 'DNS', 'titanium-mail-smtp' );
			}
			$tabs['email-log']    = __( 'Email Log', 'titanium-mail-smtp' );
			$tabs['more-plugins'] = __( 'More Plugins', 'titanium-mail-smtp' );
			$more_plugins_slug    = 'titanium-mail-smtp-more-plugins-tools';
		} else {
			$page_slug = 'titanium-mail-smtp-settings';
			$tabs      = array(
				'connections'  => __( 'Connections', 'titanium-mail-smtp' ),
				'routing'      => __( 'Smart Routing', 'titanium-mail-smtp' ),
				'alerts'       => __( 'Alerts', 'titanium-mail-smtp' ),
				'reports'      => __( 'Reports', 'titanium-mail-smtp' ),
				'misc'         => __( 'Misc', 'titanium-mail-smtp' ),
				'more-plugins' => __( 'More Plugins', 'titanium-mail-smtp' ),
			);
			$more_plugins_slug = 'titanium-mail-smtp-more-plugins-settings';
		}

		echo '<div class="wrap tmsmtp-wrap tilm-wrap is-more-plugins">';
		echo '<h1 class="screen-reader-text">' . esc_html__( 'More Plugins', 'titanium-mail-smtp' ) . '</h1>';

		$this->render_suite_header( true );

		echo '<div class="tmsmtp-tab-nav">';
		foreach ( $tabs as $key => $label ) {
			$url = 'more-plugins' === $key
				? admin_url( 'admin.php?page=' . $more_plugins_slug )
				: add_query_arg( array( 'page' => $page_slug, 'tab' => $key ), admin_url( 'admin.php' ) );
			echo '<a class="tmsmtp-tab-link ' . ( 'more-plugins' === $key ? 'is-active' : '' ) . '" href="' . esc_url( $url ) . '">' . esc_html( $label ) . '</a>';
		}
		echo '</div>';

		echo '<div class="tilm-page-shell">';
		$more_plugins = new TMSMTP_More_Plugins();
		$more_plugins->render();
		echo '</div></div>';
	}

	private function render_suite_header( $allow_page_dark_mode = true ) {
		Titanium_Suite_Header::render(
			array(
				'title'            => __( 'Mail SMTP', 'titanium-mail-smtp' ),
				'edition'          => $this->premium_available() ? __( 'Pro', 'titanium-mail-smtp' ) : __( 'Free', 'titanium-mail-smtp' ),
				'version'          => TMSMTP_VERSION,
				'storage_key'      => 'titaniumSuiteDarkMode',
				'extra_dark_class' => $allow_page_dark_mode ? 'tmsmtp-admin-dark' : '',
			)
		);
	}

	private function render_admin_shell( $section ) {
		if ( ! current_user_can( 'manage_options' ) ) { return; }
		$s = $this->settings();
		if ( 'tools' === $section ) {
			$page_slug = 'titanium-mail-smtp-tools';
			$tabs = array( 'test-email' => __( 'Test Email', 'titanium-mail-smtp' ) );
			if ( $this->premium_available() ) {
				$tabs['dns-check'] = __( 'DNS', 'titanium-mail-smtp' );
			}
			$tabs['email-log']    = __( 'Email Log', 'titanium-mail-smtp' );
			$tabs['more-plugins'] = __( 'More Plugins', 'titanium-mail-smtp' );
			$default_tab = 'test-email';
		} else {
			$page_slug = 'titanium-mail-smtp-settings';
			$tabs = array(
				'connections'  => __( 'Connections', 'titanium-mail-smtp' ),
				'routing'      => __( 'Smart Routing', 'titanium-mail-smtp' ),
				'alerts'       => __( 'Alerts', 'titanium-mail-smtp' ),
				'reports'      => __( 'Reports', 'titanium-mail-smtp' ),
				'misc'         => __( 'Misc', 'titanium-mail-smtp' ),
				'more-plugins' => __( 'More Plugins', 'titanium-mail-smtp' ),
			);
			$default_tab = 'connections';
		}
		$requested_tab = filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_SPECIAL_CHARS );
		$tab = $requested_tab ? sanitize_key( $requested_tab ) : $default_tab;
		if ( ! isset( $tabs[ $tab ] ) ) { $tab = $default_tab; }
		if ( 'more-plugins' === $tab ) { $tab = $default_tab; }

		echo '<div class="wrap tmsmtp-wrap"><h1 class="screen-reader-text tmsmtp-admin-heading">' . esc_html__( 'Titanium Mail SMTP', 'titanium-mail-smtp' ) . '</h1>';
		$this->render_suite_header( true );
		echo '<div class="tmsmtp-tab-nav">';
		$more_plugins_slug = 'tools' === $section
			? 'titanium-mail-smtp-more-plugins-tools'
			: 'titanium-mail-smtp-more-plugins-settings';
		foreach ( $tabs as $key => $label ) {
			$url = 'more-plugins' === $key
				? admin_url( 'admin.php?page=' . $more_plugins_slug )
				: add_query_arg( array( 'page' => $page_slug, 'tab' => $key ), admin_url( 'admin.php' ) );
			echo '<a class="tmsmtp-tab-link ' . ( $key === $tab ? 'is-active' : '' ) . '" href="' . esc_url( $url ) . '">' . esc_html( $label ) . '</a>';
		}
		echo '</div><div class="tmsmtp-page-shell">';

		if ( filter_input( INPUT_GET, 'tmsmtp_saved', FILTER_VALIDATE_INT ) ) {
			$this->render_result_message( 'success', __( 'Settings saved.', 'titanium-mail-smtp' ) );
		} elseif ( filter_input( INPUT_GET, 'tmsmtp_validation_error', FILTER_VALIDATE_INT ) ) {
			$message = get_transient( 'tmsmtp_settings_error_' . get_current_user_id() );
			delete_transient( 'tmsmtp_settings_error_' . get_current_user_id() );
			$this->render_result_message( 'error', __( 'Settings could not be saved.', 'titanium-mail-smtp' ), is_scalar( $message ) ? (string) $message : __( 'One or more submitted values are invalid.', 'titanium-mail-smtp' ) );
		} elseif ( filter_input( INPUT_GET, 'tmsmtp_save_error', FILTER_VALIDATE_INT ) ) {
			$this->render_result_message( 'error', __( 'Settings could not be saved.', 'titanium-mail-smtp' ), __( 'The database value did not match the submitted settings after writing.', 'titanium-mail-smtp' ) );
		}
		if ( 'tools' === $section ) { $this->render_tool_notices( $tab ); }

		if ( $this->premium_available() && class_exists( 'TMSMTP_Pro_Features' ) ) {
			$pro = TMSMTP_Pro_Features::instance();
			$pro->render_pro_assets();
			$pro->render_notices( $section, $tab );
			if ( 'settings' === $section && 'more-plugins' !== $tab ) { $pro->render_settings_tab( $tab ); }
			elseif ( 'tools' === $section && 'more-plugins' !== $tab ) { $pro->render_tools_tab( $tab ); }
			else { $this->render_more_plugins(); }
		} elseif ( 'settings' === $section ) {
			if ( 'connections' === $tab ) { $this->render_connections( $s ); }
			elseif ( 'routing' === $tab ) { TMSMTP_Free_Routing::instance()->render_admin(); }
			elseif ( 'alerts' === $tab ) { $this->render_alerts( $s ); }
			elseif ( 'reports' === $tab ) { $this->render_pro_preview( __( 'Email Reports', 'titanium-mail-smtp' ), __( 'Receive daily, weekly or monthly delivery statistics by email.', 'titanium-mail-smtp' ), array( __( 'Successful and failed counts', 'titanium-mail-smtp' ), __( 'Backup delivery statistics', 'titanium-mail-smtp' ), __( 'Scheduled reports', 'titanium-mail-smtp' ) ) ); }
			elseif ( 'misc' === $tab ) { $this->render_misc( $s ); }
			else { $this->render_more_plugins(); }
		} else {
			if ( 'test-email' === $tab ) { $this->render_test_email_tool(); }
			elseif ( 'email-log' === $tab ) { $this->render_pro_preview( __( 'Full Email Log', 'titanium-mail-smtp' ), __( 'Review sent and failed emails with their complete content and source.', 'titanium-mail-smtp' ), array( __( 'Full HTML and text body', 'titanium-mail-smtp' ), __( 'Email source detection', 'titanium-mail-smtp' ), __( 'Resend any logged email', 'titanium-mail-smtp' ) ) ); }
			else { $this->render_more_plugins(); }
		}
		echo '</div></div>';
	}

	private function is_pricing_load_authorized() {
		return current_user_can( 'manage_options' ) && 1 === absint( get_option( self::PRICING_OPT_IN_OPTION, 0 ) );
	}

	public function handle_pricing_consent() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$consent_action = filter_input( INPUT_POST, 'tmsmtp_pricing_consent_action', FILTER_SANITIZE_SPECIAL_CHARS );
		if ( ! is_string( $consent_action ) || ! in_array( $consent_action, array( 'enable', 'disable' ), true ) ) {
			return;
		}

		check_admin_referer( 'tmsmtp_pricing_consent', 'tmsmtp_pricing_consent_nonce' );

		$enabled = 'enable' === $consent_action;
		if ( $enabled ) {
			update_option( self::PRICING_OPT_IN_OPTION, 1, false );
		} else {
			delete_option( self::PRICING_OPT_IN_OPTION );
			delete_transient( 'tmsmtp_public_pricing_payload_v3' );
			delete_option( 'tmsmtp_public_pricing_cache_v3' );
		}

		$is_ajax_request = isset( $_POST['tmsmtp_pricing_consent_ajax'] )
			&& '1' === sanitize_text_field( wp_unslash( $_POST['tmsmtp_pricing_consent_ajax'] ) );
		if ( $is_ajax_request ) {
			wp_send_json_success(
				array(
					'enabled'      => $enabled,
					'pricingNonce' => $enabled ? wp_create_nonce( 'tmsmtp_pricing_nonce' ) : '',
					'consentNonce' => wp_create_nonce( 'tmsmtp_pricing_consent' ),
				)
			);
		}

		wp_safe_redirect( admin_url( 'admin.php?page=titanium-mail-smtp-pro' ) );
		exit;
	}



	public function enqueue_admin_assets( $hook ) {
		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$plugin_pages = array( 'titanium-mail-smtp', 'titanium-mail-smtp-settings', 'titanium-mail-smtp-tools', 'titanium-mail-smtp-pro', 'titanium-mail-smtp-more-plugins-settings', 'titanium-mail-smtp-more-plugins-tools' );
		if ( ! in_array( $page, $plugin_pages, true ) ) {
			return;
		}

		$is_more_plugins_page = in_array( $page, array( 'titanium-mail-smtp-more-plugins-settings', 'titanium-mail-smtp-more-plugins-tools' ), true );
		if ( $is_more_plugins_page ) {
			$more_plugins_css = TMSMTP_DIR . 'assets/more-plugins.css';
			wp_enqueue_style( 'tmsmtp-admin', TMSMTP_URL . 'assets/admin.css', array(), TMSMTP_VERSION );
			wp_enqueue_style(
				'tmsmtp-more-plugins',
				TMSMTP_URL . 'assets/more-plugins.css',
				array( 'tmsmtp-admin' ),
				file_exists( $more_plugins_css ) ? (string) filemtime( $more_plugins_css ) : TMSMTP_VERSION
			);
			Titanium_Suite_Header::enqueue_assets(
				array(
					'storage_key'      => 'titaniumSuiteDarkMode',
					'extra_dark_class' => 'tmsmtp-admin-dark',
				)
			);
			return;
		}

		$is_upgrade_page = 'titanium-mail-smtp-pro' === $page;
		if ( $is_upgrade_page ) {
			 
			wp_enqueue_style( 'tmsmtp-admin-upgrade', TMSMTP_URL . 'assets/admin-upgrade.css', array(), TMSMTP_VERSION );
			wp_enqueue_style( 'tmsmtp-pricing', TMSMTP_URL . 'assets/pricing.css', array( 'tmsmtp-admin-upgrade' ), TMSMTP_VERSION );
		}
		$admin_style_dependencies = $is_upgrade_page ? array( 'tmsmtp-pricing' ) : array();
		wp_enqueue_style( 'tmsmtp-admin', TMSMTP_URL . 'assets/admin.css', $admin_style_dependencies, TMSMTP_VERSION );

		Titanium_Suite_Header::enqueue_assets(
			array(
				'storage_key'      => 'titaniumSuiteDarkMode',
				'extra_dark_class' => $is_upgrade_page ? '' : 'tmsmtp-admin-dark',
			)
		);
		wp_enqueue_script( 'tmsmtp-admin', TMSMTP_URL . 'assets/admin.js', array(), TMSMTP_VERSION, true );
		wp_localize_script(
			'tmsmtp-admin',
			'tmsmtpAdmin',
			array( 'processingText' => __( 'Processing…', 'titanium-mail-smtp' ) )
		);

		if ( ! $is_upgrade_page ) {
			return;
		}

		$pricing_enabled = $this->is_pricing_load_authorized();
		$no_cache        = $pricing_enabled && isset( $_GET['no_cache'] ) && '1' === sanitize_text_field( wp_unslash( $_GET['no_cache'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		wp_enqueue_script( 'tmsmtp-pricing', TMSMTP_URL . 'assets/pricing.js', array(), TMSMTP_VERSION, true );
		wp_localize_script(
			'tmsmtp-pricing',
			'tmsmtpPricing',
			array(
				'ajaxUrl'                 => admin_url( 'admin-ajax.php' ),
				'action'                  => 'tmsmtp_get_freemius_pricing',
				'consentNonce'            => wp_create_nonce( 'tmsmtp_pricing_consent' ),
				'checkoutScriptUrl'       => 'https://checkout.freemius.com/js/v1/',
				'pricingEnabled'          => $pricing_enabled,
				'cachedPricingPayload'    => $pricing_enabled && ! $no_cache ? $this->get_cached_public_pricing_payload() : array(),
				'pricingCacheFresh'       => $pricing_enabled && ! $no_cache ? $this->was_pricing_checked_recently() : false,
				'noCache'                 => $no_cache,
				'productId'               => 34725,
				'planId'                  => 57101,
				'currency'                => 'gbp',
				'button'                  => __( 'UPGRADE NOW', 'titanium-mail-smtp' ),
				'perYear'                 => __( '/ year', 'titanium-mail-smtp' ),
				'loadingPricesText'       => __( 'Loading prices...', 'titanium-mail-smtp' ),
				'priceUnavailableText'    => __( 'Prices could not be downloaded. Secure checkout will show the current price.', 'titanium-mail-smtp' ),
				'discountText'            => __( '50% discount applied.', 'titanium-mail-smtp' ),
				'manualCouponText'        => __( 'Have a different coupon code?', 'titanium-mail-smtp' ),
				'enablePricesText'        => __( 'ENABLE CURRENT PRICES', 'titanium-mail-smtp' ),
				'disablePricesText'       => __( 'DISABLE CURRENT PRICES', 'titanium-mail-smtp' ),
				'showPriceText'           => __( 'SHOW CURRENT PRICE', 'titanium-mail-smtp' ),
				'pricesEnabledTitle'      => __( 'Current prices are enabled', 'titanium-mail-smtp' ),
				'pricesDisabledTitle'     => __( 'Choose whether to display current prices', 'titanium-mail-smtp' ),
			)
		);
	}

	private function premium_available() {
		return function_exists( 'tmsmtp_is_premium_available' ) && tmsmtp_is_premium_available();
	}

	public function print_upgrade_menu_css() {
		if ( ! current_user_can( 'manage_options' ) || $this->premium_available() ) { return; }
		wp_register_style( 'tmsmtp-upgrade-menu-css', false, array(), TMSMTP_VERSION );
		wp_enqueue_style( 'tmsmtp-upgrade-menu-css' );
		wp_add_inline_style( 'tmsmtp-upgrade-menu-css', '#adminmenu a[href="admin.php?page=titanium-mail-smtp-pro"],#adminmenu a[href$="admin.php?page=titanium-mail-smtp-pro"]{color:#22c55e!important;font-weight:800!important;background:transparent!important;box-shadow:none!important;}#adminmenu a[href="admin.php?page=titanium-mail-smtp-pro"]:hover,#adminmenu a[href$="admin.php?page=titanium-mail-smtp-pro"]:hover,#adminmenu li.current a[href="admin.php?page=titanium-mail-smtp-pro"],#adminmenu li.current a[href$="admin.php?page=titanium-mail-smtp-pro"]{color:#16a34a!important;background:transparent!important;box-shadow:none!important;}' );
	}

	private function get_current_license_marker() {
		$marker = apply_filters( 'tmsmtp_current_license_marker', array( 'pricing_id' => '', 'licenses' => '' ) );
		if ( ! is_array( $marker ) ) { return array( 'pricing_id' => '', 'licenses' => '' ); }
		$licenses = sanitize_text_field( (string) ( $marker['licenses'] ?? '' ) );
		return array(
			'pricing_id' => sanitize_text_field( (string) ( $marker['pricing_id'] ?? '' ) ),
			'licenses'   => 'unlimited' === strtolower( $licenses ) ? 'unlimited' : ( $licenses ? (string) absint( $licenses ) : '' ),
		);
	}

	private function get_hosted_checkout_url( $plan_id, $pricing_id ) {
		$plan_id    = absint( $plan_id );
		$pricing_id = (string) $pricing_id;
		if ( $plan_id <= 0 || '' === $pricing_id ) {
			return '';
		}
		return add_query_arg(
			array( 'pricing_id' => $pricing_id, 'billing_cycle' => 'annual', 'currency' => 'gbp' ),
			'https://checkout.freemius.com/product/34725/plan/' . $plan_id . '/'
		);
	}

	private function get_checkout_url( $licenses = '1', $pricing_id = '', $plan_id = '' ) {
		$hosted = $this->get_hosted_checkout_url( $plan_id, $pricing_id );
		if ( '' !== $hosted ) {
			return $hosted;
		}
		if ( function_exists( 'tmsmtp_fs' ) ) {
			$fs = tmsmtp_fs();
			if ( is_object( $fs ) && method_exists( $fs, 'checkout_url' ) ) {
				$extra = array( 'currency' => 'gbp' );
				if ( absint( $plan_id ) > 0 ) { $extra['plan_id'] = (string) absint( $plan_id ); }
				if ( 'unlimited' !== $licenses && absint( $licenses ) > 0 ) { $extra['licenses'] = absint( $licenses ); }
				$url = $fs->checkout_url( 'annual', false, $extra );
				if ( is_string( $url ) && '' !== $url && false === strpos( $url, 'page=titanium-mail-smtp-pro' ) ) {
					return $url;
				}
			}
		}
		return (string) apply_filters( 'tmsmtp/pro_url', 'https://adminplugins.com/mail-smtp/' );
	}

	private function get_hosted_upgrade_url( $plan_id, $pricing_id ) {
		$fallback = $this->get_plan_change_url();
		$url = apply_filters( 'tmsmtp_hosted_upgrade_url', $fallback, absint( $plan_id ), sanitize_text_field( (string) $pricing_id ) );
		$url = esc_url_raw( is_string( $url ) ? $url : '', array( 'https' ) );
		return $url ?: $fallback;
	}

	private function get_plan_change_url() {
		if ( function_exists( 'tmsmtp_fs' ) ) {
			$fs = tmsmtp_fs();
			foreach ( array( 'get_upgrade_url', 'pricing_url' ) as $method ) {
				if ( is_object( $fs ) && method_exists( $fs, $method ) ) {
					$url = $fs->{$method}( 'annual', false );
					if ( is_string( $url ) && '' !== $url ) {
						return add_query_arg( 'currency', 'gbp', $url );
					}
				}
			}
		}
		return $this->get_checkout_url( '1' );
	}

	private function get_freemius_account_url_if_connected() {
		if ( ! function_exists( 'tmsmtp_fs' ) ) { return ''; }
		$fs = tmsmtp_fs();
		if ( ! is_object( $fs ) || ! method_exists( $fs, 'get_account_url' ) ) { return ''; }
		if ( method_exists( $fs, 'is_registered' ) && ! $fs->is_registered() ) { return ''; }
		$url = $fs->get_account_url();
		return is_string( $url ) ? $url : '';
	}





	public function ajax_get_freemius_pricing() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission to view pricing.', 'titanium-mail-smtp' ) ), 403 );
		}
		if ( ! $this->is_pricing_load_authorized() ) {
			wp_send_json_error( array( 'message' => __( 'Current price loading is disabled.', 'titanium-mail-smtp' ) ), 403 );
		}
		check_ajax_referer( 'tmsmtp_pricing_nonce', 'nonce' );
		$force_refresh = isset( $_POST['no_cache'] ) && '1' === sanitize_text_field( wp_unslash( $_POST['no_cache'] ) );
		$payload = $this->get_public_pricing_payload( $force_refresh );
		if ( is_array( $payload ) && ! empty( $payload['pricing'] ) ) {
			wp_send_json_success( array( 'pricingPayload' => $payload, 'proActive' => $this->premium_available() ) );
		}
		$plans = $this->get_freemius_pricing_cards();
		if ( empty( $plans ) ) {
			wp_send_json_error( array( 'message' => __( 'Prices could not be downloaded. Secure checkout will show the current price.', 'titanium-mail-smtp' ) ) );
		}
		wp_send_json_success( array( 'plans' => $plans, 'proActive' => $this->premium_available() ) );
	}

	private function get_pricing_cache_record() {
		$record = get_option( 'tmsmtp_public_pricing_cache_v3', array() );
		return is_array( $record ) ? $record : array();
	}

	private function get_stale_public_pricing_payload() {
		$record  = $this->get_pricing_cache_record();
		$payload = isset( $record['payload'] ) && is_array( $record['payload'] ) ? $record['payload'] : array();
		return ! empty( $payload['pricing'] ) && is_array( $payload['pricing'] ) ? $payload : array();
	}

	private function was_pricing_checked_recently() {
		$record = $this->get_pricing_cache_record();
		$now    = time();
		if ( ! empty( $record['payload']['pricing'] ) && absint( $record['expires_at'] ?? 0 ) > $now ) { return true; }
		$attempted = absint( $record['last_attempt_at'] ?? ( $record['checked_at'] ?? 0 ) );
		return $attempted > 0 && ( $now - $attempted ) < 5 * MINUTE_IN_SECONDS;
	}

	private function store_public_pricing_cache( $payload, $successful = true ) {
		$record                    = $this->get_pricing_cache_record();
		$record['last_attempt_at'] = time();
		unset( $record['checked_at'] );
		if ( $successful && is_array( $payload ) && ! empty( $payload['pricing'] ) && is_array( $payload['pricing'] ) ) {
			$record['expires_at'] = $record['last_attempt_at'] + DAY_IN_SECONDS;
			$record['payload']    = $payload;
			set_transient( 'tmsmtp_public_pricing_payload_v3', $payload, DAY_IN_SECONDS );
		}
		update_option( 'tmsmtp_public_pricing_cache_v3', $record, false );
	}

	private function get_cached_public_pricing_payload() {
		$cached = get_transient( 'tmsmtp_public_pricing_payload_v3' );
		if ( is_array( $cached ) && ! empty( $cached['pricing'] ) && is_array( $cached['pricing'] ) ) {
			return $cached;
		}

		$record     = $this->get_pricing_cache_record();
		$expires_at = isset( $record['expires_at'] ) ? absint( $record['expires_at'] ) : 0;
		$payload    = isset( $record['payload'] ) && is_array( $record['payload'] ) ? $record['payload'] : array();
		if ( $expires_at > time() && ! empty( $payload['pricing'] ) && is_array( $payload['pricing'] ) ) {
			set_transient( 'tmsmtp_public_pricing_payload_v3', $payload, max( 60, $expires_at - time() ) );
			return $payload;
		}
		return array();
	}

	private function get_public_pricing_payload( $force_refresh = false ) {
		if ( ! $force_refresh ) {
			$cached = $this->get_cached_public_pricing_payload();
			if ( ! empty( $cached['pricing'] ) ) { return $cached; }
			if ( $this->was_pricing_checked_recently() ) { return array(); }
		}

		$query = array( 'source' => 'plugin' );
		if ( $force_refresh ) { $query['no_cache'] = '1'; }
		$urls = array(
			add_query_arg( $query, 'https://adminplugins.com/wp-json/tmsmtp-freemius/v1/pricing' ),
			add_query_arg( array_merge( array( 'rest_route' => '/tmsmtp-freemius/v1/pricing' ), $query ), 'https://adminplugins.com/' ),
		);
		$payload = array();
		foreach ( $urls as $url ) {
			$response = wp_remote_get(
				$url,
				array(
					'timeout'             => 12,
					'redirection'         => 0,
					'limit_response_size' => 262144,
					'headers'             => array(
						'Accept'     => 'application/json',
						'User-Agent' => 'Titanium-Mail-SMTP-Pricing/1.0',
					),
				)
			);
			if ( is_wp_error( $response ) ) { continue; }
			$status = (int) wp_remote_retrieve_response_code( $response );
			if ( $status < 200 || $status >= 300 ) { continue; }
			$payload = json_decode( wp_remote_retrieve_body( $response ), true );
			if ( is_array( $payload ) && ! empty( $payload['pricing'] ) && is_array( $payload['pricing'] ) ) { break; }
		}
		if ( ! is_array( $payload ) || empty( $payload['pricing'] ) || ! is_array( $payload['pricing'] ) ) {
			$stale = $this->get_stale_public_pricing_payload();
			$this->store_public_pricing_cache( $stale, false );
			return $stale;
		}

		$expected_product_id = 34725;
		$expected_plan_id    = 57101;
		$product_id          = isset( $payload['product_id'] ) ? absint( $payload['product_id'] ) : $expected_product_id;
		$plan_id             = isset( $payload['plan_id'] ) ? absint( $payload['plan_id'] ) : $expected_plan_id;
		$currency            = isset( $payload['currency'] ) ? sanitize_key( (string) $payload['currency'] ) : 'gbp';
		if ( $expected_product_id !== $product_id || $expected_plan_id !== $plan_id || 'gbp' !== $currency ) {
			$stale = $this->get_stale_public_pricing_payload();
			$this->store_public_pricing_cache( $stale, false );
			return $stale;
		}

		$expected_pricing = array(
			'76766' => '1',
			'76767' => '3',
			'76768' => '5',
			'76769' => '10',
			'76770' => '20',
			'80169' => '50',
		);
		$clean = array(
			'product_id' => $expected_product_id,
			'plan_id'    => $expected_plan_id,
			'currency'   => 'gbp',
			'pricing'    => array(),
			'coupon'     => null,
		);
		$has_current_50_pricing = isset( $payload['pricing']['80169'] ) && is_array( $payload['pricing']['80169'] );
		foreach ( (array) $payload['pricing'] as $pricing_id => $item ) {
			$source_key = sanitize_key( (string) $pricing_id );
			$key        = ( '76771' === $source_key && ! $has_current_50_pricing ) ? '80169' : $source_key;
			if ( ! isset( $expected_pricing[ $key ] ) || ! is_array( $item ) ) { continue; }
			$id       = sanitize_key( (string) ( isset( $item['id'] ) ? $item['id'] : $source_key ) );
			$annual   = isset( $item['annual_price'] ) ? $item['annual_price'] : '';
			$item_cur = isset( $item['currency'] ) ? sanitize_key( (string) $item['currency'] ) : 'gbp';
			$amount   = is_numeric( $annual ) ? (float) $annual : -1;
			if ( $source_key !== $id || 'gbp' !== $item_cur || $amount <= 0 || $amount > 100000 ) { continue; }
			$clean['pricing'][ $key ] = array(
				'id'           => $key,
				'currency'     => 'gbp',
				'licenses'     => $expected_pricing[ $key ],
				'annual_price' => (string) $annual,
			);
		}

		if ( ! empty( $payload['coupon'] ) && is_array( $payload['coupon'] ) ) {
			$coupon   = $payload['coupon'];
			$discount = 0.0;
			foreach ( array( 'discount', 'discount_amount', 'amount', 'coupon_discount' ) as $discount_key ) {
				if ( isset( $coupon[ $discount_key ] ) && is_numeric( $coupon[ $discount_key ] ) ) {
					$discount = (float) $coupon[ $discount_key ];
					break;
				}
			}

			$raw_type = isset( $coupon['discount_type'] ) ? (string) $coupon['discount_type'] : ( isset( $coupon['type'] ) ? (string) $coupon['type'] : '' );
			$raw_type = strtolower( trim( $raw_type ) );
			if ( in_array( $raw_type, array( 'percentage', 'percent', '%' ), true ) ) {
				$type = 'percentage';
			} elseif ( in_array( $raw_type, array( 'fixed', 'money', 'amount', 'currency' ), true ) ) {
				$type = 'fixed';
			} else {
				$type = sanitize_key( $raw_type );
			}

			$code   = isset( $coupon['code'] ) ? sanitize_text_field( (string) $coupon['code'] ) : '';
			$active = true;
			foreach ( array( 'is_active', 'active' ) as $active_key ) {
				if ( array_key_exists( $active_key, $coupon ) ) {
					$active_value = $coupon[ $active_key ];
					if ( is_bool( $active_value ) ) {
						$active = $active_value;
					} elseif ( is_numeric( $active_value ) ) {
						$active = 1 === (int) $active_value;
					} else {
						$active = in_array( strtolower( trim( (string) $active_value ) ), array( '1', 'true', 'yes', 'on', 'active', 'enabled', 'published' ), true );
					}
					break;
				}
			}
			foreach ( array( 'status', 'state' ) as $status_key ) {
				if ( ! empty( $coupon[ $status_key ] ) ) {
					$status_value = strtolower( trim( (string) $coupon[ $status_key ] ) );
					if ( in_array( $status_value, array( 'inactive', 'disabled', 'deleted', 'archived', 'draft', 'expired' ), true ) ) { $active = false; }
					if ( in_array( $status_value, array( 'active', 'enabled', 'published' ), true ) ) { $active = true; }
				}
			}
			foreach ( array( 'is_deleted', 'deleted', 'is_disabled', 'disabled', 'is_archived', 'archived' ) as $inactive_key ) {
				if ( array_key_exists( $inactive_key, $coupon ) ) {
					$inactive_value = $coupon[ $inactive_key ];
					$inactive = is_bool( $inactive_value ) ? $inactive_value : in_array( strtolower( trim( (string) $inactive_value ) ), array( '1', 'true', 'yes', 'on' ), true );
					if ( $inactive ) { $active = false; break; }
				}
			}
			$valid_discount = 'percentage' === $type ? $discount <= 100 : $discount <= 100000;
			if ( $active && '' !== $code && strlen( $code ) <= 100 && $discount > 0 && $valid_discount && in_array( $type, array( 'percentage', 'fixed' ), true ) ) {
				$clean['coupon'] = array(
					'code'          => $code,
					'discount'      => $discount,
					'discount_type' => $type,
					'is_active'     => true,
				);
			}
		}

		if ( ! empty( $clean['pricing'] ) ) {
			$this->store_public_pricing_cache( $clean );
			return $clean;
		}
		$stale = $this->get_stale_public_pricing_payload();
		$this->store_public_pricing_cache( $stale, false );
		return $stale;
	}

	private function get_freemius_pricing_cards() {
		if ( ! function_exists( 'tmsmtp_fs' ) ) { return array(); }
		$fs = tmsmtp_fs();
		if ( ! is_object( $fs ) || ! method_exists( $fs, 'is_registered' ) || ! $fs->is_registered() || ! method_exists( $fs, 'is_tracking_allowed' ) || ! $fs->is_tracking_allowed() || ! method_exists( $fs, 'get_api_plugin_scope' ) || ! method_exists( $fs, 'add_show_pending' ) ) { return array(); }
		$api = $fs->get_api_plugin_scope();
		if ( ! is_object( $api ) || ! method_exists( $api, 'get' ) ) { return array(); }
		$path = $fs->add_show_pending( 'pricing.json?' . http_build_query( array( 'is_enriched' => 'true', 'currency' => 'gbp' ) ) );
		$response = $api->get( $path );
		if ( is_object( $response ) && isset( $response->error ) ) { return array(); }
		return $this->build_pricing_cards_from_freemius_response( $response );
	}

	private function build_pricing_cards_from_freemius_response( $response ) {
		$plans = $this->pricing_value( $response, 'plans' );
		if ( ! is_array( $plans ) ) { return array(); }
		$pro_plan = null;
		foreach ( $plans as $plan ) {
			$name = strtolower( (string) $this->pricing_value( $plan, 'name' ) );
			$rows = $this->pricing_value( $plan, 'pricing' );
			if ( 'pro' === $name && is_array( $rows ) && ! empty( $rows ) ) { $pro_plan = $plan; break; }
		}
		if ( null === $pro_plan ) {
			foreach ( $plans as $plan ) { $rows = $this->pricing_value( $plan, 'pricing' ); if ( is_array( $rows ) && ! empty( $rows ) ) { $pro_plan = $plan; break; } }
		}
		if ( null === $pro_plan ) { return array(); }
		$plan_id = (string) $this->pricing_value( $pro_plan, 'id' );
		$rows    = $this->pricing_value( $pro_plan, 'pricing' );
		$cards   = array();
		foreach ( (array) $rows as $pricing ) {
			$cycle      = strtolower( (string) $this->pricing_value( $pricing, 'billing_cycle' ) );
			$currency   = strtolower( (string) $this->pricing_value( $pricing, 'currency' ) );
			$licenses   = $this->normalize_freemius_licenses( $this->pricing_value( $pricing, 'licenses' ) );
			$pricing_id = (string) $this->pricing_value( $pricing, 'id' );
			if ( '' !== $currency && 'gbp' !== $currency ) { continue; }
			if ( '' !== $cycle && ! in_array( $cycle, array( 'annual', 'yearly', 'year' ), true ) ) { continue; }
			$amount = $this->pricing_value( $pricing, 'annual_price' );
			if ( null === $amount || '' === $amount ) { $amount = $this->pricing_value( $pricing, 'annual' ); }
			if ( null === $amount || '' === $amount ) { $amount = $this->pricing_value( $pricing, 'price' ); }
			if ( null === $amount || '' === $amount || ! is_numeric( $amount ) ) { continue; }
			$cards[] = array( 'label' => $this->format_license_label( $licenses ), 'licenses' => $licenses, 'price' => $this->format_price( (float) $amount, '' !== $currency ? $currency : 'gbp' ), 'pricing_id' => $pricing_id, 'checkout' => $this->get_checkout_url( $licenses, $pricing_id, $plan_id ) );
		}
		usort( $cards, function ( array $a, array $b ) { return $this->license_sort_weight( $a['licenses'] ) <=> $this->license_sort_weight( $b['licenses'] ); } );
		return $cards;
	}

	private function pricing_value( $value, $key ) {
		if ( is_array( $value ) && array_key_exists( $key, $value ) ) { return $value[ $key ]; }
		if ( is_object( $value ) && isset( $value->{$key} ) ) { return $value->{$key}; }
		return null;
	}

	private function normalize_freemius_licenses( $licenses ) {
		if ( null === $licenses || '' === $licenses ) { return 'unlimited'; }
		$value = strtolower( (string) $licenses );
		return in_array( $value, array( 'unlimited', 'inf', 'infinite', '0' ), true ) ? 'unlimited' : (string) max( 1, absint( $value ) );
	}

	private function format_license_label( $licenses ) {
		if ( 'unlimited' === $licenses ) { return __( 'Unlimited Sites', 'titanium-mail-smtp' ); }
		if ( '1' === $licenses ) { return __( 'Single Site', 'titanium-mail-smtp' ); }
		/* translators: %s: number of websites included in the license. */
		return sprintf( __( '%s Sites', 'titanium-mail-smtp' ), number_format_i18n( (int) $licenses ) );
	}

	private function license_sort_weight( $licenses ) {
		return 'unlimited' === $licenses ? PHP_INT_MAX : (int) $licenses;
	}

	private function format_price( $amount, $currency ) {
		$symbols  = array( 'gbp' => '£', 'usd' => '$', 'eur' => '€' );
		$currency = strtolower( (string) $currency );
		return ( $symbols[ $currency ] ?? strtoupper( $currency ) . ' ' ) . number_format_i18n( $amount, 2 );
	}

	private function premium_feature_rows() {
		return array(
			array( 'label' => __( 'Postmark, Amazon SES, SendGrid, Mailgun, Brevo and Other SMTP', 'titanium-mail-smtp' ), 'free' => true, 'detail' => __( 'Six built-in delivery options are included in Free.', 'titanium-mail-smtp' ) ),
			array( 'label' => __( 'Primary plus one Additional Connection', 'titanium-mail-smtp' ), 'free' => true, 'detail' => __( 'Configure two independent delivery providers in the Free version.', 'titanium-mail-smtp' ) ),
			array( 'label' => __( 'Visual AND/OR Smart Routing', 'titanium-mail-smtp' ), 'free' => true, 'detail' => __( 'Route by recipients, sender, subject, content, headers, or the source plugin.', 'titanium-mail-smtp' ) ),
			array( 'label' => __( 'One-time WP Mail SMTP migration', 'titanium-mail-smtp' ), 'free' => true, 'detail' => __( 'Imports a supported primary mailer without deleting the source settings.', 'titanium-mail-smtp' ) ),
			array( 'label' => __( 'Test email tools', 'titanium-mail-smtp' ), 'free' => true, 'detail' => __( 'Send real test emails through the Primary and Additional Connections.', 'titanium-mail-smtp' ) ),
			array( 'label' => __( 'Simple email failure alerts', 'titanium-mail-smtp' ), 'free' => true, 'detail' => __( 'Send a notification when WordPress reports a delivery failure.', 'titanium-mail-smtp' ) ),
			array( 'label' => __( 'wp-config.php credential constants', 'titanium-mail-smtp' ), 'free' => true, 'detail' => __( 'Keep supported API keys and SMTP passwords outside the WordPress database.', 'titanium-mail-smtp' ) ),
			array( 'label' => __( 'Unlimited additional connections', 'titanium-mail-smtp' ), 'free' => false, 'detail' => __( 'Create as many provider connections and routing targets as the site needs.', 'titanium-mail-smtp' ) ),
			array( 'label' => __( 'Automatic backup delivery and failover', 'titanium-mail-smtp' ), 'free' => false, 'detail' => __( 'Retry through a selected backup connection when the chosen delivery fails.', 'titanium-mail-smtp' ) ),
			array( 'label' => __( 'Protected failure alerts and grouped summaries', 'titanium-mail-smtp' ), 'free' => false, 'detail' => __( 'Reduce alert loops and combine repeated failures into clearer notifications.', 'titanium-mail-smtp' ) ),
			array( 'label' => __( 'Full Email Log, automatic retry, and masked transcript for SMTP deliveries', 'titanium-mail-smtp' ), 'free' => false, 'detail' => __( 'Store complete messages for support, automatic retry, and manual resend while masking authentication data.', 'titanium-mail-smtp' ) ),
			array( 'label' => __( 'Daily, weekly or monthly reports', 'titanium-mail-smtp' ), 'free' => false, 'detail' => __( 'Receive sent, failed and successful backup-delivery statistics by email.', 'titanium-mail-smtp' ) ),
		);
	}
	private function render_locked_pro_feature_card( $index, $title, $description ) {
		echo '<div class="tmsmtp-pro-feature-card"><span class="tmsmtp-feature-icon" aria-hidden="true">' . esc_html( $index ) . '</span><strong>' . esc_html( $title ) . '</strong><p>' . esc_html( $description ) . '</p></div>';
	}

	private function render_pricing_consent_form( $enabled, $compact = false ) {
		$action = $enabled ? 'disable' : 'enable';
		$label  = $enabled
			? __( 'DISABLE CURRENT PRICES', 'titanium-mail-smtp' )
			: ( $compact ? __( 'SHOW CURRENT PRICE', 'titanium-mail-smtp' ) : __( 'ENABLE CURRENT PRICES', 'titanium-mail-smtp' ) );
		$class  = $compact ? 'tmsmtp-price-consent-inline' : 'tmsmtp-pricing-consent-form';
		?>
		<form class="<?php echo esc_attr( $class ); ?>" method="post" action="<?php echo esc_url( admin_url( 'admin.php?page=titanium-mail-smtp-pro' ) ); ?>">
			<input type="hidden" name="tmsmtp_pricing_consent_nonce" value="<?php echo esc_attr( wp_create_nonce( 'tmsmtp_pricing_consent' ) ); ?>">
			<input type="hidden" name="tmsmtp_pricing_consent_action" value="<?php echo esc_attr( $action ); ?>">
			<button class="<?php echo esc_attr( $compact ? 'tmsmtp-price-consent-button' : 'tmsmtp-upgrade-secondary tmsmtp-upgrade-secondary--bright' ); ?>" type="submit"><?php echo esc_html( $label ); ?></button>
		</form>
		<?php
	}

	private function render_pricing_plan_placeholders( $current_license_marker = array(), $pro_active = false, $pricing_enabled = false ) {
		$plan_id = 57101;
		$plans = array(
			array( 'pricing_id' => '76766', 'label' => __( 'Single Site', 'titanium-mail-smtp' ), 'licenses' => '1', 'short' => __( 'Single site license', 'titanium-mail-smtp' ) ),
			array( 'pricing_id' => '76767', 'label' => __( '3 Sites', 'titanium-mail-smtp' ), 'licenses' => '3', 'short' => __( '3 site license', 'titanium-mail-smtp' ) ),
			array( 'pricing_id' => '76768', 'label' => __( '5 Sites', 'titanium-mail-smtp' ), 'licenses' => '5', 'short' => __( '5 site license', 'titanium-mail-smtp' ) ),
			array( 'pricing_id' => '76769', 'label' => __( '10 Sites', 'titanium-mail-smtp' ), 'licenses' => '10', 'short' => __( '10 site license', 'titanium-mail-smtp' ) ),
			array( 'pricing_id' => '76770', 'label' => __( '20 Sites', 'titanium-mail-smtp' ), 'licenses' => '20', 'short' => __( '20 site license', 'titanium-mail-smtp' ) ),
			array( 'pricing_id' => '80169', 'label' => __( '50 Sites', 'titanium-mail-smtp' ), 'licenses' => '50', 'short' => __( '50 site license', 'titanium-mail-smtp' ) ),
		);
		$current        = isset( $current_license_marker['licenses'] ) ? (string) $current_license_marker['licenses'] : '';
		$current_weight = '' !== $current ? $this->license_sort_weight( $current ) : 0;
		foreach ( $plans as $plan ) {
			$active   = $pro_active && '' !== $current && (string) $plan['licenses'] === $current;
			$lower    = $pro_active && '' !== $current && ! $active && $this->license_sort_weight( $plan['licenses'] ) < $current_weight;
			$class    = $active ? 'tmsmtp-upgrade-card-button tmsmtp-upgrade-card-button--active' : ( $lower ? 'tmsmtp-upgrade-card-button tmsmtp-upgrade-card-button--disabled' : 'tmsmtp-upgrade-card-button' );
			$text     = $active ? __( 'ACTIVE', 'titanium-mail-smtp' ) : __( 'UPGRADE NOW', 'titanium-mail-smtp' );
			$checkout = $pro_active ? $this->get_hosted_upgrade_url( $plan_id, $plan['pricing_id'] ) : $this->get_checkout_url( $plan['licenses'], $plan['pricing_id'], $plan_id );
			?>
			<div class="tmsmtp-pricing-card-premium<?php echo $active ? ' tmsmtp-pricing-card-premium--active' : ''; ?>" data-tmsmtp-pricing-id="<?php echo esc_attr( $plan['pricing_id'] ); ?>" data-tmsmtp-licenses="<?php echo esc_attr( $plan['licenses'] ); ?>">
				<div class="tmsmtp-pricing-shine"></div><div class="tmsmtp-pricing-card-head"><span class="tmsmtp-plan-pro-badge"><?php esc_html_e( 'PRO', 'titanium-mail-smtp' ); ?></span><span class="tmsmtp-plan-cycle"><?php esc_html_e( 'ANNUAL', 'titanium-mail-smtp' ); ?></span></div>
				<h3><?php echo esc_html( $plan['label'] ); ?></h3>
				<?php if ( $pricing_enabled ) : ?>
					<div class="tmsmtp-pricing-price-premium tmsmtp-pricing-price-premium--loading"><span class="tmsmtp-pricing-spinner" aria-hidden="true"></span><span><?php esc_html_e( 'Loading prices...', 'titanium-mail-smtp' ); ?></span></div>
				<?php else : ?>
					<div class="tmsmtp-pricing-price-premium tmsmtp-pricing-price-premium--consent"><?php $this->render_pricing_consent_form( false, true ); ?></div>
				<?php endif; ?>
				<span class="tmsmtp-plan-license-pill"><?php echo esc_html( $plan['short'] ); ?></span><div class="tmsmtp-plan-includes"><span><?php esc_html_e( 'All Pro features', 'titanium-mail-smtp' ); ?></span><span><?php esc_html_e( 'Updates and support', 'titanium-mail-smtp' ); ?></span><span><?php esc_html_e( 'License managed by Freemius', 'titanium-mail-smtp' ); ?></span></div>
				<?php if ( $active || $lower ) : ?><button class="<?php echo esc_attr( $class ); ?>" type="button" disabled><?php echo esc_html( $text ); ?></button><span class="tmsmtp-manual-coupon-link tmsmtp-manual-coupon-link--disabled" aria-disabled="true"><?php esc_html_e( 'Have a different coupon code?', 'titanium-mail-smtp' ); ?></span><?php else : ?><a class="<?php echo esc_attr( $class ); ?>" href="<?php echo esc_url( $checkout ); ?>"><?php echo esc_html( $text ); ?></a><a class="tmsmtp-manual-coupon-link" href="<?php echo esc_url( $checkout ); ?>"><?php esc_html_e( 'Have a different coupon code?', 'titanium-mail-smtp' ); ?></a><?php endif; ?>
			</div>
			<?php
		}
	}



	public function render_pro_admin() {
		if ( ! current_user_can( 'manage_options' ) ) { return; }
		$current         = $this->get_current_license_marker();
		$account_url     = admin_url( 'admin.php?page=titanium-mail-smtp-account' );
		$pricing_enabled = $this->is_pricing_load_authorized();
		echo '<div class="wrap tmsmtp-wrap tmsmtp-upgrade-wrap tmsmtp-admin-page tmsmtp-pro-page--premium"><h1 class="screen-reader-text">' . esc_html__( 'Titanium Mail SMTP Pro', 'titanium-mail-smtp' ) . '</h1>';
		$this->render_suite_header( false );
		echo '<div class="tmsmtp-pro-page">';

		echo '<section class="tmsmtp-pro-section tmsmtp-comparison-section"><div class="tmsmtp-pro-section-header tmsmtp-section-header-centered"><span class="tmsmtp-section-eyebrow">' . esc_html__( 'Compare plans', 'titanium-mail-smtp' ) . '</span></div><div class="tmsmtp-plan-compare-wrap"><table class="widefat tmsmtp-plan-compare-table"><thead><tr><th class="tmsmtp-plan-compare-empty" aria-hidden="true"></th><th class="tmsmtp-plan-compare-heading tmsmtp-plan-compare-heading--free">' . esc_html__( 'Free', 'titanium-mail-smtp' ) . '</th><th class="tmsmtp-plan-compare-heading tmsmtp-plan-compare-heading--pro">' . esc_html__( 'Pro', 'titanium-mail-smtp' ) . '</th></tr></thead><tbody>';
		foreach ( $this->premium_feature_rows() as $row ) {
			echo '<tr><td><span class="tmsmtp-plan-feature-title">' . esc_html( $row['label'] ) . '</span>';
			if ( ! empty( $row['detail'] ) ) { echo '<span class="tmsmtp-feature-detail">' . esc_html( $row['detail'] ) . '</span>'; }
			echo '</td><td>' . ( $row['free'] ? '<span class="tmsmtp-plan-check" aria-label="' . esc_attr__( 'Included', 'titanium-mail-smtp' ) . '">✓</span>' : '<span class="tmsmtp-plan-cross" aria-label="' . esc_attr__( 'Not included', 'titanium-mail-smtp' ) . '">×</span>' ) . '</td><td><span class="tmsmtp-plan-check" aria-label="' . esc_attr__( 'Included', 'titanium-mail-smtp' ) . '">✓</span></td></tr>';
		}
		echo '</tbody></table></div></section>';

		echo '<div class="tmsmtp-license-panel tmsmtp-pricing-consent-panel"><div><span class="tmsmtp-section-eyebrow">' . esc_html__( 'Current price display', 'titanium-mail-smtp' ) . '</span><h2>' . esc_html( $pricing_enabled ? __( 'Current prices are enabled', 'titanium-mail-smtp' ) : __( 'Choose whether to display current prices', 'titanium-mail-smtp' ) ) . '</h2><p>' . esc_html__( 'Current prices are disabled by default. Enabling them allows this site to request public pricing from AdminPlugins.com and sends only source=plugin. No email settings, messages, credentials, user details, passwords, or license keys are added. You can disable price loading again at any time. Upgrade Now continues to open the Freemius checkout even while prices are hidden.', 'titanium-mail-smtp' ) . '</p></div>';
		$this->render_pricing_consent_form( $pricing_enabled );
		echo '</div>';

		echo '<section class="tmsmtp-pro-section tmsmtp-pricing-section"><div class="tmsmtp-pro-section-header tmsmtp-section-header-centered"><span class="tmsmtp-section-eyebrow">' . esc_html__( 'Simple annual pricing', 'titanium-mail-smtp' ) . '</span><h2>' . esc_html__( 'Choose your Pro license', 'titanium-mail-smtp' ) . '</h2><p>' . esc_html__( 'Every license unlocks the same Pro features. Pick only the number of websites you need.', 'titanium-mail-smtp' ) . '</p></div>';
		echo '<div id="tmsmtp-dynamic-pricing" class="tmsmtp-pricing-grid tmsmtp-pricing-grid--dynamic" data-nonce="' . esc_attr( $pricing_enabled ? wp_create_nonce( 'tmsmtp_pricing_nonce' ) : '' ) . '" data-button="' . esc_attr__( 'UPGRADE NOW', 'titanium-mail-smtp' ) . '" data-error="' . esc_attr__( 'Prices could not be downloaded. Secure checkout will show the current price.', 'titanium-mail-smtp' ) . '" data-current-licenses="' . esc_attr( $current['licenses'] ) . '">';
		$this->render_pricing_plan_placeholders( $current, $this->premium_available(), $pricing_enabled );
		echo '</div></section>';

		echo '<div class="tmsmtp-license-panel"><div><span class="tmsmtp-section-eyebrow">' . esc_html__( 'Already purchased?', 'titanium-mail-smtp' ) . '</span><h2>' . esc_html__( 'Connect and activate your existing license', 'titanium-mail-smtp' ) . '</h2><p>' . esc_html__( 'Connect this website with Freemius, then open the Account page and activate the available Pro license.', 'titanium-mail-smtp' ) . '</p></div><a class="tmsmtp-upgrade-secondary tmsmtp-upgrade-secondary--bright" href="' . esc_url( $account_url ) . '">' . esc_html__( 'Connect & activate license', 'titanium-mail-smtp' ) . '</a></div>';

		echo '<section class="tmsmtp-pro-section tmsmtp-pro-feature-showcase"><div class="tmsmtp-pro-section-header tmsmtp-section-header-centered"><span class="tmsmtp-section-eyebrow">' . esc_html__( 'Pro toolkit', 'titanium-mail-smtp' ) . '</span><h2>' . esc_html__( 'Built for reliable email delivery', 'titanium-mail-smtp' ) . '</h2><p>' . esc_html__( 'Scale beyond Free routing with unlimited connections, automatic recovery, complete delivery records and scheduled reporting.', 'titanium-mail-smtp' ) . '</p></div><div class="tmsmtp-pro-preview-grid">';
		$this->render_locked_pro_feature_card( '01', __( 'Unlimited Connections', 'titanium-mail-smtp' ), __( 'Create and test as many provider connections and routing targets as the site needs.', 'titanium-mail-smtp' ) );
		$this->render_locked_pro_feature_card( '02', __( 'Backup & Automatic Retry', 'titanium-mail-smtp' ), __( 'Fail over to a selected backup connection and protect failed messages in the automatic retry queue.', 'titanium-mail-smtp' ) );
		$this->render_locked_pro_feature_card( '03', __( 'Full Log & Reports', 'titanium-mail-smtp' ), __( 'Review complete sent and failed messages, resend any logged email, inspect diagnostics and receive scheduled reports.', 'titanium-mail-smtp' ) );
		echo '</div>';
		echo '<a class="tmsmtp-feature-request-panel tmsmtp-feature-request-panel--link" href="' . esc_url( 'https://adminplugins.com/contact/' ) . '"><div class="tmsmtp-feature-request-orb" aria-hidden="true"></div><div><span class="tmsmtp-section-eyebrow">' . esc_html__( 'Have a useful idea?', 'titanium-mail-smtp' ) . '</span><h3>' . esc_html__( 'Feature requests are welcome', 'titanium-mail-smtp' ) . '</h3><p>' . esc_html__( 'If your email workflow needs a feature that would help other users too, send the idea in.', 'titanium-mail-smtp' ) . '</p><span class="tmsmtp-feature-request-cta">' . esc_html__( 'Open Contact Us', 'titanium-mail-smtp' ) . '</span></div></a>';
		echo '</section>';
		echo '</div></div>';
	}

	private function render_result_message( $type, $title, $message = '' ) {
		$allowed_types = array( 'info', 'success', 'warning', 'error' );
		$type          = in_array( $type, $allowed_types, true ) ? $type : 'info';
		$title         = is_scalar( $title ) ? (string) $title : '';
		$message       = is_scalar( $message ) ? (string) $message : '';

		echo '<div class="tmsmtp-result-message tmsmtp-result-' . esc_attr( $type ) . '" role="status">';
		echo '<div class="tmsmtp-result-copy"><strong>' . esc_html( $title ) . '</strong>';
		if ( '' !== $message ) {
			echo ' <span>' . esc_html( $message ) . '</span>';
		}
		echo '</div>';
		echo '<button type="button" class="tmsmtp-result-dismiss" aria-label="' . esc_attr__( 'Dismiss this message.', 'titanium-mail-smtp' ) . '"><span aria-hidden="true">×</span></button>';
		echo '</div>';
	}

	private function render_tool_notices( $tab ) {
		$test_result = filter_input( INPUT_GET, 'tmsmtp_test_result', FILTER_SANITIZE_SPECIAL_CHARS );
		if ( 'test-email' === $tab && $test_result ) {
			$result = get_transient( 'tmsmtp_test_result_' . get_current_user_id() );
			delete_transient( 'tmsmtp_test_result_' . get_current_user_id() );
			$status = is_array( $result ) ? ( 'success' === ( $result['status'] ?? '' ) ? 'success' : 'error' ) : ( 'success' === sanitize_key( (string) $test_result ) ? 'success' : 'error' );
			$message = is_array( $result ) ? (string) ( $result['message'] ?? '' ) : '';
			$recipient = is_array( $result ) ? sanitize_email( $result['recipient'] ?? '' ) : '';
			if ( 'success' === $status && '' === $message ) {
				$message = $recipient
					/* translators: %s: recipient email address. */
					? sprintf( __( 'Recipient: %s', 'titanium-mail-smtp' ), $recipient )
					: '';
			} elseif ( 'error' === $status && '' === $message ) {
				$message = __( 'The test email failed. Check the selected provider credentials, verified sender address, and network access.', 'titanium-mail-smtp' );
			}
			$this->render_result_message( $status, 'success' === $status ? __( 'Test email sent successfully.', 'titanium-mail-smtp' ) : __( 'Test email failed.', 'titanium-mail-smtp' ), $message );
		}
	}

	private function sanitize_secret_value( $submitted, $saved, $was_submitted = true ) {
		$saved = is_scalar( $saved ) ? (string) $saved : '';
		if ( ! $was_submitted ) {
			return $saved;
		}
		$submitted = is_scalar( $submitted ) ? (string) $submitted : '';
		if ( self::SECRET_MASK === $submitted ) {
			return $saved;
		}
		return str_replace( array( "\r", "\n" ), '', $submitted );
	}

	private function secret_field( $key, $saved_value, $constant_name = '', $optional = false, $legacy_constant_name = '' ) {
		$active_constant = '';
		if ( '' !== $constant_name && defined( $constant_name ) ) {
			$constant_value = constant( $constant_name );
			if ( is_scalar( $constant_value ) && '' !== trim( (string) $constant_value ) ) {
				$active_constant = $constant_name;
			}
		}
		if ( '' === $active_constant && '' !== $legacy_constant_name && defined( $legacy_constant_name ) ) {
			$legacy_value = constant( $legacy_constant_name );
			if ( is_scalar( $legacy_value ) && '' !== trim( (string) $legacy_value ) ) {
				$active_constant = $legacy_constant_name;
			}
		}

		$from_constant = '' !== $active_constant;
		$has_secret    = $from_constant || '' !== trim( (string) $saved_value );
		$value         = $has_secret ? self::SECRET_MASK : '';
		$placeholder   = $optional ? __( 'Optional', 'titanium-mail-smtp' ) : __( 'Enter credential', 'titanium-mail-smtp' );
		$status = $has_secret
			? '<span class="tmsmtp-secret-status tmsmtp-secret-status-set"><span class="tmsmtp-secret-check" aria-hidden="true">✓</span>' . ( $from_constant ? esc_html__( 'Set in wp-config.php', 'titanium-mail-smtp' ) : esc_html__( 'Credential saved', 'titanium-mail-smtp' ) ) . '</span>'
			: '<span class="tmsmtp-secret-status tmsmtp-secret-status-empty">' . esc_html__( 'Not configured', 'titanium-mail-smtp' ) . '</span>';
		$name  = 'tmsmtp[connection][' . $key . ']';
		$input = $from_constant
			? '<input type="hidden" name="' . esc_attr( $name ) . '" value=""><input type="password" class="regular-text" value="' . esc_attr__( 'Defined in wp-config.php', 'titanium-mail-smtp' ) . '" disabled="disabled">'
			: '<input type="password" class="regular-text" name="' . esc_attr( $name ) . '" value="' . esc_attr( $value ) . '" placeholder="' . esc_attr( $placeholder ) . '" autocomplete="new-password">';

		return '<div class="tmsmtp-secret-field">' . $input . $status . '</div>';
	}

	private function render_connections( $s ) {
		$c = $s['connection'];
		$status = $this->connection_status( $this->apply_constants( $c ) );
		echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '">';
		wp_nonce_field( 'tmsmtp_save' );
		echo '<input type="hidden" name="action" value="tmsmtp_save"><input type="hidden" name="tmsmtp_tab" value="connections"><div class="tmsmtp-card"><div class="tmsmtp-card-head"><div><span class="tmsmtp-mini-label">' . esc_html__( 'Primary Connection', 'titanium-mail-smtp' ) . '</span><h2>' . esc_html__( 'Email connection', 'titanium-mail-smtp' ) . '</h2><p>' . esc_html__( 'Select a provider and enter its credentials.', 'titanium-mail-smtp' ) . '</p></div></div>';
		if ( empty( $status['configured'] ) ) {
			echo '<div class="tmsmtp-inline-status tmsmtp-inline-status-warning"><strong>' . esc_html__( 'Provider not configured.', 'titanium-mail-smtp' ) . '</strong> ' . esc_html( $status['message'] ) . ' ' . esc_html__( 'WordPress default mail remains active until this is completed.', 'titanium-mail-smtp' ) . '</div>';
		} elseif ( ! empty( $status['default'] ) ) {
			echo '<div class="tmsmtp-inline-status"><strong>' . esc_html__( 'WordPress default mail is active.', 'titanium-mail-smtp' ) . '</strong> ' . esc_html__( 'Emails are not being routed through an external provider.', 'titanium-mail-smtp' ) . '</div>';
		}
		echo '<table class="form-table tmsmtp-form-table">';
		$this->row( __( 'Mailer', 'titanium-mail-smtp' ), '<select class="tmsmtp-select-medium tmsmtp-mailer-select" name="tmsmtp[connection][mailer]">' . $this->mailer_options( $c['mailer'] ) . '</select>' );
		$this->row( __( 'From email', 'titanium-mail-smtp' ), '<div class="tmsmtp-inline-fields"><input type="email" class="regular-text" name="tmsmtp[connection][from_email]" value="' . esc_attr( $c['from_email'] ) . '"><label><input type="checkbox" name="tmsmtp[connection][force_from_email]" value="1" ' . checked( ! empty( $c['force_from_email'] ), true, false ) . '> ' . esc_html__( 'Force', 'titanium-mail-smtp' ) . '</label></div>' );
		$this->row( __( 'From name', 'titanium-mail-smtp' ), '<div class="tmsmtp-inline-fields"><input class="regular-text" name="tmsmtp[connection][from_name]" value="' . esc_attr( $c['from_name'] ) . '"><label><input type="checkbox" name="tmsmtp[connection][force_from_name]" value="1" ' . checked( ! empty( $c['force_from_name'] ), true, false ) . '> ' . esc_html__( 'Force', 'titanium-mail-smtp' ) . '</label></div>' );
		$this->provider_rows( $c );
		echo '</table></div><div class="tmsmtp-submit-row"><button type="submit" class="button tmsmtp-btn">' . esc_html__( 'Save Settings', 'titanium-mail-smtp' ) . '</button></div></form>';
		$this->render_pro_preview( __( 'Additional Connections', 'titanium-mail-smtp' ), __( 'Use multiple providers or separate connections for different email types.', 'titanium-mail-smtp' ), array( __( 'Unlimited connections', 'titanium-mail-smtp' ), __( 'Per-connection test emails', 'titanium-mail-smtp' ), __( 'Works with routing and backup', 'titanium-mail-smtp' ) ) );
	}

	private function mailer_options( $selected ) {
		$items = array(
			'default'   => __( 'Default (WordPress mail)', 'titanium-mail-smtp' ),
			'postmark'  => 'Postmark',
			'amazonses' => 'Amazon SES',
			'sendgrid'  => 'SendGrid',
			'mailgun'   => 'Mailgun',
			'brevo'     => 'Brevo',
			'smtp'      => __( 'Other SMTP', 'titanium-mail-smtp' ),
		);
		$output = '';
		foreach ( $items as $key => $label ) {
			$output .= '<option value="' . esc_attr( $key ) . '" ' . selected( $selected, $key, false ) . '>' . esc_html( $label ) . '</option>';
		}
		return $output;
	}

	private function provider_rows($c){
		$this->row(__( 'Postmark token', 'titanium-mail-smtp' ),$this->secret_field('postmark_token',$c['postmark_token'],'TMSMTP_POSTMARK_PRIMARY_TOKEN',false,'TMS_POSTMARK_PRIMARY_TOKEN'),'tmsmtp-provider-row tmsmtp-mailer-postmark');
		$this->row(__( 'Message stream', 'titanium-mail-smtp' ),'<input class="regular-text" name="tmsmtp[connection][message_stream]" value="'.esc_attr($c['message_stream']).'">','tmsmtp-provider-row tmsmtp-mailer-postmark');
		$this->row(__( 'SendGrid API key', 'titanium-mail-smtp' ),$this->secret_field('sendgrid_api_key',$c['sendgrid_api_key'],'TMSMTP_SENDGRID_PRIMARY_API_KEY',false,'TMS_SENDGRID_PRIMARY_API_KEY'),'tmsmtp-provider-row tmsmtp-mailer-sendgrid');
		$this->row(__( 'Mailgun API key', 'titanium-mail-smtp' ),$this->secret_field('mailgun_api_key',$c['mailgun_api_key'],'TMSMTP_MAILGUN_PRIMARY_API_KEY',false,'TMS_MAILGUN_PRIMARY_API_KEY'),'tmsmtp-provider-row tmsmtp-mailer-mailgun');
		$this->row(__( 'Mailgun domain', 'titanium-mail-smtp' ),'<input class="regular-text" name="tmsmtp[connection][mailgun_domain]" value="'.esc_attr($c['mailgun_domain']).'">','tmsmtp-provider-row tmsmtp-mailer-mailgun');
		$this->row(__( 'Mailgun region', 'titanium-mail-smtp' ),'<select name="tmsmtp[connection][mailgun_region]"><option '.selected($c['mailgun_region'],'US',false).'>US</option><option '.selected($c['mailgun_region'],'EU',false).'>EU</option></select>','tmsmtp-provider-row tmsmtp-mailer-mailgun');
		$this->row(__( 'Brevo API key', 'titanium-mail-smtp' ),$this->secret_field('brevo_api_key',$c['brevo_api_key'],'TMSMTP_BREVO_PRIMARY_API_KEY',false,'TMS_BREVO_PRIMARY_API_KEY'),'tmsmtp-provider-row tmsmtp-mailer-brevo');
		$this->row(__( 'SES access key', 'titanium-mail-smtp' ),$this->secret_field('ses_access_key',$c['ses_access_key'],'TMSMTP_SES_PRIMARY_ACCESS_KEY',false,'TMS_SES_PRIMARY_ACCESS_KEY'),'tmsmtp-provider-row tmsmtp-mailer-amazonses');
		$this->row(__( 'SES secret key', 'titanium-mail-smtp' ),$this->secret_field('ses_secret_key',$c['ses_secret_key'],'TMSMTP_SES_PRIMARY_SECRET_KEY',false,'TMS_SES_PRIMARY_SECRET_KEY'),'tmsmtp-provider-row tmsmtp-mailer-amazonses');
		$this->row(__( 'SES session token', 'titanium-mail-smtp' ),$this->secret_field('ses_session_token',$c['ses_session_token'],'TMSMTP_SES_PRIMARY_SESSION_TOKEN',true,'TMS_SES_PRIMARY_SESSION_TOKEN'),'tmsmtp-provider-row tmsmtp-mailer-amazonses');
		$this->row(__( 'SES region', 'titanium-mail-smtp' ),'<input class="regular-text" name="tmsmtp[connection][ses_region]" value="'.esc_attr($c['ses_region']).'">','tmsmtp-provider-row tmsmtp-mailer-amazonses');
		$this->row(__( 'SMTP host / port', 'titanium-mail-smtp' ),'<div class="tmsmtp-inline-fields"><input class="regular-text" name="tmsmtp[connection][smtp_host]" value="'.esc_attr($c['smtp_host']).'"><input type="number" class="small-text tmsmtp-input-small" name="tmsmtp[connection][smtp_port]" value="'.esc_attr($c['smtp_port']).'"></div>','tmsmtp-provider-row tmsmtp-mailer-smtp');
		$this->row(__( 'SMTP security', 'titanium-mail-smtp' ),'<div class="tmsmtp-check-row"><select name="tmsmtp[connection][smtp_encryption]"><option value="none" '.selected($c['smtp_encryption'],'none',false).'>' . esc_html__( 'None', 'titanium-mail-smtp' ) . '</option><option value="ssl" '.selected($c['smtp_encryption'],'ssl',false).'>SSL</option><option value="tls" '.selected($c['smtp_encryption'],'tls',false).'>TLS</option></select><label><input type="checkbox" name="tmsmtp[connection][smtp_autotls]" value="1" '.checked(!empty($c['smtp_autotls']),true,false).'> ' . esc_html__( 'Auto TLS', 'titanium-mail-smtp' ) . '</label><label><input type="checkbox" name="tmsmtp[connection][smtp_auth]" value="1" '.checked(!empty($c['smtp_auth']),true,false).'> ' . esc_html__( 'Authentication', 'titanium-mail-smtp' ) . '</label></div>','tmsmtp-provider-row tmsmtp-mailer-smtp');
		$this->row(__( 'SMTP username / password', 'titanium-mail-smtp' ),'<div class="tmsmtp-inline-fields"><input class="regular-text" name="tmsmtp[connection][smtp_user]" value="'.esc_attr($c['smtp_user']).'">'.$this->secret_field('smtp_pass',$c['smtp_pass'],'TMSMTP_SMTP_PRIMARY_PASSWORD',false,'TMS_SMTP_PRIMARY_PASSWORD').'</div>','tmsmtp-provider-row tmsmtp-mailer-smtp');
	}

	private function render_alerts( $s ) {
		echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '">';
		wp_nonce_field( 'tmsmtp_save' );
		echo '<input type="hidden" name="action" value="tmsmtp_save"><input type="hidden" name="tmsmtp_tab" value="alerts">';
		echo '<div class="tmsmtp-card"><div class="tmsmtp-card-head"><div><span class="tmsmtp-mini-label">' . esc_html__( 'Alerts', 'titanium-mail-smtp' ) . '</span><h2>' . esc_html__( 'Email failure alert', 'titanium-mail-smtp' ) . '</h2><p>' . esc_html__( 'Send one simple notification when WordPress reports a delivery failure.', 'titanium-mail-smtp' ) . '</p></div></div><table class="form-table tmsmtp-form-table">';
		$this->row( __( 'Enable alerts', 'titanium-mail-smtp' ), '<label><input type="checkbox" name="tmsmtp[alerts_enabled]" value="1" ' . checked( ! empty( $s['alerts_enabled'] ), true, false ) . '> ' . esc_html__( 'Send a failure notification', 'titanium-mail-smtp' ) . '</label>' );
		$this->row( __( 'Recipient', 'titanium-mail-smtp' ), '<input type="email" class="regular-text" name="tmsmtp[alert_recipient]" value="' . esc_attr( $s['alert_recipient'] ) . '">' );
		echo '</table></div><div class="tmsmtp-submit-row"><button type="submit" class="button tmsmtp-btn" name="tmsmtp_save_button" value="1">' . esc_html__( 'Save Settings', 'titanium-mail-smtp' ) . '</button></div></form>';
		$this->render_pro_preview( __( 'Backup Connection', 'titanium-mail-smtp' ), __( 'Retry a failed email once through a separate connection.', 'titanium-mail-smtp' ), array( __( 'Single fallback connection', 'titanium-mail-smtp' ), __( 'No fallback loops', 'titanium-mail-smtp' ), __( 'Failure status retained', 'titanium-mail-smtp' ) ) );
	}

	private function render_test_email_tool() {
		$status = $this->connection_status();
		echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '" class="tmsmtp-card">';
		wp_nonce_field( 'tmsmtp_test' );
		echo '<input type="hidden" name="action" value="tmsmtp_test">';
		echo '<div class="tmsmtp-card-head"><div><span class="tmsmtp-mini-label">' . esc_html__( 'Test Email', 'titanium-mail-smtp' ) . '</span><h2>' . esc_html__( 'Send a test email', 'titanium-mail-smtp' ) . '</h2><p>' . esc_html( $status['message'] ) . '</p></div></div><input type="email" class="regular-text" name="test_to" value="' . esc_attr( get_option( 'admin_email' ) ) . '"><div class="tmsmtp-submit-row"><button type="submit" class="button tmsmtp-btn">' . esc_html__( 'Send Test Email', 'titanium-mail-smtp' ) . '</button></div></form>';
	}

	private function render_misc($s){echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '">';wp_nonce_field('tmsmtp_save');echo '<input type="hidden" name="action" value="tmsmtp_save"><input type="hidden" name="tmsmtp_tab" value="misc"><div class="tmsmtp-card"><div class="tmsmtp-card-head"><div><span class="tmsmtp-mini-label">' . esc_html__( 'Misc', 'titanium-mail-smtp' ) . '</span><h2>' . esc_html__( 'Data removal', 'titanium-mail-smtp' ) . '</h2></div></div><label><input type="checkbox" name="tmsmtp[delete_on_uninstall]" value="1" '.checked(!empty($s['delete_on_uninstall']),true,false).'> ' . esc_html__( 'Delete Titanium Mail SMTP settings when the plugin is uninstalled', 'titanium-mail-smtp' ) . '</label></div><div class="tmsmtp-submit-row"><button type="submit" class="button tmsmtp-btn">' . esc_html__( 'Save Settings', 'titanium-mail-smtp' ) . '</button></div></form>';}
	private function render_pro_preview($title,$description,$items){echo '<div class="tmsmtp-card tmsmtp-pro-preview" aria-label="'.esc_attr($title).'"><div class="tmsmtp-card-head"><div><span class="tmsmtp-mini-label">'.esc_html($title).'</span><p>'.esc_html($description).'</p></div><span class="tmsmtp-pill tmsmtp-pill-pro">' . esc_html__( 'PRO', 'titanium-mail-smtp' ) . '</span></div><div class="tmsmtp-preview-lines">';foreach($items as $item)echo '<div class="tmsmtp-preview-line"><span></span>'.esc_html($item).'</div>';echo '</div></div>'; }
	private function row( $label, $field, $class = '' ) {
		echo '<tr' . ( $class ? ' class="' . esc_attr( $class ) . '"' : '' ) . '><th scope="row">' . esc_html( $label ) . '</th><td>' . wp_kses( $field, self::allowed_form_html() ) . '</td></tr>';
	}

	private static function allowed_form_html() {
		return array(
			'div'    => array( 'class' => true ),
			'label'  => array( 'class' => true ),
			'input'  => array( 'type' => true, 'class' => true, 'name' => true, 'value' => true, 'placeholder' => true, 'checked' => true, 'disabled' => true, 'min' => true, 'max' => true, 'autocomplete' => true ),
			'select' => array( 'class' => true, 'name' => true, 'disabled' => true ),
			'option' => array( 'value' => true, 'selected' => true ),
			'span'   => array( 'class' => true ),
			'strong' => array(),
		);
	}

	private function render_more_plugins() {
		$more_plugins = new TMSMTP_More_Plugins();
		$more_plugins->render();
	}
}
