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

namespace PortalPeople\palletforce\models;

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

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

    /** @var string Palletforce REST API base URL. */
    public $apiUrl;

    /** @var string Unique access key provided by Palletforce. */
    public $accessKey;

    /** @var string Customer account number (assigned by Palletforce). */
    public $accountNumber;

    /** @var string Requesting depot code (3 chars, assigned by Palletforce). */
    public $depotCode;

    /** @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', 'accessKey', 'accountNumber', 'depotCode'], 'required'],
            [['apiUrl'], 'url', 'defaultScheme' => 'https'],
            [['accessKey', 'accountNumber', 'depotCode'], 'string'],
            [['depotCode'], 'string', 'max' => 3],
            [['timeout'], 'integer', 'min' => 5, 'max' => 120],
            [['enabled', 'debug'], 'boolean'],
        ];
    }

    /** @inheritdoc */
    public function attributeLabels(): array
    {
        return [
            'enabled'       => 'Enable Integration',
            'apiUrl'        => 'API Base URL',
            'accessKey'     => 'Access Key',
            'accountNumber' => 'Customer Account Number',
            'depotCode'     => 'Requesting Depot Code',
            'timeout'       => 'Request Timeout (seconds)',
            'debug'         => 'Enable Debug Logging',
        ];
    }

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

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

        $this->enabled       = (bool) ($config['enabled']       ?? false);
        $this->apiUrl        = $config['apiUrl']                ?? '';
        $this->accessKey     = Security::decryptSensitiveData($config['accessKey']     ?? '');
        $this->accountNumber = $config['accountNumber']         ?? '';
        $this->depotCode     = $config['depotCode']             ?? '';
        $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, 'palletforce');
            return false;
        }

        $params = require $paramsFile;

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

        $params['plugins']['palletforce'] = [
            'enabled'       => $this->enabled,
            'apiUrl'        => $this->apiUrl,
            'accessKey'     => Security::encryptSensitiveData($this->accessKey),
            'accountNumber' => $this->accountNumber,
            'depotCode'     => $this->depotCode,
            '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\palletforce\components\PalletforceClient([
            'apiUrl'        => $this->apiUrl,
            'accessKey'     => $this->accessKey,
            'accountNumber' => $this->accountNumber,
            'depotCode'     => $this->depotCode,
            'timeout'       => (int) $this->timeout,
            'debug'         => $this->debug,
        ]);

        return $client->testConnection();
    }
}
