<?php

namespace App\Models;

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

class Amenity extends Model
{
    use HasFactory;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'amenities';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'icon',
        'is_active',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'is_active' => 'boolean',
    ];

    /**
     * Get the amenity type that owns this amenity.
     */
    public function type()
    {
        return $this->belongsTo(AmenityType::class, 'type_id');
    }

    /**
     * Get the locations that have this amenity.
     */
    public function locations()
    {
        return $this->belongsToMany(Location::class, 'location_amenities');
    }

    /**
     * دریافت نام ترجمه‌شده امکانات بر اساس زبان فعال
     * 
     * @param string $languageCode کد زبان (fa, en, ...)
     * @return string نام ترجمه‌شده
     */
    public function getTranslatedName($languageCode = 'fa')
    {
        // استفاده از کش برای بهبود عملکرد
        $cacheKey = "amenity_{$this->id}_name_{$languageCode}";
        
        return cache()->remember($cacheKey, now()->addHours(24), function () use ($languageCode) {
            // اولویت اول: ترجمه در جدول translations
            $translation = $this->translations()
                ->where('language_code', $languageCode)
                ->first();
            
            if ($translation && !empty($translation->name)) {
                return $translation->name;
            }
            
            // اولویت دوم: نام اصلی
            return $this->name;
        });
    }
}
