<?php
/**
 * Mailer Service
 *
 * Single entry point for all outgoing transactional email in AmbassadorHub.
 * Wraps content in the HTML email template and dispatches via wp_mail().
 *
 * Future: swap the delivery back-end by wiring an email connector through
 * ConnectorRegistry — the call sites stay unchanged.
 *
 * @package AmbassadorHub\Mail
 */

namespace AmbassadorHub\Mail;

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

/**
 * Sends transactional email through the WordPress mail stack.
 *
 * Usage:
 *   MailerService::send( $to, $subject, $body_html );
 *   MailerService::send( $to, $subject, $body_html, 'Short preview text' );
 */
final class MailerService {

	/**
	 * Send a transactional email.
	 *
	 * The $body_html is wrapped in the shared HTML email template before sending.
	 * Pass simple HTML: <p>, <a>, <strong>, <ul>/<li> — the template provides
	 * the outer chrome (header, background, footer).
	 *
	 * @param string $to           Recipient email address.
	 * @param string $subject      Email subject line (plain text).
	 * @param string $body_html    Main content as HTML fragment.
	 * @param string $preview_text Optional. Short text shown in inbox previews
	 *                             (≈ 90 chars). Falls back to nothing if omitted.
	 * @return bool True if wp_mail() accepted the message, false otherwise.
	 */
	public static function send(
		string $to,
		string $subject,
		string $body_html,
		string $preview_text = ''
	): bool {
		if ( ! is_email( $to ) ) {
			return false;
		}

		$html = EmailTemplate::wrap( $body_html, $preview_text );

		/**
		 * Filter the headers array before the email is dispatched.
		 *
		 * @param string[] $headers  wp_mail() headers. HTML content-type is always set.
		 * @param string   $to       Recipient address.
		 * @param string   $subject  Email subject.
		 */
		$headers = apply_filters(
			'ambh_mailer_headers',
			array( 'Content-Type: text/html; charset=UTF-8' ),
			$to,
			$subject
		);

		return (bool) wp_mail( $to, $subject, $html, $headers );
	}
}
