<?php

namespace App\Models\Forums;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;


class ForumThread extends Model
{

    use SoftDeletes;

    /**
     * Don't auto-apply mass assignment protection.
     *
     * @var array
     */
    protected $guarded = [];

    // I like to explicitly define tables
    protected $table = 'forum_threads';

    // also fillable
    protected $fillable = [
        'user_id',
        'forum_channels_id',
        'title',
        'body'
    ];

    // the thread path
    public function path()
    {
        if(isset($this->channel->lab_id)){
            return route('frontend.lab.forum.thread', [$this->channel->lab_id, $this->id]);
           // return \url("lab/{$this->channel->lab_id}/forum/threads/") . '/' . $this->id;
        }else {
            return \url('/forum/threads/') . '/' . $this->id;
        }
        //return "/threads/{$this->channel->slug}/{$this->id}";
    }

    // the user that created this thread
    public function user()
    {
        return $this->hasOne('App\Models\Auth\User', 'id', 'user_id');
    }

    // the replies to this thread
    public function replies()
    {
        return $this->hasMany('App\Models\Forums\ForumReply', 'thread_id', 'id');
    }

    // the channel(s)/topics this thread belongs to
    public function channel()
    {
       // return $this->belongsTo('App\Models\Forums\ForumChannel', 'forum_channels_id', 'id');
        return $this->hasOne('\App\Models\Forums\ForumChannel', 'id', 'forum_channels_id');
//        return $this->belongsToMany('App\Models\Forums\ForumChannel', 'forum_channels_forum_threads', 'forum_threads_id', 'forum_channels_id')->withPivot('forum_channels_id');
    }

    // the channel(s)/topics this thread belongs to
    public function tags()
    {
        return $this->belongsToMany('App\Models\Tag', 'forum_threads_tags', 'tag_id', 'forum_thread_id');
    }

    // add a reply. Should this be in the controller?
    public function addReply($forumReply)
    {
        $this->replies()->create($forumReply);
    }

    // filter by tags
    public function scopeWithTags($query, $tags)
    {
        return $query->whereHas('tags', function($q) use ($tags){
            $q->whereIn('tags.id',$tags);
        });
    }
    // Get channels for a given lab
    public function scopeInLabForum($query, $lab_id)
    {
        return $query->whereHas('channel', function($q) use ($lab_id){
            $q->where('lab_id',$lab_id);
        });
    }

    // Get threads *not* in a lab
    public function scopeNotInLabForum($query)
    {
        return $query->whereHas('channel', function($q) {
            $q->whereNull('lab_id');
        });
    }

    //public function scopeSearch
}
