<?php
/**
 * DNS helper methods.
 *
 * @package MailDoctor
 */

namespace MailDoctor\Helpers;

use WP_Error;

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

/**
 * DNS helper methods.
 */
class DNS {

	/**
	 * Perform TXT record lookup, returning records or WP_Error.
	 *
	 * @param string $host Hostname to query.
	 * @return array<int, string>|WP_Error
	 */
	public static function get_txt( string $host ) {
		if ( ! function_exists( 'dns_get_record' ) ) {
			return new WP_Error(
				'mail_doctor_dns_unavailable',
				__( 'DNS lookups are not available on this server. Contact your host to run SPF/DKIM/DMARC checks.', 'mail-doctor' )
			);
		}

		$records = @dns_get_record( $host, DNS_TXT ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged

		if ( false === $records ) {
			return new WP_Error(
				'mail_doctor_dns_failed',
				sprintf(
					/* translators: %s: domain name */
					__( 'DNS lookup for %s failed. Verify that the domain is valid or try again later.', 'mail-doctor' ),
					$host
				)
			);
		}

		$txt = array();
		foreach ( $records as $entry ) {
			if ( isset( $entry['txt'] ) ) {
				$txt[] = $entry['txt'];
			}
		}

		return $txt;
	}
}
