<?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,$patchName , $serverKeyOption, $serverKeyOwnerType, $company, $db_type, $cur_ver;
    public $perPage = 10;
    public $search = '';
    public $server_lists;
    public $selectedOwnerType = '';
    public $message;
    public $searchSelected = 'SNKEY';
    public $keyword = '';
    public $selectedPenddings = [];
    public $serverkey = '', $showSearch = false, $searchInProgress = false, $resultsServerkey = [];
    public $serverKeyWaitingSend = [], $serverKeySuccess = [];
    protected $listeners = ['deletePatch', 'refreshComponent' => '$refresh'];
    public function mount($editPid)
    {
        $this->PID = $editPid;
        $patch = ConfSmartupdate::where("PID", $editPid)->first();
        $this->patchName = $patch->PATCHNAME;
        // $this->PID = 15670;

        // $this->updateServerLists();
    }

    public function updatedServerkey()
    {
        $this->searchResults();
    }
    public function updatedCompany()
    {
        $this->searchResults();
    }

    public function updatedDbType()
    {
        $this->searchResults();
    }

    public function updatedCurVer()
    {
        $this->searchResults();
    }
    public function selectAllResults()
    {
        $this->searchInProgress = true;
        foreach ($this->resultsServerkey as $result) {
            $this->selectResult($result->SNKEY);
        }
        $this->serverkey = '';
    }
    public function searchResults()
    {
        if ($this->searchInProgress) {
            $this->reset('resultsServerkey');
        }
        $this->searchInProgress = true;
        $query = ConfServerLicense::query();
        if (!empty($this->serverkey)) {
            $query->where('SNKEY', 'LIKE', '%' . $this->serverkey . '%');
        }
        if (!empty($this->company)) {
            $query->where('COMPANY', 'LIKE', '%' . $this->company . '%');
        }

        if (!empty($this->db_type)) {
            $query->where('DATABASETYPE', 'LIKE', '%' . $this->db_type . '%');
        }
        if (!empty($this->cur_ver)) {
            $query->where('CUR_VERSION', 'LIKE', '%' . $this->cur_ver . '%');
        }

        $this->resultsServerkey = $query->take(50)->get();
        $this->showSearch = true;
        $this->searchInProgress = false;
    }
    public function selectResult($key)
    {
        $this->serverkey = $key;
        $this->resultsServerkey = [];
        $this->showSearch = false;
        $temp = ConfServerLicense::where('SNKEY',  $key)->first();

        $keys = array_column($this->serverKeyWaitingSend, 'key');
        if (!in_array($key, $keys)) {
            $this->serverKeyWaitingSend[] = ['id' => $temp->ID, 'key' => $key, 'db' => $temp->DATABASE_TYPE, 'cur_ver' => $temp->CUR_VERSION];
        }
    }
    public function removeServerKey($key)
    {
        $this->serverKeyWaitingSend = array_filter($this->serverKeyWaitingSend, function ($serverKey) use ($key) {
            return $serverKey['key'] !== $key;
        });

        $this->serverKeyWaitingSend = array_values($this->serverKeyWaitingSend);
    }

    public function updatedSelectedOwnerType($value)
    {

        if (!empty($value)) {
            $serverKeyOwnerType = $this->fetchServerKeyOption($value);
            if (count($serverKeyOwnerType) > 0) {
                foreach ($serverKeyOwnerType as  $sk) {
                    $this->selectResult($sk["name"]);
                }
            }
        } else {
            $this->serverKeyOwnerType = [];
        }
        $this->serverkey = '';
    }

    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 sendPatch()
    {


        $arr_server_lists = $this->serverKeyWaitingSend;

        if (isset($arr_server_lists)) {
 
            foreach ($arr_server_lists as $server) {
                $serverPedding  = new ConfServerPendding;
                $serverPedding->ServerID = $server["id"];
                $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, $server["id"], "Add Patch");
                array_push($this->serverKeySuccess , $server);
                $this->emit('patchSent', $server);
            }
        }
        $this->serverKeyWaitingSend = [];
    }

    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();
    }

    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();
    
        $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.send-patch.send-patch-edit', compact('ownerType', 'results'));
    }
}
