<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Translation extends Model
{
    use HasFactory;

    protected $fillable = ['locale', 'group', 'key', 'value'];

    /**
     * Get translation for a specific locale, group and key
     */
    public static function getTranslated($locale, $group, $key, $default = null)
    {
        $cacheKey = "translation.{$locale}.{$group}." . md5($key);
        
        return cache()->remember($cacheKey, 3600, function () use ($locale, $group, $key, $default) {
            $translation = static::where('locale', $locale)
                                ->where('group', $group)
                                ->where('key', $key)
                                ->first();
            
            return $translation ? $translation->value : ($default ?? $key);
        });
    }

    /**
     * Store or update translation
     */
    public static function setTranslated($locale, $group, $key, $value)
    {
        $translation = static::updateOrCreate(
            ['locale' => $locale, 'group' => $group, 'key' => $key],
            ['value' => $value]
        );
        
        // Clear cache
        cache()->forget("translation.{$locale}.{$group}." . md5($key));
        
        return $translation;
    }
}