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

namespace PortalPeople\palletforce;

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

/**
 * Palletforce Delivery Module
 *
 * Provides integration with the Palletforce Alliance REST API for creating,
 * managing and tracking pallet consignments.
 *
 * Configuration (backend/config/params-local.php):
 * ```php
 * 'plugins' => [
 *     'palletforce' => [
 *         'enabled'        => true,
 *         'apiUrl'         => 'https://api.palletforce.com',
 *         'accessKey'      => '<encrypted>',
 *         'accountNumber'  => 'XXXXXXX',
 *         'depotCode'      => '000',
 *         'fuelSurcharge' => 0.0,
 *         'discount'      => 0.0,
 *         'debug'          => false,
 *     ],
 * ],
 * ```
 */
class Module extends BaseModule implements \yii\base\BootstrapInterface
{
    /** @var string Yii2 controller namespace. */
    public $controllerNamespace = 'PortalPeople\palletforce\controllers';

    /** @var string Palletforce REST API base URL (provided by Palletforce after testing sign-off). */
    public $apiUrl;

    /** @var string Unique API access key supplied by Palletforce. */
    public $accessKey;

    /** @var string Customer account number issued by Palletforce. */
    public $accountNumber;

    /** @var string Your assigned requesting depot code (3 chars). */
    public $depotCode;

    /** @var float Fuel surcharge rate as a decimal fraction. */
    public $fuelSurcharge = 0.0;

    /** @var float Discount rate as a decimal fraction. */
    public $discount = 0.0;

    /** @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 = 'palletforce';

        if ($app instanceof \yii\console\Application) {
            $this->controllerNamespace = 'PortalPeople\\palletforce\\commands';
            $app->setModule($this->id, $this);
            return;
        }

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

        self::init();
    }

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

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

            $this->apiUrl        = $config['apiUrl']        ?? $this->apiUrl;
            $this->accessKey     = Security::decryptSensitiveData($config['accessKey'] ?? '');
            $this->accountNumber = $config['accountNumber'] ?? $this->accountNumber;
            $this->depotCode     = $config['depotCode']     ?? $this->depotCode;
            $this->fuelSurcharge = (float) ($config['fuelSurcharge'] ?? $this->fuelSurcharge);
            $this->discount      = (float) ($config['discount'] ?? $this->discount);
            $this->debug         = $config['debug']         ?? $this->debug;
        }
        Yii::$app->on('netsuite.createlabels-PAL001', function ($event) {
            $model = $event->model;
            // Instantiate the service and execute immediately, returning its result.
            $service = new \PortalPeople\palletforce\services\NewConsignment();
            $event->result = $service->create($model);
            return $event;
        });

        $this->registerComponents();
    }

    /**
     * Register module-level components.
     */
    protected function registerComponents()
    {
        Yii::$app->setComponents([
            'palletforceClient' => [
                'class'         => 'PortalPeople\palletforce\components\PalletforceClient',
                'apiUrl'        => $this->apiUrl,
                'accessKey'     => $this->accessKey,
                'accountNumber' => $this->accountNumber,
                'depotCode'     => $this->depotCode,
                'fuelSurcharge' => $this->fuelSurcharge,
                'discount'      => $this->discount,
                'debug'         => $this->debug,
            ],
        ]);
    }

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