<?php
namespace BLR\Backline\Core;

if (!defined('ABSPATH')) {
    exit;
}

final class Money {
    public static function normalize_amount($value): string {
        $value = str_replace([',', '$', ' '], '', (string) $value);
        if ($value === '') {
            return '';
        }

        if (!is_numeric($value)) {
            return '';
        }

        return number_format((float) $value, 2, '.', '');
    }

    public static function signed_amount(string $type, $value): float {
        $amount = (float) self::normalize_amount($value);
        if (strcasecmp($type, 'Expense') === 0) {
            return -abs($amount);
        }

        return abs($amount);
    }

    public static function money_label($value, string $currency = 'USD'): string {
        $normalized = self::normalize_amount($value);
        if ($normalized === '') {
            return '—';
        }

        $currency = strtoupper(sanitize_key($currency ?: 'USD'));
        if ($currency === '') {
            $currency = 'USD';
        }

        return $currency . ' ' . number_format((float) $normalized, 2);
    }
}
