<?php

namespace App\Components\Report;

use App\Models\Claim\Claim;
use App\Models\Client\Client;
use App\Models\History;
use App\Models\User\User;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
use Livewire\WithPagination;

class LatestActionsReport extends Component {
    use AuthorizesRequests, WithPagination;

    public int $perPage = 50;
    public string $search = '';
    public ?int $userId = null;

    public function mount(): void {
        $this->authorize('reports.latest-actions.view');
    }

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

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

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

    public function render() {
        $entries = History::query()
            ->whereIn('owner_type', [Client::class, Claim::class])
            ->with([
                'user',
                'owner' => fn($morphTo) => $morphTo->morphWith([
                    Claim::class => ['client'],
                ]),
            ])
            ->when($this->search, fn($q) => $q->where('action', 'like', "%{$this->search}%"))
            ->when($this->userId, fn($q) => $q->where('user_id', $this->userId))
            ->latest('created_at')
            ->paginate($this->perPage);

        return view('components.report.latest-actions-report', [
            'entries' => $entries,
            'users'   => User::orderBy('name_first')->get(),
        ]);
    }
}
