<?php
namespace App\Livewire\Assets;

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

class AssetTable extends Component
{
    use WithPagination;

    public string $search       = '';
    public string $filterStatus = '';
    public string $filterCat    = '';
    public string $filterDept   = '';
    public int    $perPage      = 20;

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

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

    public function render()
    {
        $assets = Asset::with(['category','model','assignedUser','department'])
            ->when($this->search, fn($q) => $q->where(function($q) {
                $q->where('code', 'like', "%{$this->search}%")
                  ->orWhere('name', 'like', "%{$this->search}%")
                  ->orWhere('serial_number', 'like', "%{$this->search}%")
                  ->orWhereHas('assignedUser', fn($u) => $u->where('name','like',"%{$this->search}%"));
            }))
            ->when($this->filterStatus, fn($q) => $q->where('status', $this->filterStatus))
            ->when($this->filterCat,    fn($q) => $q->where('category_id', $this->filterCat))
            ->when($this->filterDept,   fn($q) => $q->where('department_id', $this->filterDept))
            ->orderBy('code')
            ->paginate($this->perPage);

        return view('livewire.assets.asset-table', compact('assets'));
    }
}
