<?php
/**
 * Back-in-Stock WooCommerce email.
 *
 * @package Kramar
 * @since   1.0.0
 */

declare( strict_types=1 );

namespace Kramar\Modules\Marketing;

defined( 'ABSPATH' ) || exit;

/**
 * WooCommerce email sent to a subscriber when a product returns to stock.
 *
 * Registered via `woocommerce_email_classes` so it appears in WC → Settings →
 * Emails and is compatible with Kramar's Email Manager block template pipeline.
 *
 * @since 1.0.0
 */
class Email_Back_In_Stock extends \WC_Email {

	/**
	 * HMAC unsubscribe URL for the current send (used by the block pipeline).
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	private string $kramar_unsub_link = '';

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->id             = 'kramar_back_in_stock';
		$this->title          = __( 'Back in Stock Notification', 'kramar' );
		$this->description    = __( 'Sent to customers who signed up to be notified when an out-of-stock product becomes available again.', 'kramar' );
		$this->customer_email = true;
		$this->template_html  = '';
		$this->template_plain = '';

		parent::__construct();
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_default_subject(): string {
		/* translators: {product_name}: product name */
		return __( '{product_name} is back in stock!', 'kramar' );
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_default_heading(): string {
		return __( 'Good news — your item is available again', 'kramar' );
	}

	/**
	 * Send the back-in-stock email.
	 *
	 * @since 1.0.0
	 *
	 * @param string      $recipient    Subscriber email address.
	 * @param \WC_Product $product      Product that is now in stock.
	 * @param string      $unsub_link   HMAC-signed unsubscribe URL.
	 */
	public function trigger( string $recipient, \WC_Product $product, string $unsub_link ): void {
		if ( ! $this->is_enabled() || ! is_email( $recipient ) ) {
			return;
		}

		$this->setup_locale();

		$this->recipient       = $recipient;
		$this->object          = $product;
		$this->kramar_unsub_link = $unsub_link;

		// Replace {product_name} merge tag in subject/heading.
		$product_name   = $product->get_name();
		$product_url    = $product->get_permalink();
		$product_price  = wp_strip_all_tags( wc_price( (float) $product->get_price() ) );

		$subject = str_replace( '{product_name}', $product_name, $this->get_subject() );
		$content = $this->build_content( $product_name, $product_url, $product_price, $unsub_link );

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

		$this->restore_locale();
	}

	/**
	 * Build the email HTML body.
	 *
	 * @since 1.0.0
	 *
	 * @param string $product_name  Product display name.
	 * @param string $product_url   Product page permalink.
	 * @param string $product_price Formatted product price.
	 * @param string $unsub_link    Unsubscribe URL.
	 * @return string HTML content.
	 */
	private function build_content(
		string $product_name,
		string $product_url,
		string $product_price,
		string $unsub_link
	): string {
		ob_start();

		$email_heading = $this->get_heading();

		wc_get_template(
			'emails/email-header.php',
			[ 'email_heading' => $email_heading ]
		);
		?>
		<p><?php esc_html_e( 'Good news!', 'kramar' ); ?></p>
		<p>
			<?php
			printf(
				/* translators: %s: product name as link */
				esc_html__( '%s is back in stock and available for purchase.', 'kramar' ),
				'<a href="' . esc_url( $product_url ) . '">' . esc_html( $product_name ) . '</a>'
			);
			?>
		</p>
		<p>
			<?php
			printf(
				/* translators: %s: formatted price */
				esc_html__( 'Current price: %s', 'kramar' ),
				'<strong>' . wp_kses_post( $product_price ) . '</strong>'
			);
			?>
		</p>
		<p>
			<a href="<?php echo esc_url( $product_url ); ?>" style="display:inline-block;padding:.75em 1.5em;background:#000;color:#fff;text-decoration:none;border-radius:3px;">
				<?php esc_html_e( 'Shop now', 'kramar' ); ?>
			</a>
		</p>
		<p style="font-size:.85em;color:#777;margin-top:2em;">
			<?php
			printf(
				/* translators: %s: unsubscribe link */
				esc_html__( 'You are receiving this email because you signed up for back-in-stock notifications. %s', 'kramar' ),
				'<a href="' . esc_url( $unsub_link ) . '">' . esc_html__( 'Unsubscribe', 'kramar' ) . '</a>'
			);
			?>
		</p>
		<?php

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

		return (string) ob_get_clean();
	}

	/**
	 * Provide the merge context for Kramar's Email Manager block pipeline.
	 *
	 * Lets the back-in-stock email be designed in the visual builder using
	 * {product_name}, {product_url}, {product_price}, {product_image} and
	 * {unsubscribe_url} merge fields. When the Email Manager is inactive the
	 * hardcoded build_content() fallback is used instead.
	 *
	 * @since 1.0.0
	 *
	 * @return array<string, mixed> Data context: [ 'merge' => [ tag => value ] ].
	 */
	public function kramar_block_context(): array {
		$product = $this->object instanceof \WC_Product ? $this->object : null;
		if ( null === $product ) {
			return [];
		}

		$image = $product->get_image_id()
			? (string) wp_get_attachment_image_url( $product->get_image_id(), 'medium' )
			: '';

		return [
			'merge' => [
				'{product_name}'    => $product->get_name(),
				'{product_url}'     => $product->get_permalink(),
				'{product_price}'   => wp_strip_all_tags( wc_price( (float) $product->get_price() ) ),
				'{product_image}'   => $image,
				'{unsubscribe_url}' => $this->kramar_unsub_link,
			],
		];
	}

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

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