<?php
/**
 * Helper methods for building token payloads.
 *
 * @package MailDoctor
 */

namespace MailDoctor;

use WC_Order;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Helper routines referenced by the core token builder.
 */
trait WPMD_Email_Tokens_Helpers {

	/**
	 * Determine password reset URL token.
	 *
	 * @param array<string, mixed> $context Rendering context.
	 * @return string
	 */
	protected static function resolve_reset_url( array $context ): string {
		if ( ! empty( $context['extra_tokens']['reset_url'] ) ) {
			return esc_url_raw( (string) $context['extra_tokens']['reset_url'] );
		}

		if ( function_exists( 'wc_get_account_endpoint_url' ) ) {
			return esc_url_raw( wc_get_account_endpoint_url( 'lost-password' ) );
		}

		if ( function_exists( 'wp_lostpassword_url' ) ) {
			return esc_url_raw( wp_lostpassword_url() );
		}

		return esc_url_raw( home_url( '/my-account/lost-password/' ) );
	}

	/**
	 * Generate formatted items table markup for an order.
	 *
	 * @param WC_Order             $order   Order instance.
	 * @param array<string, mixed> $context Rendering context.
	 * @return string
	 */
	protected static function build_items_table( $order, array $context ): string {
		if ( ! class_exists( 'WC_Order' ) || ! $order instanceof WC_Order ) {
			return '';
		}

		if ( ! function_exists( 'wc_get_email_order_items' ) ) {
			return '';
		}

		$email = $context['email'] ?? null;

		$items = wc_get_email_order_items(
			$order,
			array(
				'plain_text'          => false,
				'show_sku'            => true,
				'show_image'          => true,
				'show_download_links' => true,
				'sent_to_admin'       => ! empty( $context['sent_to_admin'] ),
				'email'               => is_object( $email ) ? $email : null,
			)
		);

		$totals = self::build_order_totals_rows( $order );

		$table  = '<table class="wpmd-items-table" cellpadding="0" cellspacing="0" role="presentation">';
		$table .= '<thead><tr><th scope="col">' . esc_html__( 'Product', 'mail-doctor' ) . '</th><th scope="col">' . esc_html__( 'Total', 'mail-doctor' ) . '</th></tr></thead>';
		$table .= '<tbody>' . $items . '</tbody>';
		$table .= $totals;
		$table .= '</table>';

		return $table;
	}

	/**
	 * Build totals rows markup.
	 *
	 * @param WC_Order $order Order instance.
	 * @return string
	 */
	protected static function build_order_totals_rows( $order ): string {
		if ( ! class_exists( 'WC_Order' ) || ! $order instanceof WC_Order ) {
			return '';
		}

		$rows   = '';
		$totals = $order->get_order_item_totals();

		if ( empty( $totals ) ) {
			return $rows;
		}

		$rows .= '<tfoot>';
		foreach ( $totals as $total ) {
			if ( empty( $total['label'] ) ) {
				continue;
			}

			$rows .= '<tr><th scope="row">' . wp_kses_post( $total['label'] ) . '</th><td>' . wp_kses_post( $total['value'] ) . '</td></tr>';
		}
		$rows .= '</tfoot>';

		return $rows;
	}

	/**
	 * Generate download links markup when available.
	 *
	 * @param WC_Order $order Order instance.
	 * @return string
	 */
	protected static function build_download_links( $order ): string {
		if ( ! class_exists( 'WC_Order' ) || ! $order instanceof WC_Order ) {
			return '';
		}

		if ( ! $order->has_downloadable_item() ) {
			return '';
		}

		$downloads = $order->get_downloadable_items();

		if ( empty( $downloads ) ) {
			return '';
		}

		$list = '<ul class="wpmd-download-links">';
		foreach ( $downloads as $download ) {
			if ( empty( $download['download_url'] ) || empty( $download['name'] ) ) {
				continue;
			}

			$list .= sprintf(
				'<li><a href="%1$s">%2$s</a></li>',
				esc_url( $download['download_url'] ),
				esc_html( $download['name'] )
			);
		}
		$list .= '</ul>';

		return $list;
	}

	/**
	 * Build refund total string.
	 *
	 * @param WC_Order $order Order instance.
	 * @return string
	 */
	protected static function format_refund_total( $order ): string {
		if ( ! class_exists( 'WC_Order' ) || ! $order instanceof WC_Order ) {
			return '';
		}

		$total = (float) $order->get_total_refunded();

		if ( $total <= 0 ) {
			return '';
		}

		if ( function_exists( 'wc_price' ) ) {
			return wp_strip_all_tags( wc_price( $total ) );
		}

		return (string) $total;
	}

	/**
	 * Provide shipping method label.
	 *
	 * @param WC_Order $order Order instance.
	 * @return string
	 */
	protected static function format_shipping_method( $order ): string {
		if ( ! class_exists( 'WC_Order' ) || ! $order instanceof WC_Order ) {
			return '';
		}
		$items = $order->get_shipping_methods();

		if ( empty( $items ) ) {
			return '';
		}

		$names = array();

		foreach ( $items as $item ) {
			$name = $item->get_name();
			if ( $name ) {
				$names[] = $name;
			}
		}

		return implode( ', ', $names );
	}

	/**
	 * Generate unsubscribe link when possible.
	 *
	 * @param WC_Order|null $order Optional order instance.
	 * @return string
	 */
	protected static function build_unsubscribe_link( $order = null ): string {
		$email = ( class_exists( 'WC_Order' ) && $order instanceof WC_Order ) ? $order->get_billing_email() : '';

		$url = home_url(
			add_query_arg(
				array(
					'wpmd-unsubscribe' => 1,
					'email'            => $email ? rawurlencode( $email ) : '',
				),
				'/'
			)
		);

		return esc_url_raw( $url );
	}
}
