<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Topic extends Model
{
    protected $table = 'topics';

    protected $fillable = [
        'id', 'code', 'title', 'thumbnail', 'author', 'rank_id', 'category_id', 'total_comment',
        'number_of_views', 'seo_robots', 'seo_title', 'seo_description', 'seo_keywords',
        'is_allow_comment', 'is_activated', 'is_deleted', 'created_at', 'updated_at'
    ];

    public function scopeIsDeleted($query)
    {
        return $query->where('is_deleted', true);
    }

    public function scopeNotDeleted($query)
    {
        return $query->where('is_deleted', false);
    }

    public function scopeActivated($query)
    {
        return $query->where('is_activated', true);
    }

    public function scopeNotActivated($query)
    {
        return $query->where('is_activated', false);
    }

    public function scopePublished($query)
    {
        return $query->where('is_deleted', false)->where('is_activated', true);
    }

    public function keyword_list()
    {
        return $this->hasMany(TopicKeyword::class, 'topic_id', 'id')->with('keyword')->select('id', 'topic_id', 'keyword_id');
    }

    public function rank()
    {
        return $this->belongsTo(Rank::class, 'rank_id', 'id');
    }

    public function comment()
    {
        return $this->hasMany(Comment::class, 'topic_id', 'id')->with('detail')->where('is_deleted', false)->where('is_activated', true)->where('parent_id', 0)->orderBy('created_at');
    }

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

    public function firstComment()
    {
        return $this->hasOne(Comment::class, 'topic_id', 'id')->with('detail')->where('is_deleted', false)->where('is_activated', true)->where('parent_id', 0)->orderBy('id')->limit(1);
    }
}
