<?php

namespace App\Services;

final class TaxEngine
{
    public static function computeFromGross(float $gross, float $vatRate, float $withholdingRate): array
    {
        if ($gross < 0) {
            throw new \InvalidArgumentException('Gross must be non-negative');
        }

        $base = ($vatRate == 0.0) ? $gross : ($gross / (1.0 + $vatRate));
        $vatAmount = $base * $vatRate;
        $withholdingAmount = $base * $withholdingRate;
        $chequeNet = $gross - $withholdingAmount;
        $operatingNet = $base - $withholdingAmount;

        return [
            'gross' => self::round2($gross),
            'base' => self::round2($base),
            'vat_amount' => self::round2($vatAmount),
            'withholding_amount' => self::round2($withholdingAmount),
            'cheque_net' => self::round2($chequeNet),
            'operating_net' => self::round2($operatingNet),
        ];
    }

    private static function round2(float $value): float
    {
        return round($value, 2);
    }
}
