<?php

namespace App\Livewire\Admin\Aktivitas;

use App\Models\User;
use Illuminate\Support\Carbon;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;
use Spatie\Activitylog\Models\Activity;

#[Layout('layouts.admin')]
#[Title('Aktivitas')]
class Index extends Component
{
    use WithPagination;

    // ── Filter & Search ──────────────────────────────────────────────────
    #[Url(as: 'user')]
    public string $filterUser = '';

    #[Url(as: 'modul')]
    public string $filterModul = ''; // log_name

    #[Url(as: 'tanggal')]
    public string $filterTanggal = '';

    public string $search = '';

    public int $perPage = 25;

    public function updatingFilterUser(): void    { $this->resetPage(); }
    public function updatingFilterModul(): void   { $this->resetPage(); }
    public function updatingFilterTanggal(): void { $this->resetPage(); }
    public function updatingSearch(): void        { $this->resetPage(); }
    public function updatingPerPage(): void       { $this->resetPage(); }

    public function resetFilters(): void
    {
        $this->reset(['filterUser', 'filterModul', 'filterTanggal', 'search']);
        $this->resetPage();
    }

    /**
     * Parsing sederhana nama browser dari User-Agent string,
     * tanpa dependency tambahan (mis. jenssegers/agent).
     */
    private function parseBrowser(?string $userAgent): string
    {
        if (! $userAgent) {
            return '—';
        }

        return match (true) {
            str_contains($userAgent, 'Edg/')      => 'Edge',
            str_contains($userAgent, 'OPR/')      => 'Opera',
            str_contains($userAgent, 'Chrome/')   => 'Chrome',
            str_contains($userAgent, 'Firefox/')  => 'Firefox',
            str_contains($userAgent, 'Safari/')   => 'Safari',
            default => 'Lainnya',
        };
    }

    public function render()
    {
        $activities = Activity::query()
            ->with('causer')
            ->when($this->filterUser, fn ($q) =>
                $q->where('causer_id', $this->filterUser))
            ->when($this->filterModul, fn ($q) =>
                $q->where('log_name', $this->filterModul))
            ->when($this->filterTanggal, fn ($q) =>
                $q->whereDate('created_at', $this->filterTanggal))
            ->when($this->search, fn ($q) =>
                $q->where('description', 'like', "%{$this->search}%"))
            ->latest()
            ->paginate($this->perPage);

        // Tambahkan IP & Browser hasil parsing ke setiap item
        // (tidak mengubah struktur Activity, hanya menambah atribut sementara untuk view).
        $activities->getCollection()->transform(function (Activity $activity) {
            $activity->ip_display      = $activity->properties->get('ip_address', '—');
            $activity->browser_display = $this->parseBrowser($activity->properties->get('user_agent'));
            return $activity;
        });

        $users   = User::role(['super_admin', 'admin'])->orderBy('name')->get();
        $modules = Activity::query()->whereNotNull('log_name')->distinct()->pluck('log_name')->sort()->values();

        return view('livewire.admin.aktivitas.index', compact('activities', 'users', 'modules'));
    }
}
