<?php

namespace App\Http\Livewire\Pages\SendPatch;

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

class SendMultiPatchList extends Component
{
    use WithPagination;
    public $action  = 'list';
    public $searchBy, $editPid, $message, $keyword, $perPage = 10, $searchSelected = 'PID';
    public $selectedPatches = [];
    public $insertedIds = [];
    public $totalItems;

    protected $listeners = ['deleteItem', 'deleteSelected', 'showMultiPatchList'];

    public function mount()
    {
        $this->searchBy = [
            'PID' => 'PID',
            'PATCHNAME' => 'Patch Name',
            'PDESC' => 'Description',
            'MAJOR_VERSION' => 'Major Version',
            'Remark' => 'Remark'

        ];
        $this->selectedPatches = [];
        // $this->dispatchBrowserEvent('grandchild-component-loaded');
    }
    public function updatedPerPage($value)
    {
        $this->adjustPageForNewPerPage();
    }

    public function adjustPageForNewPerPage()
    {
        $lastPage = ceil($this->totalItems / $this->perPage);
        if ($this->page > $lastPage) {
            $this->setPage($lastPage);
        }
    }
    public function search()
    {
        $this->resetPage();
    }

    public function showMultiPatchList()
    {
        $this->render();
    }

    public function loadPage($page)
    {
        $this->emit('menuChanged', $page);
    }
    public function render()
    {
        $query = ConfSmartUpdate::select('PID', 'PATCHNAME', 'PDESC', 'PDATE', 'PLEVEL', 'Remark', 'MAJOR_VERSION');

        if ($this->searchSelected && $this->keyword) {
            $query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
        }
        $query->orderBy('PID', 'DESC');
        $results = $query->paginate($this->perPage);
        $this->totalItems = $results->total();
        return view('livewire.pages.send-patch.send-multi-patch-list', [
            'results' => $results,
            'selectedPatches' => ConfSmartUpdate::whereIn('PID', $this->selectedPatches)->get()
        ]);
    }
}
