<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;

trait Auditable
{
    public static function bootAuditable()
    {
        static::creating(function ($model) {
            if (Auth::check()) {
                $model->created_by = Auth::id();
                $model->updated_by = Auth::id();
            }
        });

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

        // Check if the model uses SoftDeletes before adding the deleting event
        if (in_array(SoftDeletes::class, class_uses(self::class))) {
            static::deleting(function ($model) {
                if (Auth::check() && ! $model->isForceDeleting()) {
                    $model->deleted_by = Auth::id();
                    $model->save();
                }
            });

            static::restoring(function ($model) {
                // Optional: Clear deleted_by when restoring
                $model->deleted_by = null;
            });
        }
    }
}
