<?php

namespace App\Livewire\TenagaAhli;

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

class Index extends Component
{
    use WithPagination;

    public $search = '';

    public function createNew()
    {
        $this->dispatch('form-show');
    }

    public function edit($id)
    {
        $this->dispatch('form-show', tenagaAhliId: $id);
    }

    #[On('item-saved')]
    public function handleSaved()
    {
        $this->dispatch('notify', title: 'Sukses!', message: 'Data tenaga ahli berhasil disimpan.');
    }

    public function delete($id)
    {
        TenagaAhli::find($id)->delete();
        $this->dispatch('notify', title: 'Sukses!', message: 'Data tenaga ahli berhasil dihapus.');
    }

    public function render()
    {
        $tenagaAhli = TenagaAhli::query()
            ->when($this->search, function($query) {
                $query->where('nama', 'like', '%'.$this->search.'%')
                    ->orWhere('alamat', 'like', '%'.$this->search.'%');
            })
            ->paginate(10);

        return view('livewire.tenaga-ahli.index', [
            'tenagaAhli' => $tenagaAhli
        ]);
    }
}
