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

namespace PortalPeople\upn\models;

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

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

    /** @var string UPN External Links SOAP API URL. */
    public $apiUrl = 'https://services.upn.co.uk:20675/ExternalLinks';

    /** @var int UPN depot number (integer provided by UPN). */
    public $depot;

    /** @var int UPN customer ID (unique per customer account at your depot). */
    public $customerId;

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

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

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

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

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

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

    /** @inheritdoc */
    public function attributeLabels(): array
    {
        return [
            'enabled'    => 'Enable Integration',
            'apiUrl'     => 'API URL',
            'depot'      => 'Depot Number',
            'customerId' => 'Customer ID',
            'username'   => 'Username',
            'password'   => 'Password',
            'timeout'    => 'Request Timeout (seconds)',
            'debug'      => 'Enable Debug Logging',
        ];
    }

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

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

        $this->enabled    = (bool) ($config['enabled']    ?? false);
        $this->apiUrl     = $config['apiUrl']              ?? 'https://services.upn.co.uk:20675/ExternalLinks';
        $this->depot      = (int)  ($config['depot']       ?? 0);
        $this->customerId = (int)  ($config['customerId']  ?? 0);
        $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, 'upn');
            return false;
        }

        $params = require $paramsFile;

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

        $params['plugins']['upn'] = [
            'enabled'    => $this->enabled,
            'apiUrl'     => $this->apiUrl,
            'depot'      => (int) $this->depot,
            'customerId' => (int) $this->customerId,
            '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\upn\components\UpnClient([
            'apiUrl'     => $this->apiUrl,
            'depot'      => (int) $this->depot,
            'customerId' => (int) $this->customerId,
            'username'   => $this->username,
            'password'   => $this->password,
            'timeout'    => (int) $this->timeout,
            'debug'      => $this->debug,
        ]);
        $client->init();

        return $client->testConnection();
    }
}
