<?php
/**
 * Review Reminder WooCommerce email.
 *
 * @package Kramar
 * @since   1.0.0
 */

declare( strict_types=1 );

namespace Kramar\Modules\Marketing;

defined( 'ABSPATH' ) || exit;

/**
 * WooCommerce email sent to a customer after their order completes, asking
 * them to leave a product/platform review.
 *
 * Registered via `woocommerce_email_classes` so it appears in WC → Settings →
 * Emails and is compatible with Kramar's Email Manager block template pipeline.
 *
 * Merge fields `{review_url}` and `{review_unsub_url}` are exposed for the
 * Email Manager's block template system, so the button URL in the Email Builder
 * resolves to the configured review target.
 *
 * @since 1.0.0
 */
class Email_Review_Reminder extends \WC_Email {

	/**
	 * Review CTA URL for the current send — set before trigger() is called.
	 * Read by the `kramar_email_merge_field_values` filter in Review_Reminder.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	public static string $current_review_url = '';

	/**
	 * Unsubscribe URL for the current send.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	public static string $current_unsub_url = '';

	/**
	 * Selected review platform URLs for the current send, keyed by platform
	 * ('woocommerce', 'google', 'trustpilot'). Read by the merge-field filter.
	 *
	 * @since 1.0.0
	 *
	 * @var array<string, string>
	 */
	public static array $current_targets = [];

	/**
	 * Platform display metadata (label + button colour).
	 *
	 * @since 1.0.0
	 *
	 * @return array<string, array{label: string, bg: string}>
	 */
	public static function platform_meta(): array {
		return [
			'woocommerce' => [ 'label' => __( 'Leave a product review', 'kramar' ), 'bg' => '#000000' ],
			'google'      => [ 'label' => __( 'Review us on Google', 'kramar' ), 'bg' => '#4285F4' ],
			'trustpilot'  => [ 'label' => __( 'Review us on Trustpilot', 'kramar' ), 'bg' => '#00b67a' ],
		];
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->id             = 'kramar_review_reminder';
		$this->title          = __( 'Review Reminder', 'kramar' );
		$this->description    = __( 'Sent to customers a configurable number of days after their order completes, asking them to leave a review. Choose any combination of platforms (WooCommerce, Google, Trustpilot).', 'kramar' );
		$this->customer_email = true;
		$this->template_html  = '';
		$this->template_plain = '';

		parent::__construct();
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_default_subject(): string {
		return __( 'How was your order? Leave us a review', 'kramar' );
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_default_heading(): string {
		return __( 'We\'d love your feedback', 'kramar' );
	}

	/**
	 * Send the review reminder email.
	 *
	 * Sets the static merge-field properties so the Email Manager's block
	 * renderer can resolve `{review_url}` and `{review_unsub_url}`.
	 *
	 * @since 1.0.0
	 *
	 * @param \WC_Order             $order       The completed order.
	 * @param array<string, string> $target_urls Selected platform => review URL map.
	 * @param string                $unsub_link  HMAC-signed unsubscribe URL.
	 */
	public function trigger(
		\WC_Order $order,
		array $target_urls,
		string $unsub_link
	): void {
		$recipient = $order->get_billing_email();

		if ( ! $this->is_enabled() || ! is_email( $recipient ) ) {
			return;
		}

		$this->setup_locale();

		$this->recipient = $recipient;
		$this->object    = $order;

		// Expose for Email Manager merge field resolution.
		self::$current_targets    = $target_urls;
		self::$current_review_url = (string) ( reset( $target_urls ) ?: '' );
		self::$current_unsub_url  = $unsub_link;

		$content = $this->build_content( $order, $target_urls, $unsub_link );

		$this->send(
			$recipient,
			$this->get_subject(),
			$content,
			$this->get_headers(),
			$this->get_attachments()
		);

		// Clear static state after send.
		self::$current_review_url = '';
		self::$current_unsub_url  = '';
		self::$current_targets    = [];

		$this->restore_locale();
	}

	/**
	 * Build the email HTML body.
	 *
	 * This content is used as a fallback. When Kramar's Email Manager module
	 * is active it replaces the body via `woocommerce_mail_callback_params`,
	 * using the block template for `kramar_review_reminder` instead.
	 *
	 * @since 1.0.0
	 *
	 * @param \WC_Order             $order       The completed order.
	 * @param array<string, string> $target_urls Selected platform => review URL map.
	 * @param string                $unsub_link  Unsubscribe URL.
	 * @return string HTML content.
	 */
	private function build_content(
		\WC_Order $order,
		array $target_urls,
		string $unsub_link
	): string {
		ob_start();

		$email_heading = $this->get_heading();
		$first_name    = $order->get_billing_first_name();
		$shop_name     = get_bloginfo( 'name' );

		wc_get_template(
			'emails/email-header.php',
			[ 'email_heading' => $email_heading ]
		);
		?>
		<p>
			<?php
			if ( $first_name ) {
				printf(
					/* translators: %s: customer first name */
					esc_html__( 'Hi %s,', 'kramar' ),
					esc_html( $first_name )
				);
			} else {
				esc_html_e( 'Hi there,', 'kramar' );
			}
			?>
		</p>

		<p>
			<?php
			printf(
				/* translators: %s: shop name */
				esc_html__( 'Thank you for your recent order at %s. We hope you are enjoying your purchase!', 'kramar' ),
				esc_html( $shop_name )
			);
			?>
		</p>

		<p>
			<?php esc_html_e( 'We would really appreciate it if you could take a moment to share your experience. Your feedback helps us improve and helps other shoppers make informed decisions.', 'kramar' ); ?>
		</p>

		<?php
		$meta    = self::platform_meta();
		$buttons = '';
		foreach ( $target_urls as $key => $url ) {
			if ( '' === $url || ! isset( $meta[ $key ] ) ) {
				continue;
			}
			$buttons .= '<a href="' . esc_url( $url ) . '" style="display:inline-block;padding:.75em 1.5em;background:' . esc_attr( $meta[ $key ]['bg'] ) . ';color:#fff;text-decoration:none;border-radius:3px;margin:0 .5em .5em 0;">' . esc_html( $meta[ $key ]['label'] ) . '</a>';
		}
		if ( '' !== $buttons ) :
			?>
		<p><?php echo wp_kses_post( $buttons ); ?></p>
			<?php
		endif;
		?>

		<p style="font-size:.85em;color:#777;margin-top:2em;">
			<?php
			printf(
				/* translators: %s: unsubscribe link */
				esc_html__( 'You are receiving this because you recently completed an order with us. %s', 'kramar' ),
				'<a href="' . esc_url( $unsub_link ) . '">' . esc_html__( 'Unsubscribe from review reminder emails', 'kramar' ) . '</a>'
			);
			?>
		</p>
		<?php

		wc_get_template( 'emails/email-footer.php' );

		return (string) ob_get_clean();
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_content_html(): string {
		return '';
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_content_plain(): string {
		return '';
	}
}
