<?php
namespace App\Traits;
use App\Models\AuditLog;
use Illuminate\Support\Facades\Auth;
trait Auditable {
    public static function bootAuditable(): void {
        static::created(fn($m) => $m->writeAudit('created', null, $m->auditSnapshot()));
        static::updated(fn($m) => $m->writeAudit('updated', $m->auditSnapshot($m->getOriginal()), $m->auditSnapshot()));
        static::deleted(fn($m) => $m->writeAudit('deleted', $m->auditSnapshot(), null));
    }
    protected function auditSnapshot($attrs = null): array {
        $attrs ??= $this->attributesToArray();
        unset($attrs['password'], $attrs['remember_token']);
        return $attrs;
    }
    protected function writeAudit($action, $old, $new): void {
        try {
            AuditLog::create(['user_id' => Auth::id(), 'action' => $action,
                'auditable_type' => static::class, 'auditable_id' => $this->getKey(),
                'old_values' => $old, 'new_values' => $new,
                'ip' => app()->runningInConsole() ? 'console' : request()->ip(),
                'user_agent' => app()->runningInConsole() ? 'console' : substr((string) request()->userAgent(), 0, 500)]);
        } catch (\Throwable $e) {}
    }
}
