<?php

namespace App\Modules\Bookings;

use Illuminate\Support\Facades\Auth;
use App\Models\ValidationModel;
use App\Modules\Clients\Client;
use App\Modules\Clients\Customer;
use App\Modules\Clients\Site;
use App\Modules\Clients\SiteUser;
use App\Models\User;
use App\Modules\Bookings\Comment;

class Message extends ValidationModel
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'messages';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['client_id', 'client_type', 'site_user_id', 'assigned_to', 'contact_number', 'message', 'status', 'closed'];

    /**
     * Array of validation rules.
     *
     * @var  array
     */
    protected static $rules = [
        'client_id'   => 'required',
        'client_type' => 'required',
        'assigned_to' => 'required',
        'message'     => 'required',
    ];

    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    public static function boot()
    {
        parent::boot();

        // Set up morphMap for polymorphic relationships
        \Illuminate\Database\Eloquent\Relations\Relation::morphMap([
            'client' => Client::class,
            'customer' => Customer::class,
        ]);

        // When a transaction is created we want to
        // update the created_by field
        static::creating(function ($model) {
            $model->created_by = Auth::user()->id;
        });
    }

    /**
     * Get the client (polymorphic relationship).
     * This can be either a Client or Customer model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function client()
    {
        return $this->morphTo('client', 'client_type', 'client_id');
    }

    /**
     * Returns the user who created the comment.
     *
     * @return \User
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Returns the user the message is assigned to.
     *
     * @return \User
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'assigned_to');
    }

    /**
     * Returns the site model.
     *
     * @return App\Modules\Clients\Site
     */
    public function site()
    {
        return $this->belongsTo(Site::class, 'site_id');
    }

    /**
     * Returns the site user who is associated to this message.
     *
     * @return App\Modules\Clients\SiteUser
     */
    public function site_user()
    {
        return $this->belongsTo(SiteUser::class, 'site_user_id');
    }

    /**
     * Returns all the comments for a particular task.
     *
     * @return App\Modules\Bookings\Comment
     */
    public function comments()
    {
        return $this->hasMany(Comment::class, 'related_id')->where('related_type', '=', 'message');
    }
}
