<?php

namespace PortalPeople\magento\models;

use Yii;
use yii\base\Model;

class ConfigForm extends Model
{
    public $enabled = true;
    public $apiUrl = '';
    public $accessToken = '';
    public $adminUsername = '';
    public $adminPassword = '';
    public $storeCode = 'default';
    public $debug = false;
    public $useQueue = false;
    public $timeout = 30;
    public $productSyncFields = 'price1,price2,price3';

    public function rules(): array
    {
        return [
            [['apiUrl'], 'required'],
            [['apiUrl'], 'url', 'defaultScheme' => 'https', 'skipOnEmpty' => true],
            [['enabled', 'debug', 'useQueue'], 'boolean'],
            [['timeout'], 'integer', 'min' => 5, 'max' => 120],
            [['apiUrl', 'accessToken', 'adminUsername', 'adminPassword', 'storeCode', 'productSyncFields'], 'string'],
        ];
    }

    public function attributeLabels(): array
    {
        return [
            'enabled' => 'Enable Integration',
            'apiUrl' => 'Magento API Base URL',
            'accessToken' => 'Access Token',
            'adminUsername' => 'Admin Username',
            'adminPassword' => 'Admin Password',
            'storeCode' => 'Store Code',
            'debug' => 'Debug Logging',
            'useQueue' => 'Use Queue',
            'timeout' => 'Request Timeout (seconds)',
            'productSyncFields' => 'Product Sync Fields',
        ];
    }

    public function attributeHints(): array
    {
        return [
            'apiUrl' => 'Base Magento URL, e.g. https://your-store.com',
            'accessToken' => 'Magento REST access token (preferred)',
            'adminUsername' => 'Only needed if you prefer token generation from admin credentials',
            'productSyncFields' => 'Comma-separated fields to monitor for product updates',
        ];
    }

    public function loadFromParams(): void
    {
        $config = Yii::$app->params['plugins']['magento'] ?? [];
        $this->enabled = (bool) ($config['enabled'] ?? true);
        $this->apiUrl = (string) ($config['apiUrl'] ?? '');
        $this->accessToken = (string) ($config['accessToken'] ?? '');
        $this->adminUsername = (string) ($config['adminUsername'] ?? '');
        $this->adminPassword = (string) ($config['adminPassword'] ?? '');
        $this->storeCode = (string) ($config['storeCode'] ?? 'default');
        $this->debug = (bool) ($config['debug'] ?? false);
        $this->useQueue = (bool) ($config['useQueue'] ?? false);
        $this->timeout = (int) ($config['timeout'] ?? 30);
        $this->productSyncFields = is_array($config['productSyncFields'] ?? null)
            ? implode(',', $config['productSyncFields'])
            : (string) ($config['productSyncFields'] ?? 'price1,price2,price3');
    }

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

        $params = require $paramsFile;
        $params['plugins']['magento'] = [
            'enabled' => (bool) $this->enabled,
            'apiUrl' => (string) $this->apiUrl,
            'accessToken' => (string) $this->accessToken,
            'adminUsername' => (string) $this->adminUsername,
            'adminPassword' => (string) $this->adminPassword,
            'storeCode' => (string) $this->storeCode,
            'debug' => (bool) $this->debug,
            'useQueue' => (bool) $this->useQueue,
            'timeout' => (int) $this->timeout,
            'productSyncFields' => array_values(array_filter(array_map('trim', explode(',', $this->productSyncFields))))
        ];

        $content = "<?php\nreturn " . var_export($params, true) . ";\n";
        return file_put_contents($paramsFile, $content) !== false;
    }
}
