<?php
/**
 * Resolves Tax ID (NIP) from POST and order meta.
 *
 * Handles classic and block checkout flows.
 *
 * @package Simplyin\Simplyin_W_Plugin\Service\Order
 */

declare(strict_types=1);

namespace Simplyin\Simplyin_W_Plugin\Service\Order;

use WC_Order;

class Tax_Id_Resolver {

	private const TAX_FIELD_NAME = 'billing_tax_id_simply';

	private const ORDER_META_KEYS = [
		'_billing_tax_id_simply',
		'billing_tax_id_simply',
	];

	/**
	 * Resolve tax ID from POST or order meta.
	 *
	 * @param WC_Order $order
	 *
	 * @return string
	 */
	public function resolve( WC_Order $order ): string {
		$from_post = $this->resolve_from_post();
		if ( $from_post !== '' ) {
			return $from_post;
		}

		return $this->resolve_from_order_meta( $order );
	}

	private function resolve_from_post(): string {
		$custom_tax_field_id = $this->get_sanitized_post( 'simply_tax_label_id' );
		if ( $custom_tax_field_id !== '' ) {
			$value = $this->get_sanitized_post( $custom_tax_field_id );
			if ( $value !== '' ) {
				return $value;
			}
		}

		$direct_value = $this->get_sanitized_post( self::TAX_FIELD_NAME );
		if ( $direct_value !== '' ) {
			return $direct_value;
		}

		return '';
	}

	private function resolve_from_order_meta( WC_Order $order ): string {
		foreach ( self::ORDER_META_KEYS as $meta_key ) {
			$value = $order->get_meta( $meta_key, true );
			if ( is_string( $value ) && trim( $value ) !== '' ) {
				return trim( $value );
			}
		}

		return '';
	}

	private function get_sanitized_post( string $key ): string {
		// phpcs:disable WordPress.Security.NonceVerification.Missing
		if ( ! isset( $_POST[ $key ] ) || ! is_string( $_POST[ $key ] ) ) {
			// phpcs:enable WordPress.Security.NonceVerification.Missing
			return '';
		}

		return trim( sanitize_text_field( wp_unslash( $_POST[ $key ] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
	}
}
