<?php 
namespace modules\netsuite;
use yii;
use backend\components\AdminViewsRegistry;

class Module extends \yii\base\Module
{
    public $controllerNamespace = 'modules\netsuite\controllers';
    
    public function init()
    {
        parent::init();
        
        // Load NetSuite configuration and merge into Yii::$app->params
        $this->loadNetSuiteConfig();
        
        // Register URL rules for settings
        Yii::$app->Urlmanager->addRules([
            '<controller:netsuite-settings>' => 'netsuite/<controller>/index',
            '<controller:netsuite-settings>/<action:[\w\-]+>' => 'netsuite/<controller>/<action>',
        ]);
        
        // Register all view customizations from this module's config directory
        AdminViewsRegistry::registerModuleViews('netsuite');
    }
    
    /**
     * Load NetSuite configuration from ns.php and merge into application params
     */
    protected function loadNetSuiteConfig()
    {
        $configFile = __DIR__ . '/config/ns.php';
        
        if (file_exists($configFile)) {
            try {
                $netsuiteConfig = require $configFile;
                
                if (is_array($netsuiteConfig)) {
                    // Merge into application params
                    Yii::$app->params['netsuite'] = array_merge(
                        Yii::$app->params['netsuite'] ?? [],
                        $netsuiteConfig
                    );
                    
                    if (YII_DEBUG) {
                        Yii::info('NetSuite configuration loaded from ns.php', __CLASS__);
                    }
                }
            } catch (\Exception $e) {
                Yii::error("Failed to load NetSuite config: " . $e->getMessage(), __CLASS__);
            }
        } else {
            // Initialize with default empty config
            if (!isset(Yii::$app->params['netsuite'])) {
                Yii::$app->params['netsuite'] = [
                    'enabled' => false,
                    'account_id' => '',
                    'consumer_key' => '',
                    'consumer_secret' => '',
                    'token_id' => '',
                    'token_secret' => '',
                    'environment' => 'production',
                ];
            }
        }
    }
}