<?php

namespace PortalPeople\palletline\models;

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

class ConfigForm extends Model
{
    public $enabled = false;

    public $apiUrl = 'https://pl570.tms.live/api/v1';

    public $username;

    public $password;

    public $networkAccount = '';

    public $collectionContactName = '';

    public $collectionCompanyName = '';

    public $collectionLine = '';

    public $collectionLine2 = '';

    public $collectionTown = '';

    public $collectionCounty = '';

    public $collectionPostcode = '';

    public $collectionCountry = 'GB';

    public $collectionTelephone = '';

    public $collectionEmail = '';

    public $autoConfirm = false;

    public $timeout = 30;

    public $debug = false;

    public function rules(): array
    {
        return [
            [[
                'apiUrl',
                'username',
                'password',
                'collectionCompanyName',
                'collectionLine',
                'collectionTown',
                'collectionCounty',
                'collectionPostcode',
            ], 'required'],
            [['apiUrl'], 'url', 'defaultScheme' => 'https'],
            [[
                'username',
                'password',
                'networkAccount',
                'collectionContactName',
                'collectionCompanyName',
                'collectionLine',
                'collectionLine2',
                'collectionTown',
                'collectionCounty',
                'collectionTelephone',
                'collectionEmail',
            ], 'string'],
            [['collectionEmail'], 'email'],
            [['collectionCountry'], 'string', 'length' => 2],
            [['collectionPostcode'], 'string', 'max' => 10],
            [['collectionPostcode'], 'trim'],
            [['timeout'], 'integer', 'min' => 5, 'max' => 120],
            [['enabled', 'autoConfirm', 'debug'], 'boolean'],
        ];
    }

    public function attributeLabels(): array
    {
        return [
            'enabled' => 'Enable Integration',
            'apiUrl' => 'API Base URL',
            'username' => 'Username',
            'password' => 'Password',
            'networkAccount' => 'Network Account',
            'collectionContactName' => 'Collection Contact Name',
            'collectionCompanyName' => 'Collection Company Name',
            'collectionLine' => 'Collection Address Line 1',
            'collectionLine2' => 'Collection Address Line 2',
            'collectionTown' => 'Collection Town',
            'collectionCounty' => 'Collection County',
            'collectionPostcode' => 'Collection Postcode',
            'collectionCountry' => 'Collection Country (ISO Code)',
            'collectionTelephone' => 'Collection Telephone',
            'collectionEmail' => 'Collection Email',
            'autoConfirm' => 'Auto-Confirm Consignments',
            'timeout' => 'Request Timeout (seconds)',
            'debug' => 'Enable Debug Logging',
        ];
    }

    public function loadFromParams(): void
    {
        $config = Yii::$app->params['plugins']['palletline'] ?? [];

        $this->enabled = (bool) ($config['enabled'] ?? false);
        $this->apiUrl = $config['apiUrl'] ?? $this->apiUrl;
        $this->username = Security::decryptSensitiveData($config['username'] ?? '');
        $this->password = Security::decryptSensitiveData($config['password'] ?? '');
        $this->networkAccount = (string) ($config['networkAccount'] ?? '');
        $this->collectionContactName = (string) ($config['collectionContactName'] ?? '');
        $this->collectionCompanyName = (string) ($config['collectionCompanyName'] ?? '');
        $this->collectionLine = (string) ($config['collectionLine'] ?? '');
        $this->collectionLine2 = (string) ($config['collectionLine2'] ?? '');
        $this->collectionTown = (string) ($config['collectionTown'] ?? '');
        $this->collectionCounty = (string) ($config['collectionCounty'] ?? '');
        $this->collectionPostcode = (string) ($config['collectionPostcode'] ?? '');
        $this->collectionCountry = (string) ($config['collectionCountry'] ?? 'GB');
        $this->collectionTelephone = (string) ($config['collectionTelephone'] ?? '');
        $this->collectionEmail = Security::decryptSensitiveData($config['collectionEmail'] ?? '');
        $this->autoConfirm = (bool) ($config['autoConfirm'] ?? false);
        $this->timeout = (int) ($config['timeout'] ?? 30);
        $this->debug = (bool) ($config['debug'] ?? false);
    }

    public function saveToParams(): bool
    {
        $paramsFile = Yii::getAlias('@backend/config/params-local.php');
        if (!file_exists($paramsFile)) {
            Yii::error('params-local.php not found: ' . $paramsFile, 'palletline');
            return false;
        }

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

        $params['plugins']['palletline'] = [
            'enabled' => $this->enabled,
            'apiUrl' => $this->apiUrl,
            'username' => Security::encryptSensitiveData($this->username),
            'password' => Security::encryptSensitiveData($this->password),
            'networkAccount' => $this->networkAccount,
            'collectionContactName' => $this->collectionContactName,
            'collectionCompanyName' => $this->collectionCompanyName,
            'collectionLine' => $this->collectionLine,
            'collectionLine2' => $this->collectionLine2,
            'collectionTown' => $this->collectionTown,
            'collectionCounty' => $this->collectionCounty,
            'collectionPostcode' => strtoupper($this->collectionPostcode ?: ''),
            'collectionCountry' => strtoupper($this->collectionCountry ?: 'GB'),
            'collectionTelephone' => $this->collectionTelephone,
            'collectionEmail' => Security::encryptSensitiveData($this->collectionEmail),
            'autoConfirm' => $this->autoConfirm,
            'timeout' => (int) $this->timeout,
            'debug' => $this->debug,
        ];

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

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

    public function testConnection(): array
    {
        if (!$this->validate()) {
            return ['success' => false, 'message' => 'Validation failed: ' . implode(', ', $this->getFirstErrors())];
        }

        $client = new \PortalPeople\palletline\components\PalletlineClient([
            'apiUrl' => $this->apiUrl,
            'username' => $this->username,
            'password' => $this->password,
            'networkAccount' => $this->networkAccount,
            'autoConfirm' => $this->autoConfirm,
            'timeout' => (int) $this->timeout,
            'debug' => $this->debug,
        ]);

        return $client->testConnection();
    }
}
