<?php

namespace App\Modules\Product\Cloudmin;

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

class Cloudmin extends AbstractProduct
{
    // CloudMin API varsayılan port
    protected $apiPort = 10000;

    // CloudMin VPS yönetim endpoint
    protected $apiEndpoint = '/server-manager/remote.cgi';

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

    /**
     * Yeni bir CloudMin VPS oluşturur (create-system)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function createAccount(array $params)
    {
        // Oluşturulacak sistemin hostname'i (builder → $params['domain'])
        $host = $params['domain'] ?? $params['hostname'] ?? null;

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

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

        $postData = [
            'host' => $host,
            'ssh-pass' => $params['password'],
            'desc' => 'ProCP Service ID ' . ($params['service_id'] ?? ''),
        ];

        // VPS tipi (xen, openvz, vservers, zones, real) — flat veya config-option
        $type = $params['type'] ?? $this->configOption($params, 'Type', $this->moduleConfig($params, 'type'));
        if (! empty($type)) {
            $postData['type'] = $type;
        }

        // Plan flat ($params['plan'], builder module-config'ten emit) + fallback
        $plan = ! empty($params['plan'])
            ? $params['plan']
            : $this->configOption($params, 'Plan Name', $this->moduleConfig($params, 'plan'));
        if (! empty($plan)) {
            $postData['plan'] = $plan;
        }

        // OS şablonu/image — flat veya config-option
        $image = $params['os_template'] ?? $this->configOption($params, 'Image', $this->moduleConfig($params, 'os_template'));
        if (! empty($image)) {
            $postData['image'] = $image;
        }

        // Xen host — flat veya config-option
        $xenHost = $params['xen_host'] ?? $this->configOption($params, 'Xen Host', $this->moduleConfig($params, 'xen_host'));
        if (! empty($xenHost)) {
            $postData['xen-host'] = $xenHost;
        }

        // Owner belirtildiyse ekle
        if (! empty($params['owner'])) {
            $postData['owner'] = $params['owner'];
        }

        $response = $this->callCloudminApi('create-system', $postData, $params);

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

            // Yanıtta hostname parse edildiyse ekle
            if (! empty($response['hostname'])) {
                $result['data']['hostname'] = $response['hostname'];
            }

            // Olay tetikleme
            AccountCreated::dispatch($params, $result);

            return $result;
        }

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

        // Başarısız olsa bile olayı tetikle
        AccountCreated::dispatch($params, $result);

        return $result;
    }

    /**
     * Bir CloudMin VPS'i askıya alır (disable-system)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function suspendAccount(array $params)
    {
        $host = $this->resolveHost($params);
        if ($host === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cloudmin_hostname_required'),
            ];
        }

        $postData = [
            'host' => $host,
        ];

        // Cloudmin remote program adı: pause-system (WHMCS referansı)
        $response = $this->callCloudminApi('pause-system', $postData, $params);

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

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

    /**
     * Askıya alınmış bir CloudMin VPS'i aktifleştirir (enable-system)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function unsuspendAccount(array $params)
    {
        $host = $this->resolveHost($params);
        if ($host === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cloudmin_hostname_required'),
            ];
        }

        $postData = [
            'host' => $host,
        ];

        // Cloudmin remote program adı: unpause-system (WHMCS referansı)
        $response = $this->callCloudminApi('unpause-system', $postData, $params);

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

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

    /**
     * Bir CloudMin VPS'i siler (delete-system)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function terminateAccount(array $params)
    {
        $host = $this->resolveHost($params);
        if ($host === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cloudmin_hostname_required'),
            ];
        }

        $postData = [
            'host' => $host,
        ];

        $response = $this->callCloudminApi('delete-system', $postData, $params);

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

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

    /**
     * Bir CloudMin VPS'in şifresini değiştirir (modify-system)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function changeAccountPassword(array $params)
    {
        $host = $this->resolveHost($params);
        if ($host === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cloudmin_hostname_required'),
            ];
        }

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

        // Cloudmin modify-system --pass ile root/SSH parolasını değiştirir
        $postData = [
            'host' => $host,
            'pass' => $params['password'],
        ];

        $response = $this->callCloudminApi('modify-system', $postData, $params);

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

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

    /**
     * Bir CloudMin VPS'in planını değiştirir (change-system-plan)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function changeAccountPackage(array $params)
    {
        $host = $this->resolveHost($params);
        if ($host === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cloudmin_hostname_required'),
            ];
        }

        // Plan flat ($params['plan']) + config-option/module-config fallback
        $plan = ! empty($params['plan'])
            ? $params['plan']
            : $this->configOption($params, 'Plan Name', $this->moduleConfig($params, 'plan'));

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

        // Cloudmin modify-system --change-plan ile sistem planını değiştirir
        $postData = [
            'host' => $host,
            'change-plan' => $plan,
        ];

        $response = $this->callCloudminApi('modify-system', $postData, $params);

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

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

    /**
     * Bağlantı testini gerçekleştirir (list-systems)
     *
     * @param  array  $params  Test parametreleri
     * @return array Test sonucu
     */
    public function testConnection(array $params = [])
    {
        $response = $this->callCloudminApi('list-systems', [], $params);

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

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

    /**
     * Tek Oturum Açma (SSO) bağlantısı oluşturur - Webmin login URL'i döndürür
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function createSSOLogin(array $params)
    {
        // CloudMin/Webmin doğrudan token-tabanlı SSO desteklemez; host/creds
        // serverConfig'ten çözülür ve Webmin login sayfası URL'i döndürülür.
        $server = $this->serverConfig($params);
        $serverHost = $server['hostname'] !== '' ? $server['hostname'] : $server['ip'];

        if ($serverHost === '') {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cloudmin_hostname_required'),
            ];
        }

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

        $loginUrl = "{$protocol}://{$serverHost}:{$port}";

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

    /**
     * Admin panelinde gösterilecek alanları döndürür
     *
     * @return array Admin panel alanları
     */
    public function adminFields()
    {
        return [
            'hostname' => [
                'name' => __('admin/modules.cloudmin_field_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.cloudmin_field_hostname_description'),
                'required' => true,
            ],
            'port' => [
                'name' => __('admin/modules.cloudmin_field_port'),
                'type' => 'text',
                'description' => __('admin/modules.cloudmin_field_port_description'),
                'required' => false,
                'default' => '10000',
            ],
            'username' => [
                'name' => __('admin/modules.cloudmin_field_username'),
                'type' => 'text',
                'description' => __('admin/modules.cloudmin_field_username_description'),
                'required' => true,
            ],
            'password' => [
                'name' => __('admin/modules.cloudmin_field_password'),
                'type' => 'password',
                'description' => __('admin/modules.cloudmin_field_password_description'),
                'required' => true,
            ],
            'plan' => [
                'name' => __('admin/modules.cloudmin_field_plan'),
                'type' => 'text',
                'description' => __('admin/modules.cloudmin_field_plan_description'),
                'required' => false,
            ],
            'os_template' => [
                'name' => __('admin/modules.cloudmin_field_os_template'),
                'type' => 'text',
                'description' => __('admin/modules.cloudmin_field_os_template_description'),
                'required' => false,
            ],
            'secure' => [
                'name' => __('admin/modules.cloudmin_field_secure'),
                'type' => 'checkbox',
                'description' => __('admin/modules.cloudmin_field_secure_description'),
                'default' => true,
            ],
        ];
    }

    /**
     * Müşteri panelinde gösterilecek alanları döndürür
     *
     * @return array Müşteri panel alanları
     */
    public function clientFields()
    {
        return [
            'hostname' => [
                'name' => __('admin/modules.cloudmin_field_client_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.cloudmin_field_client_hostname_description'),
                'required' => true,
            ],
            'password' => [
                'name' => __('admin/modules.cloudmin_field_client_password'),
                'type' => 'password',
                'description' => __('admin/modules.cloudmin_field_client_password_description'),
                'required' => true,
            ],
            'email' => [
                'name' => __('admin/modules.cloudmin_field_client_email'),
                'type' => 'text',
                'description' => __('admin/modules.cloudmin_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.cloudmin_field_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.cloudmin_field_hostname_description'),
                'required' => true,
            ],
            'port' => [
                'name' => __('admin/modules.cloudmin_field_port'),
                'type' => 'text',
                'description' => __('admin/modules.cloudmin_field_port_description'),
                'required' => false,
                'default' => '10000',
            ],
            'username' => [
                'name' => __('admin/modules.cloudmin_field_username'),
                'type' => 'text',
                'description' => __('admin/modules.cloudmin_field_username_description'),
                'required' => true,
            ],
            'password' => [
                'name' => __('admin/modules.cloudmin_field_password'),
                'type' => 'password',
                'description' => __('admin/modules.cloudmin_field_password_description'),
                'required' => true,
            ],
            'secure' => [
                'name' => __('admin/modules.cloudmin_field_secure'),
                'type' => 'checkbox',
                'description' => __('admin/modules.cloudmin_field_secure_description'),
                'default' => true,
            ],
        ];
    }

    /**
     * Yapılandırma doğrulaması
     *
     * @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.cloudmin_config_hostname_missing'));
        }

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

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

        return true;
    }

    /**
     * VPS kaynak kullanım bilgilerini döndürür (info-system)
     *
     * @param  array  $params  Parametreler
     * @return array|null Kaynak kullanım verileri veya null
     */
    public function getResourceUsage(array $params): ?array
    {
        $host = $this->resolveHost($params);
        if ($host === null) {
            return null;
        }

        $postData = [
            'host' => $host,
        ];

        $response = $this->callCloudminApi('info-system', $postData, $params);

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

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

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

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

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

        // Bandwidth kullanımı
        if (isset($rawData['bandwidth_used']) && isset($rawData['bandwidth_limit'])) {
            $bwUsed = (float) $rawData['bandwidth_used'];
            $bwLimit = (float) $rawData['bandwidth_limit'];
            $resources[] = [
                'name' => __('admin/modules.cloudmin_resource_bandwidth'),
                'used' => $bwUsed,
                'limit' => $bwLimit,
                'unit' => 'GB',
                'percentage' => $bwLimit > 0 ? round(($bwUsed / $bwLimit) * 100, 2) : 0,
            ];
        }

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

    /**
     * Admin panelde gösterilecek özel butonları döndürür
     *
     * @return array Admin butonları
     */
    public function getAdminButtons(): array
    {
        return [
            [
                'action' => 'reboot',
                'label' => __('admin/modules.cloudmin_action_reboot'),
                'icon' => 'fas fa-sync',
                'class' => 'btn-outline-warning',
            ],
            [
                'action' => 'startup',
                'label' => __('admin/modules.cloudmin_action_startup'),
                'icon' => 'fas fa-play',
                'class' => 'btn-outline-success',
            ],
            [
                'action' => 'shutdown',
                'label' => __('admin/modules.cloudmin_action_shutdown'),
                'icon' => 'fas fa-power-off',
                'class' => 'btn-outline-danger',
            ],
        ];
    }

    /**
     * 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
    {
        $programMap = [
            'reboot' => 'reboot-system',
            'startup' => 'startup-system',
            'shutdown' => 'shutdown-system',
        ];

        // Desteklenmeyen op → dürüst unsupported (sahte-success yok)
        if (! isset($programMap[$action])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cloudmin_action_not_supported', ['action' => $action]),
            ];
        }

        $host = $this->resolveHost($params);
        if ($host === null) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cloudmin_hostname_required'),
            ];
        }

        $postData = [
            'host' => $host,
        ];

        $response = $this->callCloudminApi($programMap[$action], $postData, $params);

        if ($response['status'] === 'success') {
            $messageKey = 'admin/modules.cloudmin_action_' . $action . '_success';

            return [
                'status' => 'success',
                'message' => __($messageKey),
            ];
        }

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

    /**
     * Client area'da gösterilecek action'ları döndürür
     *
     * @return array Client action'ları
     */
    public function getClientActions(): array
    {
        $actions = parent::getClientActions();

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

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

        $actions['shutdown'] = [
            'label' => __('admin/modules.cloudmin_action_shutdown'),
            'icon' => 'fas fa-power-off',
            'class' => 'btn-outline-danger',
            '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);
        }

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

    /**
     * Uzak VPS sisteminin host kimliğini çözer.
     *
     * Kontrat: uzak-id önce remoteId() (account_id/module_handler_id), yoksa
     * builder'ın emit ettiği $params['domain'] (oluşturulan sistemin hostname'i),
     * son çare admin custom field $params['hostname']. procp iç FK'leri asla.
     */
    protected function resolveHost(array $params): ?string
    {
        $host = $this->remoteId($params);
        if ($host !== null && $host !== '') {
            return $host;
        }

        foreach (['domain', 'hostname'] as $key) {
            if (! empty($params[$key]) && is_scalar($params[$key])) {
                return (string) $params[$key];
            }
        }

        return null;
    }

    /**
     * CloudMin API ile iletişim kurar (Webmin/Cloudmin remote.cgi).
     *
     * Host/creds DAİMA serverConfig() üzerinden (atanmış sunucu öncelikli);
     * inline $this->config[...] okuma yok (PRC-1015 kontratı).
     *
     * @param  string  $program  CloudMin API program adı
     * @param  array  $postData  remote.cgi'ye gönderilecek POST alanları
     * @param  array  $params  Modül context (host/creds serverConfig ile çözülür)
     * @return array API yanıtı
     */
    protected function callCloudminApi($program, array $postData = [], array $params = [])
    {
        $server = $this->serverConfig($params);

        $hostname = $server['hostname'] !== '' ? $server['hostname'] : $server['ip'];
        $port = ! empty($server['port']) ? $server['port'] : $this->apiPort;
        $username = $server['username'];
        $password = $server['password'];
        $protocol = $server['secure'] ? 'https' : 'http';

        if ($hostname === '' || $username === '' || $password === '') {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cloudmin_config_hostname_missing'),
            ];
        }

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

        // Program parametresini ekle
        $postData['program'] = $program;
        $params = $postData;

        // 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($params));
        curl_setopt($ch, CURLOPT_USERPWD, "{$username}:{$password}");
        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);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        $curlErrno = curl_errno($ch);

        curl_close($ch);

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

        // Yetkisiz erişim kontrolü
        if (strpos($response, 'Unauthorized') !== false) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cloudmin_auth_failed'),
            ];
        }

        // HTTP hata kontrolü (raw response PCI riski taşıyabilir → dışa sızdırma)
        if ($httpCode >= 400) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cloudmin_api_call_failed', ['code' => $httpCode]),
            ];
        }

        // CloudMin yanıt formatı: "Exit status: 0" başarı anlamına gelir
        $exitStatusPos = strpos($response, 'Exit status:');
        if ($exitStatusPos !== false) {
            $exitStatus = trim(substr($response, $exitStatusPos + 12));

            if ($exitStatus === '0') {
                $result = [
                    'status' => 'success',
                    'message' => __('admin/modules.cloudmin_api_success'),
                    'data' => [],
                ];

                // create-system yanıtından hostname parse et
                if ($program === 'create-system') {
                    $parsedHostname = $this->parseCreatedHostname($response);
                    if ($parsedHostname) {
                        $result['hostname'] = $parsedHostname;
                    }
                }

                // info-system yanıtından kaynak bilgilerini parse et
                if ($program === 'info-system') {
                    $result['data'] = array_merge(
                        $result['data'],
                        $this->parseSystemInfo($response)
                    );
                }

                return $result;
            }
        }

        // Başarısız yanıt - ilk satırı hata mesajı olarak al (raw sızdırma yok)
        $lines = explode("\n", $response);

        return [
            'status' => 'error',
            'message' => $lines[0] ?? __('admin/modules.cloudmin_api_unknown_error'),
        ];
    }

    /**
     * create-system yanıtından oluşturulan hostname'i parse eder
     *
     * @param  string  $response  API yanıtı
     * @return string|null Hostname veya null
     */
    protected function parseCreatedHostname(string $response): ?string
    {
        $patterns = [
            'Creation of Xen system ',
            'Creation of OpenVZ system ',
            'Creation of VServer system ',
            'Creation of Zone system ',
            'Creation of Real system ',
        ];

        foreach ($patterns as $pattern) {
            $pos1 = strpos($response, $pattern);
            if ($pos1 !== false) {
                $pos2 = strpos($response, ' is complete', $pos1);
                if ($pos2 !== false) {
                    return substr($response, $pos1 + strlen($pattern), $pos2 - $pos1 - strlen($pattern));
                }
            }
        }

        return null;
    }

    /**
     * info-system yanıtından sistem bilgilerini parse eder
     *
     * @param  string  $response  API yanıtı
     * @return array Parse edilmiş sistem bilgileri
     */
    protected function parseSystemInfo(string $response): array
    {
        $info = [];
        $lines = explode("\n", $response);

        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line) || strpos($line, ':') === false) {
                continue;
            }

            // "Key: Value" formatını parse et
            [$key, $value] = explode(':', $line, 2);
            $key = trim(strtolower(str_replace(' ', '_', $key)));
            $value = trim($value);

            // Bilinen kaynak anahtarlarını map et
            $keyMap = [
                'disk_space_used' => 'disk_used',
                'disk_space_limit' => 'disk_limit',
                'memory_used' => 'memory_used',
                'memory_limit' => 'memory_limit',
                'cpu_usage' => 'cpu_percent',
                'bandwidth_used' => 'bandwidth_used',
                'bandwidth_limit' => 'bandwidth_limit',
                'status' => 'status',
                'type' => 'type',
                'hostname' => 'hostname',
                'ip_address' => 'ip_address',
                'operating_system' => 'operating_system',
            ];

            if (isset($keyMap[$key])) {
                $info[$keyMap[$key]] = $value;
            }
        }

        return $info;
    }
}
