<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Casts\Attribute;

class Post extends Model
{
    use HasFactory;

    protected $fillable=['image','slug'];

    const FILE_PATH = '/admin/images/posts/';
    
    protected static function boot()
    {
        parent::boot();
        static::deleting(function($item){
            if(file_exists(self::FILE_PATH.$item->image)){
                unlink(self::FILE_PATH.$item->image);
            }
        });
    }

    public function translations()
    {
        return $this->hasMany(PostTranslation::class);
    }

    public function getTranslatedAttributes($localeId)
    {
        return $this->translations->where('localization_id', $localeId)->first();
    }


    protected function title(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => $this->translations->where('localization_id', session('locale_id'))->first()->title
        );
    }
}
