<?php

namespace App\Components\Admin\Users;

use App\Models\User\Role;
use App\Models\User\User;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
use Livewire\WithPagination;

class UserIndex extends Component {
    use AuthorizesRequests, WithPagination;

    public int $perPage = 25;
    public string $search = '';
    public ?string $role = null;

    public function delete(HistoryService $historyService, int $userId): void {
        $user = User::findOrFail($userId);
        $this->authorize('delete', $user);

        $label = "{$user->name_first} {$user->name_last}";
        $user->delete();

        $historyService->add(
            auth()->user(),
            "Deleted user '{$label}'",
            ['target_user_id' => $user->id]
        );

        $this->dispatch('toast',
            title: 'Deleted',
            message: 'User has been removed.',
            type: 'success'
        );
    }

    public function render() {
        $users = User::query()
            ->with('roles')
            ->when($this->search, fn($q) => $q->where('name_first', 'like', "%{$this->search}%")
                ->orWhere('name_last', 'like', "%{$this->search}%")
                ->orWhere('email_address', 'like', "%{$this->search}%")
            )
            ->when($this->role, fn($q) => $q->whereHas('roles', fn($r) => $r->where('name', $this->role))
            )
            ->paginate($this->perPage);

        return view('components.admin.users.user-index', [
            'users' => $users,
            'roles' => Role::orderBy('name')->get()
        ]);
    }
}
