<?php 
namespace PortalPeople\netsuite;
use Yii;
use yii\base\Module as BaseModule;

/**
 * Netsuite Sync Module
 * 
 * This module provides integration with Netsuite API for product and Order synchronization
 */
class Module extends BaseModule implements \yii\base\BootstrapInterface
{
    public $controllerNamespace = 'PortalPeople\netsuite\controllers';
    
    public function bootstrap($app)
    {
         $this->id = 'netsuite';
        // Register the module if not already registered
        //   Yii::warning($app->getModules()[$this->id], 'Module bootstrap');
        if (!isset($app->getModules()[$this->id])) {
            $app->setModule($this->id, $this);
        }
        
        // Register URL rules
        $app->urlManager->addRules([
            // Specific action routes (most specific first)
            "{$this->id}/<action:[\w\-]+>" => "{$this->id}/config/<action>",
            "{$this->id}/<controller:[\w\-]+>/<action:[\w\-]+>" => "{$this->id}/<controller>/<action>",
            
        ], false); // false = append rules (don't prepend)
        
        // Load NetSuite configuration and merge into Yii::$app->params
        $this->loadNetSuiteConfig();
        
        // 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',
                ];
            }
        }
    }
}