<?php

namespace App\Livewire;

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

class ActivityLogs extends Component
{
    use WithPagination;

    #[Url(except: '')]
    public string $search = '';

    #[Url(except: '')]
    public string $logName = '';

    #[Url(except: '')]
    public string $event = '';

    #[Url(except: '')]
    public string $dateFrom = '';

    #[Url(except: '')]
    public string $dateTo = '';

    #[Url(except: '')]
    public string $causerId = '';

    public function updating(): void { $this->resetPage(); }

    public function clearFilters(): void
    {
        $this->reset('search', 'logName', 'event', 'dateFrom', 'dateTo', 'causerId');
        $this->resetPage();
    }

    public function render()
    {
        $logs = Activity::query()
            ->with(['causer'])
            ->when($this->search, fn($q) => $q
                ->where('description', 'like', "%{$this->search}%")
                ->orWhere('subject_type',  'like', "%{$this->search}%")
                ->orWhere('log_name',      'like', "%{$this->search}%")
            )
            ->when($this->logName,  fn($q) => $q->where('log_name', $this->logName))
            ->when($this->event,    fn($q) => $q->where('event',    $this->event))
            ->when($this->causerId, fn($q) => $q->where('causer_id', $this->causerId))
            ->when($this->dateFrom, fn($q) => $q->whereDate('created_at', '>=', $this->dateFrom))
            ->when($this->dateTo,   fn($q) => $q->whereDate('created_at', '<=', $this->dateTo))
            ->latest()
            ->paginate(50);

        $logNames = Activity::distinct()->orderBy('log_name')->pluck('log_name')->filter()->values();
        $events   = Activity::distinct()->orderBy('event')->pluck('event')->filter()->values();

        $hasFilters = $this->logName || $this->event || $this->dateFrom || $this->dateTo || $this->causerId;

        return view('livewire.activity-logs', compact('logs', 'logNames', 'events', 'hasFilters'));
    }
}
