<?php

namespace App\Livewire\PaketPekerjaan;

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

    public function showDetail($id)
    {
        $this->dispatch('detail-show', paketPekerjaanId: $id);
    }

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

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

    public function render()
    {
        $paketPekerjaans = PaketPekerjaan::with(['pekerjaans', 'opd', 'badanUsaha', 'tenagaAhli'])
            ->when($this->search, function ($query) {
                $query->where('nama_paket', 'like', '%' . $this->search . '%')
                    ->orWhere('kode_paket', 'like', '%' . $this->search . '%')
                    ->orWhereHas('opd', function ($q) {
                        $q->where('nama_opd', 'like', '%' . $this->search . '%')
                          ->orWhere('kode_opd', 'like', '%' . $this->search . '%');
                    })
                    ->orWhereHas('badanUsaha', function ($q) {
                        $q->where('nama_badan_usaha', 'like', '%' . $this->search . '%');
                    });
            })
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('livewire.paket-pekerjaan.index', [
            'paketPekerjaans' => $paketPekerjaans,
            'statusList' => PaketPekerjaan::STATUS_LIST
        ]);
    }
}
