<?php

namespace App\Modules\Product\Virtualizor;

use App\Core\Product\AbstractProduct;
use App\Core\Product\Events\AccountCreated;
use Illuminate\Support\Facades\Log;

class Virtualizor extends AbstractProduct
{
    /**
     * Uzak VPS kimliğini çözer (PRC-1015).
     *
     * Öncelik: kanonik remoteId (account_id / module_handler_id) → modülün kendi
     * `vpsid` alanı. procp iç `server_id` FK ASLA uzak-id olarak kullanılmaz.
     */
    protected function resolveVpsId(array $params): ?string
    {
        $remote = $this->remoteId($params);
        if ($remote !== null) {
            return $remote;
        }

        if (isset($params['vpsid']) && is_scalar($params['vpsid']) && trim((string) $params['vpsid']) !== '') {
            return (string) $params['vpsid'];
        }

        return null;
    }

    /**
     * Virtualizor iki ayrı kimlik ister: apikey + apipass. `serverConfig()` tek
     * `password` verdiği için (api_key alias'ı), ikisini de atanmış-sunucu öncelikli
     * olarak burada çözeriz (server → module_config/`$this->config`).
     *
     * @return array{api_key:string,api_pass:string}
     */
    protected function resolveCredentials(array $params): array
    {
        $server = (isset($params['server']) && is_array($params['server'])) ? $params['server'] : [];
        $config = (isset($params['module_config']) && is_array($params['module_config']))
            ? $params['module_config']
            : (is_array($this->config) ? $this->config : []);

        $pick = function (array $keys) use ($server, $config) {
            foreach ([$server, $config] as $source) {
                foreach ($keys as $key) {
                    if (isset($source[$key]) && is_scalar($source[$key]) && trim((string) $source[$key]) !== '') {
                        return (string) $source[$key];
                    }
                }
            }

            return '';
        };

        return [
            'api_key'  => $pick(['api_key', 'apikey']),
            'api_pass' => $pick(['api_pass', 'apipass']),
        ];
    }

    /**
     * Virtualizor API port (default admin panel port)
     */
    protected $apiPort = 4085;

    /**
     * Virtualizor modulu server gerektirir
     */
    public function requiresServer(): bool
    {
        return true;
    }

    /**
     * Provisioning mapping schema (PRC-1015).
     *
     * Bu override olmadan `paramSchema()` default `[]` döner → mapping pipeline
     * flat builder'a düşer (`domain`/`password` var ama `plid`/`osid`/`hostname`/
     * `rootpass` yok) ve `createAccount` param-gate'te fail eder. Schema, VM
     * plan (`plid`) ve OS template (`osid`) alanlarını config_options/module-config
     * üzerinden `$params`'a doldurur; hostname/rootpass builder flat emit eder.
     *
     * Ref: kardeş Product/HetznerCloud paramSchema deseni.
     */
    public function paramSchema(): array
    {
        return [
            ['key' => 'plid', 'label' => 'Virtualizor Plan ID', 'required' => true],
            ['key' => 'osid', 'label' => 'OS Template ID', 'required' => true],
            ['key' => 'virt', 'label' => 'Virtualization Type', 'required' => false],
            ['key' => 'serid', 'label' => 'Server/Node ID', 'required' => false],
        ];
    }

    /**
     * Yeni bir VPS olusturur (act=addvs)
     *
     * KVM, Xen, OpenVZ veya LXC sanallaştırma türlerini destekler.
     *
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function createAccount(array $params)
    {
        // Plan (plid) ve OS (osid): flat param → config-option → module-config.
        $plid = $params['plid']
            ?? $this->configOption($params, 'plid')
            ?? $this->configOption($params, 'plan')
            ?? $this->moduleConfig($params, 'plid')
            ?? $this->moduleConfig($params, 'plan');

        $osid = $params['osid']
            ?? $this->configOption($params, 'osid')
            ?? $this->configOption($params, 'os')
            ?? $this->moduleConfig($params, 'osid')
            ?? $this->moduleConfig($params, 'os');

        $virt = $params['virt']
            ?? $this->configOption($params, 'virt')
            ?? $this->moduleConfig($params, 'virt')
            ?? 'kvm';

        // Hostname: flat param (module ClientDomain/hostname) → domain fallback.
        $hostname = $params['hostname'] ?? $params['domain'] ?? null;
        $rootpass = $params['rootpass'] ?? $params['password'] ?? null;

        $resolved = [
            'hostname' => $hostname,
            'rootpass' => $rootpass,
            'plid' => $plid,
            'osid' => $osid,
        ];

        foreach ($resolved as $param => $value) {
            if ($value === null || $value === '') {
                return [
                    'status' => 'error',
                    'message' => __('admin/modules.virtualizor_param_missing', ['param' => $param]),
                ];
            }
        }

        $apiParams = [
            // Resmî addvs bayrakları: addvps=1 (formu işle) + node_select=1
            // (uygun node'u otomatik seç). Bunlar olmadan addvs formu submit
            // edilmiş sayılmaz → VPS oluşturulmaz.
            'addvps' => 1,
            'node_select' => 1,
            'hostname' => $hostname,
            'rootpass' => $rootpass,
            'virt' => $virt,
            'plid' => $plid,
            'osid' => $osid,
            'ips' => $params['ips'] ?? 1,
            'space' => $params['space'] ?? 20,
            'ram' => $params['ram'] ?? 1024,
            'bandwidth' => $params['bandwidth'] ?? 0,
            'cpu' => $params['cpu'] ?? 1000,
            'cores' => $params['cores'] ?? 1,
        ];

        // Opsiyonel parametreler
        if (! empty($params['serid'])) {
            $apiParams['serid'] = $params['serid'];
        }

        if (! empty($params['uid'])) {
            $apiParams['uid'] = $params['uid'];
        }

        if (! empty($params['email'])) {
            $apiParams['email'] = $params['email'];
        }

        $response = $this->callApi('addvs', $apiParams, $params);

        $vpsId = $this->extractNewVpsId($response);

        if ($vpsId !== null || (isset($response['done']) && ! empty($response['done']))) {

            $result = [
                'status' => 'success',
                'message' => __('admin/modules.virtualizor_account_created_success'),
                'data' => [
                    'vpsid' => $vpsId,
                ],
            ];

            AccountCreated::dispatch($params, $result);

            return $result;
        }

        $errorMessage = $this->extractError($response);

        $result = [
            'status' => 'error',
            'message' => $errorMessage ?: __('admin/modules.virtualizor_account_create_failed'),
        ];

        AccountCreated::dispatch($params, $result);

        return $result;
    }

    /**
     * Bir VPS'i askiya alir (act=vs&suspend={vpsid})
     *
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function suspendAccount(array $params)
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_vpsid_required'),
            ];
        }

        $response = $this->callApi('vs', [
            'suspend' => $vpsId,
        ], $params);

        if (isset($response['done']) && ! empty($response['done'])) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.virtualizor_account_suspended_success'),
            ];
        }

        $errorMessage = $this->extractError($response);

        return [
            'status' => 'error',
            'message' => $errorMessage ?: __('admin/modules.virtualizor_account_suspend_failed'),
        ];
    }

    /**
     * Askiya alinmis bir VPS'i aktiflestirir (act=vs&unsuspend={vpsid})
     *
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function unsuspendAccount(array $params)
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_vpsid_required'),
            ];
        }

        $response = $this->callApi('vs', [
            'unsuspend' => $vpsId,
        ], $params);

        if (isset($response['done']) && ! empty($response['done'])) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.virtualizor_account_unsuspended_success'),
            ];
        }

        $errorMessage = $this->extractError($response);

        return [
            'status' => 'error',
            'message' => $errorMessage ?: __('admin/modules.virtualizor_account_unsuspend_failed'),
        ];
    }

    /**
     * Bir VPS'i siler (act=vs&delete={vpsid})
     *
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function terminateAccount(array $params)
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_vpsid_required'),
            ];
        }

        $response = $this->callApi('vs', [
            'delete' => $vpsId,
        ], $params);

        if (isset($response['done']) && ! empty($response['done'])) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.virtualizor_account_deleted_success'),
            ];
        }

        $errorMessage = $this->extractError($response);

        return [
            'status' => 'error',
            'message' => $errorMessage ?: __('admin/modules.virtualizor_account_delete_failed'),
        ];
    }

    /**
     * Bir VPS'in root sifresini degistirir (act=editvs)
     *
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function changeAccountPassword(array $params)
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_vpsid_required'),
            ];
        }

        $rootpass = $params['rootpass'] ?? $params['password'] ?? null;
        if ($rootpass === null || $rootpass === '') {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_password_required'),
            ];
        }

        // editvps=1 zorunlu bayrak — aksi halde editvs formu submit sayılmaz (no-op).
        $response = $this->callApi('editvs', [
            'vpsid' => $vpsId,
            'editvps' => 1,
            'rootpass' => $rootpass,
            'conf' => $rootpass,
        ], $params);

        if (isset($response['done']) && ! empty($response['done'])) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.virtualizor_password_changed_success'),
            ];
        }

        $errorMessage = $this->extractError($response);

        return [
            'status' => 'error',
            'message' => $errorMessage ?: __('admin/modules.virtualizor_password_change_failed'),
        ];
    }

    /**
     * Bir VPS'in kaynak limitlerini degistirir (act=editvs)
     *
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function changeAccountPackage(array $params)
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_vpsid_required'),
            ];
        }

        $apiParams = [
            'vpsid' => $vpsId,
            // editvps=1 zorunlu bayrak — resize/plan değişimi aksi halde uygulanmaz.
            'editvps' => 1,
        ];

        // Plan ile degisim: flat param → config-option → module-config
        $plid = $params['plid']
            ?? $this->configOption($params, 'plid')
            ?? $this->configOption($params, 'plan')
            ?? $this->moduleConfig($params, 'plid')
            ?? $this->moduleConfig($params, 'plan');
        if (! empty($plid)) {
            $apiParams['plid'] = $plid;
        }

        // Bireysel kaynak limitleri
        if (isset($params['ram'])) {
            $apiParams['ram'] = $params['ram'];
        }

        if (isset($params['space'])) {
            $apiParams['space'] = $params['space'];
        }

        if (isset($params['bandwidth'])) {
            $apiParams['bandwidth'] = $params['bandwidth'];
        }

        if (isset($params['cpu'])) {
            $apiParams['cpu'] = $params['cpu'];
        }

        if (isset($params['cores'])) {
            $apiParams['cores'] = $params['cores'];
        }

        if (isset($params['ips'])) {
            $apiParams['ips'] = $params['ips'];
        }

        $response = $this->callApi('editvs', $apiParams, $params);

        if (isset($response['done']) && ! empty($response['done'])) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.virtualizor_package_changed_success'),
            ];
        }

        $errorMessage = $this->extractError($response);

        return [
            'status' => 'error',
            'message' => $errorMessage ?: __('admin/modules.virtualizor_package_change_failed'),
        ];
    }

    /**
     * Baglanti testini gerceklestirir (act=servers)
     *
     * @param  array  $params  Test parametreleri
     * @return array Test sonucu
     */
    public function testConnection(array $params = [])
    {
        $response = $this->callApi('servers', [], $params);

        if (isset($response['servs']) || (isset($response['timenow']) && ! empty($response['timenow']))) {
            $serverCount = isset($response['servs']) ? count($response['servs']) : 0;

            return [
                'status' => 'success',
                'message' => __('admin/modules.virtualizor_connection_test_success', ['count' => $serverCount]),
                'data' => [
                    'server_count' => $serverCount,
                ],
            ];
        }

        $errorMessage = $this->extractError($response);

        return [
            'status' => 'error',
            'message' => $errorMessage ?: __('admin/modules.virtualizor_connection_test_failed'),
        ];
    }

    /**
     * Admin panelinde gosterilecek alanlari dondurur
     *
     * @return array Admin panel alanlari
     */
    public function adminFields()
    {
        return [
            'hostname' => [
                'name' => __('admin/modules.virtualizor_field_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.virtualizor_field_hostname_description'),
                'required' => true,
            ],
            'port' => [
                'name' => __('admin/modules.virtualizor_field_port'),
                'type' => 'text',
                'description' => __('admin/modules.virtualizor_field_port_description'),
                'default' => '4085',
                'required' => false,
            ],
            'api_key' => [
                'name' => __('admin/modules.virtualizor_field_api_key'),
                'type' => 'text',
                'description' => __('admin/modules.virtualizor_field_api_key_description'),
                'required' => true,
            ],
            'api_pass' => [
                'name' => __('admin/modules.virtualizor_field_api_pass'),
                'type' => 'password',
                'description' => __('admin/modules.virtualizor_field_api_pass_description'),
                'required' => true,
            ],
            'use_ssl' => [
                'name' => __('admin/modules.virtualizor_field_use_ssl'),
                'type' => 'checkbox',
                'description' => __('admin/modules.virtualizor_field_use_ssl_description'),
                'default' => true,
            ],
        ];
    }

    /**
     * Musteri panelinde gosterilecek alanlari dondurur
     *
     * @return array Musteri panel alanlari
     */
    public function clientFields()
    {
        return [
            'hostname' => [
                'name' => __('admin/modules.virtualizor_field_client_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.virtualizor_field_client_hostname_description'),
                'required' => false,
            ],
            'vps_id' => [
                'name' => __('admin/modules.virtualizor_field_client_vps_id'),
                'type' => 'text',
                'description' => __('admin/modules.virtualizor_field_client_vps_id_description'),
                'required' => true,
            ],
        ];
    }

    /**
     * Server yonetimi icin gosterilecek alanlari dondurur
     *
     * @return array Server yonetimi alanlari
     */
    public function serverFields()
    {
        return [
            'api_key' => [
                'name' => __('admin/modules.virtualizor_field_api_key'),
                'type' => 'text',
                'description' => __('admin/modules.virtualizor_field_api_key_description'),
                'required' => true,
            ],
            'api_pass' => [
                'name' => __('admin/modules.virtualizor_field_api_pass'),
                'type' => 'password',
                'description' => __('admin/modules.virtualizor_field_api_pass_description'),
                'required' => true,
            ],
        ];
    }

    /**
     * Admin panelde gosterilecek ozel butonlari dondurur
     *
     * @return array Admin butonlari
     */
    public function getAdminButtons(): array
    {
        return [
            [
                'action' => 'list_plans',
                'label' => __('admin/modules.virtualizor_action_list_plans'),
                'icon' => 'fas fa-list',
                'class' => 'btn-outline-info',
            ],
            [
                'action' => 'list_os_templates',
                'label' => __('admin/modules.virtualizor_action_list_os_templates'),
                'icon' => 'fas fa-compact-disc',
                'class' => 'btn-outline-primary',
            ],
            [
                'action' => 'list_servers',
                'label' => __('admin/modules.virtualizor_action_list_servers'),
                'icon' => 'fas fa-server',
                'class' => 'btn-outline-secondary',
            ],
            [
                'action' => 'vps_info',
                'label' => __('admin/modules.virtualizor_action_vps_info'),
                'icon' => 'fas fa-info-circle',
                'class' => 'btn-outline-success',
            ],
            [
                'action' => 'reinstall',
                'label' => __('admin/modules.virtualizor_action_reinstall'),
                'icon' => 'fas fa-redo',
                'class' => 'btn-outline-warning',
            ],
            [
                'action' => 'list_ips',
                'label' => __('admin/modules.virtualizor_action_list_ips'),
                'icon' => 'fas fa-network-wired',
                'class' => 'btn-outline-secondary',
            ],
        ];
    }

    /**
     * Admin ozel action'i isler
     *
     * @param  string  $action  Action adi (list_plans, list_os_templates, list_servers, vps_info)
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function adminCustomAction(string $action, array $params): array
    {
        switch ($action) {
            case 'list_plans':
                $response = $this->callApi('plans', [], $params);

                if (! isset($response['plans'])) {
                    return [
                        'status' => 'error',
                        'message' => $this->extractError($response) ?: __('admin/modules.virtualizor_list_plans_failed'),
                    ];
                }

                $plans = [];
                foreach ($response['plans'] as $planId => $plan) {
                    $plans[] = [
                        'id' => $planId,
                        'name' => $plan['plan_name'] ?? '',
                        'virt' => $plan['virt'] ?? '',
                        'ram' => $plan['ram'] ?? 0,
                        'space' => $plan['space'] ?? 0,
                        'bandwidth' => $plan['bandwidth'] ?? 0,
                        'cpu' => $plan['cpu'] ?? 0,
                        'cores' => $plan['cores'] ?? 0,
                    ];
                }

                return [
                    'status' => 'success',
                    'message' => __('admin/modules.virtualizor_list_plans_success'),
                    'data' => $plans,
                ];

            case 'list_os_templates':
                $response = $this->callApi('ostemplates', [], $params);

                if (! isset($response['ostemplates'])) {
                    return [
                        'status' => 'error',
                        'message' => $this->extractError($response) ?: __('admin/modules.virtualizor_list_os_templates_failed'),
                    ];
                }

                $templates = [];
                foreach ($response['ostemplates'] as $osId => $osGroup) {
                    if (is_array($osGroup)) {
                        foreach ($osGroup as $template) {
                            $templates[] = [
                                'osid' => $template['osid'] ?? $osId,
                                'name' => $template['name'] ?? '',
                                'filename' => $template['file'] ?? '',
                                'type' => $template['type'] ?? '',
                            ];
                        }
                    }
                }

                return [
                    'status' => 'success',
                    'message' => __('admin/modules.virtualizor_list_os_templates_success'),
                    'data' => $templates,
                ];

            case 'list_servers':
                $response = $this->callApi('servers', [], $params);

                if (! isset($response['servs'])) {
                    return [
                        'status' => 'error',
                        'message' => $this->extractError($response) ?: __('admin/modules.virtualizor_list_servers_failed'),
                    ];
                }

                $servers = [];
                foreach ($response['servs'] as $serverId => $server) {
                    $servers[] = [
                        'id' => $serverId,
                        'name' => $server['server_name'] ?? '',
                        'ip' => $server['ip'] ?? '',
                        'virt' => $server['virt'] ?? '',
                        'ram' => $server['ram'] ?? 0,
                        'total_ram' => $server['totalram'] ?? 0,
                    ];
                }

                return [
                    'status' => 'success',
                    'message' => __('admin/modules.virtualizor_list_servers_success'),
                    'data' => $servers,
                ];

            case 'vps_info':
                $vpsId = $this->resolveVpsId($params);
                if ($vpsId === null) {
                    return [
                        'status' => 'error',
                        'message' => __('admin/modules.virtualizor_vpsid_required'),
                    ];
                }

                $response = $this->callApi('vs', [
                    'vpsid' => $vpsId,
                ], $params);

                if (! isset($response['vs'])) {
                    return [
                        'status' => 'error',
                        'message' => $this->extractError($response) ?: __('admin/modules.virtualizor_vps_info_failed'),
                    ];
                }

                $vps = $response['vs'];

                return [
                    'status' => 'success',
                    'message' => __('admin/modules.virtualizor_vps_info_success'),
                    'data' => [
                        'vpsid' => $vps['vpsid'] ?? '',
                        'hostname' => $vps['hostname'] ?? '',
                        'os' => $vps['os_name'] ?? '',
                        'ip' => $vps['ips'] ?? '',
                        'ram' => $vps['ram'] ?? 0,
                        'space' => $vps['space'] ?? 0,
                        'bandwidth' => $vps['bandwidth'] ?? 0,
                        'cpu' => $vps['cpu'] ?? 0,
                        'cores' => $vps['cores'] ?? 0,
                        'virt' => $vps['virt'] ?? '',
                        'status' => $vps['status'] ?? '',
                    ],
                ];

            case 'reinstall':
                return $this->reinstallVps($params);

            case 'change_hostname':
                return $this->changeHostname($params);

            case 'list_ips':
                return $this->listIps($params);

            case 'add_ip':
                return $this->addIp($params);

            case 'remove_ip':
                return $this->removeIp($params);

            default:
                return [
                    'status' => 'error',
                    'message' => __('admin/modules.virtualizor_action_not_supported', ['action' => $action]),
                ];
        }
    }

    /**
     * Client area'da gosterilecek action'lari dondurur
     *
     * VPS yonetimi icin start, stop, restart, change_password ve vnc_console action'lari.
     *
     * @return array Client action'lari
     */
    public function getClientActions(): array
    {
        $actions = parent::getClientActions();

        $actions['start'] = [
            'label' => __('admin/modules.virtualizor_action_start'),
            'icon' => 'fas fa-play',
            'class' => 'btn-outline-success',
            'enabled' => true,
        ];

        $actions['stop'] = [
            'label' => __('admin/modules.virtualizor_action_stop'),
            'icon' => 'fas fa-stop',
            'class' => 'btn-outline-danger',
            'enabled' => true,
        ];

        $actions['poweroff'] = [
            'label' => __('admin/modules.virtualizor_action_poweroff'),
            'icon' => 'fas fa-power-off',
            'class' => 'btn-outline-danger',
            'enabled' => true,
        ];

        $actions['restart'] = [
            'label' => __('admin/modules.virtualizor_action_restart'),
            'icon' => 'fas fa-sync',
            'class' => 'btn-outline-warning',
            'enabled' => true,
        ];

        $actions['vnc_console'] = [
            'label' => __('admin/modules.virtualizor_action_vnc_console'),
            'icon' => 'fas fa-terminal',
            'class' => 'btn-outline-info',
            'enabled' => true,
        ];

        return $actions;
    }

    /**
     * Client action'i isler
     *
     * VPS start/stop/restart, VNC console ve sifre degistirme islemlerini yonetir.
     *
     * @param  string  $action  Action adi
     * @param  array  $params  Parametreler
     * @return array Sonuc
     */
    public function handleClientAction(string $action, array $params): array
    {
        switch ($action) {
            case 'start':
                return $this->startVps($params);

            case 'stop':
                return $this->stopVps($params);

            case 'poweroff':
                return $this->powerOffVps($params);

            case 'restart':
                return $this->restartVps($params);

            case 'vnc_console':
                return $this->getVncConsole($params);

            default:
                return parent::handleClientAction($action, $params);
        }
    }

    /**
     * VPS kaynak kullanim bilgilerini dondurur (act=vs&vs_stats)
     *
     * Disk, RAM, bandwidth ve CPU kullanim istatistiklerini getirir.
     *
     * @param  array  $params  Parametreler (vpsid gerekli)
     * @return array|null Kaynak kullanim verileri veya null
     */
    public function getResourceUsage(array $params): ?array
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return null;
        }

        // Resmî endpoint ayrı bir act'tir: act=vps_stats&vpsid={id}. Yanıt
        // `vps_data` altında K_ prefix'li istatistikler döndürür (SDK deseni).
        $response = $this->callApi('vps_stats', [
            'vpsid' => $vpsId,
        ], $params);

        $vpsData = $response['vps_data'] ?? $response['vs'] ?? $response['info'] ?? [];

        if (empty($vpsData) || ! is_array($vpsData)) {
            return null;
        }

        // vps_data çoğu sürümde {vpsid => {stats...}} sarmalıdır; iç kaydı aç.
        if (! isset($vpsData['ram']) && ! isset($vpsData['K_ram']) && ! isset($vpsData['disk'])) {
            $inner = reset($vpsData);
            if (is_array($inner)) {
                $vpsData = $inner;
            }
        }

        // K_ prefix'li anahtarları normalize et (K_ram → ram vb.).
        $vps = [];
        foreach ($vpsData as $k => $v) {
            $vps[$k] = $v;
            if (is_string($k) && str_starts_with($k, 'K_')) {
                $vps[substr($k, 2)] = $v;
            }
        }

        if (empty($vps)) {
            return null;
        }

        $resources = [];

        // Disk kullanimi
        $diskUsed = (float) ($vps['disk_used'] ?? $vps['used_space'] ?? 0);
        $diskLimit = (float) ($vps['space'] ?? $vps['disk'] ?? 0);
        $diskPercentage = $diskLimit > 0 ? round(($diskUsed / $diskLimit) * 100, 2) : 0;

        $resources[] = [
            'name' => 'Disk Space',
            'used' => round($diskUsed, 2),
            'limit' => round($diskLimit, 2),
            'unit' => 'GB',
            'percentage' => $diskPercentage,
        ];

        // RAM kullanimi
        $ramUsed = (float) ($vps['ram_used'] ?? $vps['used_ram'] ?? 0);
        $ramLimit = (float) ($vps['ram'] ?? 0);
        $ramPercentage = $ramLimit > 0 ? round(($ramUsed / $ramLimit) * 100, 2) : 0;

        $resources[] = [
            'name' => 'RAM',
            'used' => round($ramUsed, 2),
            'limit' => round($ramLimit, 2),
            'unit' => 'MB',
            'percentage' => $ramPercentage,
        ];

        // Bandwidth kullanimi
        $bwUsed = (float) ($vps['bandwidth_used'] ?? $vps['used_bandwidth'] ?? 0);
        $bwLimit = (float) ($vps['bandwidth'] ?? 0);
        $bwPercentage = $bwLimit > 0 ? round(($bwUsed / $bwLimit) * 100, 2) : 0;

        $resources[] = [
            'name' => 'Bandwidth',
            'used' => round($bwUsed, 2),
            'limit' => round($bwLimit, 2),
            'unit' => 'GB',
            'percentage' => $bwPercentage,
        ];

        // CPU kullanimi
        $cpuUsed = (float) ($vps['cpu_used'] ?? $vps['cpu_usage'] ?? 0);
        $cpuLimit = (float) ($vps['cpu'] ?? $vps['cpus'] ?? 100);
        $cpuPercentage = min(round($cpuUsed, 2), 100);

        $resources[] = [
            'name' => 'CPU',
            'used' => round($cpuUsed, 2),
            'limit' => round($cpuLimit, 2),
            'unit' => '%',
            'percentage' => $cpuPercentage,
        ];

        return $resources;
    }

    /**
     * Bir veya birden çok VPS'in çalışma durumunu toplu sorgular (#14 status-sync).
     *
     * Resmî toplu status endpoint'i: `act=vs&vs_status={csv-ids}` — her VPS için
     * çalışıyor/kapalı/askıda durumunu döndürür (SDK `status`). Tek-VPS `vps_info`
     * yerine bu, durum-senkron akışının (list → eşleştir → güncelle) çekirdeğidir.
     *
     * @param  array<int|string>  $vpsIds  Sorgulanacak vpsid listesi (boşsa tümü)
     * @return array<string,string> vpsid => status ('online'|'offline'|'suspended'|...)
     */
    public function getBulkVpsStatus(array $params, array $vpsIds = []): array
    {
        $idCsv = implode(',', array_map('strval', $vpsIds));

        $response = $this->callApi('vs', [
            'vs_status' => $idCsv !== '' ? $idCsv : 1,
        ], $params);

        $statusMap = $response['status'] ?? $response['vs_status'] ?? [];
        if (! is_array($statusMap)) {
            return [];
        }

        $out = [];
        foreach ($statusMap as $vpsid => $info) {
            // Virtualizor status yapısı: {status:1/0, ...} veya doğrudan skaler.
            if (is_array($info)) {
                $raw = $info['status'] ?? $info['stat'] ?? null;
            } else {
                $raw = $info;
            }

            $out[(string) $vpsid] = $this->mapVpsStatus($raw);
        }

        return $out;
    }

    /**
     * Virtualizor ham status değerini kanonik string'e map'ler.
     *
     * @param  mixed  $raw
     */
    protected function mapVpsStatus($raw): string
    {
        if ($raw === null || $raw === '') {
            return 'unknown';
        }

        // 1 = online, 0 = offline; 's'/'suspended' = suspended.
        if (is_numeric($raw)) {
            return ((int) $raw) === 1 ? 'online' : 'offline';
        }

        $s = strtolower((string) $raw);
        if (in_array($s, ['online', 'running', 'on', 'up'], true)) {
            return 'online';
        }
        if (in_array($s, ['suspended', 's', 'susp'], true)) {
            return 'suspended';
        }

        return 'offline';
    }

    /**
     * Yapilandirma dogrulamasi
     *
     * @return bool Yapilandirma dogru mu?
     *
     * @throws \Exception Eksik yapilandirma durumunda
     */
    public function validateConfig()
    {
        if (empty($this->config['hostname'])) {
            throw new \Exception(__('admin/modules.virtualizor_config_hostname_missing'));
        }

        if (empty($this->config['api_key'])) {
            throw new \Exception(__('admin/modules.virtualizor_config_api_key_missing'));
        }

        if (empty($this->config['api_pass'])) {
            throw new \Exception(__('admin/modules.virtualizor_config_api_pass_missing'));
        }

        return true;
    }

    /**
     * Resmî Virtualizor güç-operasyonu şeması (S2 fix).
     *
     * Tüm power op'lar: `act=vs&action={op}&serid=0&vpsid={id}` (SDK admin.php
     * start/stop/restart/poweroff). Eski `['start'=>id]` şeması geçerli bir
     * Virtualizor sub-action DEĞİLdi → gerçek sunucuda no-op oluyordu.
     *
     * @param  string  $action  start|stop|restart|poweroff
     */
    protected function powerAction(array $params, string $action, string $successKey, string $failKey): array
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_vpsid_required'),
            ];
        }

        // serid: atanmış node (serid/server_node) → 0 (master).
        $serid = $params['serid'] ?? $this->moduleConfig($params, 'serid', 0);

        $response = $this->callApi('vs', [
            'action' => $action,
            'serid' => (int) $serid,
            'vpsid' => $vpsId,
        ], $params);

        if (isset($response['done']) && ! empty($response['done'])) {
            return [
                'status' => 'success',
                'message' => __($successKey),
            ];
        }

        $errorMessage = $this->extractError($response);

        return [
            'status' => 'error',
            'message' => $errorMessage ?: __($failKey),
        ];
    }

    /**
     * VPS'i baslatir (act=vs&action=start&serid=0&vpsid={id})
     */
    protected function startVps(array $params): array
    {
        return $this->powerAction(
            $params,
            'start',
            'admin/modules.virtualizor_vps_started_success',
            'admin/modules.virtualizor_vps_start_failed'
        );
    }

    /**
     * VPS'i durdurur — graceful shutdown (act=vs&action=stop&serid=0&vpsid={id})
     */
    protected function stopVps(array $params): array
    {
        return $this->powerAction(
            $params,
            'stop',
            'admin/modules.virtualizor_vps_stopped_success',
            'admin/modules.virtualizor_vps_stop_failed'
        );
    }

    /**
     * VPS'i zorla kapatir — force poweroff (act=vs&action=poweroff&serid=0&vpsid={id})
     *
     * WiseCP stop=graceful / poweroff=force ayrımı; bu ayrı bir güç-op'tur.
     */
    protected function powerOffVps(array $params): array
    {
        return $this->powerAction(
            $params,
            'poweroff',
            'admin/modules.virtualizor_vps_poweroff_success',
            'admin/modules.virtualizor_vps_poweroff_failed'
        );
    }

    /**
     * VPS'i yeniden baslatir (act=vs&action=restart&serid=0&vpsid={id})
     */
    protected function restartVps(array $params): array
    {
        return $this->powerAction(
            $params,
            'restart',
            'admin/modules.virtualizor_vps_restarted_success',
            'admin/modules.virtualizor_vps_restart_failed'
        );
    }

    /**
     * VPS'i yeniden kurar / OS değiştirir — rebuild (act=rebuild&reos=1) (#12 MISSING fix).
     *
     * SDK `rebuild`: `act=rebuild&reos=1&vpsid={id}&osid={os}&newpass={pass}`.
     * osid flat param → config-option → module-config; newpass zorunlu (yeni root).
     * changeserid = atanmış node (serid) veya 0.
     */
    protected function reinstallVps(array $params): array
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_vpsid_required'),
            ];
        }

        $osid = $params['osid']
            ?? $this->configOption($params, 'osid')
            ?? $this->configOption($params, 'os')
            ?? $this->moduleConfig($params, 'osid')
            ?? $this->moduleConfig($params, 'os');

        if (empty($osid)) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_param_missing', ['param' => 'osid']),
            ];
        }

        // Yeni root parolası zorunlu — yıkıcı boş-parola default'u YOK.
        $newpass = $params['rootpass'] ?? $params['newpass'] ?? $params['password'] ?? null;
        if ($newpass === null || $newpass === '') {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_password_required'),
            ];
        }

        $serid = $params['serid'] ?? $this->moduleConfig($params, 'serid', 0);

        $response = $this->callApi('rebuild', [
            'reos' => 1,
            'vpsid' => $vpsId,
            'osid' => $osid,
            'newpass' => $newpass,
            'conf' => $newpass,
            'changeserid' => (int) $serid,
        ], $params);

        if (isset($response['done']) && ! empty($response['done'])) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.virtualizor_vps_reinstalled_success'),
            ];
        }

        $errorMessage = $this->extractError($response);

        return [
            'status' => 'error',
            'message' => $errorMessage ?: __('admin/modules.virtualizor_vps_reinstall_failed'),
        ];
    }

    /**
     * VPS hostname değiştirir (act=editvs&editvps=1&hostname=) (#15 MISSING fix).
     */
    protected function changeHostname(array $params): array
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_vpsid_required'),
            ];
        }

        $hostname = $params['hostname'] ?? null;
        if ($hostname === null || $hostname === '') {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_param_missing', ['param' => 'hostname']),
            ];
        }

        // editvs bayrak zorunlu (editvps=1) — aksi halde editvs no-op.
        $response = $this->callApi('editvs', [
            'vpsid' => $vpsId,
            'editvps' => 1,
            'hostname' => $hostname,
        ], $params);

        if (isset($response['done']) && ! empty($response['done'])) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.virtualizor_hostname_changed_success'),
            ];
        }

        $errorMessage = $this->extractError($response);

        return [
            'status' => 'error',
            'message' => $errorMessage ?: __('admin/modules.virtualizor_hostname_change_failed'),
        ];
    }

    /**
     * Bir VPS'in atanmış IP'lerini listeler (act=ips&vpsid={id}) (#16 IP mgmt).
     */
    protected function listIps(array $params): array
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_vpsid_required'),
            ];
        }

        $response = $this->callApi('ips', [
            'vpsid' => $vpsId,
        ], $params);

        $ips = $response['ips'] ?? [];
        if (! is_array($ips)) {
            $ips = [];
        }

        return [
            'status' => 'success',
            'message' => __('admin/modules.virtualizor_list_ips_success'),
            'data' => array_values($ips),
        ];
    }

    /**
     * Bir VPS'e yeni IP ekler (act=addips&vpsid={id}&addips=1) (#16 IP mgmt).
     *
     * `ips[]` verilmezse Virtualizor havuzdan otomatik atar ( nresip / ips_num).
     */
    protected function addIp(array $params): array
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_vpsid_required'),
            ];
        }

        // Resmî SDK addips() submit bayrağı: submitip=1 (addips=1 DEĞİL — sdk/admin.php:218).
        $apiParams = [
            'vpsid' => $vpsId,
            'submitip' => 1,
        ];

        if (! empty($params['ips']) && is_array($params['ips'])) {
            $apiParams['ips'] = $params['ips'];
        } else {
            // Havuzdan otomatik: eklenecek adet.
            $apiParams['ips_num'] = (int) ($params['ips_num'] ?? 1);
        }

        $response = $this->callApi('addips', $apiParams, $params);

        if (isset($response['done']) && ! empty($response['done'])) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.virtualizor_add_ip_success'),
                'data' => is_array($response['done']) ? $response['done'] : [],
            ];
        }

        $errorMessage = $this->extractError($response);

        return [
            'status' => 'error',
            'message' => $errorMessage ?: __('admin/modules.virtualizor_add_ip_failed'),
        ];
    }

    /**
     * Bir VPS'ten IP siler (act=editips&vpsid={id}&delips[]=) (#16 IP mgmt).
     */
    protected function removeIp(array $params): array
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_vpsid_required'),
            ];
        }

        $delIps = $params['ips'] ?? $params['delips'] ?? null;
        if (empty($delIps)) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_param_missing', ['param' => 'ips']),
            ];
        }
        if (! is_array($delIps)) {
            $delIps = [$delIps];
        }

        $response = $this->callApi('editips', [
            'vpsid' => $vpsId,
            'editips' => 1,
            'delips' => array_values($delIps),
        ], $params);

        if (isset($response['done']) && ! empty($response['done'])) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.virtualizor_remove_ip_success'),
            ];
        }

        $errorMessage = $this->extractError($response);

        return [
            'status' => 'error',
            'message' => $errorMessage ?: __('admin/modules.virtualizor_remove_ip_failed'),
        ];
    }

    /**
     * VNC konsol bilgilerini getirir (act=vnc)
     *
     * @param  array  $params  Parametreler
     * @return array VNC bilgileri
     */
    protected function getVncConsole(array $params): array
    {
        $vpsId = $this->resolveVpsId($params);
        if ($vpsId === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.virtualizor_vpsid_required'),
            ];
        }

        $response = $this->callApi('vnc', [
            'novnc' => $vpsId,
        ], $params);

        if (isset($response['done']) && ! empty($response['done'])) {
            $server = $this->serverConfig($params);
            $protocol = $server['secure'] ? 'https' : 'http';
            $hostname = $server['hostname'];
            $port = (! empty($server['port']) && (int) $server['port'] > 0) ? (int) $server['port'] : $this->apiPort;

            $vncUrl = (is_array($response['done']) ? ($response['done']['url'] ?? null) : null)
                ?? "{$protocol}://{$hostname}:{$port}/index.php?act=vnc&novnc={$vpsId}";

            return [
                'status' => 'success',
                'message' => __('admin/modules.virtualizor_vnc_console_success'),
                'url' => $vncUrl,
                'data' => is_array($response['done']) ? $response['done'] : [],
            ];
        }

        $errorMessage = $this->extractError($response);

        return [
            'status' => 'error',
            'message' => $errorMessage ?: __('admin/modules.virtualizor_vnc_console_failed'),
        ];
    }

    /**
     * 8 karakterlik rastgele anahtar üretir (Virtualizor SDK `randStr` eşdeğeri).
     *
     * Her API çağrısında yeni bir `$key` üretilir; `apikey` bu key ile hash'lenir.
     */
    protected function randKey(int $length = 8): string
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $max = strlen($chars) - 1;
        $out = '';
        for ($i = 0; $i < $length; $i++) {
            $out .= $chars[random_int(0, $max)];
        }

        return $out;
    }

    /**
     * Virtualizor resmî auth-hash (SDK `make_apikey`): apikey = key . md5(apipass . key).
     *
     * Ham `apipass` ASLA URL'e konmaz; yalnız hash gider.
     */
    protected function makeApiKey(string $key, string $apiPass): string
    {
        return $key.md5($apiPass.$key);
    }

    /**
     * Virtualizor API'sine istek gonderir (resmî Admin SDK auth şeması, S1 fix).
     *
     * URL: https://{host}:{port}/index.php?act={act}&api=serialize&apikey={rand.md5(pass.rand)}
     *      &apidata={rawurlencode(base64(serialize($requestParams)))}
     *
     * Kimlik dogrulama (SDK `admin.php` make_apikey): her istekte 8-char rastgele
     * `$key` + `apikey = $key.md5($apipass.$key)`. Ham `apipass` GÖNDERİLMEZ.
     * Yanıt PHP-serialize'dir → `unserialize` ile çözülür.
     *
     * Host/creds tek doğru kaynaktan gelir (PRC-1015): atanmış sunucu öncelikli
     * `serverConfig($params)` (hostname/port/secure) + `resolveCredentials($params)`
     * (apikey/apipass). Modül `$this->config`'i inline OKUMAZ.
     *
     * @param  string  $act  Virtualizor API act'i (addvs, vs, editvs, servers, plans, vnc vb.)
     * @param  array  $requestParams  Gonderilecek act parametreleri (apidata + query)
     * @param  array  $params  Modül params (host/creds çözümü için thread edilir)
     * @return array API yaniti (unserialize edilmiş)
     */
    protected function callApi($act, $requestParams = [], $params = [])
    {
        if (! is_array($requestParams)) {
            $requestParams = [];
        }
        if (! is_array($params)) {
            $params = [];
        }

        $server = $this->serverConfig($params);
        $creds = $this->resolveCredentials($params);

        $protocol = $server['secure'] ? 'https' : 'http';
        $hostname = $server['hostname'];
        $port = (! empty($server['port']) && (int) $server['port'] > 0) ? (int) $server['port'] : $this->apiPort;
        $apiKey = $creds['api_key'];
        $apiPass = $creds['api_pass'];

        if ($hostname === '' || $apiKey === '' || $apiPass === '') {
            return [
                'error' => __('admin/modules.virtualizor_config_hostname_missing'),
            ];
        }

        // Resmî SDK auth: per-request rand key + hashed apikey; ham apipass gitmez.
        $randKey = $this->randKey(8);
        $hashedApiKey = $this->makeApiKey($randKey, $apiPass);

        // Resmî SDK transport (sdk/admin.php call()): URL query yalnız auth
        // (act + api=serialize + apikey); TÜM aksiyon parametreleri POST gövdesine
        // http_build_query ile form-encoded gider ($post kanalı). SDK apidata
        // ($data) kanalını admin action'larında HİÇ kullanmıyor (daima array()),
        // bu yüzden addvs/editvs/addips/rebuild vb. ham form field olarak POST edilir.
        $query = [
            'act' => $act,
            'api' => 'serialize',
            'apikey' => $hashedApiKey,
        ];

        $url = "{$protocol}://{$hostname}:{$port}/index.php?".http_build_query($query);

        // Tüm aksiyon parametreleri form-encoded POST gövdesi.
        $postFields = ! empty($requestParams) ? http_build_query($requestParams) : '';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // TLS doğrulaması AÇIK: Virtualizor panelleri sık sık self-signed sertifika
        // kullansa da man-in-the-middle riskini önlemek için verify açık tutulur.
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

        if ($postFields !== '') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        }

        $body = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        $curlErrno = curl_errno($ch);

        curl_close($ch);

        // cURL hata kontrolu — kimlik/anahtar sızıntısı riski nedeniyle ham gövde
        // veya URL (apikey/apipass içerir) ASLA loglanmaz; yalnız act + transport hata.
        if ($curlErrno) {
            Log::error('Virtualizor API cURL error', [
                'act' => $act,
                'errno' => $curlErrno,
                'error' => $curlError,
            ]);

            return [
                'error' => __('admin/modules.virtualizor_curl_error', [
                    'errno' => $curlErrno,
                    'error' => $curlError,
                ]),
            ];
        }

        // HTTP hata kodu kontrolu — ham response loglanmaz.
        if ($httpCode >= 400) {
            Log::error('Virtualizor API HTTP error', [
                'act' => $act,
                'http_code' => $httpCode,
            ]);

            return [
                'error' => __('admin/modules.virtualizor_api_call_failed', ['code' => $httpCode]),
            ];
        }

        // Yanıt PHP-serialize (api=serialize). Güvenli unserialize: obje inflate
        // edilmez (yalnız skaler/array) — ham response loglanmaz.
        $responseData = @unserialize((string) $body, ['allowed_classes' => false]);

        if ($responseData === false && trim((string) $body) !== serialize(false)) {
            Log::error('Virtualizor API response parse error', [
                'act' => $act,
            ]);

            return [
                'error' => __('admin/modules.virtualizor_api_json_error'),
            ];
        }

        return is_array($responseData) ? $responseData : [];
    }

    /**
     * API yanitindan hata mesajini cikarir
     *
     * @param  array  $response  API yaniti
     * @return string Hata mesaji veya bos string
     */
    protected function extractError(array $response): string
    {
        if (isset($response['error']) && is_array($response['error'])) {
            return implode(', ', $response['error']);
        }

        if (isset($response['error']) && is_string($response['error'])) {
            return $response['error'];
        }

        if (isset($response['errors']) && is_array($response['errors'])) {
            return implode(', ', $response['errors']);
        }

        return '';
    }

    /**
     * addvs yanıtından yeni VPS id'sini çıkarır.
     *
     * Resmî addvs `vs_info` (yeni VPS satırı) döndürür; SDK bunu `newvs`'ten
     * map'ler. Sırayla `vs_info.vpsid` → `newvs.vpsid` → `done.vpsid` → done
     * (skaler) yollarını dener.
     *
     * @return string|null Yeni vpsid veya bulunamazsa null
     */
    protected function extractNewVpsId(array $response): ?string
    {
        foreach (['vs_info', 'newvs'] as $key) {
            if (isset($response[$key]) && is_array($response[$key])) {
                $node = $response[$key];
                if (isset($node['vpsid']) && is_scalar($node['vpsid']) && (string) $node['vpsid'] !== '') {
                    return (string) $node['vpsid'];
                }
                // Bazı sürümler {vpsid => {...}} sarmalar; ilk anahtar vpsid olabilir.
                $firstKey = array_key_first($node);
                if (is_numeric($firstKey)) {
                    return (string) $firstKey;
                }
            }
        }

        if (isset($response['done']) && is_array($response['done'])) {
            if (isset($response['done']['vpsid']) && is_scalar($response['done']['vpsid'])) {
                $v = (string) $response['done']['vpsid'];

                return $v !== '' ? $v : null;
            }
        }

        if (isset($response['vpsid']) && is_scalar($response['vpsid']) && (string) $response['vpsid'] !== '') {
            return (string) $response['vpsid'];
        }

        return null;
    }
}
