<?php
/**
 * Donor thank-you email.
 *
 * @package Donatico\Emails
 */

declare(strict_types=1);

namespace Donatico\Emails;

use Donatico\Models\Donation;

/**
 * Sends the donor a thank-you receipt after a successful donation.
 * Subject and body copy come from Settings → Notifications so admins
 * can customise them without touching code.
 * Hooked to the donatico_donation_completed action.
 */
class DonorThankYou {

	/** @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 thank-you email to the donor.
	 * Hooked to donatico_donation_completed.
	 *
	 * @param Donation $donation
	 * @return void
	 */
	public function onDonationCompleted( Donation $donation ): void {
		if ( ! \get_option( 'donatico_notify_donor', true ) ) {
			return;
		}

		$to = $donation->getDonorEmail();

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

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

	/**
	 * Build and deliver the thank-you email to $to.
	 * Public so that the test-email AJAX handler can call it with the admin
	 * email as the recipient.
	 *
	 * @param Donation $donation
	 * @param string   $to       Recipient address (defaults to donor's email).
	 * @return bool
	 */
	public function send( Donation $donation, string $to = '' ): bool {
		if ( $to === '' ) {
			$to = $donation->getDonorEmail();
		}

		$this->renderer->setDonation( $donation );
		$this->renderer->setSiteTags();

		// Subject may contain merge tags (e.g. {site_name}).
		$raw_subject = (string) \get_option(
			'donatico_donor_email_subject',
			/* translators: %s: site name */
			\sprintf( \__( 'Thank you for your donation to %s', 'donatico' ), \get_bloginfo( 'name' ) )
		);
		$subject = $this->renderer->replaceTags( $raw_subject );

		$body = $this->renderer->render(
			DONATICO_PLUGIN_DIR . 'templates/emails/donor-thank-you.php',
			array( 'donation' => $donation )
		);

		// Honour the configured Reply-To so donors can reply directly.
		$reply_to = $this->emailService->getFromName() . ' <' . $this->emailService->getFromEmail() . '>';
		$extra_headers = array( 'Reply-To: ' . $reply_to );

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