<?php
/**
 * Admin alert for failed payments.
 *
 * @package Donatico\Emails
 */

declare(strict_types=1);

namespace Donatico\Emails;

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

/**
 * Sends the admin a brief alert when a payment fails so they can follow up
 * with the donor if needed. Hooked to donatico_donation_failed.
 */
class PaymentFailedAlert {

	/** @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 failed-payment alert.
	 * Hooked to donatico_donation_failed by Plugin::defineEmailHooks().
	 *
	 * @param Donation $donation
	 * @return void
	 */
	public function onDonationFailed( Donation $donation ): void {
		// Only alert admin when admin notifications are enabled.
		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->renderer->setDonation( $donation );
		$this->renderer->setSiteTags();
		$this->renderer->setAdminTags();

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

		$subject = \sprintf(
			/* translators: 1: formatted amount with symbol, 2: donor display name */
			\__( '⚠️ Payment failed: %1$s from %2$s', 'donatico' ),
			$amount,
			$donation->getDisplayName()
		);

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

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