<?php

namespace App\Livewire\Pekerjaan;

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

class Index extends Component
{
    use WithPagination;

    public $search = '';

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

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

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

    public function handleSaved()
    {
        $this->dispatch('notify', [
            'type' => 'success',
            'message' => 'Data pekerjaan berhasil disimpan!'
        ]);
    }

    public function delete($id)
    {
        $pekerjaan = Pekerjaan::find($id);
        if ($pekerjaan) {
            $pekerjaan->tenagaAhli()->detach();
            $pekerjaan->delete();
            $this->dispatch('notify', [
                'type' => 'success',
                'message' => 'Data pekerjaan berhasil dihapus!'
            ]);
        }
    }

    public function render()
    {
        $pekerjaans = Pekerjaan::with(['penyedia', 'paketPekerjaan', 'tenagaAhli'])
            ->when($this->search, function ($query) {
                $query->where('nama', 'like', '%' . $this->search . '%')
                    ->orWhereHas('penyedia', function ($q) {
                        $q->where('nama_badan_usaha', 'like', '%' . $this->search . '%');
                    });
            })
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('livewire.pekerjaan.index', [
            'pekerjaans' => $pekerjaans
        ]);
    }
}
