<?php

declare(strict_types=1);

namespace Australcode\Rewards\Frontend;

use Australcode\Rewards\Domain\Settings\SettingsRepository;
use Australcode\Rewards\Service\WalletService;
use WC_Email;
use WC_Order;

defined( 'ABSPATH' ) || exit;

/**
 * Appends a points line to the customer's WooCommerce order email when that
 * order earned points — reusing WC's existing transactional emails rather than
 * shipping standalone email classes. Skips admin copies and orders that didn't
 * earn (no awarded meta).
 */
final class OrderEmailPoints {

	private const AWARDED_META = '_acrwd_points_awarded';

	public function __construct(
		private readonly WalletService $wallet,
		private readonly SettingsRepository $settings,
	) {
	}

	public function register(): void {
		add_action( 'woocommerce_email_after_order_table', array( $this, 'render' ), 15, 4 );
	}

	public function render( WC_Order $order, bool $sent_to_admin, bool $plain_text, WC_Email $email ): void {
		unset( $email );
		if ( $sent_to_admin ) {
			return;
		}

		$user_id = $order->get_customer_id();
		if ( $user_id <= 0 || '' === (string) $order->get_meta( self::AWARDED_META ) ) {
			return;
		}

		$settings = $this->settings->get();
		if ( ! $settings->show_order_email ) {
			return;
		}
		$balance = $this->wallet->get_balance( $user_id )->points_balance;
		$label   = 1 === $balance ? $settings->points_label_singular : $settings->points_label_plural;

		/* translators: keep the {balance} and {points_label} placeholders. */
		$default  = __( 'You earned rewards with this order. Your points balance is now {balance} {points_label}.', 'australcode-points-rewards' );
		$template = '' !== $settings->msg_email ? $settings->msg_email : $default;
		$message  = MessageTemplate::render(
			$template,
			array(
				'{balance}'      => number_format_i18n( $balance ),
				'{points_label}' => $label,
			)
		);

		if ( $plain_text ) {
			echo "\n" . esc_html( $message ) . "\n";
		} else {
			echo '<p style="margin:16px 0;">' . esc_html( $message ) . '</p>';
		}
	}
}
