<?php

declare( strict_types=1 );

namespace Brightfern\Invoice\Model;

/**
 * An allowance (discount) or charge, at document level (BG-20/BG-21) or line
 * level (BG-27/BG-28).
 *
 *  - isCharge=false → allowance (discount). BT-92 amount, BT-94 % , BT-93 base.
 *  - isCharge=true  → charge.               BT-99 amount, BT-101 %, BT-100 base.
 *
 * A DOCUMENT-level allowance/charge MUST carry its own VAT category + rate
 * (BT-95/BT-96 or BT-102/BT-103) because it feeds the VAT breakdown. A
 * LINE-level one does not — it just adjusts the line net amount (BT-131).
 */
final class AllowanceCharge {
	public bool $isCharge = false;
	public float $amount = 0.0;          // Always a positive number; direction is isCharge.
	public ?float $baseAmount = null;    // Optional base the percentage applies to.
	public ?float $percent = null;       // Optional percentage.
	public string $reasonCode = '';      // UNCL5189 (allowance) / UNCL7161 (charge).
	public string $reasonText = '';      // Free-text reason (e.g. "Volume discount").

	// Only meaningful for document-level entries.
	public ?string $vatCategoryCode = null; // e.g. VatCategory::STANDARD.
	public ?float $vatPercent = null;

	public static function allowance( float $amount, string $reasonText = '', string $reasonCode = '' ): self {
		$ac             = new self();
		$ac->isCharge   = false;
		$ac->amount     = $amount;
		$ac->reasonText = $reasonText;
		$ac->reasonCode = $reasonCode;
		return $ac;
	}

	public static function charge( float $amount, string $reasonText = '', string $reasonCode = '' ): self {
		$ac             = new self();
		$ac->isCharge   = true;
		$ac->amount     = $amount;
		$ac->reasonText = $reasonText;
		$ac->reasonCode = $reasonCode;
		return $ac;
	}

	/** Signed contribution to a net total: charges add, allowances subtract. */
	public function signedAmount(): float {
		return $this->isCharge ? $this->amount : -$this->amount;
	}
}
