<?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 SendPatch extends Component
{
    use WithPagination;
    // protected $paginationTheme = 'bootstrap';
    public $searchBy, $editPid, $message, $keyword, $perPage = 10, $searchSelected = 'PID', 
    // $action = 'list';
    $action = 'edit'; // test


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

        ];
        $this->message = session('message');
    }

    public function render()
    {
        $numServerSubquery = DB::table('conf_server_pendding as p2')
            ->select(DB::raw('count(p2.ServerID) as NUMSERVER'), 'p2.PatchID')
            ->groupBy('p2.PatchID');

        // Query หลัก
        $query = ConfSmartUpdate::from('conf_smartupdate as p1')
            ->select('p1.PID', 'p1.PATCHNAME', 'p1.PDESC', 'p1.PDATE', 'p1.PLEVEL', 'p1.Remark', 'p3.NUMSERVER')
            ->leftJoinSub($numServerSubquery, 'p3', function ($join) {
                $join->on('p1.PID', '=', 'p3.PatchID');
            });

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

        return view('livewire.pages.sendpatch.send-patch', compact('results'));
    }

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