<?php
namespace App\Support;
use InvalidArgumentException;
final class AtomicAmount {
 public static function fromDecimal(string $amount,int $decimals):string {
  if(!preg_match('/^(?:0|[1-9]\d*)(?:\.\d+)?$/',$amount)) throw new InvalidArgumentException('Invalid decimal amount.');
  [$whole,$fraction]=array_pad(explode('.',$amount,2),2,'');
  if(strlen($fraction)>$decimals) throw new InvalidArgumentException('Amount exceeds asset precision.');
  $atomic=ltrim($whole.str_pad($fraction,$decimals,'0'),'0'); return $atomic===''?'0':$atomic;
 }
 public static function toDecimal(string $atomic,int $decimals,bool $trim=false):string {
  if(!preg_match('/^\d+$/',$atomic)) throw new InvalidArgumentException('Invalid atomic amount.');
  $atomic=str_pad(ltrim($atomic,'0')?:'0',$decimals+1,'0',STR_PAD_LEFT);
  $whole=substr($atomic,0,-$decimals); $fraction=$decimals?substr($atomic,-$decimals):'';
  if($trim&&$fraction!=='') $fraction=rtrim($fraction,'0');
  return $fraction===''?$whole:$whole.'.'.$fraction;
 }
}
