<?php

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

if (! function_exists('currency')) {
    function currency(?string $value = null, ?string $currency = null, ?string $locale = 'id_ID'): string
    {
        if ($value === null) {
            return '';
        }

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

if (! function_exists('replaceCurrency')) {
    function replaceCurrency(?string $value = null)
    {
        if ($value === null) {
            return null;
        }

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

        return (int) $cleaned;
    }
}

if (! function_exists('percentage')) {
    function percentage(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')) {
    function formatDiscount($amount, VoucherType $type, string $currency = 'Rp'): string
    {
        return $type === VoucherType::PERCENTAGE
            ? percentage($amount)
            : currency($amount, $currency);
    }
}

if (! function_exists('generateReferralCode')) {
    function generateReferralCode(string $username, int $unique): string
    {
        $prefix = Str::substr($username, 0, 6);
        $year = date('y');

        return Str::upper($prefix).$year.$unique;
    }
}

if (! function_exists('sanitizeIntegers')) {
    function sanitizeIntegers(array $data, array $integerKeys = []): array
    {
        foreach ($data as $key => $value) {
            if (empty($integerKeys) || in_array($key, $integerKeys)) {
                if ($value === '' || $value === null) {
                    $data[$key] = 0;
                }
            }
        }

        return $data;
    }
}

if (! function_exists('formatPhoneNumber')) {
    function formatPhoneNumber(string $number, string $prefix = '+62', bool $useDash = false): string
    {
        $clean = preg_replace('/\D+/', '', $number);

        $clean = preg_replace('/^(0|62)/', '', $clean);

        $formatted = $prefix.$clean;

        if ($useDash) {
            $formatted = preg_replace('/(\d{3})(\d{3,4})(\d{3,4})(\d+)?/', $prefix.'-$1-$2-$3$4', $formatted);
        }

        return $formatted;
    }
}
