<?php

namespace App\Models;

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

use App\Models\Admin;
use App\Models\Category;
use Illuminate\Support\Str;
// use Modules\Blog\Entities\PostCategory;
// use Modules\Blog\Entities\PostComment;

class Page extends Model
{
    use HasFactory;


    protected $fillable = [
        'category_id', 'author_id', 'title', 'slug', 'image', 'short_description', 'description', 'status',
        'url','tag_id','meta_description','meta_title','display_date','created_date','modified_by','meta_keywords','fields'
    ];

    protected $appends = ['image_url'];


    /**
     * Scope Define => published
     */
    public function scopePublished($query)
    {
        return $query->where('status', 'published');
    }

    /**
     * Scope Define => Draft
     */
    public function scopeDraft($query)
    {
        return $query->where('status', 'draft');
    }

    public function setTitleAttribute($value)
    {
        $this->attributes['title'] = $value;
        $this->attributes['slug'] = Str::slug($value);
    }

    public function getImageUrlAttribute()
    {
        if (is_null($this->image)) {
            return asset('backend/image/default-post.png');
        }

        return asset($this->image);
    }

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }

    public function author()
    {
        return $this->belongsTo(Admin::class, 'author_id');
    }

    public function modified()
    {
        return $this->belongsTo(Admin::class, 'modified_by');
    }

    public function comments()
    {
        return $this->hasMany(\Modules\Blog\Entities\PostComment::class, 'post_id', 'id')->whereNull('parent_id')->latest();
    }

    public function commentsCount()
    {
        return $this->hasMany(\Modules\Blog\Entities\PostComment::class, 'post_id', 'id')->count();
    }
}
