<?php

namespace App\Traits;

use App\Models\ActivityLog;

trait LogsActivity
{
    public static function bootLogsActivity()
    {
        // Log model events
        static::created(function ($model) {
            self::logActivity('created', $model);
        });

        static::updated(function ($model) {
            self::logActivity('updated', $model);
        });

        static::deleted(function ($model) {
            self::logActivity('deleted', $model);
        });
    }

    protected static function logActivity(string $action, $model)
    {
        ActivityLog::query()
            ->create([
                'user_id' => auth('web')->id(),
                'action' => $action,
                'model_type' => get_class($model),
                'model_id' => $model->id,
                'old_values' => $action === 'updated' ? json_encode($model->getOriginal()) : null,
                'new_values' => $action !== 'deleted' ? json_encode($model->getAttributes()) : null,
                'ip_address' => request()->ip(),
                'user_agent' => request()->userAgent()
            ]);
    }
}
