<?php

namespace AutoAdmin\Bundle\Core\Util;

class SizeConverter
{
    const KB = 1024;
    const MB = 1024 * self::KB;
    const GB = 1024 * self::MB;
    const TB = 1024 * self::GB;

    public function bytesToReadable(int $size): string
    {
        if ($size < self::KB) {
            return $size.' B';
        } elseif ($size < self::MB) {
            return round($size / self::KB, 2).' Ko';
        } elseif ($size < self::GB) {
            return round($size / self::MB, 2).' Mo';
        } elseif ($size < self::TB) {
            return round($size / self::GB, 2).' Go';
        } else {
            return round($size / self::TB, 2).' To';
        }
    }


    protected function convertReadableToBytes(string $config): int
    {
        $unit = strtolower(substr($config, -1));
        $size = floatval($config);
        if ($unit == 'k') {
            $size *= 1024;
        } elseif ($unit == 'm') {
            $size *= 1024;
            $size *= 1024;
        } elseif ($unit == 'g') {
            $size *= 1024;
            $size *= 1024;
            $size *= 1024;
        } elseif ($unit == 't') {
            $size *= 1024;
            $size *= 1024;
            $size *= 1024;
            $size *= 1024;
        }

        return (int)$size;
    }

    public function getMinUploadSizeAsBytes(): int
    {
        $sizes = array();
        $sizes[] = ini_get('upload_max_filesize');
        $sizes[] = ini_get('post_max_size');
        $sizes[] = ini_get('memory_limit');
        for ($x = 0; $x < count($sizes); $x++) {
            $sizes[$x] = $this->convertReadableToBytes($sizes[$x]);
        }

        return min($sizes);
    }
    public function getMinUploadSizeReadable(): string
    {
        return $this->bytesToReadable($this->getMinUploadSizeAsBytes());
    }
}