<?php

if (! function_exists('translatedRoute')) {
    function translatedRoute($name, $parameters = [], $lang = null, $absolute = true)
    {
        if ($lang && in_array($lang, config('multilingualism.available_locales'))) {
            return app('url')->route($lang.'_'.$name, $parameters, $absolute);
        }

        $locale_prefix = config('multilingualism.locale_prefix');

        if (empty($locale_prefix)) {
            $locale_prefix = app()->getLocale();
        }

        if (empty($locale_prefix)) {
            $locale_prefix = config('app.fallback_locale');
        }

        return app('url')->route($locale_prefix.'_'.$name, $parameters, $absolute);
    }
}

if (! function_exists('daylightAsset')) {
    function daylightAsset(string $path): string
    {
        static $manifests = [];

        $reloadPath = public_path('vendor/daylight/hot');

        if (file_exists($reloadPath)) {
            return file_get_contents($reloadPath) . '/' . $path;
        }

        $manifestPath = public_path('vendor/daylight/build/manifest.json');

        if (! isset($manifests[$manifestPath])) {
            if (! file_exists($manifestPath)) {
                if (app()->runningInConsole()) {
                    return false;
                }

                throw new RuntimeException("Vite manifest not found at [$manifestPath].");
            }

            $manifests[$manifestPath] = json_decode(file_get_contents($manifestPath), true);
        }

        $manifest = $manifests[$manifestPath];

        if (! isset($manifest[$path])) {
            return asset("vendor/daylight/build/{$manifest[$path]['file']}");
        }

        return asset("vendor/daylight/build/{$manifest[$path]['file']}");
    }
}

if (! function_exists('formatPrice')) {

    function formatPrice(mixed $price, int $decimals = 2): string
    {
        if (app()->getLocale() == 'fr') {
            return number_format($price, $decimals, ',', ' ').' €';
        }

        if (in_array(app()->getLocale(), ['de', 'es'])) {
            return number_format($price, $decimals, ',', '.').' €';
        }

        return '€ '.number_format($price, $decimals, ',', '.');
    }
}
