<?php
/**
 * Admin donation notification email.
 *
 * @package Donatico\Emails
 */

declare(strict_types=1);

namespace Donatico\Emails;

use Donatico\Helpers\Currency;
use Donatico\Models\Donation;

/**
 * Sends the admin a notification email whenever a donation is completed.
 * Hooked to the donatico_donation_completed action fired by WebhookHandler.
 */
class AdminNotification {

	/** @var EmailService */
	private EmailService $emailService;

	/** @var TemplateRenderer */
	private TemplateRenderer $renderer;

	/**
	 * @param EmailService     $emailService
	 * @param TemplateRenderer $renderer
	 */
	public function __construct( EmailService $emailService, TemplateRenderer $renderer ) {
		$this->emailService = $emailService;
		$this->renderer     = $renderer;
	}

	/**
	 * Send the admin notification for a completed donation.
	 * Hooked to donatico_donation_completed.
	 *
	 * @param Donation $donation
	 * @return void
	 */
	public function onDonationCompleted( Donation $donation ): void {
		if ( ! \get_option( 'donatico_notify_admin', true ) ) {
			return;
		}

		$to = \sanitize_email( (string) \get_option( 'donatico_admin_email', \get_option( 'admin_email', '' ) ) );

		if ( ! \is_email( $to ) ) {
			return;
		}

		$this->send( $donation, $to );
	}

	/**
	 * Build and deliver the notification to $to.
	 * Public so that the test-email AJAX handler can call it directly.
	 *
	 * @param Donation $donation
	 * @param string   $to       Recipient address.
	 * @return bool
	 */
	public function send( Donation $donation, string $to ): bool {
		$this->renderer->setDonation( $donation );
		$this->renderer->setSiteTags();
		$this->renderer->setAdminTags();

		$currency = $donation->getCurrency() ?: (string) \get_option( 'donatico_currency', 'USD' );
		$symbol   = Currency::getSymbol( $currency );
		$amount   = $symbol . $donation->getFormattedAmount();
		$name     = $donation->getDisplayName();

		$subject = \sprintf(
			/* translators: 1: formatted amount with symbol, 2: donor display name */
			\__( '🎉 New donation: %1$s from %2$s', 'donatico' ),
			$amount,
			$name
		);

		$body = $this->renderer->render(
			DONATICO_PLUGIN_DIR . 'templates/emails/admin-notification.php',
			array(
				'donation' => $donation,
				'amount'   => $amount,
				'name'     => $name,
			)
		);

		return $this->emailService->send( $to, $subject, $body );
	}
}
