<?php

namespace App\ValueObjects;

class Amount {
    private string $currency;
    private float $amount;

    public static function fromString(string $amountString, string $currency = ' Euro') : Amount {
        return new self(
            (float)str_replace(',', '.', $amountString)
            , $currency);
    }


    public function __construct(float $amount, string $currency) {
        $this->currency = $currency;
        $this->amount = $amount;
    }

    public function getAmount() : float {
        return $this->amount;
    }

    public function getRoundedAmount() : int {
        return round($this->amount);
    }

    public function getCurrency() : string {
        return $this->currency;
    }

    public function toString() : string {
        $value = number_format( round( $this->amount, 2 ), 2, ',', '.' );
        return sprintf('%1$s %2$s', $value, $this->currency)
        |> trim(...)
        |> function (string $value) : string { return str_replace('.', ',', $value); };
    }

    public function addAmount(Amount $amount) : Amount {
        $this->amount += $amount->getAmount();
        return $this;
    }

    public function subtractAmount(Amount $amount) : void {
        $this->amount -= $amount->getAmount();
    }

    public function multiply(float $factor) : Amount {
        $this->amount *= $factor;
        return $this;
    }

    public function getFormattedAmount() : string {
        $value = number_format( round( $this->amount, 2 ), 2, ',', '.' );
        return $value
                |> trim(...)
                |> function (string $value) : string { return str_replace('.', ',', $value); };
    }
}
