<?php

namespace App\Http\Livewire\Pages\Patch;

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

class PatchIndex extends Component
{
    use WithPagination;
    public $action  = 'list';
    public $searchBy, $editPid, $message, $keyword, $perPage = 10, $searchSelected = 'PID' , $selectedPatch = [] ;
    public $totalItems;
    protected $listeners = [ 'deleteItem', 'deleteSelected' ,'showpatchListForm'];
    public function mount()
    {
        $this->searchBy = [
            'PID' => 'PID',
            'PATCHNAME' => 'Patch Name',
            'PDESC' => 'Description',
            'MAJOR_VERSION' => 'Major Version',
            'Remark' => 'Remark'

        ];
    }
    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.patch.patch-index', compact('results'));
    }
    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 showpatchListForm()
    {
        $this->action = 'list';
    }

    public function showpatchAddForm()
    {
        $this->action = 'add';
    }

    public function showpatchEditForm($pid)
    {
        $this->editPid = $pid;
        $this->action = 'edit';
    }

    public function showDeleteModal($patchFileId)
    {
        $this->emit('showDeleteModal' ,$patchFileId);
    }

    public function deleteItem($pid) {
    
        TabPatchFile::where("ptid", $pid)->delete();
        ConfSmartUpdate::where("PID", $pid)->delete();
        $message = "Deleted Patch ID : " . json_encode($pid) . " Successfully";
        $this->message = $message;
    }
 
}
