<?php
/**
 * Frontend order tracking display.
 *
 * Shows fulfillment details (carrier, tracking number, tracking URL)
 * on the customer-facing My Account > View Order page.
 *
 * @package Memwc_Connector
 * @since   1.0.0
 */

defined( 'ABSPATH' ) || exit;

class Memwc_Order_Tracking {

	private static $instance = null;

	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'woocommerce_order_details_after_order_table', [ $this, 'render_tracking_details' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_styles' ] );
	}

	/**
	 * Enqueue tracking styles only on the view-order endpoint.
	 */
	public function enqueue_styles() {
		if ( ! is_wc_endpoint_url( 'view-order' ) ) {
			return;
		}

		wp_enqueue_style(
			'mem-order-tracking',
			MEMWC_CONNECTOR_URL . 'assets/css/mem-order-tracking.css',
			[],
			MEMWC_CONNECTOR_VERSION
		);
	}

	/**
	 * Render tracking details after the order table on the View Order page.
	 *
	 * @param WC_Order $order The order object.
	 */
	public function render_tracking_details( $order ) {
		if ( ! $order ) {
			return;
		}

		$tracking_number = $order->get_meta( '_mem_tracking_number' );
		$carrier         = $order->get_meta( '_mem_carrier' );
		$tracking_url    = $order->get_meta( '_mem_tracking_url' );

		if ( empty( $tracking_number ) && empty( $carrier ) && empty( $tracking_url ) ) {
			return;
		}
		?>
		<section class="mem-tracking-section">
			<h2 class="mem-tracking-heading"><?php esc_html_e( 'Shipment Tracking', 'my-easy-monogram' ); ?></h2>

			<div class="mem-tracking-card">
				<?php if ( ! empty( $carrier ) ) : ?>
					<div class="mem-tracking-row">
						<span class="mem-tracking-label"><?php esc_html_e( 'Carrier', 'my-easy-monogram' ); ?></span>
						<span class="mem-tracking-value"><?php echo esc_html( $carrier ); ?></span>
					</div>
				<?php endif; ?>

				<?php if ( ! empty( $tracking_number ) ) : ?>
					<div class="mem-tracking-row">
						<span class="mem-tracking-label"><?php esc_html_e( 'Tracking Number', 'my-easy-monogram' ); ?></span>
						<code class="mem-tracking-value mem-tracking-code"><?php echo esc_html( $tracking_number ); ?></code>
					</div>
				<?php endif; ?>

				<?php if ( ! empty( $tracking_url ) ) : ?>
					<div class="mem-tracking-row mem-tracking-row--action">
						<a href="<?php echo esc_url( $tracking_url ); ?>" target="_blank" rel="noopener noreferrer" class="mem-tracking-link">
							<?php esc_html_e( 'Track Shipment', 'my-easy-monogram' ); ?>
							<span aria-hidden="true">&rarr;</span>
						</a>
					</div>
				<?php endif; ?>
			</div>
		</section>
		<?php
	}
}
