<?php

namespace LoftyIDX\includes\common;

defined('ABSPATH') || exit;

class LoftyIDXNumberFormatter
{
    public const NUMBER_UNITS = ['', 'K', 'M'];

    public static function numberFormat($num, $units, $fixed, $prefix = '')
    {
        //  use  is_numeric()  Check if a variable is a number or a string of numbers
        if (!is_numeric($num)) {
            return '';
        }

        $num = floatval($num);
        $fixed = intval($fixed);
        if ($units) {
            if (is_nan($fixed)) {
                $fixed = 1;
            }
            $idx = intval((strlen(strval(intval($num))) - 1) / 3);
            $maxIdx = count(self::NUMBER_UNITS) - 1;
            if ($idx >= $maxIdx) {
                $idx = $maxIdx;
                $num = (string)($num / pow(1000, $idx));
                $num = number_format($num, $fixed, '.', ',');
            } else {
                $num = (string)($num / pow(1000, $idx));
                $num = number_format($num, $fixed, '.', ',');
                if ($num >= 1000) {
                    $num = (string)($num / 1000);
                    $num = number_format($num, $fixed, '.', ',');
                    $idx += 1;
                }
            }
            $num .= self::NUMBER_UNITS[$idx];
        } elseif (!is_nan($fixed)) {
            $num = number_format($num, $fixed, '.', ',');
        }
        return $prefix .  preg_replace('/(\.0+)$/', '', $num);
    }
}
