<?php
namespace App\Services;
use Brick\Math\BigDecimal;
use Brick\Math\RoundingMode;
final class MoneyMath {
 public function effectiveRate(string $rate,string $marginPercent):string{return BigDecimal::of($rate)->multipliedBy(BigDecimal::one()->minus(BigDecimal::of($marginPercent)->dividedBy(100,12,RoundingMode::HALF_DOWN)))->toScale(8,RoundingMode::HALF_DOWN)->__toString();}
 public function fee(int $amountMinor,int $flatMinor,string $percent):int{$pct=BigDecimal::of($amountMinor)->multipliedBy($percent)->dividedBy(100,0,RoundingMode::HALF_UP)->toInt();return $flatMinor+$pct;}
 public function payout(int $sendMinor,int $sendDecimals,int $receiveDecimals,string $effectiveRate):int{
  $sendMajor=BigDecimal::of($sendMinor)->dividedBy(BigDecimal::of(10)->power($sendDecimals),$sendDecimals+12,RoundingMode::UNNECESSARY);
  return $sendMajor->multipliedBy($effectiveRate)->multipliedBy(BigDecimal::of(10)->power($receiveDecimals))->toScale(0,RoundingMode::HALF_DOWN)->toInt();
 }
 public function format(int $minor,string $currency,int $decimals):array{$negative=$minor<0;$digits=(string)abs($minor);if($decimals>0){$digits=str_pad($digits,$decimals+1,'0',STR_PAD_LEFT);$whole=substr($digits,0,-$decimals);$fraction=substr($digits,-$decimals);}else{$whole=$digits;$fraction='';}$wholeWithSeparators=preg_replace('/\B(?=(\d{3})+(?!\d))/',',',$whole);$formatted=$currency.' '.($negative?'-':'').$wholeWithSeparators.($decimals>0?'.'.$fraction:'');return ['minor'=>$minor,'currency'=>$currency,'decimals'=>$decimals,'formatted'=>$formatted];}
}
