<?php

namespace PortalPeople\magento;

use Yii;
use yii\base\BootstrapInterface;
use yii\base\Module as BaseModule;
use yii\base\Event;
use yii\console\Application as ConsoleApplication;
use PortalPeople\magento\services\MonitoringService;

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'];
    /**
     * @var bool Enable automatic sync
     */
    public $autoSync = true;

    /**
     * @var array Price fields to sync
     */
    public $priceFields = ['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/new-orders' => 'magento/default/new-orders',
                'magento/orders/<action:[\w\-]+>' => 'magento/default/orders',
                'magento/orders' => 'magento/default/orders',
                'magento/carts/index' => 'magento/orders/index',
                'magento/carts' => 'magento/carts/index',
                'magento/carts/<action:[\w\-]+>' => 'magento/carts/<action>',
                'magento/<action:[\w\-]+>' => 'magento/carts/<action>',
            ], false);
        }
        
        // Register module components
        $this->registerComponents();
        Event::on(\modules\custom\models\ProductsData::class, 'products-set-data-types', function($event) {
            $event->buttons['magento'] = 'magento';
        });
        Yii::$app->on('products-after-DataLoad-magento', function($event) {
           $event->result = \PortalPeople\magento\models\products\Magento::class;
        });
        
        Event::on(\backend\models\CartsData::class, 'carts-set-data-types', function($event) {
            $event->customData['magento'] = 'magento';
        });
        Yii::$app->on('cart-order-sendtonetsuite-GAR001', function ($event) {
            \PortalPeople\netsuite\components\NetSuite::SendOrderToNetsuite($event->model->id);
        });
        Yii::$app->on(
            'carts-after-DataLoad-magento', 
            function($event) {
                $event->result = \PortalPeople\magento\models\carts\Magento::class;
            }
        );
        
        Yii::$app->on(
            'cart-index-orderref', 
            function($event) {
                $data = json_decode($event->customData ?? null, false);
                Yii::warning($data, 'magento');
                $event->result .= property_exists($data, 'magento') && !is_string($data->magento) && !empty($data->magento->orderId) ? 'MG: '.$data->magento->orderId . '<br />' : ''; 
            }
        );

    }
    /**
     * Register module components
     */
    protected function registerComponents()
    {
        Yii::$app->setComponents([
            'magentoClient' => [
                'class' => 'PortalPeople\magento\components\MagentoClient',
                'apiUrl' => $this->apiUrl,
                'accessToken' => $this->accessToken,
                'adminUsername' => $this->adminUsername,
                'adminPassword' => $this->adminPassword,
                'storeCode' => $this->storeCode,
                'debug' => $this->debug,
            ],
            'magentoSync' => [
                'class' => 'PortalPeople\magento\components\ProductSyncComponent',
                'priceFields' => $this->priceFields,
                'debug' => $this->debug,
            ]
        ]);
    }

    public function init()
    {
        parent::init();
        
        if (Yii::$app instanceof ConsoleApplication) {
            $this->controllerNamespace = 'PortalPeople\\magento\\commands';
        }
        $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);
    }

    public function getMonitoringConfig(): array
    {
        return (new MonitoringService())->getMonitoringConfig($this);
    }

    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));
    }
}
