<?php

namespace App\Modules\Product\Helm;

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

class Helm extends AbstractProduct
{
    /**
     * Default Helm API port (Helm 4 default)
     */
    protected int $apiPort = 8086;

    /**
     * Helm API version indicator
     * Supports: '3' (billing_api.asp) and '4' (ServiceAPI/HttpAPI.aspx)
     */
    protected string $helmVersion = '4';

    /**
     * Helm result codes
     */
    const RESULT_SUCCESS = '0';

    /**
     * Account status constants
     */
    const STATUS_ACTIVE = 'active';

    const STATUS_SUSPENDED = 'suspended';

    const STATUS_TERMINATED = 'terminated';

    /**
     * Helm module requires a server
     */
    public function requiresServer(): bool
    {
        return true;
    }

    // =========================================================================
    // ACCOUNT OPERATIONS
    // =========================================================================

    /**
     * Yeni bir Helm hosting hesabi olusturur
     *
     * Islem adimlari:
     * 1. Helm 4: GetAccountByName ile mevcut hesap kontrolu
     * 2. CreateAccount/AddUser ile kullanici olusturma
     * 3. AddPackage ile paket atama
     * 4. AddDomain/AddDomainToPackage ile domain ekleme
     *
     * @param  array  $params  Gerekli: username, password, domain, plan_id
     *                         Opsiyonel: email, first_name, last_name, company, address1,
     *                         city, state, postcode, country, phone, account_role_id,
     *                         reseller_plan_id, package_name, auto_username
     * @return array Islem sonucu
     */
    public function createAccount(array $params)
    {
        // Plan/paket: flat $params['plan'] (builder module-config'ten emit eder)
        // veya module-config fallback ile plan_id'yi doldur (PRC-1015).
        $params['plan_id'] = $this->resolvePlanId($params);

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

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

        // UK -> GB donusumu (Helm API gerekliligi)
        $country = $params['country'] ?? '';
        if (strtoupper($country) === 'UK') {
            $country = 'GB';
        }

        try {
            $helmAccountId = null;
            $helmUsername = null;

            if ($this->isVersion4()) {
                // ----------------------------------------------------------
                // Helm 4: Once mevcut hesabi kontrol et
                // ----------------------------------------------------------
                $email = $params['email'] ?? '';

                if (! empty($email)) {
                    $checkResult = $this->callHelmApi('GetAccountByName', [
                        'UserAccountName' => $email,
                        'IncludeChildren' => 'false',
                    ], $params);

                    if ($this->isSuccess($checkResult)) {
                        $helmAccountId = $this->extractValue($checkResult, 'RESULTDATA.RECORD.ACCOUNTID');
                        $helmUsername = $this->extractValue($checkResult, 'RESULTDATA.RECORD.PRIMARYLOGINNAME');
                    }
                }

                // Hesap yoksa yeni olustur
                if (! $helmAccountId) {
                    $createFields = [
                        'AccountRoleId' => $params['account_role_id'] ?? '1',
                        'NewAccountName' => $params['email'] ?? $params['username'],
                        'CompanyName' => ! empty($params['company'])
                            ? $params['company']
                            : trim(($params['first_name'] ?? '') . ' ' . ($params['last_name'] ?? '')),
                        'AccountEmailAddress' => $params['email'] ?? '',
                        'AdminLoginName' => $params['username'],
                        'AdminLoginPassword' => $params['password'],
                        'AdminEmailAddress' => $params['email'] ?? '',
                        'FirstName' => $params['first_name'] ?? '',
                        'LastName' => $params['last_name'] ?? '',
                        'Address1' => $params['address1'] ?? '',
                        'Address2' => $params['address2'] ?? '',
                        'Address3' => '',
                        'Town' => $params['city'] ?? '',
                        'PostCode' => $params['postcode'] ?? '',
                        'CountryCode' => $country,
                        'CountyName' => $params['state'] ?? '',
                    ];

                    $createResult = $this->callHelmApi('CreateAccount', $createFields, $params);

                    if (! $this->isSuccess($createResult)) {
                        $result = [
                            'status' => 'error',
                            'message' => $this->getResultDescription($createResult)
                                ?? __('admin/modules.helm_account_create_failed'),
                            'data' => $createResult,
                        ];

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

                        return $result;
                    }

                    $helmAccountId = $this->getResultData($createResult);
                }

                // Paket ekle
                $packageResult = $this->callHelmApi('AddPackage', [
                    'UserAccountID' => $helmAccountId,
                    'PlanID' => $params['plan_id'],
                    'PackageName' => $params['domain'],
                    'Quantity' => '1',
                ], $params);

                if (! $this->isSuccess($packageResult)) {
                    $result = [
                        'status' => 'error',
                        'message' => $this->getResultDescription($packageResult)
                            ?? __('admin/modules.helm_package_add_failed'),
                        'data' => $packageResult,
                    ];

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

                    return $result;
                }

                $helmPackageId = $this->extractValue($packageResult, 'RESULTDATA.RECORD.PACKAGEID')
                    ?? $this->getResultData($packageResult);

                // Domain ekle
                $domainResult = $this->callHelmApi('AddDomainToPackage', [
                    'UserAccountID' => $helmAccountId,
                    'PackageID' => $helmPackageId,
                    'DomainName' => $params['domain'],
                    'IsPark' => 'false',
                ], $params);

                if (! $this->isSuccess($domainResult)) {
                    $result = [
                        'status' => 'error',
                        'message' => $this->getResultDescription($domainResult)
                            ?? __('admin/modules.helm_domain_add_failed'),
                        'data' => $domainResult,
                    ];

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

                    return $result;
                }
            } else {
                // ----------------------------------------------------------
                // Helm 3: billing_api.asp kullanimi
                // ----------------------------------------------------------

                // Auto-username ozelligi
                $accountUsername = ! empty($params['auto_username']) ? '' : $params['username'];

                $createFields = [
                    'FirstName' => urlencode($params['first_name'] ?? ''),
                    'LastName' => urlencode($params['last_name'] ?? ''),
                    'PrimaryEmail' => $params['email'] ?? '',
                    'Address1' => urlencode($params['address1'] ?? ''),
                    'PostCode' => urlencode($params['postcode'] ?? ''),
                    'CountryCode' => $country,
                    'CompanyName' => urlencode($params['company'] ?? ''),
                    'Town' => urlencode($params['city'] ?? ''),
                    'County' => urlencode($params['state'] ?? ''),
                    'HomePhone' => $params['phone'] ?? '',
                    'NewAccountNumber' => $accountUsername,
                    'NewAccountPassword' => urlencode($params['password']),
                    'ResellerPlanId' => $params['reseller_plan_id'] ?? '0',
                ];

                $createResult = $this->callHelmApi('AddUser', $createFields, $params);

                if (! $this->isSuccess($createResult)) {
                    $result = [
                        'status' => 'error',
                        'message' => $this->getResultDescription($createResult)
                            ?? __('admin/modules.helm_account_create_failed'),
                        'data' => $createResult,
                    ];

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

                    return $result;
                }

                // Helm 3 kullanici numarasini dondurur
                $helmAccountId = $this->getResultData($createResult);
                $helmUsername = $helmAccountId;

                // Paket ekle
                $packageResult = $this->callHelmApi('AddPackage', [
                    'UserAccountNumber' => $helmAccountId,
                    'PackageTypeId' => $params['plan_id'],
                    'FriendlyName' => $params['package_name'] ?? $params['domain'],
                ], $params);

                if (! $this->isSuccess($packageResult)) {
                    $result = [
                        'status' => 'error',
                        'message' => $this->getResultDescription($packageResult)
                            ?? __('admin/modules.helm_package_add_failed'),
                        'data' => $packageResult,
                    ];

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

                    return $result;
                }

                $helmPackageId = $this->getResultData($packageResult);

                // Domain ekle
                $domainResult = $this->callHelmApi('AddDomain', [
                    'PackageId' => $helmPackageId,
                    'DomainName' => $params['domain'],
                ], $params);

                if (! $this->isSuccess($domainResult)) {
                    $result = [
                        'status' => 'error',
                        'message' => $this->getResultDescription($domainResult)
                            ?? __('admin/modules.helm_domain_add_failed'),
                        'data' => $domainResult,
                    ];

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

                    return $result;
                }
            }

            $result = [
                'status' => 'success',
                'message' => __('admin/modules.helm_account_created_success'),
                'data' => [
                    'helm_account_id' => $helmAccountId,
                    'helm_username' => $helmUsername ?? $params['username'],
                    'helm_package_id' => $helmPackageId ?? null,
                    'domain' => $params['domain'],
                ],
            ];

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

            return $result;
        } catch (\Exception $e) {
            $result = [
                'status' => 'error',
                'message' => __('admin/modules.helm_account_create_exception', ['error' => $e->getMessage()]),
            ];

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

            return $result;
        }
    }

    /**
     * Bir Helm hesabini askiya alir
     *
     * @param  array  $params  Gerekli: username
     *                         Opsiyonel: email (Helm 4 icin hesap tespitinde kullanilir)
     * @return array Islem sonucu
     */
    public function suspendAccount(array $params)
    {
        if (empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_username_required'),
            ];
        }

        try {
            if ($this->isVersion4()) {
                $accountId = $this->resolveAccountId($params);

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

                $response = $this->callHelmApi('SuspendAccount', [
                    'UserAccountId' => $accountId,
                    'IncludeChildren' => 'false',
                ], $params);
            } else {
                $response = $this->callHelmApi('SuspendUser', [
                    'UserAccountNumber' => $params['username'],
                ], $params);
            }

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

            return [
                'status' => 'error',
                'message' => $this->getResultDescription($response)
                    ?? __('admin/modules.helm_account_suspend_failed'),
                'data' => $response,
            ];
        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_suspend_exception', ['error' => $e->getMessage()]),
            ];
        }
    }

    /**
     * Askiya alinmis bir Helm hesabini yeniden aktif eder
     *
     * @param  array  $params  Gerekli: username
     *                         Opsiyonel: email (Helm 4 icin)
     * @return array Islem sonucu
     */
    public function unsuspendAccount(array $params)
    {
        if (empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_username_required'),
            ];
        }

        try {
            if ($this->isVersion4()) {
                $accountId = $this->resolveAccountId($params);

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

                $response = $this->callHelmApi('UnsuspendAccount', [
                    'UserAccountId' => $accountId,
                    'IncludeChildren' => 'false',
                ], $params);
            } else {
                $response = $this->callHelmApi('UnsuspendUser', [
                    'UserAccountNumber' => $params['username'],
                ], $params);
            }

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

            return [
                'status' => 'error',
                'message' => $this->getResultDescription($response)
                    ?? __('admin/modules.helm_account_unsuspend_failed'),
                'data' => $response,
            ];
        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_unsuspend_exception', ['error' => $e->getMessage()]),
            ];
        }
    }

    /**
     * Bir Helm hesabini tamamen siler
     *
     * Helm 4 icin islem adimlari:
     * 1. GetAccountByName ile hesap ID tespiti
     * 2. GetPackages ile paketleri listeleme
     * 3. GetDomainsByPackageID ile domain tespiti
     * 4. DeleteDomain ile domainleri silme
     * 5. DeletePackage ile paketi silme
     *
     * Helm 3 icin:
     * 1. DeleteUser ile kullaniciyi dogrudan siler
     *
     * @param  array  $params  Gerekli: username, domain
     *                         Opsiyonel: email (Helm 4 icin)
     * @return array Islem sonucu
     */
    public function terminateAccount(array $params)
    {
        if (empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_username_required'),
            ];
        }

        try {
            if ($this->isVersion4()) {
                $accountId = $this->resolveAccountId($params);

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

                // Paketleri listele
                $packagesResult = $this->callHelmApi('GetPackages', [
                    'UserAccountId' => $accountId,
                ], $params);

                if (! $this->isSuccess($packagesResult)) {
                    return [
                        'status' => 'error',
                        'message' => $this->getResultDescription($packagesResult)
                            ?? __('admin/modules.helm_get_packages_failed'),
                        'data' => $packagesResult,
                    ];
                }

                // Ilgili paketi bul (domain adina gore)
                $helmPackageId = $this->findPackageIdByDomain($packagesResult, $params['domain'] ?? '');

                if ($helmPackageId) {
                    // Paket domain'lerini sil
                    $domainsResult = $this->callHelmApi('GetDomainsByPackageID', [
                        'UserAccountId' => $accountId,
                        'PackageID' => $helmPackageId,
                    ], $params);

                    if ($this->isSuccess($domainsResult)) {
                        $domains = $this->extractRecords($domainsResult);

                        foreach ($domains as $domain) {
                            if (! empty($domain['DOMAINID'])) {
                                $this->callHelmApi('DeleteDomain', [
                                    'DomainID' => $domain['DOMAINID'],
                                ], $params);
                            }
                        }
                    }

                    // Paketi sil
                    $deletePackageResult = $this->callHelmApi('DeletePackage', [
                        'UserAccountId' => $accountId,
                        'PackageID' => $helmPackageId,
                    ], $params);

                    if (! $this->isSuccess($deletePackageResult)) {
                        return [
                            'status' => 'error',
                            'message' => $this->getResultDescription($deletePackageResult)
                                ?? __('admin/modules.helm_package_delete_failed'),
                            'data' => $deletePackageResult,
                        ];
                    }
                }

                return [
                    'status' => 'success',
                    'message' => __('admin/modules.helm_account_terminated_success'),
                ];
            } else {
                // Helm 3: Dogrudan kullanici silme
                $response = $this->callHelmApi('DeleteUser', [
                    'UserAccountNumber' => $params['username'],
                ], $params);

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

                return [
                    'status' => 'error',
                    'message' => $this->getResultDescription($response)
                        ?? __('admin/modules.helm_account_terminate_failed'),
                    'data' => $response,
                ];
            }
        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_terminate_exception', ['error' => $e->getMessage()]),
            ];
        }
    }

    /**
     * Helm hesap sifresini degistirir
     *
     * @param  array  $params  Gerekli: username, password
     * @return array Islem sonucu
     */
    public function changeAccountPassword(array $params)
    {
        if (empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_username_required'),
            ];
        }

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

        try {
            if ($this->isVersion4()) {
                $accountId = $this->resolveAccountId($params);

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

                $response = $this->callHelmApi('UpdateAccountPassword', [
                    'UserAccountId' => $accountId,
                    'LoginName' => $params['username'],
                    'NewPassword' => $params['password'],
                ], $params);
            } else {
                $response = $this->callHelmApi('UpdateUserPassword', [
                    'UserAccountNumber' => $params['username'],
                    'NewAccountPassword' => urlencode($params['password']),
                ], $params);
            }

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

            return [
                'status' => 'error',
                'message' => $this->getResultDescription($response)
                    ?? __('admin/modules.helm_password_change_failed'),
                'data' => $response,
            ];
        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_password_change_exception', ['error' => $e->getMessage()]),
            ];
        }
    }

    /**
     * Helm hesap paketini degistirir (yukseltme/dusurme)
     *
     * Sadece Helm 4 destekler (UpgradePackage API).
     * Helm 3'te paket degisikligi manuel yapilmalidir.
     *
     * @param  array  $params  Gerekli: username, plan_id, domain
     *                         Opsiyonel: email (Helm 4 icin)
     * @return array Islem sonucu
     */
    public function changeAccountPackage(array $params)
    {
        if (empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_username_required'),
            ];
        }

        // Yeni plan flat $params['plan'] veya module-config'ten cozulebilir (PRC-1015).
        $params['plan_id'] = $this->resolvePlanId($params);

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

        if (! $this->isVersion4()) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_change_package_not_supported_v3'),
            ];
        }

        try {
            $accountId = $this->resolveAccountId($params);

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

            // Paketleri listele ve domain'e gore bul
            $packagesResult = $this->callHelmApi('GetPackages', [
                'UserAccountId' => $accountId,
            ], $params);

            if (! $this->isSuccess($packagesResult)) {
                return [
                    'status' => 'error',
                    'message' => $this->getResultDescription($packagesResult)
                        ?? __('admin/modules.helm_get_packages_failed'),
                    'data' => $packagesResult,
                ];
            }

            $helmPackageId = $this->findPackageIdByDomain($packagesResult, $params['domain'] ?? '');

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

            $response = $this->callHelmApi('UpgradePackage', [
                'UserAccountId' => $accountId,
                'PackageID' => $helmPackageId,
                'NewPlanID' => $params['plan_id'],
            ], $params);

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

            return [
                'status' => 'error',
                'message' => $this->getResultDescription($response)
                    ?? __('admin/modules.helm_package_change_failed'),
                'data' => $response,
            ];
        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_change_package_exception', ['error' => $e->getMessage()]),
            ];
        }
    }

    // =========================================================================
    // FIELD DEFINITIONS
    // =========================================================================

    /**
     * Admin panelinde gosterilecek alanlari dondurur
     *
     * @return array Admin panel alanlari
     */
    public function adminFields()
    {
        return [
            'hostname' => [
                'name' => __('admin/modules.helm_field_hostname'),
                'type' => 'text',
                'description' => __('admin/modules.helm_field_hostname_description'),
                'required' => true,
            ],
            'port' => [
                'name' => __('admin/modules.helm_field_port'),
                'type' => 'text',
                'description' => __('admin/modules.helm_field_port_description'),
                'required' => false,
                'default' => '8086',
            ],
            'username' => [
                'name' => __('admin/modules.helm_field_username'),
                'type' => 'text',
                'description' => __('admin/modules.helm_field_username_description'),
                'required' => true,
            ],
            'password' => [
                'name' => __('admin/modules.helm_field_password'),
                'type' => 'password',
                'description' => __('admin/modules.helm_field_password_description'),
                'required' => true,
            ],
            'secure' => [
                'name' => __('admin/modules.helm_field_secure'),
                'type' => 'checkbox',
                'description' => __('admin/modules.helm_field_secure_description'),
                'default' => false,
            ],
            'helm_version' => [
                'name' => __('admin/modules.helm_field_version'),
                'type' => 'select',
                'description' => __('admin/modules.helm_field_version_description'),
                'options' => [
                    '3' => 'Helm 3',
                    '4' => 'Helm 4',
                ],
                'default' => '4',
            ],
            'plan_id' => [
                'name' => __('admin/modules.helm_field_plan_id'),
                'type' => 'text',
                'description' => __('admin/modules.helm_field_plan_id_description'),
                'required' => true,
            ],
            'account_role_id' => [
                'name' => __('admin/modules.helm_field_account_role_id'),
                'type' => 'text',
                'description' => __('admin/modules.helm_field_account_role_id_description'),
                'required' => false,
                'default' => '1',
            ],
            'reseller_plan_id' => [
                'name' => __('admin/modules.helm_field_reseller_plan_id'),
                'type' => 'text',
                'description' => __('admin/modules.helm_field_reseller_plan_id_description'),
                'required' => false,
                'default' => '0',
            ],
            'auto_username' => [
                'name' => __('admin/modules.helm_field_auto_username'),
                'type' => 'checkbox',
                'description' => __('admin/modules.helm_field_auto_username_description'),
                'default' => false,
            ],
        ];
    }

    /**
     * Musteri panelinde gosterilecek alanlari dondurur
     *
     * @return array Musteri panel alanlari
     */
    public function clientFields()
    {
        return [
            'domain' => [
                'name' => __('admin/modules.helm_field_domain'),
                'type' => 'text',
                'description' => __('admin/modules.helm_field_domain_description'),
                'required' => true,
            ],
            'username' => [
                'name' => __('admin/modules.helm_field_client_username'),
                'type' => 'text',
                'description' => __('admin/modules.helm_field_client_username_description'),
                'required' => true,
            ],
            'password' => [
                'name' => __('admin/modules.helm_field_client_password'),
                'type' => 'password',
                'description' => __('admin/modules.helm_field_client_password_description'),
                'required' => true,
            ],
        ];
    }

    /**
     * Server yonetimi icin gosterilecek alanlari dondurur
     *
     * @return array Server yonetimi alanlari
     */
    public function serverFields()
    {
        return [
            'password' => [
                'name' => __('admin/modules.helm_field_server_password'),
                'type' => 'password',
                'description' => __('admin/modules.helm_field_server_password_description'),
                'required' => true,
            ],
        ];
    }

    // =========================================================================
    // CONNECTION TEST
    // =========================================================================

    /**
     * Helm sunucusuna baglanti testini gerceklestirir
     *
     * Helm 4: GetAccountByName ile admin hesabini kontrol eder
     * Helm 3: AddUser action'i ile baglanti dogrular (bos istekle hata kontrolu)
     *
     * @param  array  $params  Test parametreleri
     * @return array Test sonucu
     */
    public function testConnection(array $params = [])
    {
        try {
            $conn = $this->serverConfig($params);

            if ($this->isVersion4()) {
                // Helm 4: Admin hesap kontrolu ile test
                $response = $this->callHelmApi('GetAccountByName', [
                    'UserAccountName' => $conn['username'],
                    'IncludeChildren' => 'false',
                ], $params);

                // Basarili yanit veya gecerli hata kodu (hesap bulunamadi bile olsa baglanti calisiyor)
                if (isset($response['RESULTS'])) {
                    return [
                        'status' => 'success',
                        'message' => __('admin/modules.helm_connection_test_success'),
                        'data' => [
                            'helm_version' => '4',
                            'server' => $conn['hostname'],
                        ],
                    ];
                }
            } else {
                // Helm 3: Basit API cagrisi ile baglanti testi
                $response = $this->callHelmApi('GetSystemInfo', [], $params);

                if (isset($response['RESULTS'])) {
                    return [
                        'status' => 'success',
                        'message' => __('admin/modules.helm_connection_test_success'),
                        'data' => [
                            'helm_version' => '3',
                            'server' => $conn['hostname'],
                        ],
                    ];
                }
            }

            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_connection_test_failed'),
                'data' => $response ?? [],
            ];
        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_connection_test_exception', ['error' => $e->getMessage()]),
            ];
        }
    }

    // =========================================================================
    // SSO LOGIN
    // =========================================================================

    /**
     * Helm kontrol paneline SSO (tek oturum acma) baglantisi olusturur
     *
     * @param  array  $params  Gerekli: username
     * @return array SSO sonucu (url icerir)
     */
    public function createSSOLogin(array $params)
    {
        if (empty($params['username'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_username_required'),
            ];
        }

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

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

        // Helm imzali tek-oturum token URL'i sunmaz; panelin acilis
        // adresini dondururuz (kullanici kendi kimligiyle giris yapar).
        $loginUrl = "{$protocol}://{$hostname}:{$port}/";

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

    // =========================================================================
    // ADMIN BUTTONS & CUSTOM ACTIONS
    // =========================================================================

    /**
     * Admin panelde gosterilecek ozel butonlari dondurur
     *
     * @return array Admin butonlari
     */
    public function getAdminButtons(): array
    {
        return [
            [
                'action' => 'list_packages',
                'label' => __('admin/modules.helm_action_list_packages'),
                'icon' => 'fas fa-list',
                'class' => 'btn-outline-info',
            ],
            [
                'action' => 'account_details',
                'label' => __('admin/modules.helm_action_account_details'),
                'icon' => 'fas fa-info-circle',
                'class' => 'btn-outline-primary',
            ],
            [
                'action' => 'check_status',
                'label' => __('admin/modules.helm_action_check_status'),
                'icon' => 'fas fa-check-circle',
                'class' => 'btn-outline-success',
            ],
        ];
    }

    /**
     * Admin ozel action'i isler
     *
     * @param  string  $action  Action adi (list_packages, account_details, check_status)
     * @param  array  $params  Parametreler
     * @return array Islem sonucu
     */
    public function adminCustomAction(string $action, array $params): array
    {
        switch ($action) {
            case 'list_packages':
                return $this->adminActionListPackages($params);

            case 'account_details':
                return $this->adminActionAccountDetails($params);

            case 'check_status':
                return $this->adminActionCheckStatus($params);

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

    /**
     * Hesaba ait paketleri listeler
     *
     * @param  array  $params  Parametreler
     * @return array Paket listesi
     */
    protected function adminActionListPackages(array $params): array
    {
        if (! $this->isVersion4()) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_list_packages_not_supported_v3'),
            ];
        }

        $accountId = $this->resolveAccountId($params);

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

        $response = $this->callHelmApi('GetPackages', [
            'UserAccountId' => $accountId,
        ], $params);

        if (! $this->isSuccess($response)) {
            return [
                'status' => 'error',
                'message' => $this->getResultDescription($response)
                    ?? __('admin/modules.helm_list_packages_failed'),
            ];
        }

        $packages = $this->extractRecords($response);

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

    /**
     * Hesap detaylarini getirir
     *
     * @param  array  $params  Parametreler
     * @return array Hesap detaylari
     */
    protected function adminActionAccountDetails(array $params): array
    {
        if (empty($params['username']) && empty($params['email'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_username_required'),
            ];
        }

        if ($this->isVersion4()) {
            $email = $params['email'] ?? $params['username'];

            $response = $this->callHelmApi('GetAccountByName', [
                'UserAccountName' => $email,
                'IncludeChildren' => 'true',
            ], $params);

            if (! $this->isSuccess($response)) {
                return [
                    'status' => 'error',
                    'message' => $this->getResultDescription($response)
                        ?? __('admin/modules.helm_account_details_failed'),
                ];
            }

            $record = $this->extractValue($response, 'RESULTDATA.RECORD');

            return [
                'status' => 'success',
                'message' => __('admin/modules.helm_account_details_success'),
                'data' => [
                    'account_id' => $record['ACCOUNTID'] ?? '',
                    'account_name' => $record['ACCOUNTNAME'] ?? '',
                    'primary_login' => $record['PRIMARYLOGINNAME'] ?? '',
                    'status' => $record['STATUS'] ?? '',
                ],
            ];
        }

        // Helm 3 dogrudan hesap bilgisi donduremez
        return [
            'status' => 'success',
            'message' => __('admin/modules.helm_account_details_success'),
            'data' => [
                'username' => $params['username'],
                'helm_version' => '3',
            ],
        ];
    }

    /**
     * Hesap durumunu kontrol eder
     *
     * @param  array  $params  Parametreler
     * @return array Durum bilgisi
     */
    protected function adminActionCheckStatus(array $params): array
    {
        if (empty($params['username']) && empty($params['email'])) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_username_required'),
            ];
        }

        if (! $this->isVersion4()) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.helm_check_status_not_supported_v3'),
            ];
        }

        $accountId = $this->resolveAccountId($params);

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

        $response = $this->callHelmApi('GetAccountByName', [
            'UserAccountName' => $params['email'] ?? $params['username'],
            'IncludeChildren' => 'false',
        ], $params);

        if (! $this->isSuccess($response)) {
            return [
                'status' => 'error',
                'message' => $this->getResultDescription($response)
                    ?? __('admin/modules.helm_check_status_failed'),
            ];
        }

        $record = $this->extractValue($response, 'RESULTDATA.RECORD');
        $accountStatus = $record['STATUS'] ?? 'unknown';

        $isSuspended = stripos($accountStatus, 'suspend') !== false;

        return [
            'status' => 'success',
            'message' => $isSuspended
                ? __('admin/modules.helm_account_status_suspended')
                : __('admin/modules.helm_account_status_active'),
            'data' => [
                'suspended' => $isSuspended,
                'raw_status' => $accountStatus,
            ],
        ];
    }

    // =========================================================================
    // CLIENT ACTIONS
    // =========================================================================

    /**
     * Client area'da gosterilecek action'lari dondurur
     *
     * @return array Client action'lari
     */
    public function getClientActions(): array
    {
        $actions = parent::getClientActions();

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

        return $actions;
    }

    /**
     * Client action'i isler
     *
     * @param  string  $action  Action adi
     * @param  array  $params  Parametreler
     * @return array Sonuc
     */
    public function handleClientAction(string $action, array $params): array
    {
        switch ($action) {
            case 'login_helm':
                return $this->createSSOLogin($params);

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

    // =========================================================================
    // RESOURCE USAGE
    // =========================================================================

    /**
     * Kaynak kullanim bilgilerini dondurur
     *
     * Helm 4'te GetPackages ile disk ve bandwidth bilgisi alinabilir.
     *
     * @param  array  $params  Parametreler (username, email, domain)
     * @return array|null Kaynak kullanim verileri veya null
     */
    public function getResourceUsage(array $params): ?array
    {
        if (! $this->isVersion4()) {
            return null;
        }

        try {
            $accountId = $this->resolveAccountId($params);

            if (! $accountId) {
                return null;
            }

            $response = $this->callHelmApi('GetPackages', [
                'UserAccountId' => $accountId,
            ], $params);

            if (! $this->isSuccess($response)) {
                return null;
            }

            $packages = $this->extractRecords($response);
            $resources = [];

            foreach ($packages as $package) {
                $packageName = $package['NAME'] ?? 'Unknown';

                if (isset($package['DISKSPACEUSED']) && isset($package['DISKSPACELIMIT'])) {
                    $diskUsed = (float) ($package['DISKSPACEUSED'] ?? 0);
                    $diskLimit = (float) ($package['DISKSPACELIMIT'] ?? 0);

                    $resources[] = [
                        'name' => "Disk Space ({$packageName})",
                        'used' => $diskUsed,
                        'limit' => $diskLimit,
                        'unit' => 'MB',
                        'percentage' => $diskLimit > 0 ? round(($diskUsed / $diskLimit) * 100, 2) : 0,
                    ];
                }

                if (isset($package['BANDWIDTHUSED']) && isset($package['BANDWIDTHLIMIT'])) {
                    $bwUsed = (float) ($package['BANDWIDTHUSED'] ?? 0);
                    $bwLimit = (float) ($package['BANDWIDTHLIMIT'] ?? 0);

                    $resources[] = [
                        'name' => "Bandwidth ({$packageName})",
                        'used' => $bwUsed,
                        'limit' => $bwLimit,
                        'unit' => 'MB',
                        'percentage' => $bwLimit > 0 ? round(($bwUsed / $bwLimit) * 100, 2) : 0,
                    ];
                }
            }

            return ! empty($resources) ? $resources : null;
        } catch (\Exception $e) {
            return null;
        }
    }

    // =========================================================================
    // CONFIGURATION VALIDATION
    // =========================================================================

    /**
     * Yapilandirma dogrulamasi (module-config duzeyinde en-iyi-caba).
     *
     * Helm server-based bir moduldur: host/creds calisma aninda atanmis
     * sunucudan ($params['server']) de gelebilir. Bu yuzden module-config'te
     * host/creds bos olsa bile hard-fail ETMEZ; yalnizca hicbir kaynaktan
     * (config) hostname yoksa uyar. Gercek dogrulama transport'ta serverConfig()
     * ile yapilir.
     *
     * @return bool
     *
     * @throws \Exception Module-config hem de sunucu olmadan tamamen bosalsa
     */
    public function validateConfig()
    {
        $conn = $this->serverConfig([]);

        if (empty($conn['hostname'])) {
            throw new \Exception(__('admin/modules.helm_config_hostname_missing'));
        }

        return true;
    }

    // =========================================================================
    // HELM API COMMUNICATION
    // =========================================================================

    /**
     * Helm API'sine HTTP POST cagrisi yapar
     *
     * Helm 3: billing_api.asp endpoint'ine POST
     * Helm 4: ServiceAPI/HttpAPI.aspx endpoint'ine POST
     *
     * Tum istekler admin kimlik bilgilerini icerir.
     *
     * @param  string  $action  Helm API action adi
     * @param  array  $fields  Gonderilecek alanlar
     * @param  array  $params  Provizyon parametreleri (atanmis sunucu / module_config kaynagi)
     * @return array XML parse edilmis API yaniti
     *
     * @throws \Exception cURL hatasi durumunda
     */
    protected function callHelmApi(string $action, array $fields, array $params = []): array
    {
        // Host/creds tek kaynak: atanmis sunucu oncelikli, yoksa module_config (PRC-1015).
        $conn = $this->serverConfig($params);

        $protocol = $conn['secure'] ? 'https' : 'http';
        $hostname = $conn['hostname'];
        $port = $this->getApiPort($conn['port']);
        $adminUsername = $conn['username'];
        $adminPassword = $conn['password'];

        if ($this->isVersion4()) {
            // Helm 4: ServiceAPI/HttpAPI.aspx
            $url = "{$protocol}://{$hostname}:{$port}/ServiceAPI/HttpAPI.aspx";

            $requestFields = array_merge([
                'AccountName' => $adminUsername,
                'Username' => $adminUsername,
                'Password' => $adminPassword,
                'action' => $action,
            ], $fields);

            $postData = http_build_query($requestFields);
        } else {
            // Helm 3: billing_api.asp
            $url = "{$protocol}://{$hostname}/billing_api.asp";

            $requestFields = array_merge([
                'Username' => $adminUsername,
                'Password' => $adminPassword,
                'action' => $action,
            ], $fields);

            $postData = http_build_query($requestFields);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
        ]);

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

        curl_close($ch);

        if ($curlErrno) {
            throw new \Exception(
                __('admin/modules.helm_curl_error', [
                    'error' => $curlError,
                    'code' => $curlErrno,
                ])
            );
        }

        // XML yanitini parse et
        $parsed = $this->parseXmlResponse($response);

        // Module loglama
        $this->logApiCall($action, $requestFields, $response, $parsed);

        return $parsed;
    }

    /**
     * XML yanitini array'e parse eder
     *
     * Helm API XML formatta yanit dondurur. Bu metot yaniti
     * ust harfli anahtarlarla bir array'e donusturur.
     *
     * @param  string  $xml  XML yanit
     * @return array Parse edilmis veri
     */
    protected function parseXmlResponse(string $xml): array
    {
        if (empty($xml)) {
            return [];
        }

        // HTML hata kontrolu (Helm bazen HTML hata sayfasi dondurur)
        if (stripos($xml, '<h1>') !== false) {
            preg_match('/<h1>(.*?)<\/h1>/i', $xml, $matches);

            return [
                'HTML_ERROR' => $matches[1] ?? 'Unknown HTML error',
                '_raw' => $xml,
            ];
        }

        libxml_use_internal_errors(true);
        $xmlObj = simplexml_load_string($xml);

        if ($xmlObj === false) {
            return [
                'PARSE_ERROR' => 'XML parse failed',
                '_raw' => $xml,
            ];
        }

        $result = json_decode(json_encode($xmlObj), true);

        // Ust harfe donustur (Helm standardi)
        $result = $this->arrayKeysToUpper($result);

        // Ham XML'i de sakla (Helm 4 terminate isleminde gerekli)
        $result['_raw'] = $xml;

        return $result;
    }

    /**
     * Array anahtarlarini recursive olarak ust harfe donusturur
     *
     * @param  array  $array  Donusturulecek array
     * @return array Donusturulmus array
     */
    protected function arrayKeysToUpper(array $array): array
    {
        $result = [];

        foreach ($array as $key => $value) {
            $upperKey = strtoupper((string) $key);

            if (is_array($value)) {
                $result[$upperKey] = $this->arrayKeysToUpper($value);
            } else {
                $result[$upperKey] = $value;
            }
        }

        return $result;
    }

    // =========================================================================
    // HELPER METHODS
    // =========================================================================

    /**
     * Helm versiyonunun 4 olup olmadigini kontrol eder
     *
     * @return bool Helm 4 mu?
     */
    protected function isVersion4(): bool
    {
        $version = $this->config['helm_version'] ?? $this->helmVersion;

        return (string) $version === '4';
    }

    /**
     * API port numarasini dondurur
     *
     * Cozulmus baglanti portu (serverConfig) varsa onu, yoksa varsayilan portu kullanir.
     *
     * @param  mixed  $resolvedPort  serverConfig()'ten gelen port (null olabilir)
     * @return int Port numarasi
     */
    protected function getApiPort($resolvedPort = null): int
    {
        if ($resolvedPort !== null && (int) $resolvedPort > 0) {
            return (int) $resolvedPort;
        }

        return $this->apiPort;
    }

    /**
     * API yanitinin basarili olup olmadigini kontrol eder
     *
     * Helm API basarili islemlerde RESULTCODE=0 dondurur.
     *
     * @param  array  $response  API yaniti
     * @return bool Basarili mi?
     */
    protected function isSuccess(array $response): bool
    {
        return isset($response['RESULTS']['RESULTCODE'])
            && (string) $response['RESULTS']['RESULTCODE'] === self::RESULT_SUCCESS;
    }

    /**
     * API yanitindan sonuc verisini (RESULTDATA) dondurur
     *
     * @param  array  $response  API yaniti
     * @return string|null Sonuc verisi
     */
    protected function getResultData(array $response): ?string
    {
        $data = $response['RESULTS']['RESULTDATA'] ?? null;

        if (is_array($data)) {
            return null;
        }

        return $data;
    }

    /**
     * API yanitindan hata aciklamasini dondurur
     *
     * @param  array  $response  API yaniti
     * @return string|null Hata aciklamasi
     */
    protected function getResultDescription(array $response): ?string
    {
        if (isset($response['HTML_ERROR'])) {
            return $response['HTML_ERROR'];
        }

        $code = $response['RESULTS']['RESULTCODE'] ?? '';
        $description = $response['RESULTS']['RESULTDESCRIPTION'] ?? '';

        if (! empty($code) && ! empty($description)) {
            return "{$code} - {$description}";
        }

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

    /**
     * Nokta notasyonu ile ic ice array degerine erisir
     *
     * Ornek: extractValue($data, 'RESULTDATA.RECORD.ACCOUNTID')
     *
     * @param  array  $data  Veri array'i
     * @param  string  $path  Nokta notasyonlu yol (RESULTS altinda aranir)
     * @return mixed|null Bulunan deger veya null
     */
    protected function extractValue(array $data, string $path): mixed
    {
        $keys = explode('.', $path);
        $current = $data['RESULTS'] ?? $data;

        foreach ($keys as $key) {
            if (! is_array($current) || ! isset($current[$key])) {
                return null;
            }
            $current = $current[$key];
        }

        return $current;
    }

    /**
     * API yanitindan Record listesi cikarir
     *
     * Helm 4 API'si genellikle <Record> elementleri icerir.
     * Bu metot ham XML'den Record'lari parse eder.
     *
     * @param  array  $response  API yaniti (_raw anahtari olmali)
     * @return array Record listesi
     */
    protected function extractRecords(array $response): array
    {
        $rawXml = $response['_raw'] ?? '';

        if (empty($rawXml)) {
            // _raw yoksa RESULTDATA icerisindeki RECORD'lara bak
            $resultData = $response['RESULTS']['RESULTDATA'] ?? [];

            if (isset($resultData['RECORD'])) {
                // Tek record ise array'e sar
                if (isset($resultData['RECORD']['PACKAGEID']) || isset($resultData['RECORD']['DOMAINID'])) {
                    return [$resultData['RECORD']];
                }

                return $resultData['RECORD'];
            }

            return [];
        }

        // Ham XML'den Record'lari parse et
        $records = [];
        $parts = explode('<Record>', $rawXml);

        foreach ($parts as $part) {
            if (strpos($part, '</Record>') === false) {
                continue;
            }

            $recordXml = '<Record>' . substr($part, 0, strpos($part, '</Record>') + strlen('</Record>'));

            libxml_use_internal_errors(true);
            $xmlObj = simplexml_load_string($recordXml);

            if ($xmlObj !== false) {
                $record = json_decode(json_encode($xmlObj), true);
                $record = $this->arrayKeysToUpper($record);
                $records[] = $record;
            }
        }

        return $records;
    }

    /**
     * Hesap ID'sini email veya username ile tespit eder (Helm 4)
     *
     * @param  array  $params  username veya email icermeli
     * @return string|null Helm hesap ID'si veya null
     */
    protected function resolveAccountId(array $params): ?string
    {
        // Uzak hesap kimligi once saklanmis remote-id'den (account_id /
        // module_handler_id) — procp ic FK'lari ASLA uzak-id degil (PRC-1015).
        $remoteId = $this->remoteId($params);
        if ($remoteId !== null) {
            return $remoteId;
        }

        // Fallback: email/username ile GetAccountByName lookup.
        $lookupValue = $params['email'] ?? $params['username'] ?? '';

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

        $response = $this->callHelmApi('GetAccountByName', [
            'UserAccountName' => $lookupValue,
            'IncludeChildren' => 'false',
        ], $params);

        if ($this->isSuccess($response)) {
            return $this->extractValue($response, 'RESULTDATA.RECORD.ACCOUNTID');
        }

        // Email ile bulunamadiysa username ile dene
        if ($lookupValue === ($params['email'] ?? '') && ! empty($params['username'])) {
            $response = $this->callHelmApi('GetAccountByName', [
                'UserAccountName' => $params['username'],
                'IncludeChildren' => 'false',
            ], $params);

            if ($this->isSuccess($response)) {
                return $this->extractValue($response, 'RESULTDATA.RECORD.ACCOUNTID');
            }
        }

        return null;
    }

    /**
     * Plan/paket id'sini cozer (PRC-1015).
     *
     * Oncelik: acik $params['plan_id'] → builder flat $params['plan']/$params['package']
     * → module-config anahtarlari (plan_id/plan/package). Boylece paket kaynagi
     * per-product module-config'ten guvenilir sekilde gelir.
     *
     * @return string Cozulmus plan_id (yoksa bos string)
     */
    protected function resolvePlanId(array $params): string
    {
        foreach (['plan_id', 'plan', 'package'] as $key) {
            if (isset($params[$key]) && is_scalar($params[$key]) && trim((string) $params[$key]) !== '') {
                return (string) $params[$key];
            }
        }

        foreach (['plan_id', 'plan', 'package'] as $key) {
            $value = $this->moduleConfig($params, $key);
            if ($value !== null && trim((string) $value) !== '') {
                return (string) $value;
            }
        }

        return '';
    }

    /**
     * Domain adina gore paket ID'sini bulur
     *
     * Helm 4 GetPackages yanitindaki Record'lar arasinda domain adini arar.
     *
     * @param  array  $response  GetPackages API yaniti
     * @param  string  $domain  Aranan domain adi
     * @return string|null Paket ID'si veya null
     */
    protected function findPackageIdByDomain(array $response, string $domain): ?string
    {
        $records = $this->extractRecords($response);

        foreach ($records as $record) {
            if (isset($record['NAME']) && strtolower($record['NAME']) === strtolower($domain)) {
                return $record['PACKAGEID'] ?? null;
            }
        }

        // Domain bulunamadiysa ilk paketi dondur
        if (! empty($records)) {
            return $records[0]['PACKAGEID'] ?? null;
        }

        return null;
    }

    /**
     * API cagrisini loglar
     *
     * Debug ve sorun giderme icin API cagrilarini kaydeder.
     * Hassas bilgileri (sifre, token) maskeler.
     *
     * @param  string  $action  API action adi
     * @param  array  $requestFields  Gonderilen alanlar
     * @param  string  $rawResponse  Ham yanit
     * @param  array  $parsedResponse  Parse edilmis yanit
     */
    protected function logApiCall(string $action, array $requestFields, string $rawResponse, array $parsedResponse): void
    {
        // Hassas verileri maskele
        $maskedFields = $requestFields;
        $sensitiveKeys = ['Password', 'password', 'NewAccountPassword', 'AdminLoginPassword', 'NewPassword'];

        foreach ($sensitiveKeys as $key) {
            if (isset($maskedFields[$key])) {
                $maskedFields[$key] = '***MASKED***';
            }
        }

        logger()->debug('Helm API Call', [
            'action' => $action,
            'request' => $maskedFields,
            'response_code' => $parsedResponse['RESULTS']['RESULTCODE'] ?? 'N/A',
            'response_description' => $parsedResponse['RESULTS']['RESULTDESCRIPTION'] ?? 'N/A',
        ]);
    }
}
