<?php

namespace App\Http\Livewire\Pages\SendPatch;

use App\Models\ConfServerPendding;
use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Support\Facades\DB;
use App\Models\ConfSmartUpdate;
use Illuminate\Support\Facades\Cache;

class SendPatchIndex extends Component
{
    use WithPagination;

    public $searchBy;
    public $editPid;
    public $message;
    public $keyword;
    public $perPage = 10;
    public $searchSelected = 'PID';
    public $action = 'list';
    public $totalItems;


    protected $listeners = ['showGroupList', 'deleteItem', 'deleteSelected'];
    public function mount()
    {
        $this->searchBy = [
            'PID' => 'PID',
            'PATCHNAME' => 'Patch Name',
            'PDESC' => 'Description',
            'MAJOR_VERSION' => 'Major Version',
            'Remark' => 'Remark'

        ];
        $this->message = session('message');
    }
    public function updatedPerPage($value)
    {
        $this->adjustPageForNewPerPage();
    }

    public function adjustPageForNewPerPage()
    {
        $lastPage = ceil($this->totalItems / $this->perPage);
        if ($this->page > $lastPage) {
            $this->setPage($lastPage);
        }
    }
    public function render()
    {
        $results = [];
        if ($this->action == 'list') {
            $query = ConfSmartUpdate::select('PID', 'PATCHNAME', 'PDESC', 'PDATE', 'PLEVEL', 'Remark')
                ->withCount(['confServerPendding as NUMSERVER']);

            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-patch-index', compact('results'));
    }

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