<?php

namespace Mamad\Article\Models;


use Mamad\Comment\Models\Comment;
use Mamad\Media\Models\Media;
use Mamad\Media\Service\MediaService;
use Mamad\PostMeta\Models\Post_meta;
use Mamad\Tag\Models\Tag;
use Illuminate\Database\Eloquent\Model;
use Mamad\Category\Models\Category;
use Mehrab\User\Models\User;
use Spatie\Permission\Models\Role;

class Article extends Model
{
    protected $table="articles";
    protected $fillable=["title","post_excerpt","content","media_id","user_id","slug","status"];

    public function category()
    {
        return $this->morphToMany(Category::class, 'categoryable');
    }
public function tags()
    {
        return $this->morphToMany(Tag::class, 'tagables');
    }
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function media()
    {
        return $this->belongsTo(Media::class);
    }

    public function post_meta(){
        return $this->morphMany(Post_meta::class, 'post_metaable');
    }

    public function getPostMetaArrayAttribute(){
        return $this->post_meta->pluck("meta_value","meta_key");
    }

    public function comments()
    {
        return $this->morphMany(Comment::class,"commentable","comment_able_type","comment_able_id");
    }

    public function getSmallImage()
    {
        $file=$this->media->files["original"];
        if(isset($this->media->files["100"])) $file=$this->media->files["100"];

        return store_image_link().'/'.$file;
    }

    public function getUrlAttribute()
    {
        return route("article.index",["slug"=>$this->slug]);
    }

    public function getCommentCountAttribute(){
        if($this->comments){
            return count($this->comments);
        }
        return 0;
    }
    public function getCatDataAttribute(){
        if($category=$this->category()->where("parent","!=",0)->first()){

            return [
                "parent" => [
                    "title"=>$category->name,
                    "url"=>$category->url,
                ],

            ];
        }
    }

}
