<?php

namespace App\Traits;

use Illuminate\Support\Facades\Auth;
use App\Models\User;

trait SetCreatorAndUpdatorTrait
{
    /**
     * Boot the soft deleting trait for a model.
     *
     * @return void
     */
    public static function bootSetCreatorAndUpdatorTrait()
    {
        // When a transaction is created we want to
        // update the created_by field
        static::creating(function ($model) {
            if (Auth::check()) {
                $model->created_by = Auth::user()->id;
                $model->updated_by = Auth::user()->id;
            }
        });

        static::updating(function ($model) {
            if (Auth::check()) {
                $model->updated_by = Auth::user()->id;
            }
        });
    }

    /**
     * Get the creator's name.
     *
     * @return string
     */
    public function getCreatorNameAttribute()
    {
        if ($this->created_by) {
            $creator = User::find($this->created_by);
            return $creator ? $creator->name : '';
        }
        return '';
    }

    /**
     * Get the updater's name.
     *
     * @return string
     */
    public function getUpdaterNameAttribute()
    {
        if ($this->updated_by) {
            $updater = User::find($this->updated_by);
            return $updater ? $updater->name : '';
        }
        return '';
    }

    /**
     * Relationship with the creator user.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Relationship with the updater user.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function modifier()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }
}
