<?php

use App\Enums\VoucherType;
use Illuminate\Support\Number;
use Illuminate\Support\Str;

if (! function_exists('formatCurrencyNumber')) {
    /**
     * Format value as currency
     *
     * @param  string|null  $currency  Currency prefix (default: null)
     * @param  string  $locale  Locale for formatting (default: 'id_ID')
     */
    function formatCurrencyNumber(string|int|float|null $value = null, ?string $currency = null, string $locale = 'id_ID'): string
    {
        if ($value === null) {
            return '';
        }

        return $currency.Number::format($value, locale: $locale);
    }
}

if (! function_exists('parseRupiahToInt')) {
    /**
     * Strip currency format from string and return as integer
     */
    function parseRupiahToInt(?string $value = null): ?int
    {
        if ($value === null) {
            return null;
        }

        $cleaned = Str::of($value)
            ->replace('Rp', '')
            ->replace('.', '')
            ->replace(' ', '')
            ->__toString();

        return (int) $cleaned;
    }
}

if (! function_exists('formatPercentage')) {
    /**
     * Format value as percentage
     *
     * @param  int  $precision  Precision (default: 2)
     * @param  int  $maxPrecision  Max precision (default: 2)
     * @param  string  $locale  Locale for formatting (default: 'id_ID')
     */
    function formatPercentage(int|float $value, int $precision = 2, int $maxPrecision = 2, string $locale = 'id_ID'): string
    {
        return Number::percentage($value, $precision, $maxPrecision, $locale);
    }
}

if (! function_exists('formatDiscount')) {
    /**
     * Format discount based on voucher type (percentage or fixed amount)
     */
    function formatDiscount(int|float $amount, VoucherType $type, string $currency = 'Rp'): string
    {
        return $type === VoucherType::PERCENTAGE
            ? formatPercentage($amount)
            : formatCurrencyNumber($amount, $currency);
    }
}
