<?php

namespace App\Modules\Blog\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'status',
        'publish_date',
        'slug',
        'page_header',
        'page_description',
        'page_og_image',
        'author',
        'content_body',
        'tag_ids',
        'category_id',
    ];

    protected $casts = [
        'page_og_image' => 'array', // Преобразование JSON в массив
        'content_body' => 'array', // Преобразование JSON в массив
        'tag_ids' => 'array', // Преобразование JSON в массив
        'publish_date' => 'datetime',
    ];

//    public function category()
//    {
//        return $this->belongsTo(Category::class);
//    }


    /**
     * Получить связанные теги через Query::with()
     */
    public function getTagsAttribute(): array|\Illuminate\Support\Collection
    {
        if (is_array($this->tag_ids)) {
            $tags = Tag::whereIn('id', $this->tag_ids)->get();
            $tag_ru = [];
            $tag_en = [];
            foreach ($tags as $tag) {
                $tag_json = $tag->name;
                $tag_json = json_decode($tag_json);

                $tag_ru[] = ['id' => $tag->id , 'name' => $tag_json->ru];
                $tag_en[] = ['id' => $tag->id , 'name' => $tag_json->en];
            }

            return
                [
                    'en' => $tag_en,
                    'ru' => $tag_ru,
                ];
        }
        return collect();
    }

}
