<?php

namespace App\Livewire\OPD;

use App\Models\OPD;
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', opdId: $id);
    }

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

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

    public function render()
    {
        $opd = OPD::query()
            ->when($this->search, function($query) {
                $query->where('nama_opd', 'like', '%'.$this->search.'%')
                    ->orWhere('kode_opd', 'like', '%'.$this->search.'%')
                    ->orWhere('kepala_opd', 'like', '%'.$this->search.'%');
            })
            ->latest()
            ->paginate(10);

        return view('livewire.o-p-d.index', [
            'opd' => $opd
        ]);
    }
}
