<?php

declare(strict_types=1);

class Format
{
    public static function duration(int $seconds): string
    {
        $seconds = max(0, $seconds);
        $hours = intdiv($seconds, 3600);
        $minutes = intdiv($seconds % 3600, 60);
        $secs = $seconds % 60;

        if ($hours > 0) {
            return sprintf('%d:%02d:%02d', $hours, $minutes, $secs);
        }

        return sprintf('%02d:%02d', $minutes, $secs);
    }

    public static function number(int $n): string
    {
        if ($n >= 1000000) {
            return rtrim(rtrim(number_format($n / 1000000, 1, '.', ''), '0'), '.') . 'M';
        }

        if ($n >= 1000) {
            return rtrim(rtrim(number_format($n / 1000, 1, '.', ''), '0'), '.') . 'K';
        }

        return (string) $n;
    }

    public static function date(string $date): string
    {
        $ts = strtotime($date);
        return $ts !== false ? date('d/m/Y', $ts) : $date;
    }

    public static function timeAgo(string $date): string
    {
        $ts = strtotime($date);
        if ($ts === false) {
            return $date;
        }

        $diff = time() - $ts;
        if ($diff < 60) return __('time_seconds_ago');
        if ($diff < 3600) {
            $m = intdiv($diff, 60);
            return $m === 1 ? __('time_minute_ago') : __('time_minutes_ago', [':count' => $m]);
        }
        if ($diff < 86400) {
            $h = intdiv($diff, 3600);
            return $h === 1 ? __('time_hour_ago') : __('time_hours_ago', [':count' => $h]);
        }
        if ($diff < 2592000) {
            $d = intdiv($diff, 86400);
            return $d === 1 ? __('time_day_ago') : __('time_days_ago', [':count' => $d]);
        }
        if ($diff < 31536000) {
            $mo = intdiv($diff, 2592000);
            return $mo === 1 ? __('time_month_ago') : __('time_months_ago', [':count' => $mo]);
        }

        $y = intdiv($diff, 31536000);
        return $y === 1 ? __('time_year_ago') : __('time_years_ago', [':count' => $y]);
    }

    public static function fileSize(int $bytes): string
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $power = $bytes > 0 ? (int) floor(log($bytes, 1024)) : 0;
        $power = min($power, count($units) - 1);
        return round($bytes / pow(1024, $power), 2) . ' ' . $units[$power];
    }
}
