<?php

namespace App\Models\Concerns;

trait HasTranslations
{
    public function translate(string $attribute, ?string $locale = null): mixed
    {
        return $this->translateValue($this->getAttribute($attribute), $locale);
    }

    protected function translateValue(mixed $value, ?string $locale = null): mixed
    {
        if (! is_array($value)) {
            return $value;
        }

        $locale ??= app()->getLocale();
        $fallback = config('app.fallback_locale', 'en');

        if (array_key_exists($locale, $value) || array_key_exists($fallback, $value)) {
            return $value[$locale] ?? $value[$fallback] ?? reset($value);
        }

        return array_map(fn (mixed $item) => is_array($item) ? $this->translateValue($item, $locale) : $item, $value);
    }
}