<?php
/**
 * WordPress mail notification.
 *
 * @package LocalGuardScanner
 */

namespace LocalGuardScanner\Infrastructure\WordPress;

use LocalGuardScanner\Application\Notifications\NotificationPolicy;

/**
 * Sends a redacted summary without paths or inspected content.
 */
final class MailNotifier {
	/** @var NotificationPolicy */
	private $policy;
	/** @var Settings */
	private $settings;

	/**
	 * @param NotificationPolicy $policy   Policy.
	 * @param Settings           $settings Settings.
	 */
	public function __construct( NotificationPolicy $policy, Settings $settings ) {
		$this->policy   = $policy;
		$this->settings = $settings;
	}

	/**
	 * @param int                             $scan_id  Scan ID.
	 * @param array<int,array<string,mixed>> $findings New high-risk findings.
	 * @return bool
	 */
	public function send( $scan_id, array $findings ) {
		if ( ! $this->policy->should_send( $findings ) ) {
			return false;
		}
		$critical = 0;
		$high     = 0;
		foreach ( $findings as $finding ) {
			if ( 'critical' === $finding['severity'] ) {
				++$critical;
			} else {
				++$high;
			}
		}
		$settings          = $this->settings->all();
		$stored_recipients = isset( $settings['recipients'] ) && is_array( $settings['recipients'] ) ? $settings['recipients'] : array();
		$recipients        = array();
		foreach ( $stored_recipients as $recipient ) {
			if ( ! is_string( $recipient ) ) {
				continue;
			}
			$recipient = sanitize_email( $recipient );
			if ( is_email( $recipient ) ) {
				$recipients[ strtolower( $recipient ) ] = $recipient;
			}
		}
		$recipients = array_values( $recipients );
		if ( empty( $recipients ) ) {
			return false;
		}
		$site_name = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
		$subject   = sprintf(
			/* translators: %s: site name. */
			__( '[LocalGuard Scanner] New security findings on %s', 'localguard-scanner' ),
			$site_name
		);
		$url = is_multisite() ? network_admin_url( 'admin.php?page=localguard-scanner-findings' ) : admin_url( 'admin.php?page=localguard-scanner-findings' );

		$localguard_scanner_scan_id  = (int) $scan_id;
		$localguard_scanner_critical = $critical;
		$localguard_scanner_high     = $high;
		$localguard_scanner_url      = $url;
		ob_start();
		include LOCALGUARD_SCANNER_DIR . 'templates/email/alert-text.php';
		$message = ob_get_clean();
		if ( false === $message ) {
			return false;
		}
		return wp_mail( $recipients, $subject, $message );
	}
}
