<?php
/**
 * DX Despatch Manager Delivery Module for NGauge/Yii2
 *
 * @category    PortalPeople
 * @package     DX
 * @author      Portal People Development Team
 * @copyright   Copyright (c) 2026 Portal People (https://portalpeople.co.uk)
 */

namespace PortalPeople\dx;

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

/**
 * DX Despatch Manager Delivery Module
 *
 * Provides integration with the DX Despatch Manager REST API for creating,
 * managing and tracking consignments.
 *
 * Configuration (backend/config/params-local.php):
 * ```php
 * 'plugins' => [
 *     'dx' => [
 *         'enabled'     => true,
 *         'apiUrl'      => 'https://despatch-api.dxdelivery.com',
 *         'accountCode' => 'XXXXXXX',
 *         'username'    => 'user@example.com',
 *         'password'    => '<encrypted>',
 *         'debug'       => false,
 *     ],
 * ],
 * ```
 */
class Module extends BaseModule implements \yii\base\BootstrapInterface
{
    /** @var string Yii2 controller namespace. */
    public $controllerNamespace = 'PortalPeople\dx\controllers';

    /** @var string DX REST API base URL. */
    public $apiUrl = 'https://despatch-api.dxdelivery.com';

    /** @var string DX account code. */
    public $accountCode;

    /** @var string DX API username. */
    public $username;

    /** @var string DX API password (decrypted). */
    public $password;

    /** @var bool Enable debug logging. */
    public $debug = false;

    /** @var string URL rule class. */
    public $urlRuleClass = 'yii\web\UrlRule';

    /**
     * Bootstrap: register URL rules.
     * @param \yii\base\Application $app
     */
    public function bootstrap($app)
    {
        $this->id = 'dx';

        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['dx'] = 'dx';
        });
        Yii::$app->on(
            'carts-after-DataLoad-dx', 
            function($event){
                $event->result = \PortalPeople\dx\models\carts\Dx::class;
            }
        );
        
  Event::on(
            \yii\base\View::class,
            'cart-shipping-tab', 
            function($event){
                echo Yii::$app->view->render('@PortalPeople/dx/views/cart/viewtabs/_dx_integration_tab', ['model' => $event->model]);
            }
        );
        
        Yii::$app->on('netsuite.createlabels-DXN001', function($event){
            $model = $event->model;
            $lines = $event->customData;
            // Instantiate the service and execute immediately, returning its result.
            $service = new \PortalPeople\dx\services\NewConsignment();
            $event->result = $service->create($model, $lines);
            return $event;
        });
        self::init();
    }

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

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

            $this->apiUrl      = $config['apiUrl']      ?? $this->apiUrl;
            $this->accountCode = $config['accountCode'] ?? $this->accountCode;
            $this->username    = $config['username']    ?? $this->username;
            $this->password    = Security::decryptSensitiveData($config['password'] ?? '');
            $this->debug       = $config['debug']       ?? $this->debug;
        }

        $this->registerComponents();
    }

    /**
     * Register module-level components.
     */
    protected function registerComponents()
    {
        Yii::$app->setComponents([
            'dxClient' => [
                'class'       => 'PortalPeople\dx\components\DxClient',
                'apiUrl'      => $this->apiUrl,
                'accountCode' => $this->accountCode,
                'username'    => $this->username,
                'password'    => $this->password,
                'debug'       => $this->debug,
            ],
        ]);
    }

    /**
     * Whether the module has the minimum required configuration.
     * @return bool
     */
    public function isConfigured(): bool
    {
        return !empty($this->apiUrl) && !empty($this->accountCode) && !empty($this->username);
    }
}
