<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\WithPagination;
use Spatie\Activitylog\Models\Activity;

class AuditLog extends Component
{
    use WithPagination;

    public string $search = '';
    public string $filterEvent = '';
    public string $filterCauser = '';

    protected $queryString = [
        'search' => ['except' => ''],
        'filterEvent' => ['except' => ''],
        'filterCauser' => ['except' => ''],
    ];

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function render()
    {
        $query = Activity::with('causer')->latest();

        if ($this->search) {
            $query->where(function ($q) {
                $q->where('description', 'like', "%{$this->search}%")
                    ->orWhere('subject_type', 'like', "%{$this->search}%")
                    ->orWhere('properties', 'like', "%{$this->search}%");
            });
        }

        if ($this->filterEvent) {
            $query->where('description', $this->filterEvent);
        }

        if ($this->filterCauser) {
            $query->where('causer_id', $this->filterCauser);
        }

        $events = Activity::select('description')->distinct()->pluck('description');
        $users = \App\Models\User::orderBy('name')->get();

        return view('livewire.audit-log', [
            'activities' => $query->paginate(30),
            'events' => $events,
            'users' => $users,
        ]);
    }
}
