<?php
namespace Pay4All\Pro\License;

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

/**
 * Reduces the site's URL to its primary domain — the merchant's commercial
 * identity for licensing. Handles:
 *
 *   www.toto.ch    → toto.ch
 *   shop.toto.ch   → toto.ch
 *   https://toto.ch/boutique → toto.ch
 *
 * The MVP implementation strips `www.` and the leftmost subdomain when the
 * remaining tail has ≥ 2 labels. A future release will swap this for a
 * proper Public-Suffix-List library so `example.co.uk` collapses to
 * `example.co.uk` and not `co.uk`.
 */
final class DomainNormalizer {

	public static function current_domain() : string {
		return self::normalise( (string) home_url( '/' ) );
	}

	public static function normalise( string $url ) : string {
		$host = wp_parse_url( $url, PHP_URL_HOST );
		if ( ! is_string( $host ) || $host === '' ) { return ''; }
		$host = strtolower( $host );
		if ( strpos( $host, 'www.' ) === 0 ) { $host = substr( $host, 4 ); }

		$parts = explode( '.', $host );
		if ( count( $parts ) <= 2 ) { return $host; }

		// Best-effort : keep the last two labels unless the second-to-last is
		// a known compound TLD stub. Not exhaustive — enough for common
		// Swiss/EU cases (.co.uk, .com.au, .co.jp) until we ship a real PSL.
		$two_label_tld = [ 'co', 'com', 'net', 'org', 'gov', 'edu', 'ac' ];
		$last          = array_pop( $parts );
		$second        = array_pop( $parts );
		if ( in_array( $second, $two_label_tld, true ) && ! empty( $parts ) ) {
			$third = array_pop( $parts );
			return $third . '.' . $second . '.' . $last;
		}
		return $second . '.' . $last;
	}
}
