<?php

namespace App\Modules\Product\Hypervm;

use App\Core\Product\AbstractProduct;
use App\Core\Product\Events\AccountCreated;

class Hypervm extends AbstractProduct
{
    // HyperVM API varsayılan portlar
    protected $apiPortSsl = 8887;

    protected $apiPortNonSsl = 8888;

    // HyperVM API endpoint
    protected $apiEndpoint = '/webcommand.php';

    /**
     * HyperVM modülü server gerektirir
     */
    public function requiresServer(): bool
    {
        return true;
    }

    /**
     * Yeni bir HyperVM VPS oluşturur
     *
     * WHMCS hypervm_CreateAccount referansı:
     * - VPS tipi (openvz/xen), plan, OS template, sync server, IP sayısı
     * - Username'e ".vm" eki, hostname desteği, welcome email kontrolü
     * - Oluşturma sonrası IP adresi alarak dedicated IP kaydı
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function createAccount(array $params)
    {
        $requiredParams = [
            'username', 'password',
        ];

        foreach ($requiredParams as $param) {
            if (! isset($params[$param]) || empty($params[$param])) {
                return [
                    'status' => 'error',
                    'message' => __('admin/modules.hypervm_param_missing', ['param' => $param]),
                ];
            }
        }

        // Username ".vm" eki kontrolü (WHMCS referansı)
        $username = $params['username'];
        if (substr($username, -3) !== '.vm') {
            $username .= '.vm';
        }

        // VPS tipi (openvz veya xen) — module-config'ten
        $vpsType = $this->configOption($params, 'Type')
            ?? $this->moduleConfig($params, 'type', 'openvz');

        // Plan adı: flat $params['plan'] (builder module-config'ten emit eder) → fallback
        $planName = $params['plan']
            ?? $params['package']
            ?? $this->configOption($params, 'Plan Name')
            ?? $this->moduleConfig($params, 'plan', '');
        $planKey = $this->resolvePlanKey((string) $planName, $params);

        // OS template — configurable option override öncelikli
        $osTemplate = $this->configOption($params, 'Operating System')
            ?? $this->moduleConfig($params, 'os_template', '');

        // Sync server (Xen için)
        $syncServer = $this->moduleConfig($params, 'sync_server', '');

        // IP sayısı
        $numIps = $this->configOption($params, 'Number Of IPs')
            ?? $this->moduleConfig($params, 'num_ips', '1');

        // API isteği oluştur
        $queryParams = [
            'action' => 'add',
            'class' => 'vps',
            'v-type' => $vpsType,
            'name' => $username,
            'v-num_ipaddress_f' => $numIps,
            'v-contactemail' => $params['email'] ?? '',
            'v-password' => $params['password'],
            'v-ostemplate' => $osTemplate,
        ];

        // Sync server belirtildiyse ekle
        if (! empty($syncServer)) {
            $queryParams['v-syncserver'] = $syncServer;
        }

        // Plan belirtildiyse ekle
        if (! empty($planKey)) {
            $queryParams['v-plan_name'] = $planKey;
        }

        // Hostname desteği
        if (! empty($params['hostname'])) {
            $vhostname = $params['hostname'];
            if (! empty($params['domain']) && $vhostname !== $params['domain']) {
                if (stristr($params['domain'], $vhostname . '.') === false) {
                    $vhostname .= '.' . $params['domain'];
                }
            }
            $queryParams['v-hostname'] = $vhostname;
        } elseif (! empty($params['domain'])) {
            $queryParams['v-hostname'] = $params['domain'];
        }

        // Welcome email kontrolü (varsayılan: gönder)
        $disableWelcomeEmail = $this->moduleConfig($params, 'disable_welcome_email', false);
        if (! $disableWelcomeEmail) {
            $queryParams['v-send_welcome_f'] = 'on';
        }

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] === 'error') {
            $result = [
                'status' => 'error',
                'message' => $response['message'] ?? __('admin/modules.hypervm_account_create_failed'),
                'data' => $response,
            ];

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

            return $result;
        }

        // VPS oluşturulduktan sonra IP adresini al
        $ipAddress = $this->getVpsIpAddress($username, $params);

        $result = [
            'status' => 'success',
            'message' => __('admin/modules.hypervm_account_created_success'),
            'data' => [
                'username' => $username,
                'ip_address' => $ipAddress,
                'type' => $vpsType,
            ],
        ];

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

        return $result;
    }

    /**
     * Bir HyperVM VPS'i askıya alır (disable)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function suspendAccount(array $params)
    {
        if (! isset($params['username']) || empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_username_required'),
            ];
        }

        $queryParams = [
            'class' => 'vps',
            'name' => $params['username'],
            'action' => 'update',
            'subaction' => 'disable',
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.hypervm_account_suspended_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.hypervm_account_suspend_failed'),
            'data' => $response,
        ];
    }

    /**
     * Askıya alınmış bir HyperVM VPS'i aktifleştirir (enable)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function unsuspendAccount(array $params)
    {
        if (! isset($params['username']) || empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_username_required'),
            ];
        }

        $queryParams = [
            'class' => 'vps',
            'name' => $params['username'],
            'action' => 'update',
            'subaction' => 'enable',
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.hypervm_account_unsuspended_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.hypervm_account_unsuspend_failed'),
            'data' => $response,
        ];
    }

    /**
     * Bir HyperVM VPS'i siler (delete)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function terminateAccount(array $params)
    {
        if (! isset($params['username']) || empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_username_required'),
            ];
        }

        $queryParams = [
            'class' => 'vps',
            'name' => $params['username'],
            'action' => 'delete',
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.hypervm_account_deleted_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.hypervm_account_delete_failed'),
            'data' => $response,
        ];
    }

    /**
     * Bir HyperVM VPS'in şifresini değiştirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function changeAccountPassword(array $params)
    {
        if (! isset($params['username']) || empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_username_required'),
            ];
        }

        if (! isset($params['password']) || empty($params['password'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_password_required'),
            ];
        }

        // lxlabs gerçek subaction'ı: rootpassword (updateRootpassword),
        // alan adı v-rootpassword (vps__baselib.php:120,308). WHMCS'te
        // ChangePassword fonksiyonu yok; "change_password" fabrikasyondu.
        $queryParams = [
            'class' => 'vps',
            'name' => $params['username'],
            'action' => 'update',
            'subaction' => 'rootpassword',
            'v-rootpassword' => $params['password'],
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.hypervm_password_changed_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.hypervm_password_change_failed'),
            'data' => $response,
        ];
    }

    /**
     * Bir HyperVM VPS'in planını değiştirir (change_plan)
     *
     * WHMCS hypervm_ChangePackage referansı:
     * - Resource plan listesini alıp plan key eşleştirmesi yapar
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function changeAccountPackage(array $params)
    {
        if (! isset($params['username']) || empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_username_required'),
            ];
        }

        if (! isset($params['plan']) || empty($params['plan'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_plan_required'),
            ];
        }

        // Plan key'i resource plan listesinden çöz
        $planKey = $this->resolvePlanKey((string) $params['plan'], $params);

        if (empty($planKey)) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_plan_not_found', ['plan' => $params['plan']]),
            ];
        }

        $queryParams = [
            'class' => 'vps',
            'name' => $params['username'],
            'action' => 'update',
            'subaction' => 'change_plan',
            'v-newresourceplan' => $planKey,
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.hypervm_package_changed_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.hypervm_package_change_failed'),
            'data' => $response,
        ];
    }

    /**
     * Bağlantı testini gerçekleştirir (resource plan listesini alarak)
     *
     * @param  array  $params  Test parametreleri
     * @return array Test sonucu
     */
    public function testConnection(array $params = [])
    {
        $queryParams = [
            'action' => 'simplelist',
            'resource' => 'resourceplan',
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.hypervm_connection_test_success'),
                'data' => $response['data'] ?? [],
            ];
        }

        return [
            'status' => 'error',
            'message' => __('admin/modules.hypervm_connection_test_failed'),
            'data' => $response,
        ];
    }

    /**
     * HyperVM kontrol paneli login URL'i oluşturur
     *
     * WHMCS hypervm_LoginLink referansı:
     * - display.php?frm_action=show&frm_o_o[0][class]=vps&frm_o_o[0][nname]=USERNAME
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function createSSOLogin(array $params)
    {
        if (! isset($params['username']) || empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_username_required'),
            ];
        }

        $server = $this->serverConfig($params);
        $protocol = ! empty($server['secure']) ? 'https' : 'http';
        $hostname = $server['hostname'];
        $port = $this->getApiPort($params);

        $loginUrl = "{$protocol}://{$hostname}:{$port}/display.php"
            . '?frm_action=show'
            . '&frm_o_o[0][class]=vps'
            . '&frm_o_o[0][nname]=' . urlencode($params['username']);

        return [
            'status' => 'success',
            'message' => __('admin/modules.hypervm_sso_created_success'),
            'url' => $loginUrl,
        ];
    }

    /**
     * Admin panelinde gösterilecek alanları döndürür
     *
     * WHMCS hypervm_ConfigOptions referansı:
     * Type (openvz/xen), Plan Name, OS Template, Server, Number Of IPs, Disable Welcome Email
     *
     * @return array Admin panel alanları
     */
    public function adminFields()
    {
        return [
            'hostname' => [
                'name' => __('admin/modules.hypervm_field_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.hypervm_field_hostname_description'),
                'required' => true,
            ],
            'port' => [
                'name' => __('admin/modules.hypervm_field_port'),
                'type' => 'text',
                'description' => __('admin/modules.hypervm_field_port_description'),
                'required' => false,
                'default' => '8888',
            ],
            'username' => [
                'name' => __('admin/modules.hypervm_field_username'),
                'type' => 'text',
                'description' => __('admin/modules.hypervm_field_username_description'),
                'required' => true,
            ],
            'password' => [
                'name' => __('admin/modules.hypervm_field_password'),
                'type' => 'password',
                'description' => __('admin/modules.hypervm_field_password_description'),
                'required' => true,
            ],
            'type' => [
                'name' => __('admin/modules.hypervm_field_type'),
                'type' => 'dropdown',
                'description' => __('admin/modules.hypervm_field_type_description'),
                'options' => [
                    'openvz' => 'OpenVZ',
                    'xen' => 'Xen',
                ],
                'default' => 'openvz',
            ],
            'plan' => [
                'name' => __('admin/modules.hypervm_field_plan'),
                'type' => 'text',
                'description' => __('admin/modules.hypervm_field_plan_description'),
                'required' => false,
            ],
            'os_template' => [
                'name' => __('admin/modules.hypervm_field_os_template'),
                'type' => 'text',
                'description' => __('admin/modules.hypervm_field_os_template_description'),
                'required' => false,
            ],
            'sync_server' => [
                'name' => __('admin/modules.hypervm_field_sync_server'),
                'type' => 'text',
                'description' => __('admin/modules.hypervm_field_sync_server_description'),
                'required' => false,
            ],
            'num_ips' => [
                'name' => __('admin/modules.hypervm_field_num_ips'),
                'type' => 'dropdown',
                'description' => __('admin/modules.hypervm_field_num_ips_description'),
                'options' => [
                    '0' => '0',
                    '1' => '1',
                    '2' => '2',
                    '3' => '3',
                    '4' => '4',
                    '5' => '5',
                    '6' => '6',
                    '7' => '7',
                    '8' => '8',
                ],
                'default' => '1',
            ],
            'disable_welcome_email' => [
                'name' => __('admin/modules.hypervm_field_disable_welcome_email'),
                'type' => 'checkbox',
                'description' => __('admin/modules.hypervm_field_disable_welcome_email_description'),
                'default' => false,
            ],
            'secure' => [
                'name' => __('admin/modules.hypervm_field_secure'),
                'type' => 'checkbox',
                'description' => __('admin/modules.hypervm_field_secure_description'),
                'default' => false,
            ],
        ];
    }

    /**
     * Müşteri panelinde gösterilecek alanları döndürür
     *
     * @return array Müşteri panel alanları
     */
    public function clientFields()
    {
        return [
            'username' => [
                'name' => __('admin/modules.hypervm_field_client_username'),
                'type' => 'text',
                'description' => __('admin/modules.hypervm_field_client_username_description'),
                'required' => true,
            ],
            'password' => [
                'name' => __('admin/modules.hypervm_field_client_password'),
                'type' => 'password',
                'description' => __('admin/modules.hypervm_field_client_password_description'),
                'required' => true,
            ],
            'hostname' => [
                'name' => __('admin/modules.hypervm_field_client_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.hypervm_field_client_hostname_description'),
                'required' => false,
            ],
            'email' => [
                'name' => __('admin/modules.hypervm_field_client_email'),
                'type' => 'text',
                'description' => __('admin/modules.hypervm_field_client_email_description'),
                'required' => false,
            ],
        ];
    }

    /**
     * Server yönetimi için gösterilecek alanları döndürür
     *
     * @return array Server yönetimi alanları
     */
    public function serverFields()
    {
        return [
            'hostname' => [
                'name' => __('admin/modules.hypervm_field_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.hypervm_field_hostname_description'),
                'required' => true,
            ],
            'port' => [
                'name' => __('admin/modules.hypervm_field_port'),
                'type' => 'text',
                'description' => __('admin/modules.hypervm_field_port_description'),
                'required' => false,
                'default' => '8888',
            ],
            'username' => [
                'name' => __('admin/modules.hypervm_field_username'),
                'type' => 'text',
                'description' => __('admin/modules.hypervm_field_username_description'),
                'required' => true,
            ],
            'password' => [
                'name' => __('admin/modules.hypervm_field_password'),
                'type' => 'password',
                'description' => __('admin/modules.hypervm_field_password_description'),
                'required' => true,
            ],
            'secure' => [
                'name' => __('admin/modules.hypervm_field_secure'),
                'type' => 'checkbox',
                'description' => __('admin/modules.hypervm_field_secure_description'),
                'default' => false,
            ],
        ];
    }

    /**
     * Statik module-config doğrulaması (boot-time).
     *
     * NOT: Çalışma-zamanı bağlantı kimlik bilgileri artık `serverConfig($params)`
     * üzerinden (atanmış Server satırı öncelikli) çözülür — bu metot yalnız
     * statik fallback config'in (server atanmadığında kullanılan) tamlığını
     * denetler. Parent imzası parametresizdir; `$params` erişimi yoktur.
     *
     * @return bool Yapılandırma doğru mu?
     *
     * @throws \Exception Eksik yapılandırma durumunda
     */
    public function validateConfig()
    {
        if (empty($this->config['hostname'])) {
            throw new \Exception(__('admin/modules.hypervm_config_hostname_missing'));
        }

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

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

        return true;
    }

    /**
     * VPS kaynak kullanım bilgilerini döndürür (getproperty)
     *
     * @param  array  $params  Parametreler
     * @return array|null Kaynak kullanım verileri veya null
     */
    public function getResourceUsage(array $params): ?array
    {
        if (empty($params['username'])) {
            return null;
        }

        // VPS özelliklerini sorgula
        $queryParams = [
            'action' => 'getproperty',
            'class' => 'vps',
            'name' => $params['username'],
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] !== 'success' || empty($response['data'])) {
            return null;
        }

        $resources = [];
        $rawData = $response['data'];

        // Disk kullanımı
        if (isset($rawData['disk_usage']) || isset($rawData['diskusage'])) {
            $diskUsed = (float) ($rawData['disk_usage'] ?? $rawData['diskusage'] ?? 0);
            $diskLimit = (float) ($rawData['disk_total'] ?? $rawData['disktotal'] ?? 0);
            $resources[] = [
                'name' => __('admin/modules.hypervm_resource_disk'),
                'used' => $diskUsed,
                'limit' => $diskLimit,
                'unit' => 'MB',
                'percentage' => $diskLimit > 0 ? round(($diskUsed / $diskLimit) * 100, 2) : 0,
            ];
        }

        // Bellek kullanımı
        if (isset($rawData['memory_usage']) || isset($rawData['memusage'])) {
            $memUsed = (float) ($rawData['memory_usage'] ?? $rawData['memusage'] ?? 0);
            $memLimit = (float) ($rawData['memory_total'] ?? $rawData['memtotal'] ?? 0);
            $resources[] = [
                'name' => __('admin/modules.hypervm_resource_memory'),
                'used' => $memUsed,
                'limit' => $memLimit,
                'unit' => 'MB',
                'percentage' => $memLimit > 0 ? round(($memUsed / $memLimit) * 100, 2) : 0,
            ];
        }

        // Bandwidth/traffic kullanımı
        // lxlabs kanonik alan: traffic_usage (vpslib.php:753 $this->used->traffic_usage).
        // bandwidth_usage/bwusage yalnız geriye-uyum fallback.
        if (isset($rawData['traffic_usage']) || isset($rawData['bandwidth_usage']) || isset($rawData['bwusage'])) {
            $bwUsed = (float) ($rawData['traffic_usage'] ?? $rawData['bandwidth_usage'] ?? $rawData['bwusage'] ?? 0);
            $bwLimit = (float) ($rawData['traffic_total'] ?? $rawData['bandwidth_total'] ?? $rawData['bwtotal'] ?? 0);
            $resources[] = [
                'name' => __('admin/modules.hypervm_resource_bandwidth'),
                'used' => $bwUsed,
                'limit' => $bwLimit,
                'unit' => 'GB',
                'percentage' => $bwLimit > 0 ? round(($bwUsed / $bwLimit) * 100, 2) : 0,
            ];
        }

        // CPU kullanımı
        if (isset($rawData['cpu_usage']) || isset($rawData['cpuusage'])) {
            $cpuPercent = (float) ($rawData['cpu_usage'] ?? $rawData['cpuusage'] ?? 0);
            $resources[] = [
                'name' => __('admin/modules.hypervm_resource_cpu'),
                'used' => $cpuPercent,
                'limit' => 100,
                'unit' => '%',
                'percentage' => $cpuPercent,
            ];
        }

        return ! empty($resources) ? $resources : null;
    }

    /**
     * Admin panelde gösterilecek özel butonları döndürür
     *
     * WHMCS hypervm_AdminCustomButtonArray referansı: Restart
     * VPS modülüne uygun ek butonlar: Startup, Shutdown
     *
     * @return array Admin butonları
     */
    public function getAdminButtons(): array
    {
        return [
            [
                'action' => 'reboot',
                'label' => __('admin/modules.hypervm_action_reboot'),
                'icon' => 'fas fa-sync',
                'class' => 'btn-outline-warning',
            ],
            [
                'action' => 'startup',
                'label' => __('admin/modules.hypervm_action_startup'),
                'icon' => 'fas fa-play',
                'class' => 'btn-outline-success',
            ],
            [
                'action' => 'shutdown',
                'label' => __('admin/modules.hypervm_action_shutdown'),
                'icon' => 'fas fa-power-off',
                'class' => 'btn-outline-danger',
            ],
            [
                'action' => 'vps_info',
                'label' => __('admin/modules.hypervm_action_vps_info'),
                'icon' => 'fas fa-info-circle',
                'class' => 'btn-outline-primary',
            ],
            [
                'action' => 'list_plans',
                'label' => __('admin/modules.hypervm_action_list_plans'),
                'icon' => 'fas fa-list',
                'class' => 'btn-outline-info',
            ],
        ];
    }

    /**
     * Admin özel action'ı işler
     *
     * @param  string  $action  Action adı
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function adminCustomAction(string $action, array $params): array
    {
        switch ($action) {
            case 'reboot':
                return $this->vpsReboot($params);

            case 'startup':
                return $this->vpsStartup($params);

            case 'shutdown':
                return $this->vpsShutdown($params);

            case 'vps_info':
                return $this->vpsInfo($params);

            case 'list_plans':
                return $this->listResourcePlans($params);

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

    /**
     * Client area'da gösterilecek action'ları döndürür
     *
     * WHMCS hypervm_ClientAreaCustomButtonArray referansı: Restart
     * VPS modülüne uygun ek butonlar: Startup, Shutdown
     *
     * @return array Client action'ları
     */
    public function getClientActions(): array
    {
        $actions = parent::getClientActions();

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

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

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

        $actions['login_panel'] = [
            'label' => __('admin/modules.hypervm_action_login_panel'),
            'icon' => 'fas fa-sign-in-alt',
            'class' => 'btn-outline-primary',
            'enabled' => true,
        ];

        return $actions;
    }

    /**
     * Client action'ı işler
     *
     * @param  string  $action  Action adı
     * @param  array  $params  Parametreler
     * @return array Sonuç
     */
    public function handleClientAction(string $action, array $params): array
    {
        $vpsActions = ['reboot', 'startup', 'shutdown'];

        if (in_array($action, $vpsActions)) {
            return $this->adminCustomAction($action, $params);
        }

        if ($action === 'login_panel') {
            return $this->createSSOLogin($params);
        }

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

    // =========================================================================
    // VPS Power Management Actions
    // =========================================================================

    /**
     * VPS'i yeniden başlatır (reboot)
     *
     * WHMCS hypervm_restart referansı:
     * class=vps&name=USERNAME&action=update&subaction=reboot
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    protected function vpsReboot(array $params): array
    {
        if (empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_username_required'),
            ];
        }

        $queryParams = [
            'class' => 'vps',
            'name' => $params['username'],
            'action' => 'update',
            'subaction' => 'reboot',
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.hypervm_action_reboot_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.hypervm_action_reboot_failed'),
            'data' => $response,
        ];
    }

    /**
     * VPS'i başlatır (start/on)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    protected function vpsStartup(array $params): array
    {
        if (empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_username_required'),
            ];
        }

        // lxlabs gerçek subaction'ı: boot (updateboot, vpslib.php:2229).
        // "start" fabrikasyondu.
        $queryParams = [
            'class' => 'vps',
            'name' => $params['username'],
            'action' => 'update',
            'subaction' => 'boot',
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.hypervm_action_startup_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.hypervm_action_startup_failed'),
            'data' => $response,
        ];
    }

    /**
     * VPS'i kapatır (stop/off)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    protected function vpsShutdown(array $params): array
    {
        if (empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_username_required'),
            ];
        }

        // lxlabs gerçek subaction'ı: poweroff (updatePoweroff, vpslib.php:1732).
        // "stop" fabrikasyondu.
        $queryParams = [
            'class' => 'vps',
            'name' => $params['username'],
            'action' => 'update',
            'subaction' => 'poweroff',
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.hypervm_action_shutdown_success'),
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.hypervm_action_shutdown_failed'),
            'data' => $response,
        ];
    }

    /**
     * VPS bilgilerini getirir (getproperty)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    protected function vpsInfo(array $params): array
    {
        if (empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_username_required'),
            ];
        }

        $queryParams = [
            'action' => 'getproperty',
            'class' => 'vps',
            'name' => $params['username'],
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.hypervm_vps_info_success'),
                'data' => $response['data'] ?? [],
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.hypervm_vps_info_failed'),
            'data' => $response,
        ];
    }

    /**
     * Sunucudaki resource plan listesini getirir
     *
     * @return array İşlem sonucu
     */
    protected function listResourcePlans(array $params = []): array
    {
        $queryParams = [
            'action' => 'simplelist',
            'resource' => 'resourceplan',
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] === 'success') {
            return [
                'status' => 'success',
                'message' => __('admin/modules.hypervm_list_plans_success'),
                'data' => $response['data'] ?? [],
            ];
        }

        return [
            'status' => 'error',
            'message' => $response['message'] ?? __('admin/modules.hypervm_list_plans_failed'),
            'data' => $response,
        ];
    }

    // =========================================================================
    // HyperVM API Communication
    // =========================================================================

    /**
     * HyperVM API ile iletişim kurar (lxlabs JSON API)
     *
     * WHMCS lxlabs_get_via_json referansı:
     * - POST /webcommand.php
     * - login-class=client&login-name=USERNAME&login-password=PASSWORD&output-type=json&REQUEST_PARAMS
     * - Yanıt JSON, hata durumunda return=error, message=HATA_MESAJI
     *
     * @param  array  $params  API parametreleri (action, class, name, vb.)
     * @return array API yanıtı ['status' => 'success'|'error', 'message' => ..., 'data' => ...]
     */
    protected function callHypervmApi(array $queryParams = [], array $params = [])
    {
        // Bağlantı bilgileri — DAİMA serverConfig (atanmış sunucu öncelikli)
        $server = $this->serverConfig($params);
        $protocol = ! empty($server['secure']) ? 'https' : 'http';
        $hostname = $server['hostname'];
        $port = $this->getApiPort($params);
        $username = $server['username'];
        $password = $server['password'];

        // API URL oluştur
        $url = "{$protocol}://{$hostname}:{$port}{$this->apiEndpoint}";

        // Login ve output parametreleri ekle (lxlabs standardı)
        $postData = array_merge([
            'login-class' => 'client',
            'login-name' => $username,
            'login-password' => $password,
            'output-type' => 'json',
        ], $queryParams);

        // cURL ile API çağrısı
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);

        $response = curl_exec($ch);
        $curlError = curl_error($ch);
        $curlErrno = curl_errno($ch);

        curl_close($ch);

        // cURL hatası kontrolü
        if ($curlErrno) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_curl_error', [
                    'errno' => $curlErrno,
                    'error' => $curlError,
                ]),
            ];
        }

        // Yanıtı trimle
        $response = trim($response);

        // JSON decode
        $decoded = json_decode($response);

        if (json_last_error() !== JSON_ERROR_NONE || ! is_object($decoded)) {
            // PCI: ham yanıt (kimlik/hata dökümü içerebilir) loglanmaz/dönülmez.
            return [
                'status' => 'error',
                'message' => __('admin/modules.hypervm_invalid_response'),
            ];
        }

        // lxlabs hata kontrolü (return === "error")
        if (isset($decoded->return) && $decoded->return === 'error') {
            return [
                'status' => 'error',
                'message' => $decoded->message ?? __('admin/modules.hypervm_api_unknown_error'),
                'data' => $this->objectToArray($decoded),
            ];
        }

        // Başarılı yanıt
        return [
            'status' => 'success',
            'message' => __('admin/modules.hypervm_api_success'),
            'data' => $this->objectToArray($decoded->result ?? $decoded),
        ];
    }

    /**
     * VPS'e atanan IP adresini getirir
     *
     * WHMCS referansı (hypervm_CreateAccount:77-78):
     * action=getproperty&class=vps&name=USERNAME&v-coma_vmipaddress_a=
     * Yanıtta IP, obfuscated wrapper anahtarı altında döner:
     *   $result->result->_obfuscated_762D636F6D615F766D6970616464726573735F61_
     * Buradaki hex "762D...5F61" = "v-coma_vmipaddress_a" (bkz. hex2bin).
     * Değer tek IP ya da virgülle ayrılmış IP listesi olabilir (coma_ öneki).
     *
     * @param  string  $username  VPS kullanıcı adı
     * @return string|null IP adresi veya null
     */
    protected function getVpsIpAddress(string $username, array $params = []): ?string
    {
        $queryParams = [
            'action' => 'getproperty',
            'class' => 'vps',
            'name' => $username,
            'v-coma_vmipaddress_a' => '',
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] !== 'success' || empty($response['data'])) {
            return null;
        }

        $data = $response['data'];

        // 1) Kanonik: WHMCS'in okuduğu obfuscated wrapper anahtarı
        //    _obfuscated_<hex(v-coma_vmipaddress_a)>_
        $obfuscatedKey = '_obfuscated_' . strtoupper(bin2hex('v-coma_vmipaddress_a')) . '_';
        if (! empty($data[$obfuscatedKey])) {
            return $this->firstIp($data[$obfuscatedKey]);
        }

        // 2) Deobfuscated/düz anahtar varyasyonları
        foreach (['coma_vmipaddress_a', 'v-coma_vmipaddress_a', 'vmipaddress_a'] as $key) {
            if (! empty($data[$key])) {
                return $this->firstIp($data[$key]);
            }
        }

        // 3) Son çare: değerler arasında ilk geçerli IP'yi tara
        foreach ($data as $value) {
            $ip = $this->firstIp($value);
            if ($ip !== null) {
                return $ip;
            }
        }

        return null;
    }

    /**
     * Ham IP değerinden (tek IP, virgül/boşlukla ayrılmış liste veya dizi)
     * ilk geçerli IP adresini çıkarır.
     *
     * @param  mixed  $value
     * @return string|null
     */
    protected function firstIp($value): ?string
    {
        if (is_array($value)) {
            foreach ($value as $item) {
                $ip = $this->firstIp($item);
                if ($ip !== null) {
                    return $ip;
                }
            }

            return null;
        }

        if (! is_string($value) || $value === '') {
            return null;
        }

        foreach (preg_split('/[\s,]+/', trim($value)) as $candidate) {
            if ($candidate !== '' && filter_var($candidate, FILTER_VALIDATE_IP)) {
                return $candidate;
            }
        }

        return null;
    }

    /**
     * Plan adını resource plan key'ine çözer
     *
     * WHMCS hypervm_CreateAccount ve hypervm_ChangePackage referansı:
     * - simplelist&resource=resourceplan ile tüm planları listeler
     * - Plan adını (case-insensitive) eşleştirerek key döndürür
     *
     * @param  string  $planName  Plan adı
     * @return string|null Plan key veya null
     */
    protected function resolvePlanKey(string $planName, array $params = []): ?string
    {
        if (empty($planName)) {
            return null;
        }

        $queryParams = [
            'action' => 'simplelist',
            'resource' => 'resourceplan',
        ];

        $response = $this->callHypervmApi($queryParams, $params);

        if ($response['status'] !== 'success' || empty($response['data'])) {
            return null;
        }

        $planData = $response['data'];

        // Plan adını key ile eşleştir (case-insensitive, WHMCS referansı)
        if (is_array($planData)) {
            foreach ($planData as $key => $value) {
                if (is_string($value) && strtolower($value) === strtolower($planName)) {
                    return (string) $key;
                }
            }
        }

        // Doğrudan plan adını key olarak dene
        return $planName;
    }

    /**
     * Aktif API portunu döndürür
     *
     * @return int API portu
     */
    protected function getApiPort(array $params = []): int
    {
        $server = $this->serverConfig($params);

        // Sunucu/config'den gelen port öncelikli
        if (! empty($server['port'])) {
            return (int) $server['port'];
        }

        // SSL durumuna göre varsayılan port
        return ! empty($server['secure']) ? $this->apiPortSsl : $this->apiPortNonSsl;
    }

    /**
     * PHP objesini array'e dönüştürür (recursive)
     *
     * WHMCS hypervm_objectToArray referansı
     *
     * @param  mixed  $data  Dönüştürülecek veri
     * @return mixed Array olarak dönüştürülmüş veri
     */
    protected function objectToArray($data)
    {
        if (is_object($data)) {
            $data = get_object_vars($data);
        }

        if (is_array($data)) {
            return array_map([$this, 'objectToArray'], $data);
        }

        return $data;
    }
}
