<?php
namespace App\Livewire\Users;

use App\Models\User;
use Livewire\Component;
use Livewire\WithPagination;

class UserTable extends Component
{
    use WithPagination;

    public string $search = '';
    public string $filterRole = '';
    public string $filterDept = '';
    public string $filterStatus = '';
    public int $perPage = 15;

    protected $queryString = ['search', 'filterRole', 'filterDept', 'filterStatus'];

    public function updatingSearch() { $this->resetPage(); }
    public function updatingFilterRole() { $this->resetPage(); }
    public function updatingFilterDept() { $this->resetPage(); }
    public function updatingFilterStatus() { $this->resetPage(); }

    public function toggleStatus(int $userId) {
        abort_unless(auth()->user()->can('users.edit'), 403);
        $user = User::findOrFail($userId);
        if ($user->id === auth()->id()) return;
        $user->update(['is_active' => !$user->is_active]);
        $this->dispatch('notify', type: 'success', message: 'Estado actualizado.');
    }

    public function render() {
        $users = User::with(['roles', 'department'])
            ->when($this->search, fn($q) => $q->where(function($q) {
                $q->where('name', 'like', "%{$this->search}%")
                  ->orWhere('email', 'like', "%{$this->search}%")
                  ->orWhere('position', 'like', "%{$this->search}%");
            }))
            ->when($this->filterRole, fn($q) => $q->whereHas('roles', fn($r) => $r->where('name', $this->filterRole)))
            ->when($this->filterDept, fn($q) => $q->where('department_id', $this->filterDept))
            ->when($this->filterStatus !== '', fn($q) => $q->where('is_active', $this->filterStatus === '1'))
            ->orderBy('name')
            ->paginate($this->perPage);

        return view('livewire.users.user-table', compact('users'));
    }
}
