<?php
/**
 * Currency formatting helpers.
 *
 * @package Donatico\Helpers
 */

declare(strict_types=1);

namespace Donatico\Helpers;

/**
 * Static utility class for currency symbol lookup and amount formatting.
 * All amounts stored in the database are in the smallest currency unit (cents).
 */
class Currency {

	/**
	 * ISO code → currency symbol map.
	 *
	 * @var array<string, string>
	 */
	const SYMBOLS = array(
		'USD' => '$',
		'EUR' => '€',
		'GBP' => '£',
		'AUD' => 'A$',
		'CAD' => 'C$',
		'INR' => '₹',
		'BDT' => '৳',
	);

	/**
	 * Return the currency symbol for a given ISO code.
	 *
	 * @param string $currency Three-letter ISO code (case-insensitive).
	 * @return string Symbol, or '$' as a safe fallback.
	 */
	public static function getSymbol( string $currency ): string {
		return self::SYMBOLS[ strtoupper( $currency ) ] ?? '$';
	}

	/**
	 * Format an amount stored in cents as a human-readable string with symbol.
	 * Example: formatCents(2500, 'USD') → "$25.00"
	 *
	 * @param int    $amountCents
	 * @param string $currency
	 * @return string
	 */
	public static function formatCents( int $amountCents, string $currency ): string {
		$symbol = self::getSymbol( $currency );
		$amount = number_format( $amountCents / 100, 2 );
		return $symbol . $amount;
	}

	/**
	 * Convert a major-unit amount (dollars) to the smallest unit (cents).
	 * Uses round() to avoid floating-point truncation errors.
	 *
	 * @param float $major Amount in the major currency unit.
	 * @return int Amount in the smallest currency unit.
	 */
	public static function centsFromMajor( float $major ): int {
		return (int) round( $major * 100 );
	}

	/**
	 * Return a flat array of symbol data for JavaScript localisation.
	 *
	 * @return array<string, string>
	 */
	public static function symbolsForJs(): array {
		return self::SYMBOLS;
	}
}
