<?php
/**
 * Email Sender handler for Automation Web Platform.
 * Supports SMTP configuration and test email functionality.
 *
 * @package automation-web-platform
 */

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


/**
 * Class WAWP_Email_Sender
 *
 * @package automation-web-platform
 */
class WAWP_Email_Sender extends WAWP_Sender_Base {
	use WAWP_Settings_Handler;

	/**
	 * Singleton instance.
	 *
	 * @var WAWP_Email_Sender
	 */
	private static $instance = null;

	/**
	 * Get singleton instance.
	 *
	 * @return WAWP_Email_Sender
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Setup class properties.
	 */
	protected function setup_properties() {
		$this->nonce_action = 'wawp_nonce';
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		parent::__construct();
		add_action( 'phpmailer_init', array( $this, 'configure_phpmailer' ), 20 );
		add_filter( 'pre_wp_mail', array( $this, 'intercept_wp_mail' ), 10, 2 );
		add_action( 'wp_mail_succeeded', array( $this, 'log_wp_mail_success' ) );
		add_action( 'wp_mail_failed', array( $this, 'log_wp_mail_failure' ) );
	}

	/**
	 * AJAX: Handle listing accounts.
	 *
	 * @return array
	 */
	public function handle_list_accounts() {
		$this->check_permissions();
		return array(
			'success' => true,
			'data'    => $this->list_accounts(),
		);
	}

	/**
	 * List all SMTP accounts.
	 *
	 * @return array
	 */
	public function list_accounts() {
		global $wpdb;
		$table = $this->db->get_smtp_accounts_table_name();

		$accounts = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT * FROM %i ORDER BY created_at DESC', $table ), 'wawp_smtp_accounts_list', 'wawp_database', HOUR_IN_SECONDS );

		$has_active            = false;
		$first_validated_index = -1;

		foreach ( $accounts as $idx => &$account ) {
			$account['config']    = $this->from_db( $account['config'] );
			$account['is_active'] = (bool) $account['is_active'];
			$account['validated'] = (bool) $account['validated'];

			if ( $account['is_active'] && $account['validated'] ) {
				$has_active = true;
			}

			if ( $account['validated'] && -1 === $first_validated_index ) {
				$first_validated_index = $idx;
			}
		}

		if ( ! $has_active && -1 !== $first_validated_index ) {
			$active_id = $accounts[ $first_validated_index ]['id'];

			WAWP()->db->update_row( 'smtp_accounts', array( 'is_active' => 0 ), array( 'is_active' => 1 ) );
			WAWP()->db->update_row( 'smtp_accounts', array( 'is_active' => 1 ), array( 'id' => $active_id ) );

			wp_cache_delete( 'wawp_smtp_active', 'wawp_database' );
			wp_cache_delete( 'wawp_smtp_accounts_list', 'wawp_database' );

			$accounts[ $first_validated_index ]['is_active'] = true;
			$this->sync_to_legacy( $active_id );
		}

		return $accounts;
	}

	/**
	 * AJAX: Handle saving/updating account.
	 *
	 * @param array $data Account data.
	 * @return array
	 */
	public function handle_save_account( $data = array() ) {
		$this->check_permissions();
		global $wpdb;
		$table        = $this->db->get_smtp_accounts_table_name();
		$id           = isset( $data['id'] ) ? $data['id'] : (int) filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );
		$account_name = isset( $data['account_name'] ) ? $data['account_name'] : filter_input( INPUT_POST, 'account_name', FILTER_SANITIZE_SPECIAL_CHARS );
		$provider     = isset( $data['provider'] ) ? $data['provider'] : filter_input( INPUT_POST, 'provider', FILTER_SANITIZE_SPECIAL_CHARS );
		$config       = isset( $data['config'] ) ? $data['config'] : filter_input( INPUT_POST, 'config', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );

		// Sanitize config based on provider.
		$sanitized_config = array();
		if ( 'wp' === $provider ) {
			$sanitized_config = array(
				'from_email' => sanitize_email( isset( $config['from_email'] ) ? $config['from_email'] : '' ),
				'from_name'  => sanitize_text_field( isset( $config['from_name'] ) ? $config['from_name'] : '' ),
			);
		} elseif ( 'smtp' === $provider ) {
			$sanitized_config = array(
				'host'       => sanitize_text_field( isset( $config['host'] ) ? $config['host'] : '' ),
				'port'       => intval( isset( $config['port'] ) ? $config['port'] : 587 ),
				'encryption' => sanitize_text_field( isset( $config['encryption'] ) ? $config['encryption'] : 'tls' ),
				'user'       => sanitize_text_field( isset( $config['user'] ) ? $config['user'] : '' ),
				'from_email' => sanitize_email( isset( $config['from_email'] ) ? $config['from_email'] : '' ),
				'from_name'  => sanitize_text_field( isset( $config['from_name'] ) ? $config['from_name'] : '' ),
				'auth'       => intval( isset( $config['auth'] ) ? $config['auth'] : 1 ),
			);
		}

		if ( 'smtp' === $provider && ! empty( $config['pass'] ) ) {
			$sanitized_config['pass'] = sanitize_text_field( $config['pass'] );
		} elseif ( 'smtp' === $provider && $id > 0 ) {
			$existing = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT config FROM %i WHERE id = %d', $table, $id ), "wawp_db_row_smtp_accounts_{$id}", 'wawp_db', HOUR_IN_SECONDS );
			if ( ! empty( $existing ) ) {
				$existing_config = json_decode( $existing[0]['config'], true );
				if ( ! empty( $existing_config['pass'] ) ) {
					$sanitized_config['pass'] = $existing_config['pass'];
				}
			}
		}

		$row_data = array(
			'account_name' => $account_name,
			'provider'     => $provider,
			'config'       => wp_json_encode( $sanitized_config ),
		);

		if ( 'wp' === $provider ) {
			$row_data['validated'] = 1;
		}

		if ( $id > 0 ) {
			WAWP()->db->update_row( 'smtp_accounts', $row_data, array( 'id' => $id ) );
			$message = esc_html__( 'Account updated successfully.', 'automation-web-platform' );
		} else {
			$id      = WAWP()->db->insert( 'smtp_accounts', $row_data );
			$message = esc_html__( 'Account created successfully.', 'automation-web-platform' );
		}
		$this->sync_to_legacy( $id );
		wp_cache_delete( 'wawp_smtp_accounts_list', 'wawp_database' );
		wp_cache_delete( 'wawp_smtp_active', 'wawp_database' );
		if ( class_exists( 'WAWP' ) && method_exists( WAWP(), 'clear_dashboard_cache_on_option_update' ) ) {
			WAWP()->clear_dashboard_cache_on_option_update( 'wawp_force' );
		}

		return array(
			'success' => true,
			'id'      => $id,
			'message' => $message,
		);
	}

	/**
	 * AJAX: Handle account deletion.
	 *
	 * @param int $id Account ID.
	 * @return array
	 */
	public function handle_delete_account( $id = 0 ) {
		if ( ! $id ) {
			$this->check_permissions();
		}
		$id = $id ? $id : (int) filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );

		if ( ! $id ) {
			return array(
				'success' => false,
				'message' => 'Invalid account ID',
			);
		}

		global $wpdb;
		WAWP()->db->delete_row( 'smtp_accounts', array( 'id' => $id ) );
		wp_cache_delete( 'wawp_smtp_active', 'wawp_database' );
		wp_cache_delete( 'wawp_smtp_accounts_list', 'wawp_database' );
		return array(
			'success' => true,
			'message' => esc_html__( 'Account deleted successfully.', 'automation-web-platform' ),
		);
	}

	/**
	 * AJAX: Handle active status toggle.
	 *
	 * @param int $id     Account ID.
	 * @param int $active Active status.
	 * @return array
	 */
	public function handle_toggle_active( $id = 0, $active = null ) {
		if ( ! $id ) {
			$this->check_permissions();
		}
		$id = $id ? $id : (int) filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );

		$active = ( null !== $active ) ? $active : (int) filter_input( INPUT_POST, 'active', FILTER_SANITIZE_NUMBER_INT );

		global $wpdb;
		$table = $this->db->get_smtp_accounts_table_name();
		if ( $active ) {
			WAWP()->db->update_row( 'smtp_accounts', array( 'is_active' => 0 ), array( 'is_active' => 1 ) );
		}

		WAWP()->db->update_row( 'smtp_accounts', array( 'is_active' => $active ), array( 'id' => $id ) );
		wp_cache_delete( 'wawp_smtp_active', 'wawp_database' );
		wp_cache_delete( 'wawp_smtp_accounts_list', 'wawp_database' );
		$this->sync_to_legacy( $id );
		if ( class_exists( 'WAWP' ) && method_exists( WAWP(), 'clear_dashboard_cache_on_option_update' ) ) {
			WAWP()->clear_dashboard_cache_on_option_update( 'wawp_force' );
		}

		return array(
			'success' => true,
			'message' => esc_html__( 'Status updated successfully.', 'automation-web-platform' ),
		);
	}

	/**
	 * AJAX: Handle account validation toggle.
	 *
	 * @param int $id        Account ID.
	 * @param int $validated Validated status.
	 * @return array
	 */
	public function handle_validate_account( $id = 0, $validated = 0 ) {
		if ( ! $id ) {
			$this->check_permissions();
		}
		$id = $id ? $id : (int) filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );

		$validated = ( null !== $validated ) ? $validated : (int) filter_input( INPUT_POST, 'validated', FILTER_SANITIZE_NUMBER_INT );

		global $wpdb;
		WAWP()->db->update_row( 'smtp_accounts', array( 'validated' => $validated ), array( 'id' => $id ) );
		wp_cache_delete( 'wawp_smtp_active', 'wawp_database' );

		return array( 'success' => true );
	}

	/**
	 * Sync active account to legacy settings.
	 *
	 * @param int $account_id Account ID.
	 */
	private function sync_to_legacy( $account_id ) {
		global $wpdb;
		$table   = $this->db->get_smtp_accounts_table_name();
		$account = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $account_id ), "wawp_db_row_smtp_accounts_{$account_id}", 'wawp_db', HOUR_IN_SECONDS );
		$account = ! empty( $account ) ? (object) $account[0] : null;
		if ( ! $account || ! $account->is_active ) {
			return;
		}

		$config = json_decode( $account->config, true );
		update_option( WAWP_Settings_Registry::SMTP_HOST, isset( $config['host'] ) ? $config['host'] : '' );
		update_option( WAWP_Settings_Registry::SMTP_PORT, isset( $config['port'] ) ? $config['port'] : 587 );
		update_option( WAWP_Settings_Registry::SMTP_ENCRYPTION, isset( $config['encryption'] ) ? $config['encryption'] : 'tls' );
		update_option( WAWP_Settings_Registry::SMTP_USER, isset( $config['user'] ) ? $config['user'] : '' );
		update_option( WAWP_Settings_Registry::SMTP_PASS, isset( $config['pass'] ) ? $config['pass'] : '' );
		update_option( WAWP_Settings_Registry::SMTP_FROM_EMAIL, isset( $config['from_email'] ) ? $config['from_email'] : '' );
		update_option( WAWP_Settings_Registry::SMTP_FROM_NAME, isset( $config['from_name'] ) ? $config['from_name'] : '' );
		update_option( WAWP_Settings_Registry::SMTP_ACTIVE, $account->is_active ? 'on' : 'off' );
	}

	/**
	 * AJAX: Handle sending a test email.
	 *
	 * @param string $to_param Recipient email.
	 * @return array
	 */
	public function handle_send_test_email( $to_param = '' ) {
		$this->check_permissions();
		if ( ! $to_param ) {
			$to_param = filter_input( INPUT_POST, 'to', FILTER_SANITIZE_EMAIL );
			if ( ! $to_param ) {
				$to_param = filter_input( INPUT_POST, 'test_email', FILTER_SANITIZE_EMAIL );
			}
			if ( ! $to_param ) {
				$json = file_get_contents( 'php://input' );
				$data = json_decode( $json, true );
				if ( is_array( $data ) ) {
					$to_param = isset( $data['to'] ) ? $data['to'] : ( isset( $data['email'] ) ? $data['email'] : '' );
				}
			}
		}

		$to      = sanitize_email( wp_unslash( $to_param ) );
		$subject = 'Wawp Test Email';
		$message = "This is a test email from Automation Web Platform plugin. \n\nTime: " . current_time( 'mysql' );

		if ( wawp_messenger()->send(
			$to,
			array(
				'channel'     => 'email',
				'subject'     => $subject,
				'message'     => $message,
				'context'     => esc_html__( 'Email Test Message', 'automation-web-platform' ),
				'send_timing' => 'instant',
			)
		) ) {
			return array(
				'success' => true,
				'message' => esc_html__( 'Test email sent successfully.', 'automation-web-platform' ),
			);
		} else {
			return array(
				'success' => false,
				'message' => esc_html__( 'Failed to send test email. Please check your SMTP settings and Activity Hub for logs.', 'automation-web-platform' ),
			);
		}
	}

	/**
	 * AJAX: Handle testing connection.
	 *
	 * @param array $smtp_data SMTP connection data.
	 * @return array
	 */
	public function handle_test_connection( $smtp_data = array() ) {
		$this->check_permissions();
		$raw_data = $smtp_data ? $smtp_data : filter_input( INPUT_POST, 'smtp', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
		if ( ! is_array( $raw_data ) ) {
			$raw_data = array();
		}

		$provider = isset( $raw_data['provider'] ) ? sanitize_text_field( wp_unslash( $raw_data['provider'] ) ) : 'smtp';

		if ( 'wp' === $provider ) {
			return array(
				'success' => true,
				'message' => esc_html__( 'WordPress default mailer is ready.', 'automation-web-platform' ),
			);
		}

		$host       = isset( $raw_data['host'] ) ? sanitize_text_field( $raw_data['host'] ) : '';
		$port       = isset( $raw_data['port'] ) ? intval( $raw_data['port'] ) : 587;
		$encryption = isset( $raw_data['encryption'] ) ? sanitize_text_field( $raw_data['encryption'] ) : 'tls';
		$user       = isset( $raw_data['user'] ) ? sanitize_text_field( $raw_data['user'] ) : '';
		$pass       = isset( $raw_data['pass'] ) && '' !== $raw_data['pass'] ? sanitize_text_field( $raw_data['pass'] ) : '';

		// If password is empty, try to load from DB using account id.
		if ( '' === $pass ) {
			$account_id = isset( $raw_data['id'] ) ? intval( $raw_data['id'] ) : 0;
			if ( $account_id > 0 ) {
				global $wpdb;
				$table  = $this->db->get_smtp_accounts_table_name();
				$row    = $wpdb->get_row( $wpdb->prepare( 'SELECT config FROM %i WHERE id = %d', $table, $account_id ), ARRAY_A );
				$stored = $row ? json_decode( $row['config'], true ) : array();
				$pass   = isset( $stored['pass'] ) ? $stored['pass'] : '';
			}
			if ( '' === $pass ) {
				$pass = (string) $this->get_wawp_setting( WAWP_Settings_Registry::SMTP_PASS );
			}
		}

		if ( ! class_exists( 'PHPMailer\PHPMailer\PHPMailer' ) ) {
			require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php';
			require_once ABSPATH . WPINC . '/PHPMailer/SMTP.php';
			require_once ABSPATH . WPINC . '/PHPMailer/Exception.php';
		}

		$mail = new \PHPMailer\PHPMailer\PHPMailer( true );
		try {
			$mail->isSMTP();
			$mail->{'Host'}       = $host;
			$mail->{'SMTPAuth'}   = true;
			$mail->{'Port'}       = $port;
			$mail->{'Username'}   = $user;
			$mail->{'Password'}   = $pass;
			$mail->{'SMTPSecure'} = ( 'none' === $encryption ? '' : $encryption );
			$mail->{'Timeout'}    = 10;
			$mail->{'SMTPDebug'}  = 0;

			if ( $mail->smtpConnect() ) {
				$mail->smtpClose();

				return array(
					'success' => true,
					'message' => esc_html__( 'Connection successful!', 'automation-web-platform' ),
				);
			} else {
				return array(
					'success' => false,
					'message' => esc_html__( 'Connection failed. Please check your host and port.', 'automation-web-platform' ),
				);
			}
		} catch ( \Exception $e ) {
			return array(
				'success' => false,
				'message' => $e->getMessage(),
			);
		}
	}

	/**
	 * Intercept wp_mail to use our custom senders.
	 *
	 * @param bool  $pre_return Whether to return early.
	 * @param array $args       Email arguments.
	 * @return bool
	 */
	public function intercept_wp_mail( $pre_return, $args ) {
		// Check if the recipient email is blocked.
		$to = isset( $args['to'] ) ? $args['to'] : '';
		if ( ! empty( $to ) ) {
			$emails         = is_array( $to ) ? $to : array( $to );
			$blocked_emails = array();
			foreach ( $emails as $email ) {
				$clean_email = trim( strtolower( $this->stringify_recipient( $email, true ) ) );
				if ( WAWP()->block_manager && WAWP()->block_manager->is_recipient_blocked( $clean_email ) ) {
					$blocked_emails[] = $clean_email;
				}
			}

			if ( ! empty( $blocked_emails ) ) {
				$this->log_action(
					'Blocked',
					'Email',
					array(
						'recipient' => implode( ', ', $blocked_emails ),
						'gateway'   => 'email',
						'error'     => esc_html__( 'Recipient email or associated account is blacklisted in Block Manager.', 'automation-web-platform' ),
					),
					$args['subject']
				);
				return false;
			}
		}

		global $wpdb;
		$table = $this->db->get_smtp_accounts_table_name();

		$active_account = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT * FROM %i WHERE is_active = 1 LIMIT 1', $table ), 'wawp_smtp_active', 'wawp_database', 300 );
		$active_account = ! empty( $active_account ) ? (object) $active_account[0] : null;

		if ( ! $active_account || in_array( $active_account->provider, array( 'wp', 'smtp' ), true ) ) {
			return $pre_return;
		}

		$config = $this->from_db( $active_account->config );
		$sent   = false;
		switch ( $active_account->provider ) {
			case 'wp':
			case 'smtp':
			default:
				return $pre_return;
		}

		$this->log_action(
			$sent ? 'success' : 'failed',
			// translators: %s: Provider name (e.g. SendGrid, Mailgun).
			sprintf( esc_html__( 'API Email: %s', 'automation-web-platform' ), ucfirst( $active_account->provider ) ),
			array(
				'recipient' => $this->stringify_recipients( $args['to'] ),
				'gateway'   => 'email',
				'subject'   => $args['subject'] ?? '',
			),
			'email'
		);

		return $sent;
	}



	/**
	 * Configure PHPMailer for SMTP sending.
	 *
	 * @param PHPMailer $phpmailer PHPMailer instance.
	 */
	public function configure_phpmailer( $phpmailer ) {
		global $wpdb;
		$table = $this->db->get_smtp_accounts_table_name();

		$active_account = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT * FROM %i WHERE is_active = 1 LIMIT 1', $table ), 'wawp_smtp_active', 'wawp_database', 300 );
		$active_account = ! empty( $active_account ) ? (object) $active_account[0] : null;

		if ( ! $active_account ) {
			if ( $this->get_wawp_setting( WAWP_Settings_Registry::SMTP_ACTIVE ) !== 'on' ) {
				return;
			}
			$host = $this->get_wawp_setting( WAWP_Settings_Registry::SMTP_HOST );
			if ( empty( $host ) ) {
				return;
			}
			$port       = $this->get_wawp_setting( WAWP_Settings_Registry::SMTP_PORT, 587 );
			$user       = $this->get_wawp_setting( WAWP_Settings_Registry::SMTP_USER );
			$pass       = $this->get_wawp_setting( WAWP_Settings_Registry::SMTP_PASS );
			$enc        = $this->get_wawp_setting( WAWP_Settings_Registry::SMTP_ENCRYPTION, 'tls' );
			$from_email = $this->get_wawp_setting( WAWP_Settings_Registry::SMTP_FROM_EMAIL );
			$from_name  = $this->get_wawp_setting( WAWP_Settings_Registry::SMTP_FROM_NAME );
		} else {
			if ( 'wp' === $active_account->provider || 'smtp' !== $active_account->provider ) {
				return;
			}
			$config = json_decode( $active_account->config, true );
			$host   = $config['host'] ?? '';
			if ( empty( $host ) ) {
				return;
			}
			$port       = $config['port'] ?? 587;
			$user       = $config['user'] ?? '';
			$pass       = $config['pass'] ?? '';
			$enc        = $config['encryption'] ?? 'tls';
			$from_email = $config['from_email'] ?? '';
			$from_name  = $config['from_name'] ?? '';
		}

		$phpmailer->isSMTP();
		$phpmailer->{'Host'}     = $host;
		$phpmailer->{'SMTPAuth'} = true;
		$phpmailer->{'Port'}     = $port;
		$phpmailer->{'Username'} = $user;
		$phpmailer->{'Password'} = $pass;

		$phpmailer->{'SMTPSecure'} = ( 'none' === $enc ? '' : $enc );
		if ( ! empty( $from_email ) ) {
			$phpmailer->setFrom( $from_email, $from_name );
		}
	}

	/**
	 * Log successful wp_mail.
	 *
	 * @param array $args Email arguments.
	 */
	public function log_wp_mail_success( $args ) {
		$this->log_wp_mail( $args, 'success' );
	}

	/**
	 * Log failed wp_mail.
	 *
	 * @param WP_Error|array $error WP_Error object or arguments array.
	 */
	public function log_wp_mail_failure( $error ) {
		$args          = array();
		$error_message = '';

		if ( is_wp_error( $error ) ) {
			$args          = $error->get_error_data();
			$error_message = $error->get_error_message();
		} elseif ( is_array( $error ) ) {
			$args = $error;
		}

		if ( ! is_array( $args ) ) {
			$args = array();
		}

		$to      = isset( $args['to'] ) ? $this->stringify_recipients( $args['to'] ) : '';
		$subject = isset( $args['subject'] ) ? $args['subject'] : '';

		$this->log_action(
			'failed',
			'Email',
			array(
				'recipient' => $to,
				'gateway'   => 'email',
				'subject'   => $subject,
				'error'     => $error_message,
			),
			'email'
		);
	}

	/**
	 * Log wp_mail activity.
	 *
	 * @param array  $args   Email arguments.
	 * @param string $status Sending status.
	 */
	private function log_wp_mail( $args, $status ) {
		if ( ! is_array( $args ) ) {
			$args = array();
		}
		$to      = isset( $args['to'] ) ? $this->stringify_recipients( $args['to'] ) : '';
		$subject = isset( $args['subject'] ) ? $args['subject'] : '';

		$this->log_action(
			( 'success' === $status ) ? 'success' : 'failed',
			'Email',
			array(
				'recipient' => $to,
				'gateway'   => 'email',
				'subject'   => $subject,
			),
			'email'
		);
	}

	/**
	 * Safely stringify a single recipient which might be a string or an object.
	 *
	 * @param mixed $recipient Recipient email.
	 * @param bool  $only_email Whether to return only email address.
	 * @return string
	 */
	private function stringify_recipient( $recipient, $only_email = false ) {
		if ( is_object( $recipient ) ) {
			if ( method_exists( $recipient, 'getEmail' ) ) {
				$email = $recipient->getEmail();
				if ( $only_email ) {
					return $email;
				}
				if ( method_exists( $recipient, 'getName' ) ) {
					$name = $recipient->getName();
					if ( ! empty( $name ) ) {
						return sprintf( '%s <%s>', $name, $email );
					}
				}
				return $email;
			} elseif ( method_exists( $recipient, 'format' ) ) {
				$formatted = $recipient->format();
				if ( $only_email && preg_match( '/<(.*)>/', $formatted, $matches ) ) {
					return trim( $matches[1] );
				}
				return $formatted;
			} elseif ( method_exists( $recipient, '__toString' ) ) {
				$str = (string) $recipient;
				if ( $only_email && preg_match( '/<(.*)>/', $str, $matches ) ) {
					return trim( $matches[1] );
				}
				return $str;
			} elseif ( isset( $recipient->email ) ) {
				return $recipient->email;
			}
		}
		return (string) $recipient;
	}

	/**
	 * Safely stringify a list of recipients.
	 *
	 * @param mixed $to Recipients list.
	 * @param bool  $only_email Whether to return only email addresses.
	 * @return string
	 */
	private function stringify_recipients( $to, $only_email = false ) {
		if ( empty( $to ) ) {
			return '';
		}
		$recipients  = is_array( $to ) ? $to : array( $to );
		$stringified = array();
		foreach ( $recipients as $recipient ) {
			$stringified[] = $this->stringify_recipient( $recipient, $only_email );
		}
		return implode( ', ', $stringified );
	}

	/**
	 * Get React settings data.
	 *
	 * @return array
	 */
	public function get_react_settings_data() {
		return array(
			'allAccounts' => $this->list_accounts(),
			'nonces'      => array(
				'save'     => wp_create_nonce( 'wawp_nonce' ),
				'delete'   => wp_create_nonce( 'wawp_nonce' ),
				'toggle'   => wp_create_nonce( 'wawp_nonce' ),
				'validate' => wp_create_nonce( 'wawp_nonce' ),
				'test'     => wp_create_nonce( 'wawp_nonce' ),
			),
			'i18n'        => array(
				'title'                          => __( 'SMTP Mail Server', 'automation-web-platform' ),
				'subtitle'                       => __( 'Route system emails through your own private mail server. Support multiple accounts.', 'automation-web-platform' ),
				'addAccount'                     => __( 'Add Account', 'automation-web-platform' ),
				'smtpAccounts'                   => __( 'SMTP Accounts', 'automation-web-platform' ),
				'smtpAccountsDesc'               => __( 'Manage configurations and validation status', 'automation-web-platform' ),
				'defaultSender'                  => __( 'Default Sender', 'automation-web-platform' ),
				'accountName'                    => __( 'Account Name', 'automation-web-platform' ),
				'provider'                       => __( 'Provider', 'automation-web-platform' ),
				'serverStatus'                   => __( 'Server Status', 'automation-web-platform' ),
				'actions'                        => __( 'Actions', 'automation-web-platform' ),
				'noAccountsConfigured'           => __( 'No accounts configured yet.', 'automation-web-platform' ),
				'selected'                       => __( 'Selected', 'automation-web-platform' ),
				'setDefault'                     => __( 'Set Default', 'automation-web-platform' ),
				'active'                         => __( 'Active', 'automation-web-platform' ),
				'pendingSetup'                   => __( 'Pending Setup', 'automation-web-platform' ),
				'editAndTest'                    => __( 'Edit & Test', 'automation-web-platform' ),
				'editAccount'                    => __( 'Edit Account', 'automation-web-platform' ),
				'connectNewMailServer'           => __( 'Connect New Mail Server', 'automation-web-platform' ),
				'chooseDeliveryMethod'           => __( 'Choose Delivery Method', 'automation-web-platform' ),
				'configureCredentials'           => __( 'Configure Credentials', 'automation-web-platform' ),
				'diagnosticCheck'                => __( 'Diagnostic Check', 'automation-web-platform' ),
				'providerSelection'              => __( 'Provider Selection', 'automation-web-platform' ),
				'wpMailerDesc'                   => __( 'Using the default WordPress mailer. Simple and reliable, but subject to hosting limitations.', 'automation-web-platform' ),
				'customMailerDesc'               => __( 'Using a custom mail server. This allows for higher delivery rates and professional branding.', 'automation-web-platform' ),
				'management'                     => __( 'Management', 'automation-web-platform' ),
				'accountFriendlyName'            => __( 'Account Friendly Name', 'automation-web-platform' ),
				'accountFriendlyNamePlaceholder' => __( 'e.g. Sales Team SMTP', 'automation-web-platform' ),
				'accountFriendlyNameDesc'        => __( 'This name is only for your reference in the dashboard.', 'automation-web-platform' ),
				'connectionCredentialsFor'       => __( 'Connection Credentials for', 'automation-web-platform' ),
				'quickFillFromPreset'            => __( 'Quick-fill from a known provider', 'automation-web-platform' ),
				'searchProvidersPlaceholder'     => __( 'Search providers... (e.g. Gmail, Hostinger, SendGrid)', 'automation-web-platform' ),
				'noProvidersMatch'               => __( 'No providers match your search.', 'automation-web-platform' ),
				'wpProviderDesc'                 => __( 'Default PHPMailer', 'automation-web-platform' ),
				'smtpProviderDesc'               => __( 'Any Mail Server', 'automation-web-platform' ),
				'catPopular'                     => __( 'Popular', 'automation-web-platform' ),
				'catTransactional'               => __( 'Transactional', 'automation-web-platform' ),
				'catHosting'                     => __( 'Hosting', 'automation-web-platform' ),
				'catEnterprise'                  => __( 'Enterprise', 'automation-web-platform' ),
				'catRegional'                    => __( 'Regional / ISP', 'automation-web-platform' ),
				'providersCountLabel'            => __( 'Providers', 'automation-web-platform' ),
				'systemIntegrationReady'         => __( 'System Integration Ready', 'automation-web-platform' ),
				'systemIntegrationReadyDesc'     => __( "Wawp will use your server's default mailer. Ensure your hosting provider supports PHPMailer or has sendmail configured.", 'automation-web-platform' ),
				'smtpHost'                       => __( 'SMTP Host', 'automation-web-platform' ),
				'port'                           => __( 'Port', 'automation-web-platform' ),
				'encryption'                     => __( 'Encryption', 'automation-web-platform' ),
				'authentication'                 => __( 'Authentication', 'automation-web-platform' ),
				'loginRequired'                  => __( 'Login Required', 'automation-web-platform' ),
				'username'                       => __( 'Username', 'automation-web-platform' ),
				'password'                       => __( 'Password', 'automation-web-platform' ),
				'serverConfigured'               => __( 'Server connection details are configured. You can proceed to test the delivery.', 'automation-web-platform' ),
				'serverMissing'                  => __( 'Connection details missing. Please enter your SMTP host and port to continue.', 'automation-web-platform' ),
				'publicIdentity'                 => __( 'Public Identity', 'automation-web-platform' ),
				'fromEmail'                      => __( 'From Email', 'automation-web-platform' ),
				'fromName'                       => __( 'From Name', 'automation-web-platform' ),
				'verificationAndTesting'         => __( 'Verification & Testing', 'automation-web-platform' ),
				'verificationAndTestingDesc'     => __( 'Validate Endpoint Sync & Send Direct Mail', 'automation-web-platform' ),
				'serverIntegration'              => __( 'Server Integration', 'automation-web-platform' ),
				'serverIntegrationDesc'          => __( 'Verify that the plugin can successfully connect to your SMTP server using the provided credentials.', 'automation-web-platform' ),
				'runServerCheck'                 => __( 'Run Server Check', 'automation-web-platform' ),
				'directMailTest'                 => __( 'Direct Mail Test', 'automation-web-platform' ),
				'directMailTestDesc'             => __( 'Send a physical test email to ensure messages are routed and delivered correctly without ending up in spam.', 'automation-web-platform' ),
				'testEmailAddress'               => __( 'Test Email Address', 'automation-web-platform' ),
				'configurationNote'              => __( 'Configuration Note', 'automation-web-platform' ),
				'configurationNoteDesc'          => __( 'It is highly recommended to perform a successful test before finalizing. Accounts with a failed test will remain in "Pending" status and might not route emails correctly.', 'automation-web-platform' ),
				'close'                          => __( 'Close', 'automation-web-platform' ),
				'back'                           => __( 'Back', 'automation-web-platform' ),
				'continueSetup'                  => __( 'Continue Setup', 'automation-web-platform' ),
				'connectionSuccessful'           => __( 'Connection successful!', 'automation-web-platform' ),
				'connectionFailed'               => __( 'Connection failed.', 'automation-web-platform' ),
				'errorDuringTest'                => __( 'An error occurred during test.', 'automation-web-platform' ),
				'enterTestEmail'                 => __( 'Please enter a test email address.', 'automation-web-platform' ),
				'testEmailSent'                  => __( 'Test email sent successfully.', 'automation-web-platform' ),
				'failedSendTestEmail'            => __( 'Failed to send test email.', 'automation-web-platform' ),
				'errorOccurred'                  => __( 'An error occurred.', 'automation-web-platform' ),
				'deleteConfirm'                  => __( 'Are you sure you want to delete this account?', 'automation-web-platform' ),
			),
		);
	}
}
