<?php

namespace App\Models;

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

use App\Models\Admin;
use App\Models\Category;
use App\Models\Address;
use Illuminate\Support\Str;
use Modules\Faq\Entities\Faq;

// 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',
        'page_header','middle_content','country_id','admission_desc','city_desc','cost_of_living_desc','scholarship_desc',
        'visa_desc', 'course_overview','header_title','header_description','parent_category_id','created_at','robots',
        'imageAltText','imageTitle','relative_university','similar_countries', 'header_strip'
    ];

    // protected $appends = ['image_url', 'author', 'modified'];


    /**
     * 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['url'] = 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')->where('type', 'page');
    
    }

    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(PageComment::class, 'page_id', 'id')->where('status', 1)->whereNull('parent_id')->latest();
    }

    public function commentsCount()
    {
        return $this->hasMany(PageComment::class, 'page_id', 'id')->where('status', 1)->count();
    }


    public function faq()
    {
        return $this->hasMany(Faq::class, 'page_id', 'id')->where('category_id','48');
    }

    public function address()
    {
        return $this->hasMany(Address::class, 'page_id', 'id');
    }

//     public function commentsCount()
// {
//     return $this->hasMany(PageComment::class, 'page_id', 'id')
//                 ->whereNull('parent_id')
//                 ->latest()
//                 ->withCount('page_comments')
//                 ->count();
// }

}
