<?php

namespace App\Models;

use App\Models\ValidationModel;
use App\Models\User;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['related_id', 'related_type', 'old_user', 'new_user', 'changed_by'];

    /**
     * Array of validation rules.
     *
     * @var  array
     */
    protected static $rules = [
        'related_id'   => 'required',
        'related_type' => 'required',
        // 'old_user'     => 'required',
        'new_user'     => 'required',
    ];

    /**
     * Insert the validation checks on the model.
     * The model only gets created if the validation checks pass.
     *
     * @var void
     */
    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->changed_by = getAuthUserId();
        });
    }

    /**
     * Returns all the users changes for tasks.
     */
    public function scopeTasks($query)
    {
        return $query->where('related_type', 'task');
    }

    /**
     * Returns the old user.
     *
     * @return \User
     */
    public function old_user()
    {
        return $this->belongsTo(User::class, 'old_user');
    }

    /**
     * Returns the new user.
     *
     * @return \User
     */
    public function new_user()
    {
        return $this->belongsTo(User::class, 'new_user');
    }

    /**
     * Returns the user who made the change.
     *
     * @return \User
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'changed_by');
    }
}
