<?php

namespace App\Modules\Product\Directadmin;

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

class Directadmin extends AbstractProduct
{
    // API endpoint'leri ve yapılandırma
    protected $apiEndpoint = '';

    protected $apiPort = 2222; // DirectAdmin API portu

    /**
     * Yeni bir DirectAdmin hesabı oluşturur
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function createAccount(array $params)
    {
        // Package/plan flat okuma: builder module-config'ten emit eder (PRC-1015),
        // fallback config-option → module_config.
        $package = $params['package']
            ?? $params['plan']
            ?? $this->configOption($params, 'package')
            ?? $this->moduleConfig($params, 'package', '');

        $requiredParams = [
            'username',
            'password',
            'domain',
        ];

        foreach ($requiredParams as $param) {
            if (! isset($params[$param]) || empty($params[$param])) {
                return [
                    'status' => 'error',
                    'message' => "Gerekli parametre eksik: {$param}",
                ];
            }
        }

        if (empty($package)) {
            return [
                'status' => 'error',
                'message' => 'Gerekli parametre eksik: package',
            ];
        }

        // API'ye gönderilecek veriler (CMD_API_* → makine-okunur error=0/text=)
        $server = $this->serverConfig($params);

        $postData = [
            'action' => 'create',
            'add' => 'Submit',
            'username' => $params['username'],
            'passwd' => $params['password'],
            'passwd2' => $params['password'],
            'domain' => $params['domain'],
            'package' => $package,
            'email' => $params['email'] ?? '',
            'notify' => 'yes',
        ];

        // Sunucu IP'si (create için gerekli; atanmış sunucudan gelir)
        if (! empty($server['ip'])) {
            $postData['ip'] = $server['ip'];
        }

        // Quota/bandwidth: "unlimited" DirectAdmin'de sayısal alan değil —
        // sınırsız için uquota=ON / ubandwidth=ON gönderilir (WiseCP:205-212).
        $quota = $params['quota'] ?? 'unlimited';
        if ($quota === 'unlimited' || $quota === '' || $quota === null) {
            $postData['uquota'] = 'ON';
        } else {
            $postData['quota'] = $quota;
        }

        $bandwidth = $params['bandwidth'] ?? 'unlimited';
        if ($bandwidth === 'unlimited' || $bandwidth === '' || $bandwidth === null) {
            $postData['ubandwidth'] = 'ON';
        } else {
            $postData['bandwidth'] = $bandwidth;
        }

        // DirectAdmin API'sini kullanarak hesap oluşturma
        $response = $this->callDirectAdminApi('/CMD_API_ACCOUNT_USER', $postData, $params);

        // Yanıt işleme
        if (strpos($response, 'error=0') !== false) {
            $result = [
                'status' => 'success',
                'message' => __('admin/modules.directadmin_account_created_success'),
                'data' => $response,
            ];

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

            return $result;
        }

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

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

        return $result;
    }

    /**
     * Bir DirectAdmin hesabını askıya alır
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function suspendAccount(array $params)
    {
        if (! isset($params['username']) || empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => 'Kullanıcı adı gerekli',
            ];
        }

        $postData = [
            'location' => 'CMD_SELECT_USERS',
            'suspend' => 'Suspend',
            'select0' => $params['username'],
        ];

        $response = $this->callDirectAdminApi('/CMD_API_SELECT_USERS', $postData, $params);

        if (strpos($response, 'error=0') !== false) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.directadmin_account_suspended_success'),
            ];
        }

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

    /**
     * Askıya alınmış bir DirectAdmin hesabını aktifleştirir
     *
     * @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.directadmin_username_required'),
            ];
        }

        // DirectAdmin: unsuspend de CMD_API_SELECT_USERS üzerinden suspend=Unsuspend
        // ile yapılır (WiseCP:823) — ayrı "unsuspend" alanı yoktur.
        $postData = [
            'location' => 'CMD_SELECT_USERS',
            'suspend' => 'Unsuspend',
            'select0' => $params['username'],
        ];

        $response = $this->callDirectAdminApi('/CMD_API_SELECT_USERS', $postData, $params);

        if (strpos($response, 'error=0') !== false) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.directadmin_account_unsuspended_success'),
            ];
        }

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

    /**
     * Bir DirectAdmin hesabını siler
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function terminateAccount(array $params)
    {
        if (! isset($params['username']) || empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => 'Kullanıcı adı gerekli',
            ];
        }

        $postData = [
            'confirmed' => 'Confirm',
            'delete' => 'yes',
            'select0' => $params['username'],
        ];

        $response = $this->callDirectAdminApi('/CMD_API_SELECT_USERS', $postData, $params);

        if (strpos($response, 'error=0') !== false) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.directadmin_account_deleted_success'),
            ];
        }

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

    /**
     * Bir DirectAdmin hesabının ş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.directadmin_username_required'),
            ];
        }

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

        // DirectAdmin API: /CMD_API_USER_PASSWD (username/passwd/passwd2)
        // WiseCP:754 + WHMCS:317 referans.
        $postData = [
            'username' => $params['username'],
            'passwd' => $params['password'],
            'passwd2' => $params['password'],
        ];

        $response = $this->callDirectAdminApi('/CMD_API_USER_PASSWD', $postData, $params);

        if (strpos($response, 'error=0') !== false) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.directadmin_password_changed_success'),
            ];
        }

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

    /**
     * Admin panelinde gösterilecek alanları döndürür
     *
     * @return array Admin panel alanları
     */
    public function adminFields()
    {
        return [
            'hostname' => [
                'name' => __('admin/modules.directadmin_field_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.directadmin_field_hostname_description'),
                'required' => true,
            ],
            'username' => [
                'name' => __('admin/modules.directadmin_field_username'),
                'type' => 'text',
                'description' => __('admin/modules.directadmin_field_username_description'),
                'required' => true,
            ],
            'password' => [
                'name' => __('admin/modules.directadmin_field_password'),
                'type' => 'password',
                'description' => __('admin/modules.directadmin_field_password_description'),
                'required' => true,
            ],
            'login_key' => [
                'name' => __('admin/modules.directadmin_field_login_key'),
                'type' => 'textarea',
                'description' => __('admin/modules.directadmin_field_login_key_description'),
                'required' => false,
            ],
            'secure' => [
                'name' => __('admin/modules.directadmin_field_secure'),
                'type' => 'checkbox',
                'description' => __('admin/modules.directadmin_field_secure_description'),
                'default' => true,
            ],
            'skin' => [
                'name' => __('admin/modules.directadmin_field_skin'),
                'type' => 'text',
                'description' => __('admin/modules.directadmin_field_skin_description'),
                'required' => false,
            ],
        ];
    }

    /**
     * Müşteri panelinde gösterilecek alanları döndürür
     *
     * @return array Müşteri panel alanları
     */
    public function clientFields()
    {
        return [
            'domain' => [
                'name' => __('admin/modules.directadmin_field_domain'),
                'type' => 'text',
                'description' => __('admin/modules.directadmin_field_domain_description'),
                'required' => true,
            ],
            'username' => [
                'name' => __('admin/modules.directadmin_field_client_username'),
                'type' => 'text',
                'description' => __('admin/modules.directadmin_field_client_username_description'),
                'required' => true,
            ],
            'password' => [
                'name' => __('admin/modules.directadmin_field_client_password'),
                'type' => 'password',
                'description' => __('admin/modules.directadmin_field_client_password_description'),
                'required' => true,
            ],
            'package' => [
                'name' => __('admin/modules.directadmin_field_package'),
                'type' => 'text',
                'description' => __('admin/modules.directadmin_field_package_description'),
                'required' => true,
            ],
        ];
    }

    /**
     * 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.directadmin_field_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.directadmin_field_hostname_description'),
                'required' => true,
            ],
            'username' => [
                'name' => __('admin/modules.directadmin_field_username'),
                'type' => 'text',
                'description' => __('admin/modules.directadmin_field_username_description'),
                'required' => true,
            ],
            'password' => [
                'name' => __('admin/modules.directadmin_field_password'),
                'type' => 'password',
                'description' => __('admin/modules.directadmin_field_password_description'),
                'required' => true,
            ],
            'login_key' => [
                'name' => __('admin/modules.directadmin_field_login_key'),
                'type' => 'textarea',
                'description' => __('admin/modules.directadmin_field_login_key_description'),
                'required' => false,
            ],
            'secure' => [
                'name' => __('admin/modules.directadmin_field_secure'),
                'type' => 'checkbox',
                'description' => __('admin/modules.directadmin_field_secure_description'),
                'default' => true,
            ],
            'skin' => [
                'name' => __('admin/modules.directadmin_field_skin'),
                'type' => 'text',
                'description' => __('admin/modules.directadmin_field_skin_description'),
                'required' => false,
            ],
        ];
    }

    /**
     * DirectAdmin API'si ile iletişim kurar
     *
     * @param  string  $endpoint  API endpoint'i
     * @param  array  $params  Gönderilecek parametreler
     * @return string API yanıtı
     */
    protected function callDirectAdminApi($endpoint, array $postData = [], array $params = [])
    {
        // Host/creds tek doğru kaynak: atanmış sunucu öncelikli (PRC-1015).
        $server = $this->serverConfig($params);

        $protocol = $server['secure'] ? 'https' : 'http';
        $port = ! empty($server['port']) ? $server['port'] : $this->apiPort;
        $baseUrl = "{$protocol}://{$server['hostname']}:{$port}";
        $url = "{$baseUrl}{$endpoint}";

        // cURL ile API çağrısı — WHMCS stili "Authorization: Basic base64(user:pass)".
        $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_HTTPHEADER, [
            'Authorization: Basic '.base64_encode($server['username'].':'.$server['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_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        // Hata kontrolü
        if ($httpCode >= 400 || ! $response) {
            return 'error=1&text='.__('admin/modules.directadmin_api_call_failed', ['code' => $httpCode]);
        }

        return $response;
    }

    /**
     * Bağlantı testini gerçekleştirir
     *
     * @param  array  $params  Test parametreleri
     * @return array Test sonucu
     */
    public function testConnection(array $params = [])
    {
        // DirectAdmin API ile kullanıcı listesini almaya çalış
        $response = $this->callDirectAdminApiGet('/CMD_API_SHOW_USERS', $params);

        if (strpos($response, 'error=0') !== false || strpos($response, 'list=') !== false) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.directadmin_connection_test_success'),
                'data' => $response,
            ];
        }

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

    /**
     * Modül yapılandırmasını doğrular
     *
     * @return array Doğrulama sonucu
     */
    public function validateConfig()
    {
        $errors = [];

        if (empty($this->config['hostname'])) {
            $errors[] = __('admin/modules.directadmin_hostname_required');
        }

        if (empty($this->config['username'])) {
            $errors[] = __('admin/modules.directadmin_username_required');
        }

        if (empty($this->config['password'])) {
            $errors[] = __('admin/modules.directadmin_password_required');
        }

        return [
            'valid' => empty($errors),
            'errors' => $errors,
        ];
    }

    /**
     * Bir DirectAdmin hesabının paketini değiştirir
     *
     * DirectAdmin API: /CMD_API_MODIFY_USER
     * WHMCS Referans: directadmin_ChangePackage()
     *
     * @param  array  $params  Parametreler (username, package)
     * @return array İşlem sonucu
     */
    public function changeAccountPackage(array $params)
    {
        if (! isset($params['username']) || empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.directadmin_username_required'),
            ];
        }

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

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

        $postData = [
            'action' => 'package',
            'user' => $params['username'],
            'package' => $package,
        ];

        $response = $this->callDirectAdminApi('/CMD_API_MODIFY_USER', $postData, $params);

        if (strpos($response, 'error=0') !== false) {
            return [
                'status' => 'success',
                'message' => __('admin/modules.directadmin_package_changed_success'),
            ];
        }

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

    /**
     * Tek Oturum Açma (SSO) bağlantısı oluşturur
     *
     * DirectAdmin: /CMD_API_LOGIN_KEYS ile type=one_time_url tek-kullanımlık
     * giriş URL'si üretir (imzalı hash). Kullanıcının panel parolası gerekir;
     * yoksa/başarısızsa panel base URL'sine düşülür.
     *
     * WHMCS Referans: directadmin_ClientArea(), directadmin_AdminLink()
     *
     * @param  array  $params  Parametreler (username, password)
     * @return array İşlem sonucu
     */
    public function createSSOLogin(array $params)
    {
        if (! isset($params['username']) || empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.directadmin_username_required'),
            ];
        }

        $server = $this->serverConfig($params);
        $protocol = $server['secure'] ? 'https' : 'http';
        $hostname = $server['hostname'];
        $port = ! empty($server['port']) ? $server['port'] : $this->apiPort;
        $baseUrl = "{$protocol}://{$hostname}:{$port}";

        // Kullanıcı panel parolası varsa tek-kullanımlık login URL üret.
        $userPassword = $params['password'] ?? '';

        if (! empty($userPassword)) {
            $postData = [
                'method' => 'GET',
                'action' => 'create',
                'type' => 'one_time_url',
                'user' => $params['username'],
                'passwd' => $userPassword,
                'redirect-url' => '/',
                'expiry' => '30m',
                'login_keys_notify_on_creation' => '0',
            ];

            $response = $this->callDirectAdminApi('/CMD_API_LOGIN_KEYS', $postData, $params);
            $parsed = $this->parseDirectAdminResponse($response);

            // Başarı: error=0 + details (tek-kullanımlık URL).
            if (isset($parsed['error']) && (string) $parsed['error'] === '0') {
                $oneTimeUrl = $parsed['details'] ?? '';

                if (! empty($oneTimeUrl)) {
                    // Göreli yol dönerse base URL ile birleştir.
                    if (strpos($oneTimeUrl, 'http') !== 0) {
                        $oneTimeUrl = $baseUrl.'/'.ltrim($oneTimeUrl, '/');
                    }

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

        // Fallback: doğrudan panel URL'si (kullanıcı manuel giriş yapar).
        return [
            'status' => 'success',
            'message' => __('admin/modules.directadmin_sso_created_success'),
            'url' => $baseUrl,
        ];
    }

    /**
     * Kaynak kullanım bilgilerini döndürür (disk, bandwidth, email, database vb.)
     *
     * DirectAdmin API:
     * - /CMD_API_SHOW_USER_USAGE?user=xxx (GET) - Mevcut kullanım verileri
     * - /CMD_API_SHOW_USER_CONFIG?user=xxx (GET) - Hesap limitleri
     *
     * WHMCS Referans: directadmin_UsageUpdate()
     *
     * @param  array  $params  Parametreler (username)
     * @return array|null Kaynak kullanım verileri veya null
     */
    public function getResourceUsage(array $params): ?array
    {
        if (! isset($params['username']) || empty($params['username'])) {
            return null;
        }

        $username = $params['username'];

        // Kullanım verilerini al
        $usageResponse = $this->callDirectAdminApiGet("/CMD_API_SHOW_USER_USAGE?user={$username}", $params);
        $usage = $this->parseDirectAdminResponse($usageResponse);

        if (empty($usage) || (isset($usage['error']) && $usage['error'] != '0')) {
            return null;
        }

        // Hesap limitlerini al
        $configResponse = $this->callDirectAdminApiGet("/CMD_API_SHOW_USER_CONFIG?user={$username}", $params);
        $config = $this->parseDirectAdminResponse($configResponse);

        if (empty($config) || (isset($config['error']) && $config['error'] != '0')) {
            return null;
        }

        $resources = [];

        // Disk / Quota kullanımı
        $quotaUsed = (float) ($usage['quota'] ?? 0);
        $quotaLimit = ($config['quota'] ?? 'unlimited') === 'unlimited' ? 0 : (float) $config['quota'];
        $quotaPercentage = $quotaLimit > 0 ? round(($quotaUsed / $quotaLimit) * 100, 2) : 0;

        $resources[] = [
            'name' => __('admin/modules.directadmin_resource_disk_space'),
            'used' => round($quotaUsed),
            'limit' => round($quotaLimit),
            'unit' => 'MB',
            'percentage' => $quotaPercentage,
        ];

        // Bandwidth kullanımı
        $bandwidthUsed = (float) ($usage['bandwidth'] ?? 0);
        $bandwidthLimit = ($config['bandwidth'] ?? 'unlimited') === 'unlimited' ? 0 : (float) $config['bandwidth'];
        $bandwidthPercentage = $bandwidthLimit > 0 ? round(($bandwidthUsed / $bandwidthLimit) * 100, 2) : 0;

        $resources[] = [
            'name' => __('admin/modules.directadmin_resource_bandwidth'),
            'used' => round($bandwidthUsed),
            'limit' => round($bandwidthLimit),
            'unit' => 'MB',
            'percentage' => $bandwidthPercentage,
        ];

        // MySQL veritabanı kullanımı
        $mysqlUsed = (int) ($usage['mysql'] ?? 0);
        $mysqlLimit = ($config['mysql'] ?? 'unlimited') === 'unlimited' ? 0 : (int) $config['mysql'];
        $mysqlPercentage = $mysqlLimit > 0 ? round(($mysqlUsed / $mysqlLimit) * 100, 2) : 0;

        $resources[] = [
            'name' => __('admin/modules.directadmin_resource_mysql'),
            'used' => $mysqlUsed,
            'limit' => $mysqlLimit,
            'unit' => '',
            'percentage' => $mysqlPercentage,
        ];

        // E-posta hesapları
        $emailUsed = (int) ($usage['nemails'] ?? 0);
        $emailLimit = ($config['nemails'] ?? 'unlimited') === 'unlimited' ? 0 : (int) $config['nemails'];
        $emailPercentage = $emailLimit > 0 ? round(($emailUsed / $emailLimit) * 100, 2) : 0;

        $resources[] = [
            'name' => __('admin/modules.directadmin_resource_emails'),
            'used' => $emailUsed,
            'limit' => $emailLimit,
            'unit' => '',
            'percentage' => $emailPercentage,
        ];

        // FTP hesapları
        $ftpUsed = (int) ($usage['ftp'] ?? 0);
        $ftpLimit = ($config['ftp'] ?? 'unlimited') === 'unlimited' ? 0 : (int) $config['ftp'];
        $ftpPercentage = $ftpLimit > 0 ? round(($ftpUsed / $ftpLimit) * 100, 2) : 0;

        $resources[] = [
            'name' => __('admin/modules.directadmin_resource_ftp'),
            'used' => $ftpUsed,
            'limit' => $ftpLimit,
            'unit' => '',
            'percentage' => $ftpPercentage,
        ];

        // Alt alan adları (subdomains)
        $subdomainsUsed = (int) ($usage['nsubdomains'] ?? 0);
        $subdomainsLimit = ($config['nsubdomains'] ?? 'unlimited') === 'unlimited' ? 0 : (int) $config['nsubdomains'];
        $subdomainsPercentage = $subdomainsLimit > 0 ? round(($subdomainsUsed / $subdomainsLimit) * 100, 2) : 0;

        $resources[] = [
            'name' => __('admin/modules.directadmin_resource_subdomains'),
            'used' => $subdomainsUsed,
            'limit' => $subdomainsLimit,
            'unit' => '',
            'percentage' => $subdomainsPercentage,
        ];

        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' => 'list_packages',
                'label' => __('admin/modules.directadmin_btn_list_packages'),
                'icon' => 'fas fa-box',
                'class' => 'btn-outline-info',
            ],
            [
                'action' => 'account_info',
                'label' => __('admin/modules.directadmin_btn_account_info'),
                'icon' => 'fas fa-user-cog',
                'class' => 'btn-outline-primary',
            ],
            [
                'action' => 'server_stats',
                'label' => __('admin/modules.directadmin_btn_server_stats'),
                'icon' => 'fas fa-chart-bar',
                'class' => 'btn-outline-success',
            ],
        ];
    }

    /**
     * Admin özel action'ı işler
     *
     * DirectAdmin API:
     * - list_packages: /CMD_API_PACKAGES_USER - Paket listesi
     * - account_info: /CMD_API_SHOW_USER_CONFIG - Hesap bilgileri
     * - server_stats: /CMD_API_SHOW_ADMINS - Sunucu admin listesi
     *
     * @param  string  $action  Action adı
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function adminCustomAction(string $action, array $params): array
    {
        switch ($action) {
            case 'list_packages':
                return $this->adminListPackages($params);
            case 'account_info':
                return $this->adminAccountInfo($params);
            case 'server_stats':
                return $this->adminServerStats($params);
            default:
                return parent::adminCustomAction($action, $params);
        }
    }

    /**
     * Sunucudaki paket listesini getirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    private function adminListPackages(array $params): array
    {
        $response = $this->callDirectAdminApiGet('/CMD_API_PACKAGES_USER', $params);
        $parsed = $this->parseDirectAdminResponse($response);

        if (empty($parsed) || (isset($parsed['error']) && $parsed['error'] != '0')) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.directadmin_list_packages_failed'),
                'data' => $response,
            ];
        }

        $packages = [];
        if (isset($parsed['list'])) {
            foreach ((array) $parsed['list'] as $package) {
                $packages[] = ucwords(str_replace('_', ' ', $package));
            }
        }

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

    /**
     * Belirtilen kullanıcının hesap bilgilerini getirir
     *
     * @param  array  $params  Parametreler (username)
     * @return array İşlem sonucu
     */
    private function adminAccountInfo(array $params): array
    {
        $username = $params['username'] ?? '';

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

        $response = $this->callDirectAdminApiGet("/CMD_API_SHOW_USER_CONFIG?user={$username}", $params);
        $parsed = $this->parseDirectAdminResponse($response);

        if (empty($parsed) || (isset($parsed['error']) && $parsed['error'] != '0')) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.directadmin_account_info_failed'),
                'data' => $response,
            ];
        }

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

    /**
     * Sunucu admin listesini / istatistiklerini getirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    private function adminServerStats(array $params): array
    {
        $response = $this->callDirectAdminApiGet('/CMD_API_SHOW_ADMINS', $params);
        $parsed = $this->parseDirectAdminResponse($response);

        if (empty($parsed) || (isset($parsed['error']) && $parsed['error'] != '0')) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.directadmin_server_stats_failed'),
                'data' => $response,
            ];
        }

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

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

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

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

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

        $actions['file_manager'] = [
            'label' => __('admin/modules.directadmin_action_file_manager'),
            'icon' => 'fas fa-folder-open',
            'class' => 'btn-outline-success',
            'enabled' => true,
        ];

        return $actions;
    }

    /**
     * Client action'ı işler
     *
     * Her action için DirectAdmin panel login URL'lerini döndürür
     *
     * @param  string  $action  Action adı
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function handleClientAction(string $action, array $params): array
    {
        $server = $this->serverConfig($params);
        $protocol = $server['secure'] ? 'https' : 'http';
        $hostname = $server['hostname'];
        $port = ! empty($server['port']) ? $server['port'] : $this->apiPort;
        $baseUrl = "{$protocol}://{$hostname}:{$port}";

        switch ($action) {
            case 'login_panel':
                return [
                    'status' => 'success',
                    'message' => __('admin/modules.directadmin_action_login_panel_success'),
                    'url' => $baseUrl,
                ];

            case 'login_webmail':
                return [
                    'status' => 'success',
                    'message' => __('admin/modules.directadmin_action_login_webmail_success'),
                    'url' => "{$baseUrl}/CMD_WEBMAIL",
                ];

            case 'login_phpmyadmin':
                return [
                    'status' => 'success',
                    'message' => __('admin/modules.directadmin_action_login_phpmyadmin_success'),
                    'url' => "{$baseUrl}/CMD_PHPMYADMIN",
                ];

            case 'file_manager':
                return [
                    'status' => 'success',
                    'message' => __('admin/modules.directadmin_action_file_manager_success'),
                    'url' => "{$baseUrl}/CMD_FILE_MANAGER",
                ];

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

    /**
     * DirectAdmin API'sine GET isteği gönderir
     *
     * Mevcut callDirectAdminApi metodu sadece POST yapıyor,
     * bu metot GET istekleri için kullanılır (usage, config sorgulama vb.)
     *
     * @param  string  $endpoint  API endpoint'i (query string dahil olabilir)
     * @return string API yanıtı
     */
    protected function callDirectAdminApiGet($endpoint, array $params = [])
    {
        // Host/creds tek doğru kaynak: atanmış sunucu öncelikli (PRC-1015).
        $server = $this->serverConfig($params);

        $protocol = $server['secure'] ? 'https' : 'http';
        $port = ! empty($server['port']) ? $server['port'] : $this->apiPort;
        $baseUrl = "{$protocol}://{$server['hostname']}:{$port}";
        $url = "{$baseUrl}{$endpoint}";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPGET, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Basic '.base64_encode($server['username'].':'.$server['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_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        if ($httpCode >= 400 || ! $response) {
            return 'error=1&text='.__('admin/modules.directadmin_api_call_failed', ['code' => $httpCode]);
        }

        return $response;
    }

    /**
     * DirectAdmin URL-encoded yanıtını diziye çevirir
     *
     * DirectAdmin API yanıtları genellikle URL-encoded key=value&key2=value2 formatındadır.
     * Bu metot yanıtı parse ederek bir PHP dizisine dönüştürür.
     * WHMCS Referans: directadmin_req() parse logic, directadmin_unhtmlentities()
     *
     * @param  string  $response  DirectAdmin API yanıtı
     * @return array Ayrıştırılmış yanıt dizisi
     */
    protected function parseDirectAdminResponse($response)
    {
        if (empty($response)) {
            return [];
        }

        // HTML entity'leri düzelt (DirectAdmin bazen HTML entity kullanır)
        $response = preg_replace_callback('~&#([0-9]{2})~', function ($match) {
            return chr($match[1]);
        }, $response);

        $result = [];

        // list[] formatındaki yanıtları kontrol et (paket listesi vb.)
        if (strpos($response, 'list[]=') !== false) {
            parse_str($response, $result);

            return $result;
        }

        // Standart key=value&key2=value2 formatı
        $pairs = explode('&', $response);
        foreach ($pairs as $pair) {
            $parts = explode('=', $pair, 2);
            if (count($parts) === 2) {
                $key = urldecode(trim($parts[0]));
                $value = urldecode(trim($parts[1]));
                $result[$key] = $value;
            }
        }

        return $result;
    }
}
