<?php

namespace App\Traits;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;

trait TrackedModel {
    protected static function bootTrackedModel() {
        static::created(function (Model $model) {
            static::logChange($model, 'created');
        });

        static::updated(function (Model $model) {
            static::logChange($model, 'updated');
        });

        static::deleted(function (Model $model) {
            static::logChange($model, 'deleted');
        });
    }

    protected static function logChange(Model $model, string $action) {
        $changes = $action === 'updated' 
            ? [
                'old' => $model->getOriginal(),
                'new' => $model->getDirty()
              ]
            : $model->getAttributes();

        DB::table('model_history')->insert([
            'model_type' => get_class($model),
            'model_id' => $model->getKey(),
            'user_id' => Auth::check() ? Auth::id() : null,
            'action' => $action,
            'changes' => json_encode($changes),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}