<?php

namespace Ignite\Core\Helpers;

class Amount
{
    /**
     * @var int|float|string
     */
    protected $value;

    /**
     * Currency constructor.
     *
     * @param $value
     */
    public function __construct($value)
    {
        $this->value = $value;
    }

    /**
     * Get the value formatted.
     *
     * @param int $decimals
     * @param int $default
     * @param int $rounding
     * @return string
     */
    public function format($decimals = 0, $default = 0, $rounding = PHP_ROUND_HALF_UP)
    {
        if (is_null($this->value) || trim($this->value) === '') {
            $this->value = $default;
        }

        $amount = $this->clean($this->value);

        if (is_null($rounding)) {
            $amount = round($amount, $decimals, $rounding);
        }

        return number_format(floatval($amount), $decimals);
    }

    /**
     * Clean the given value.
     *
     * @param int $value
     *
     * @return float
     */
    protected function clean($value)
    {
        return (float) preg_replace('/[,$]/', '', $value);
    }
}
