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

namespace PortalPeople\magento\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\AccessControl;
use yii\helpers\Json;
use PortalPeople\magento\components\FieldMapper;

/**
 * Field Mapping Controller
 * 
 * Handles field mapping management for Magento integration
 */
class MappingController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'], // Require authentication
                    ],
                ],
            ],
        ];
    }

    /**
     * Display field mapping interface
     * 
     * @return string
     */
    public function actionIndex()
    {
        $fieldMapper = new FieldMapper();
        
        $ngaugeFields = $fieldMapper->getCategorizedNGaugeFields();
        $magentoFields = $fieldMapper->getCategorizedMagentoFields();
        $suggestions = $fieldMapper->getSuggestedMappings();
        
        // Load existing mapping from config
        $config = Yii::$app->params['plugins']['magento'] ?? [];
        $currentMapping = $config['field_mapping'] ?? [];
        
        return $this->render('index', [
            'ngaugeFields' => $ngaugeFields,
            'magentoFields' => $magentoFields,
            'suggestions' => $suggestions,
            'currentMapping' => $currentMapping
        ]);
    }

    /**
     * Test action to verify controller access
     * 
     * @return string
     */
    public function actionTest()
    {
        return "Magento Mapping Controller is accessible! Time: " . date('Y-m-d H:i:s');
    }

    /**
     * Get field data via AJAX
     * 
     * @return Response
     */
    public function actionGetFields()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        
        $fieldMapper = new FieldMapper();
        
        $type = Yii::$app->request->get('type', 'both');
        
        $data = [];
        
        if ($type === 'ngauge' || $type === 'both') {
            $data['ngauge'] = $fieldMapper->getCategorizedNGaugeFields();
        }
        
        if ($type === 'magento' || $type === 'both') {
            $data['magento'] = $fieldMapper->getCategorizedMagentoFields();
        }
        
        return $data;
    }

    /**
     * Get mapping suggestions via AJAX
     * 
     * @return Response
     */
    public function actionGetSuggestions()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        
        $fieldMapper = new FieldMapper();
        $suggestions = $fieldMapper->getSuggestedMappings();
        
        return [
            'success' => true,
            'suggestions' => $suggestions
        ];
    }

    /**
     * Validate field mapping via AJAX
     * 
     * @return Response
     */
    public function actionValidateMapping()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        
        $mapping = Yii::$app->request->post('mapping', []);
        
        $fieldMapper = new FieldMapper();
        $validation = $fieldMapper->validateMapping($mapping);
        
        return [
            'success' => true,
            'validation' => $validation
        ];
    }

    /**
     * Save field mapping
     * 
     * @return Response
     */
    public function actionSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        
        $mapping = Yii::$app->request->post('mapping', []);
        
        try {
            // Validate mapping first
            $fieldMapper = new FieldMapper();
            $validation = $fieldMapper->validateMapping($mapping);
            
            if (!$validation['valid']) {
                return [
                    'success' => false,
                    'message' => 'Mapping validation failed',
                    'errors' => $validation['errors']
                ];
            }
            
            // Load current config
            $configFile = Yii::getAlias('@backend/config/params-local.php');
            $config = file_exists($configFile) ? require($configFile) : [];
            
            // Ensure magento config structure exists
            if (!isset($config['plugins'])) {
                $config['plugins'] = [];
            }
            if (!isset($config['plugins']['magento'])) {
                $config['plugins']['magento'] = [];
            }
            
            // Update field mapping
            $config['plugins']['magento']['field_mapping'] = $mapping;
            
            // Save config
            $configContent = "<?php\n\nreturn " . var_export($config, true) . ";\n";
            
            if (file_put_contents($configFile, $configContent) === false) {
                return [
                    'success' => false,
                    'message' => 'Failed to save configuration file'
                ];
            }
            
            // Update runtime params
            Yii::$app->params['plugins']['magento']['field_mapping'] = $mapping;
            
            return [
                'success' => true,
                'message' => 'Field mapping saved successfully',
                'validation' => $validation
            ];
            
        } catch (\Exception $e) {
            Yii::error('Failed to save field mapping: ' . $e->getMessage());
            
            return [
                'success' => false,
                'message' => 'An error occurred while saving: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Reset field mapping to suggestions
     * 
     * @return Response
     */
    public function actionResetToSuggestions()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        
        try {
            $fieldMapper = new FieldMapper();
            $suggestions = $fieldMapper->getSuggestedMappings();
            
            // Convert suggestions to mapping format
            $mapping = [];
            foreach ($suggestions as $ngaugeField => $suggestion) {
                if ($suggestion['confidence'] >= 70) { // Only include high-confidence suggestions
                    $mapping[$ngaugeField] = $suggestion['magento_field'];
                }
            }
            
            // Save the mapping
            $configFile = Yii::getAlias('@backend/config/params-local.php');
            $config = file_exists($configFile) ? require($configFile) : [];
            
            if (!isset($config['plugins'])) {
                $config['plugins'] = [];
            }
            if (!isset($config['plugins']['magento'])) {
                $config['plugins']['magento'] = [];
            }
            
            $config['plugins']['magento']['field_mapping'] = $mapping;
            
            $configContent = "<?php\n\nreturn " . var_export($config, true) . ";\n";
            
            if (file_put_contents($configFile, $configContent) === false) {
                return [
                    'success' => false,
                    'message' => 'Failed to save configuration file'
                ];
            }
            
            // Update runtime params
            Yii::$app->params['plugins']['magento']['field_mapping'] = $mapping;
            
            return [
                'success' => true,
                'message' => 'Field mapping reset to suggestions',
                'mapping' => $mapping
            ];
            
        } catch (\Exception $e) {
            Yii::error('Failed to reset field mapping: ' . $e->getMessage());
            
            return [
                'success' => false,
                'message' => 'An error occurred: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Export field mapping configuration
     * 
     * @return Response
     */
    public function actionExport()
    {
        $config = Yii::$app->params['plugins']['magento'] ?? [];
        $mapping = $config['field_mapping'] ?? [];
        
        $fieldMapper = new FieldMapper();
        $ngaugeFields = $fieldMapper->getNGaugeFields();
        $magentoFields = $fieldMapper->getMagentoFields();
        
        // Create detailed export
        $export = [
            'exported_at' => date('Y-m-d H:i:s'),
            'mapping_count' => count($mapping),
            'mappings' => []
        ];
        
        foreach ($mapping as $ngaugeField => $magentoField) {
            $export['mappings'][] = [
                'ngauge_field' => $ngaugeField,
                'ngauge_label' => $ngaugeFields[$ngaugeField]['label'] ?? $ngaugeField,
                'magento_field' => $magentoField,
                'magento_label' => $magentoFields[$magentoField]['label'] ?? $magentoField
            ];
        }
        
        // Set response headers for download
        Yii::$app->response->format = Response::FORMAT_RAW;
        Yii::$app->response->headers->add('Content-Type', 'application/json');
        Yii::$app->response->headers->add('Content-Disposition', 'attachment; filename="magento-field-mapping-' . date('Y-m-d') . '.json"');
        
        return Json::encode($export, JSON_PRETTY_PRINT);
    }
}