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

namespace PortalPeople\gforce\models;

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

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

    /** @var string GForce REST API base URL. */
    public $apiUrl = 'https://api-uat.vigocloud.com/api/v1';

    /** @var string Customer API key issued by GForce IT. */
    public $apiKey;

    /** @var bool Automatically confirm consignments into the depot (Confirm=yes). */
    public $autoConfirm = false;

    /** @var string Default collection country code for route/service lookup. */
    public $defaultCollectionCountry = 'GB';

    /** @var string Default collection postcode for route/service lookup. */
    public $defaultCollectionPostcode = '';

    /** @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', 'apiKey'], 'required'],
            [['apiUrl'], 'url', 'defaultScheme' => 'https'],
            [['apiKey'], 'string'],
            [['defaultCollectionCountry'], 'string', 'length' => 2],
            [['defaultCollectionPostcode'], 'string', 'max' => 10],
            [['defaultCollectionPostcode'], 'trim'],
            [['timeout'], 'integer', 'min' => 5, 'max' => 120],
            [['enabled', 'autoConfirm', 'debug'], 'boolean'],
        ];
    }

    /** @inheritdoc */
    public function attributeLabels(): array
    {
        return [
            'enabled'     => 'Enable Integration',
            'apiUrl'      => 'API Base URL',
            'apiKey'      => 'API Key',
            'autoConfirm' => 'Auto-Confirm Consignments (send directly to depot)',
            'defaultCollectionCountry' => 'Default Collection Country (ISO Code)',
            'defaultCollectionPostcode' => 'Default Collection Postcode',
            'timeout'     => 'Request Timeout (seconds)',
            'debug'       => 'Enable Debug Logging',
        ];
    }

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

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

        $this->enabled     = (bool)  ($config['enabled']     ?? false);
        $this->apiUrl      = $config['apiUrl']                ?? 'https://api-uat.vigocloud.com/api/v1';
        $this->apiKey      = Security::decryptSensitiveData($config['apiKey'] ?? '');
        $this->autoConfirm = (bool)  ($config['autoConfirm'] ?? false);
        $this->defaultCollectionCountry = (string) ($config['defaultCollectionCountry'] ?? 'GB');
        $this->defaultCollectionPostcode = (string) ($config['defaultCollectionPostcode'] ?? '');
        $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, 'gforce');
            return false;
        }

        $params = require $paramsFile;

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

        $params['plugins']['gforce'] = [
            'enabled'     => $this->enabled,
            'apiUrl'      => $this->apiUrl,
            'apiKey'      => Security::encryptSensitiveData($this->apiKey),
            'autoConfirm' => $this->autoConfirm,
            'defaultCollectionCountry' => strtoupper($this->defaultCollectionCountry ?: 'GB'),
            'defaultCollectionPostcode' => strtoupper($this->defaultCollectionPostcode ?: ''),
            '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\gforce\components\GForceClient([
            'apiUrl'      => $this->apiUrl,
            'apiKey'      => $this->apiKey,
            'autoConfirm' => $this->autoConfirm,
            'timeout'     => (int) $this->timeout,
            'debug'       => $this->debug,
        ]);

        return $client->testConnection();
    }
}
