<?php

namespace App\Livewire;

use App\Models\Client;
use Livewire\Component;
use Livewire\Attributes\On;
use Livewire\WithPagination;

class ShowClient extends Component
{
    use WithPagination;
    public $filters = '';

    #[On('filters-added')]

    public function updatedFilters()
    {
        $this->resetPage();
    }

    #[On('client-deleted')]
    #[On('client-updated')]
    #[On('client-added')]
    public function refreshClients()
    {
        $this->resetPage();
    }

    public function render()
    {
        $query = Client::query();

        if (!empty($this->filters)) {
            $query->where(function ($q) {
                $q->where('name', 'LIKE', '%' . $this->filters . '%')
                    ->orWhere('legal_name', 'LIKE', '%' . $this->filters . '%')
                    ->orWhere('cnpj', 'LIKE', '%' . $this->filters . '%');
            });
        }

        return view('livewire.admin.show-client', [
            // Adicionando withView() para garantir que a template correta seja usada
            'clients' => $query->paginate(10),
        ]);
    }
}
