<?php

/**
 * Palletline Delivery Module for NGauge/Yii2
 *
 * @category    PortalPeople
 * @package     Palletline
 */

namespace PortalPeople\palletline;

use Yii;
use yii\base\Event;
use yii\base\Module as BaseModule;
use yii\web\View;
use backend\components\Security;

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

    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 $fuelSurcharge = 0.0;

    public $discount = 0.0;

    public $timeout = 30;

    public $debug = false;

    public $urlRuleClass = 'yii\web\UrlRule';

    public function bootstrap($app)
    {
        $this->id = 'palletline';

        if (!isset($app->getModules()[$this->id])) {
            $app->setModule($this->id, $this);
        }

        if (Yii::$app->name !== 'NGaugeApi') {
            $app->urlManager->addRules([
                "{$this->id}/<action:[\w\-]+>" => "{$this->id}/config/<action>",
                "{$this->id}/<controller:[\w\-]+>/<action:[\w\-]+>" => "{$this->id}/<controller>/<action>",
            ], false);
        }

        Event::on(\backend\models\CartsData::class, 'carts-set-data-types', function ($event) {
            $event->customData['palletline'] = 'palletline';
        });

        $app->on('carts-after-DataLoad-palletline', function ($event) {
            $event->result = \PortalPeople\palletline\models\carts\Palletline::class;
        });

        Event::on(View::class, 'cart-shipping-tab', function ($event) use ($app) {
            echo $app->view->render(
                '@PortalPeople/palletline/views/cart/viewtabs/_palletline_integration_tab',
                ['model' => $event->model]
            );
        });
        Yii::$app->on('netsuite.createlabels-PAL002', function ($event) {
            $model = $event->model;
            // Instantiate the service and execute immediately, returning its result.
            $service = new \PortalPeople\palletline\services\NewConsignment();
            $event->result = $service->create($model);
            return $event;
        });

        self::init();
    }

    public function init()
    {
        parent::init();

        if (isset(Yii::$app->params['plugins']['palletline'])) {
            $config = Yii::$app->params['plugins']['palletline'];

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

        $this->registerComponents();
    }

    protected function registerComponents()
    {
        Yii::$app->setComponents([
            'palletlineClient' => [
                'class' => 'PortalPeople\\palletline\\components\\PalletlineClient',
                'apiUrl' => $this->apiUrl,
                'username' => $this->username,
                'password' => $this->password,
                'networkAccount' => $this->networkAccount,
                'autoConfirm' => $this->autoConfirm,
                'fuelSurcharge' => $this->fuelSurcharge,
                'discount' => $this->discount,
                'timeout' => $this->timeout,
                'debug' => $this->debug,
            ],
        ]);
    }

    public function isConfigured(): bool
    {
        return !empty($this->apiUrl) && !empty($this->username) && !empty($this->password);
    }
}
