<?php
/**
 * Configuration Form Model – DX Despatch Manager Module
 *
 * @category    PortalPeople
 * @package     DX
 * @author      Portal People Development Team
 * @copyright   Copyright (c) 2026 Portal People (https://portalpeople.co.uk)
 */

namespace PortalPeople\dx\models;

use Yii;
use yii\base\Model;
use backend\components\Security;

/**
 * ConfigForm
 *
 * Stores and validates the DX connection settings, which are
 * persisted to `backend/config/params-local.php` under the key
 * `plugins.dx`.
 */
class ConfigForm extends Model
{
    /** @var bool Enable the integration. */
    public $enabled = false;

    /** @var string DX REST API base URL. */
    public $apiUrl = 'https://despatch-api.dxdelivery.com';

    /** @var string DX account code. */
    public $accountCode;

    /** @var string DX API username. */
    public $username;

    /** @var string DX API password. */
    public $password;

    /** @var int HTTP request timeout in seconds. */
    public $timeout = 30;

    /** @var bool Enable debug logging. */
    public $debug = false;

    // -------------------------------------------------------------------------

    /** @inheritdoc */
    public function rules(): array
    {
        return [
            [['apiUrl', 'accountCode', 'username', 'password'], 'required'],
            [['apiUrl'], 'url', 'defaultScheme' => 'https'],
            [['accountCode', 'username', 'password'], 'string'],
            [['username'], 'email'],
            [['timeout'], 'integer', 'min' => 5, 'max' => 120],
            [['enabled', 'debug'], 'boolean'],
        ];
    }

    /** @inheritdoc */
    public function attributeLabels(): array
    {
        return [
            'enabled'     => 'Enable Integration',
            'apiUrl'      => 'API Base URL',
            'accountCode' => 'Account Code',
            'username'    => 'Username (Email)',
            'password'    => 'Password',
            'timeout'     => 'Request Timeout (seconds)',
            'debug'       => 'Enable Debug Logging',
        ];
    }

    // -------------------------------------------------------------------------

    /**
     * Populate model from current params-local.php.
     */
    public function loadFromParams(): void
    {
        $config = Yii::$app->params['plugins']['dx'] ?? [];

        $this->enabled     = (bool) ($config['enabled']  ?? false);
        $this->apiUrl      = $config['apiUrl']            ?? 'https://despatch-api.dxdelivery.com';
        $this->accountCode = $config['accountCode']       ?? '';
        $this->username    = $config['username']          ?? '';
        $this->password    = Security::decryptSensitiveData($config['password'] ?? '');
        $this->timeout     = (int)  ($config['timeout']   ?? 30);
        $this->debug       = (bool) ($config['debug']     ?? false);
    }

    /**
     * Persist model data to params-local.php.
     *
     * @return bool
     */
    public function saveToParams(): bool
    {
        $paramsFile = Yii::getAlias('@backend/config/params-local.php');

        if (!file_exists($paramsFile)) {
            Yii::error('params-local.php not found: ' . $paramsFile, 'dx');
            return false;
        }

        $params = require $paramsFile;

        if (!isset($params['plugins'])) {
            $params['plugins'] = [];
        }

        $params['plugins']['dx'] = [
            'enabled'     => $this->enabled,
            'apiUrl'      => $this->apiUrl,
            'accountCode' => $this->accountCode,
            'username'    => $this->username,
            'password'    => Security::encryptSensitiveData($this->password),
            'timeout'     => (int) $this->timeout,
            'debug'       => $this->debug,
        ];

        $content = "<?php\nreturn " . var_export($params, true) . ";\n";

        return file_put_contents($paramsFile, $content) !== false;
    }

    /**
     * Test API connection using current form values (without saving).
     *
     * @return array ['success' => bool, 'message' => string]
     */
    public function testConnection(): array
    {
        if (!$this->validate()) {
            return ['success' => false, 'message' => 'Validation failed: ' . implode(', ', $this->getFirstErrors())];
        }

        $client = new \PortalPeople\dx\components\DxClient([
            'apiUrl'      => $this->apiUrl,
            'accountCode' => $this->accountCode,
            'username'    => $this->username,
            'password'    => $this->password,
            'timeout'     => (int) $this->timeout,
            'debug'       => $this->debug,
        ]);
        $client->init();

        return $client->testConnection();
    }
}
