<?php

namespace App\Observers;

use App\Models\Rental\ActivityLog;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;

class ActivityLogObserver
{
    public function created($model)
    {
        $this->logActivity($model, 'created');
    }

    public function updated($model)
    {
        $this->logActivity($model, 'updated');
    }

    public function deleted($model)
    {
        $this->logActivity($model, 'deleted');
    }

    protected function logActivity($model, $action)
    {
        if (!Auth::check()) return;

        $oldData = $action === 'updated' ? array_intersect_key($model->getOriginal(), $model->getChanges()) : null;
        $newData = $action === 'updated' ? $model->getChanges() : ($action === 'created' ? $model->toArray() : null);

        ActivityLog::create([
            'user_id' => Auth::id(),
            'module' => class_basename($model),
            'action' => $action,
            'record_id' => $model->id,
            'old_data' => $oldData,
            'new_data' => $newData,
            'ip_address' => Request::ip(),
            'user_agent' => Request::userAgent(),
        ]);
    }
}
