<?php
namespace PageVICO\Utils;

defined( 'ABSPATH' ) || exit;

class NumberFormatter {
	/**
	 * Format number to short format (K, M, B)
	 *
	 * @param int|float $number The number to format
	 * @param int       $precision The number of decimal places (default: 1)
	 * @return string Formatted number
	 */
	public static function formatShort( $number, $precision = 1 ) {

		// Check if conversion to K or M is enabled in settings
		// Check if short number format is enabled in settings
		$use_short_format = get_option( 'PageVICO_short_number', 1 );

		// If short format is disabled, return the number with standard formatting
		if ( ! $use_short_format ) {
			return number_format( $number );
		}
		if ( $number < 1000 ) {
			// Less than 1000, return as is
			return number_format( $number );
		}

		$units = array( '', 'K', 'M', 'B', 'T' );
		$pow   = floor( ( $number ? log( $number ) : 0 ) / log( 1000 ) );
		$pow   = min( $pow, count( $units ) - 1 );

		$number /= pow( 1000, $pow );

		// Remove unnecessary decimal places (e.g., 1.0K -> 1K)
		$formatted = rtrim( rtrim( number_format( $number, $precision ), '0' ), '.' );

		return $formatted . $units[ $pow ];
	}

	/**
	 * Format decimal number with specified precision
	 *
	 * @param float $number The number to format
	 * @param int   $precision The number of decimal places
	 * @return string Formatted number
	 */
	public static function formatDecimal( $number, $precision = 2 ) {
		return number_format( $number, $precision );
	}

	/**
	 * Format duration in seconds to human-readable format
	 *
	 * @param int $seconds Duration in seconds
	 * @return string Formatted duration (e.g., "2h 30m 15s")
	 */
	public static function formatDuration( $seconds ) {
		$seconds = (int) $seconds;

		if ( $seconds <= 0 ) {
			return '0s';
		}

		$hours = floor( $seconds / 3600 );
		$minutes = floor( ( $seconds % 3600 ) / 60 );
		$remainingSeconds = $seconds % 60;

		$parts = array();
		if ( $hours > 0 ) {
			$parts[] = "{$hours}h";
		}
		if ( $minutes > 0 ) {
			$parts[] = "{$minutes}m";
		}
		if ( $hours === 0 && $remainingSeconds > 0 ) {
			$parts[] = "{$remainingSeconds}s";
		}

		return implode( ' ', $parts );
	}

	/**
	 * Format number as percentage
	 *
	 * @param float $number The number to format (0-100)
	 * @param int   $precision The number of decimal places (default: 1)
	 * @return string Formatted percentage with % symbol
	 */
	public static function formatPercentage( $number, $precision = 1 ) {
		return number_format( $number, $precision ) . '%';
	}
}
