<?php

namespace App\Models\Traits;

use Illuminate\Support\Facades\Auth;

/**
 * Trait HasAuditFields
 *
 * Automatically populates created_by and updated_by fields when a model is created or updated.
 * This provides an audit trail for all changes to models using this trait.
 *
 * Usage: Add `use HasAuditFields;` to your model class.
 * Requires: created_by and updated_by columns in the database table.
 */
trait HasAuditFields
{
    /**
     * Boot the trait
     */
    public static function bootHasAuditFields(): void
    {
        // Automatically set created_by when creating a new record
        static::creating(function ($model) {
            if (Auth::check() && empty($model->created_by)) {
                $model->created_by = Auth::id();
            }
        });

        // Automatically set updated_by when updating a record
        static::updating(function ($model) {
            if (Auth::check()) {
                $model->updated_by = Auth::id();
            }
        });
    }

    /**
     * Get the user who created this record
     */
    public function creator()
    {
        return $this->belongsTo(\App\Models\User::class, 'created_by');
    }

    /**
     * Get the user who last updated this record
     */
    public function updater()
    {
        return $this->belongsTo(\App\Models\User::class, 'updated_by');
    }

    /**
     * Get the creator's name
     */
    public function getCreatorNameAttribute(): ?string
    {
        return $this->creator?->name;
    }

    /**
     * Get the updater's name
     */
    public function getUpdaterNameAttribute(): ?string
    {
        return $this->updater?->name;
    }
}
