<?php
/**
 * Front-end magic-link order view.
 *
 * @package WPDudeProducts
 */

declare(strict_types=1);

namespace WPDude\Products\Frontend;

use WPDude\Products\Access\Order_Magic_Link_Service;
use WPDude\Products\Checkout\Payment_Completion_Service;
use WPDude\Products\Orders\Statuses;
use WPDude\Products\Support\Money;

/**
 * Renders a read-only order summary from a secure token.
 */
final class Order_View {

	private Order_Magic_Link_Service $links;

	public function __construct( ?Order_Magic_Link_Service $links = null ) {
		$this->links = $links ?? new Order_Magic_Link_Service();
	}

	/**
	 * Register hooks.
	 */
	public function register(): void {
		add_action( 'template_redirect', array( $this, 'maybe_render' ) );
	}

	/**
	 * Token from the request query string.
	 */
	public static function token_from_request(): string {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- passwordless magic link.
		if ( ! isset( $_GET[ Order_Magic_Link_Service::QUERY_ARG ] ) ) {
			return '';
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$token = sanitize_text_field( wp_unslash( (string) $_GET[ Order_Magic_Link_Service::QUERY_ARG ] ) );
		$token = strtolower( $token );
		if ( ! preg_match( '/^[a-f0-9]{64}$/', $token ) ) {
			return '';
		}
		return $token;
	}

	/**
	 * Render order view or error and exit.
	 */
	public function maybe_render(): void {
		$token = self::token_from_request();
		if ( '' === $token ) {
			return;
		}

		$order = $this->links->resolve_order( $token );
		nocache_headers();
		status_header( 200 );

		Assets::mark_needed();

		get_header();
		echo '<main class="wpdude-dc-order-view" id="wpdude-dc-order-view">';
		if ( is_wp_error( $order ) ) {
			$this->render_error( $order->get_error_message() );
		} else {
			$this->render_order( $order );
		}
		echo '</main>';
		get_footer();
		exit;
	}

	/**
	 * @param array<string, mixed> $order Order.
	 */
	private function render_order( array $order ): void {
		$payload      = Payment_Completion_Service::public_success_payload( $order );
		$status       = Statuses::label( (string) ( $order['status'] ?? '' ) );
		$uuid         = (string) ( $order['uuid'] ?? '' );
		$qty          = (int) ( $payload['qty'] ?? 1 );
		$product_name = (string) ( $payload['product_name'] ?? '' );
		$options      = (string) ( $payload['options_label'] ?? '' );
		$total        = (string) ( $payload['amount_formatted'] ?? '' );
		$tax          = (int) ( $order['tax_amount'] ?? 0 );
		$shipping     = (int) ( $order['shipping_amount'] ?? 0 );
		$currency     = (string) ( $order['currency'] ?? 'usd' );
		$address      = $this->format_address( $order );
		$paid_at      = (string) ( $order['paid_at'] ?? '' );

		echo '<div class="wpdude-dc-order-view__box">';
		echo '<h1 class="wpdude-dc-order-view__title">' . esc_html__( 'Your order', 'dude-commerce' ) . '</h1>';
		echo '<p class="wpdude-dc-order-view__status"><strong>' . esc_html__( 'Status', 'dude-commerce' ) . ':</strong> ' . esc_html( $status ) . '</p>';

		echo '<ul class="wpdude-dc-return__details">';
		echo '<li><strong>' . esc_html__( 'Order ID', 'dude-commerce' ) . ':</strong> ' . esc_html( $uuid ) . '</li>';
		echo '<li><strong>' . esc_html__( 'Product', 'dude-commerce' ) . ':</strong> ' . esc_html( $product_name ) . '</li>';
		if ( '' !== $options ) {
			echo '<li><strong>' . esc_html__( 'Options', 'dude-commerce' ) . ':</strong> ' . esc_html( $options ) . '</li>';
		}
		echo '<li><strong>' . esc_html__( 'Quantity', 'dude-commerce' ) . ':</strong> ' . esc_html( (string) $qty ) . '</li>';
		if ( $shipping > 0 ) {
			echo '<li><strong>' . esc_html__( 'Shipping', 'dude-commerce' ) . ':</strong> ' . esc_html( Money::format( $shipping, $currency ) ) . '</li>';
		}
		if ( $tax > 0 ) {
			echo '<li><strong>' . esc_html__( 'Tax', 'dude-commerce' ) . ':</strong> ' . esc_html( Money::format( $tax, $currency ) ) . '</li>';
		}
		echo '<li><strong>' . esc_html__( 'Total', 'dude-commerce' ) . ':</strong> ' . esc_html( $total ) . '</li>';
		if ( '' !== $paid_at ) {
			echo '<li><strong>' . esc_html__( 'Paid', 'dude-commerce' ) . ':</strong> ' . esc_html( $paid_at ) . ' UTC</li>';
		}
		echo '</ul>';

		if ( '' !== $address ) {
			echo '<h2 class="wpdude-dc-order-view__subtitle">' . esc_html__( 'Ship to', 'dude-commerce' ) . '</h2>';
			echo '<p class="wpdude-dc-order-view__address">' . nl2br( esc_html( $address ) ) . '</p>';
		}

		echo '</div>';
	}

	private function render_error( string $message ): void {
		echo '<div class="wpdude-dc-order-view__box wpdude-dc-order-view__box--error">';
		echo '<h1 class="wpdude-dc-order-view__title">' . esc_html__( 'Order link', 'dude-commerce' ) . '</h1>';
		echo '<p class="wpdude-dc-order-view__message">' . esc_html( $message ) . '</p>';
		echo '</div>';
	}

	/**
	 * @param array<string, mixed> $order Order.
	 */
	private function format_address( array $order ): string {
		$shipping = is_array( $order['shipping_address'] ?? null ) ? $order['shipping_address'] : array();
		$lines    = array();
		$name     = trim( (string) ( $shipping['name'] ?? $order['customer_name'] ?? '' ) );
		if ( '' !== $name ) {
			$lines[] = $name;
		}

		$address = is_array( $shipping['address'] ?? null ) ? $shipping['address'] : $shipping;
		foreach ( array( 'line1', 'line2', 'city', 'state', 'postal_code', 'country' ) as $key ) {
			$val = trim( (string) ( $address[ $key ] ?? '' ) );
			if ( '' !== $val ) {
				$lines[] = $val;
			}
		}

		$phone = trim( (string) ( $shipping['phone'] ?? '' ) );
		if ( '' !== $phone ) {
			$lines[] = $phone;
		}

		return implode( "\n", $lines );
	}
}
