<?php

declare( strict_types=1 );

namespace Brightfern\Invoice\Model;

/**
 * A trading party — seller (BG-4) or buyer (BG-7).
 *
 * Key EN 16931 business terms:
 *   BT-27 / BT-44  Party legal registration name (the official name).
 *   BT-28 / BT-45  Party trading name (optional).
 *   BT-31 / BT-48  Party VAT identifier (e.g. "BE0123456789").
 *   BT-30 / BT-47  Party legal registration id (e.g. company / KBO number).
 *   BT-34 / BT-49  Party electronic address (Peppol endpoint) + its scheme id.
 *                  This is THE routing key on the Peppol network — e.g.
 *                  scheme "0208" (Belgian enterprise number) + the number, or
 *                  "9925" (BE VAT). RecipientResolver does the SMP lookup on it.
 *   BG-6  / BG-9   Contact (name / phone / email).
 */
final class Party {
	public string $registrationName = ''; // BT-27 / BT-44 (mandatory).
	public string $tradingName = '';      // BT-28 / BT-45.
	public string $vatNumber = '';        // BT-31 / BT-48, e.g. "BE0123456789".
	public string $companyId = '';        // BT-30 / BT-47 legal registration id.
	public string $companyIdScheme = '';  // ICD scheme for BT-30 (e.g. "0208").

	/** BT-34 / BT-49 — Peppol participant electronic address. */
	public string $endpointId = '';        // e.g. "0123456789".
	public string $endpointScheme = '';    // Peppol EAS code, e.g. "0208", "9925".

	public ?Address $address = null;

	// Contact (BG-6 / BG-9).
	public string $contactName = '';
	public string $contactPhone = '';
	public string $contactEmail = '';

	public function hasVat(): bool {
		return '' !== trim( $this->vatNumber );
	}

	/** The two-letter country prefix of the VAT number, if any. */
	public function vatCountry(): string {
		return strtoupper( substr( preg_replace( '/[^A-Za-z0-9]/', '', $this->vatNumber ), 0, 2 ) );
	}

	/** Peppol participant identifier in "scheme:value" form, e.g. "0208:0123456789". */
	public function participantId(): string {
		return $this->endpointScheme . ':' . $this->endpointId;
	}
}
