<?php
/**
 * Hook into phpmailer_init at priority 999 so our SMTP settings prevail
 * over any other SMTP plugin, but ONLY for emails that carry the X-SuiteMkt3k header.
 * This avoids conflicts with the site owner's general SMTP plugin.
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k\Email;

use SuiteMkt3k\Modules\Settings\Settings_Manager;
use SuiteMkt3k\Security\Encryption;
use SuiteMkt3k\Utils\Logger;

defined( 'ABSPATH' ) || exit;

final class Smtp {

	public static function register(): void {
		add_action( 'phpmailer_init', array( __CLASS__, 'configure' ), 999 );
		add_action( 'wp_mail_failed', array( __CLASS__, 'log_failure' ) );
	}

	/**
	 * @param \PHPMailer\PHPMailer\PHPMailer $phpmailer
	 */
	public static function configure( $phpmailer ): void {
		if ( ! self::is_suitemkt3k_email( $phpmailer ) ) {
			return;
		}

		$smtp = (array) Settings_Manager::get( 'smtp', '', array() );
		if ( empty( $smtp['enabled'] ) || empty( $smtp['host'] ) ) {
			return;
		}

		$phpmailer->isSMTP();
		$phpmailer->Host       = (string) $smtp['host'];
		$phpmailer->Port       = (int) ( $smtp['port'] ?? 587 );
		$phpmailer->SMTPAuth   = (bool) ( $smtp['auth'] ?? true );
		$phpmailer->Username   = (string) ( $smtp['username'] ?? '' );
		$phpmailer->Password   = Encryption::decrypt( (string) ( $smtp['password'] ?? '' ) );
		$encryption            = (string) ( $smtp['encryption'] ?? 'tls' );
		$phpmailer->SMTPSecure = 'none' === $encryption ? '' : $encryption;
		$phpmailer->SMTPAutoTLS = 'tls' === $encryption;
		$phpmailer->Timeout    = 20;

		if ( ! empty( $smtp['from_email'] ) ) {
			$phpmailer->setFrom( (string) $smtp['from_email'], (string) ( $smtp['from_name'] ?? '' ), false );
		}

		$phpmailer->SMTPOptions = array(
			'ssl' => array(
				'verify_peer'       => true,
				'verify_peer_name'  => true,
				'allow_self_signed' => false,
			),
		);
	}

	/**
	 * @param \WP_Error $error
	 */
	public static function log_failure( $error ): void {
		if ( ! ( $error instanceof \WP_Error ) ) {
			return;
		}
		$data = $error->get_error_data();
		if ( ! is_array( $data ) || empty( $data['headers'] ) ) {
			return;
		}
		$headers = is_array( $data['headers'] ) ? implode( ' ', $data['headers'] ) : (string) $data['headers'];
		if ( false === stripos( $headers, Mailer::HEADER_TAG ) ) {
			return;
		}
		Logger::error( 'smtp', $error->get_error_message() );
	}

	/**
	 * @param \PHPMailer\PHPMailer\PHPMailer $phpmailer
	 */
	private static function is_suitemkt3k_email( $phpmailer ): bool {
		if ( ! is_object( $phpmailer ) ) {
			return false;
		}
		$custom = method_exists( $phpmailer, 'getCustomHeaders' ) ? (array) $phpmailer->getCustomHeaders() : array();
		foreach ( $custom as $header ) {
			if ( is_array( $header ) && isset( $header[0] ) && Mailer::HEADER_TAG === $header[0] ) {
				return true;
			}
		}
		return false;
	}
}
