<?php

namespace Mtc\Plugins\MembersMessaging\Models;

use App\Casts\OptionalEncrypted;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Mtc\Core\AdminUser;
use Mtc\Modules\Members\Models\Member;
use Mtc\Plugins\MembersMessaging\Models\Thread;

class Message extends Eloquent
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'messenger_messages';

    /**
     * The relationships that should be touched on save.
     *
     * @var array
     */
    protected $touches = ['thread'];

    /**
     * The attributes that can be set with Mass Assignment.
     *
     * @var array
     */
    protected $fillable = [
        'id',
        'member_id',
        'admin_id',
        'thread_id',
        'text',
        'comment',
        'satisfactory',
        'private',
    ];

    protected $casts = [
        'text' => OptionalEncrypted::class,
    ];

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

    /**
     * User relationship.
     *
     * @return BelongsTo
     *
     * @codeCoverageIgnore
     */
    public function member()
    {
        return $this->belongsTo(Member::class, 'member_id');
    }

    public function admin_user()
    {
        return $this->belongsTo(AdminUser::class, 'admin_id');
    }


    /**
     * Get author of message
     *
     * @return string
     */
    public function authorName()
    {
        if ($this->admin_user) {
            return $this->admin_user->name;
        }

        if ($this->member) {
            return $this->member->fullname;
        }

        return 'Unknown Author';
    }

    public function authorType()
    {
        if ($this->admin_id > 0) {
            return 'admin';
        }

        return 'member';
    }
}
