<?php

namespace Mtc\Plugins\MembersMessaging\Classes;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Mtc\Modules\Members\Models\Member;

class MessagesRead extends Eloquent
{

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'messenger_messages_read';

    /**
     * The attributes that can be set with Mass Assignment.
     *
     * @var array
     */
    protected $fillable = [
        'id',
        'member_id',
        'message_id',
        'thread_id',
        'read_at',
    ];

    public function markRead()
    {
        $this->read_at = Carbon::now();
        return $this->save();
    }

    /**
     * Thread relationship.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     *
     * @codeCoverageIgnore
     */
    public function thread()
    {
        return $this->belongsTo(Thread::class, 'thread_id', 'id');
    }

    public function message()
    {
        return $this->hasOne(Message::class, 'id', 'message_id');
    }

    /**
     * User relationship.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     *
     * @codeCoverageIgnore
     */
    public function user()
    {
        return $this->belongsTo(Member::class, 'member_id');
    }

    /**
     * Participants relationship.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     *
     * @codeCoverageIgnore
     */
    public function participants()
    {
        return $this->hasMany(Participant::class, 'thread_id', 'thread_id');
    }

    /**
     * Recipients of this message.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function recipients()
    {
        return $this->participants()->where('member_id', '!=', $this->member_id);
    }
}
