<?php

namespace PortalPeople\magento;

use Yii;
use yii\base\BootstrapInterface;
use yii\base\Module as BaseModule;

class Module extends BaseModule implements BootstrapInterface
{
    public $controllerNamespace = 'PortalPeople\\magento\\controllers';

    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 bootstrap($app)
    {
        $this->id = 'magento';
        if (!isset($app->getModules()[$this->id])) {
            $app->setModule($this->id, $this);
        }

        if ($app->has('urlManager') && $app->name !== 'NGaugeApi') {
            $app->urlManager->addRules([
                'magento/config/<action:[\w\-]+>' => 'magento/config/<action>',
                'magento/orders/<action:[\w\-]+>' => 'magento/default/orders',
                'magento/orders' => 'magento/default/orders',
                'magento/<action:[\w\-]+>' => 'magento/default/<action>',
            ], false);
        }
    }

    public function init()
    {
        parent::init();
        $this->loadConfigFromParams();
    }

    public function isConfigured(): bool
    {
        $hasToken = trim((string) $this->accessToken) !== '';
        $hasCredentials = trim((string) $this->adminUsername) !== '' && trim((string) $this->adminPassword) !== '';

        return (bool) $this->enabled
            && trim((string) $this->apiUrl) !== ''
            && ($hasToken || $hasCredentials);
    }

    private function loadConfigFromParams(): void
    {
        $config = Yii::$app->params['plugins']['magento'] ?? [];
        $this->enabled = (bool) ($config['enabled'] ?? $this->enabled);
        $this->apiUrl = (string) ($config['apiUrl'] ?? $this->apiUrl);
        $this->accessToken = (string) ($config['accessToken'] ?? $this->accessToken);
        $this->adminUsername = (string) ($config['adminUsername'] ?? $this->adminUsername);
        $this->adminPassword = (string) ($config['adminPassword'] ?? $this->adminPassword);
        $this->storeCode = (string) ($config['storeCode'] ?? $this->storeCode);
        $this->debug = (bool) ($config['debug'] ?? $this->debug);
        $this->useQueue = (bool) ($config['useQueue'] ?? $this->useQueue);
        $this->timeout = (int) ($config['timeout'] ?? $this->timeout);

        $fields = $config['productSyncFields'] ?? $this->productSyncFields;
        $this->productSyncFields = is_array($fields) ? $fields : array_map('trim', explode(',', (string) $fields));
    }
}
