<?php

namespace App\Http\Livewire\Pages\SendPatch;

use App\Models\ConfServerLicense;
use App\Models\ConfServerOwnertype;
use App\Models\ConfServerPendding;
use App\Models\ConfSmartupdate;
use App\Models\LogSendPath2customer;
use Livewire\Component;

class SendPatchEdit extends Component
{
    public $PID, $serverKeyOption;
    public $perPage = 10;
    public $search = '';
    public $server_lists;
    public $selectedOwnerType = '';
    public $message;
    public $searchSelected = 'SNKEY';
    public $keyword = '';
    public $selectedPenddings = [];
    protected $listeners = ['deletePatch', 'refreshComponent' => '$refresh'];
    public function mount($editPid)
    {
        // $this->PID = $editPid;
        $this->PID = 15670;
        // $this->updateServerLists();
    }

    public function updatedSelectedOwnerType($value)
    {
        if (!empty($value)) {
            // อัปเดต serverKeyOption โดยพิจารณาจาก owner type ที่เลือก
            $this->serverKeyOption = $this->fetchServerKeyOption($value);
        } else {
            $this->serverKeyOption = [];
        }
    }

    protected function fetchServerKeyOption($ownerType)
    {
        $query = ConfServerLicense::query();

        if ($ownerType) {
            $query->where('OWNERTYPE', $ownerType);
        }

        if ($this->search) {
            $query->where('SNKEY', 'like', '%' . $this->search . '%');
        }
        return   $query->get(['ID as id', 'SNKEY as name'])->toArray();
    }


    public function render()
    {
        $query = ConfServerLicense::query();

        if ($this->selectedOwnerType) {
            $query->where('OWNERTYPE', $this->selectedOwnerType);
        }

        if ($this->search) {
            $query->where('SNKEY', 'like', '%' . $this->search . '%');
        }

        $this->serverKeyOption =  $query->get(['ID as id', 'SNKEY as name'])->toArray();
        //     // dd( $this->server_lists);
        $ownerType = ConfServerOwnertype::all();

        $results = $this->searchSelected && $this->keyword
            ? ConfServerPendding::join('conf_server_license as p2', 'conf_server_pendding.ServerID', '=', 'p2.ID')
            ->where('PatchID', $this->PID)
            ->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%')
            ->paginate($this->perPage)
            : ConfServerPendding::join('conf_server_license as p2', 'conf_server_pendding.ServerID', '=', 'p2.ID')
            ->where('PatchID', $this->PID)
            ->paginate($this->perPage);

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


    public function sendPatch()
    {

        if (!is_array($this->server_lists)) {
            $arr_server_lists = explode(",", $this->server_lists);
        } else {
            $arr_server_lists = $this->server_lists;
        }
        if (isset($arr_server_lists)) {
            foreach ($arr_server_lists as $serverId) {
                $serverPedding  = new ConfServerPendding;
                $serverPedding->ServerID = $serverId;
                $serverPedding->PatchID = $this->PID;
                $serverPedding->TaskDate = date("Y-m-d H:i:s");
                $serverPedding->TaskType = "";
                $serverPedding->TaskStatus = "0";
                $serverPedding->TaskRunner = auth()->user()->USERNAME;
                $serverPedding->save();

                static::logSendPatch($this->PID, $serverId, "Add Patch");

                $this->server_lists = [];
            }
        }
    }

    public function resendPatch($serverId)
    {
        $pendding = ConfServerPendding::where('ServerID', $serverId)->where('PatchID', $this->PID)->update([
            "TaskStatus" => "0",
            "TaskFinish" => '0000_00_00 00:00:00'
        ]);
        // $pendding->TaskStatus = "0";
        // $pendding->TaskFinish = '0000_00_00 00:00:00';
        // $pendding->save();
        static::logSendPatch($this->PID, $serverId, "Reload Patch");
    }
    public function deletePatch($serverId)
    {
        // if (!\Auth::user()->hasPermissions(['delete-pendding'])) {
        //     $this->showNoPermissionModal = TRUE;
        //     return;
        // }
        $pendding = ConfServerPendding::where("ServerID", $serverId)->where("PatchID", $this->PID,)->delete();

        static::logSendPatch($this->PID, $serverId, "Delete Patch");
    }
    public function deleteSelected($selectedPenddings)
    {
        // if (!\Auth::user()->hasPermissions(['delete-user'])) {
        //     $this->showNoPermissionModal = TRUE;
        //     return;
        // }
        ConfServerPendding::destroy($selectedPenddings);
        $message = "Deleted ID : " . json_encode($selectedPenddings) . " Successfully";
        $this->message = $message;
        $this->selectedPenddings = [];
    }

    public static function logSendPatch($patchId, $serverId, $logDesc)
    {
        $log = new LogSendPath2customer;
        $log->UID =  auth()->user()->UID;
        $log->PATCHID =  $patchId;
        $log->SERVERKEYID =  $serverId;
        $log->ACTDATETIME =  date("Y-m-d H:i:s");
        $log->LOGDESC =  $logDesc;
        $log->IPACTIVE =  request()->ip();
        $log->save();
    }
}
