<?php

namespace PortalPeople\shippingcosts;

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

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

    public $enabled = true;
    public $maxShippingCost = 1000.00;
    public $defaultHaulierId;
    public $debug = false;
    public $parameters = [];

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

        $this->loadConfigFromParams();

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

        if ($app->has('urlManager')) {
            $app->urlManager->addRules([
                "{$this->id}/<action:(config|setup)>" => "{$this->id}/config/<action>",
                "shippingcosts" => "{$this->id}/shippingcosts/index",
                "shippingcosts/<action:[\w-]+>" => "{$this->id}/shippingcosts/<action>",
                "ship-setting" => "{$this->id}/ship-setting/index",
                "ship-setting/<action:[\w-]+>" => "{$this->id}/ship-setting/<action>",
            ], false);
        }
    }

    public function getConfig(): array
    {
        return [
            'enabled' => (bool) $this->enabled,
            'maxShippingCost' => (float) $this->maxShippingCost,
            'defaultHaulierId' => $this->defaultHaulierId,
            'debug' => (bool) $this->debug,
            'parameters' => is_array($this->parameters) ? $this->parameters : [],
        ];
    }

    public function isConfigured(): bool
    {
        return $this->enabled;
    }

    private function loadConfigFromParams(): void
    {
        if (!isset(Yii::$app->params['plugins']['shippingcosts'])) {
            return;
        }

        $config = Yii::$app->params['plugins']['shippingcosts'];
        $this->enabled = (bool) ($config['enabled'] ?? $this->enabled);
        $this->maxShippingCost = (float) ($config['maxShippingCost'] ?? $this->maxShippingCost);
        $this->defaultHaulierId = $config['defaultHaulierId'] ?? $this->defaultHaulierId;
        $this->debug = (bool) ($config['debug'] ?? $this->debug);
        $this->parameters = is_array($config['parameters'] ?? null) ? $config['parameters'] : $this->parameters;
    }
}
