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

namespace PortalPeople\magento;

use Yii;
use yii\base\Module as BaseModule;
use yii\base\Event;
use yii\db\ActiveRecord;
use backend\components\Security;
/**
 * Magento Sync Module
 * 
 * This module provides integration with Magento API for product synchronization
 */
class Module extends BaseModule implements \yii\base\BootstrapInterface
{
    


    
    /**
     * @var string the namespace that controller classes are in
     */
    public $controllerNamespace = 'PortalPeople\magento\controllers';

    /**
     * @var string Magento API base URL
     */
    public $apiUrl;

    /**
     * @var string Magento API access token
     */
    public $accessToken;

    /**
     * @var string Magento admin username (optional, for token generation)
     */
    public $adminUsername;

    /**
     * @var string Magento admin password (optional, for token generation)
     */
    public $adminPassword;

    /**
     * @var string Magento store code
     */
    public $storeCode = 'default';

    /**
     * @var bool Enable automatic sync
     */
    public $autoSync = true;

    /**
     * @var array Price fields to sync
     */
    public $priceFields = ['price1', 'price2', 'price3'];

    /**
     * @var bool Enable debug logging
     */
    public $debug = false;
public $urlRuleClass = 'yii\web\UrlRule';
    /**
     * Bootstrap method to add URL rules when the module is loaded.
     * @param \yii\base\Application $app the application currently running
    */
    public function bootstrap($app)
    {
        $this->id = 'magento';
        // 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
        if(Yii::$app->name !== 'NGaugeApi'){
            $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)
        }
        if($app->name == 'NGaugeApi'){
            $app->urlManager->addRules([
                "v2/<controller:orders>/<action:[\w\-]+>" => "{$this->id}/api/orders/<action>",
            
            ]);
        }
        self::init();
    }
    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
    
        // Load configuration from params
        if (isset(Yii::$app->params['plugins']['magento'])) {
            $config = Yii::$app->params['plugins']['magento'];
            
            $this->apiUrl = $config['apiUrl'] ?? $this->apiUrl;
            // Decrypt sensitive authentication fields
            $this->accessToken = Security::decryptSensitiveData($config['accessToken'] ?? '');
            $this->adminUsername = Security::decryptSensitiveData($config['adminUsername'] ?? '');
            $this->adminPassword = Security::decryptSensitiveData($config['adminPassword'] ?? '');
            $this->storeCode = $config['storeCode'] ?? $this->storeCode;
            $this->autoSync = $config['autoSync'] ?? $this->autoSync;
            $this->priceFields = $config['priceFields'] ?? $this->priceFields;
            $this->debug = $config['debug'] ?? $this->debug;
        }

        // Register module components
        $this->registerComponents();

        // Attach event handlers if auto sync is enabled
        if ($this->autoSync) {
            $this->attachEventHandlers();
        }
        Event::on(\modules\custom\models\ProductsData::class, 'products-set-data-types', function($event){
            $event->buttons['magento'] = 'magento';
        });
        Yii::$app->on('products-after-DataLoad-magento', function($event){
           $event->result = \PortalPeople\magento\models\Products::class;
        });
        // Register all view customizations from this module's config directory
        //AdminViewsRegistry::registerModuleViews('magento');
    }

    /**
     * Register module components
     */
    protected function registerComponents()
    {
        Yii::$app->setComponents([
            'magentoClient' => [
                'class' => 'PortalPeople\magento\components\MagentoClient',
                'apiUrl' => $this->apiUrl,
                'accessToken' => $this->accessToken,
                'adminUsername' => $this->adminUsername,
                'adminPassword' => $this->adminPassword,
                'storeCode' => $this->storeCode,
                'debug' => $this->debug,
            ],
            'magentoSync' => [
                'class' => 'PortalPeople\magento\components\ProductSyncComponent',
                'priceFields' => $this->priceFields,
                'debug' => $this->debug,
            ]
        ]);
    }

    /**
     * Attach event handlers for automatic synchronization
     */
    protected function attachEventHandlers()
    {
        // Listen for product price changes
        Event::on(\backend\models\Productsbe::class, 'products-after-Save-Start', function($event){
            \PortalPeople\magento\handlers\ProductEventHandler::handleProductUpdate($event);
        });

        // Listen for product creation
        Event::on(
            \backend\models\Productsbe::class,
            ActiveRecord::EVENT_AFTER_INSERT,
            ['PortalPeople\magento\handlers\ProductEventHandler', 'handleProductCreate']
        );


    }

    /**
     * Get module version
     * 
     * @return string
     */
    public function getVersion()
    {
        return '1.0.0';
    }

    /**
     * Check if module is properly configured
     * 
     * @return bool
     */
    public function isConfigured()
    {
        return !empty($this->apiUrl) && 
               (!empty($this->accessToken) || (!empty($this->adminUsername) && !empty($this->adminPassword)));
    }

    /**
     * Get module configuration
     * 
     * @return array
     */
    public function getConfig()
    {
        return [
            'apiUrl' => $this->apiUrl,
            'accessToken' => $this->accessToken ? '***masked***' : null,
            'adminUsername' => $this->adminUsername,
            'storeCode' => $this->storeCode,
            'autoSync' => $this->autoSync,
            'priceFields' => $this->priceFields,
            'debug' => $this->debug,
            'version' => $this->getVersion(),
            'configured' => $this->isConfigured(),
        ];
    }
}