<?php

namespace App\Traits;

use App\ActivityLog;
use Illuminate\Support\Facades\Auth;

trait HasActivityLogging
{
    public static function bootHasActivityLogging(): void
    {
        static::updated(function ($model) {
            $watch = property_exists($model, 'activityLogWatch') ? (array) $model->activityLogWatch : [];
            if (empty($watch)) return;

            foreach ($watch as $field) {
                if (method_exists($model, 'wasChanged') && $model->wasChanged($field)) {
                    $model->activityLogs()->create([
                        'user_id' => Auth::id(),              // who did it (null = system)
                        'action'  => 'field_changed',
                        'field'   => $field,
                        'from'    => (string) $model->getOriginal($field),
                        'to'      => (string) $model->{$field},
                        'meta'    => null,
                    ]);
                }
            }
        });
    }

    public function activityLogs()
    {
        return $this->morphMany(ActivityLog::class, 'loggable')->latest();
    }

    // Optional helper to add custom notes/reasons
    public function logActivity(string $action, array $attributes = [])
    {
        return $this->activityLogs()->create([
            'user_id' => auth()->id(),
            'action'  => $action,
            'field'   => $attributes['field'] ?? null,
            'from'    => $attributes['from'] ?? null,
            'to'      => $attributes['to'] ?? null,
            'meta'    => $attributes['meta'] ?? null,
        ]);
    }
}
