<?php

use Livewire\Component;
use App\Models\User;
use Spatie\Permission\Models\Role;

return new class extends Component
{
    public string $search = '';
    public string $roleFilter = '';

    public function deleteUser(int $id): void
    {
        $user = User::findOrFail($id);

        // Prevent deleting your own account or another superadmin
        if ($user->id === auth()->id()) {
            session()->flash('error', 'You cannot delete your own account.');
            return;
        }

        if ($user->hasRole('superadmin')) {
            session()->flash('error', 'Cannot delete a superadmin account.');
            return;
        }

        $user->delete();
        session()->flash('success', 'User deleted successfully.');
    }

    public function render()
    {
        return $this->view()->layout('layouts::auth');
    }

    public function with(): array
    {
        $query = User::with('roles')
            ->when($this->search, fn($q) => $q->where(function ($q) {
                $q->where('name', 'like', '%' . $this->search . '%')
                  ->orWhere('email', 'like', '%' . $this->search . '%');
            }))
            ->when($this->roleFilter, fn($q) => $q->whereHas('roles', fn($q) => $q->where('name', $this->roleFilter)))
            ->latest();

        return [
            'users' => $query->paginate(15),
            'roles'  => Role::orderBy('name')->pluck('name'),
        ];
    }

    protected function view($data = [])
    {
        return app('view')->file('D:\02-my freelance\00-DR_Padhi\DR_PADHI\storage\framework/views/livewire/views/16b7ce05.blade.php', $data);
    }
};
