<?php

namespace App\Http\Livewire\Pages\SendPatch;

use App\Models\ConfServerLicense;
use App\Models\ConfServerPendding;
use App\Models\ConfSmartupdate;
use Livewire\Component;
use Livewire\WithPagination;

class DeleteMultiPatchList extends Component
{

    use WithPagination;
    public $serverkey = '';
    public $searchBy, $serverId, $editPid, $message, $keyword, $perPage = 10, $searchSelected = 'PID';
    public $selectedPatches = [];
    protected $results;
    
    protected $listeners = ['updateServerkey' , 'updateSelectPatchAfterDeleted', 'removePatchSelected'];
    public function mount()
    {

        $this->searchBy = [
            'PID' => 'PID',
            'PATCHNAME' => 'Patch Name',
            'PDESC' => 'Description',
            'MAJOR_VERSION' => 'Major Vaersion',
            'Remark' => 'Remark'

        ];
        // dd($results);
        // $this->selectedPatches = [];
    }
    public function search()
    {
        $this->resetPage();
    }

    public function updateServerkey($serverkey)
    {

        $serverLicense = ConfServerLicense::where("SNKEY", $serverkey)->first();
        if (isset($serverLicense)) {
            $this->serverId = $serverLicense->ID;
        }
        $this->render();
    }
    public function updateSelectPatchAfterDeleted()
    {

        $this->selectedPatches = [];
        $this->render();
    }

    public function removePatchSelected($key)
    {
        $this->selectedPatches = array_filter($this->selectedPatches, function ($patch) use ($key) {
            return $patch!== $key;
        });
        $this->resetPage();
         
    }

    public function render()
    {

        $query = ConfServerPendding::select('PID', 'PATCHNAME', 'PDESC', 'PDATE', 'PLEVEL', 'Remark', 'MAJOR_VERSION')
            ->join('conf_smartupdate', 'conf_smartupdate.PID', '=', 'conf_server_pendding.PatchID')
            ->where('conf_server_pendding.ServerID', $this->serverId)
            ->where('conf_server_pendding.TaskStatus' , '!=', '999');

        if ($this->searchSelected && $this->keyword) {
            $query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
        }
        $query->orderBy('PID', 'DESC');
        $results = $query->paginate($this->perPage);

        return view('livewire.pages.send-patch.delete-multi-patch-list', [
            'results' => $results
        ]);
    }
}
