<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class ActivityLog extends Model
{
    protected $fillable = [
        'user_id','client_user_id','module','action',
        'subject_type','subject_id','description',
        'old_values','new_values','ip_address','user_agent'
    ];
    protected $casts = ['old_values'=>'array','new_values'=>'array'];

    public function user() { return $this->belongsTo(User::class); }

    public static function log(
        string $module,
        string $action,
        string $description,
        $subject = null,
        array $old = [],
        array $new = []
    ): void {
        try {
            self::create([
                'user_id'      => auth()->id(),
                'module'       => $module,
                'action'       => $action,
                'subject_type' => $subject ? get_class($subject) : null,
                'subject_id'   => $subject ? $subject->id : null,
                'description'  => $description,
                'old_values'   => $old ?: null,
                'new_values'   => $new ?: null,
                'ip_address'   => request()->ip(),
                'user_agent'   => request()->userAgent(),
            ]);
        } catch (\Exception $e) {
            // jangan crash jika log gagal
        }
    }
}
