<?php
/**
 * Configuration Controller for Magento Module
 *
 * @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\VerbFilter;
use yii\filters\AccessControl;
use yii\widgets\ActiveForm;
use PortalPeople\magento\models\ConfigForm;

/**
 * Configuration Controller
 * 
 * Handles Magento module configuration through web interface
 */
class ConfigController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'], // Only authenticated users
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'test-connection' => ['POST'],
                    'save' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Display configuration form
     * 
     * @return string
     */
    public function actionIndex()
    {
        $model = new ConfigForm();
        $model->loadFromParams();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->saveToParams()) {
                Yii::$app->session->setFlash('success', 'Magento configuration saved successfully!');
                return $this->refresh();
            } else {
                Yii::$app->session->setFlash('error', 'Failed to save configuration. Please check file permissions.');
            }
        }

        return $this->render('index', [
            'model' => $model,
        ]);
    }

    /**
     * Get Magento client instance
     * 
     * @return \PortalPeople\magento\components\MagentoClient
     * @throws \Exception
     */
    protected function getMagentoClient()
    {
        $config = Yii::$app->params['plugins']['magento'] ?? [];

        if (empty($config) || !($config['enabled'] ?? false)) {
            throw new \Exception('Magento module is not configured or enabled');
        }

        // Filter out configuration properties that aren't MagentoClient properties
        $clientConfig = array_intersect_key($config, array_flip([
            'apiUrl', 'accessToken', 'adminUsername', 'adminPassword', 
            'storeCode', 'timeout', 'debug'
        ]));

        return new \PortalPeople\magento\components\MagentoClient($clientConfig);
    }

    /**
     * Get available Magento product fields
     * 
     * @return Response
     */
    public function actionGetFields()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        try {
            $client = $this->getMagentoClient();
            $fields = $client->getCategorizedProductFields();
            
            return [
                'success' => true,
                'fields' => $fields
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * Test Magento API connection
     * 
     * @return Response
     */
    public function actionTestConnection()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $model = new ConfigForm();
        
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $result = $model->testConnection();
            
            return [
                'success' => $result['success'],
                'message' => $result['message'],
                'details' => $result['details'] ?? null
            ];
        }

        return [
            'success' => false,
            'message' => 'Invalid configuration data',
            'errors' => $model->errors
        ];
    }

    /**
     * Get current sync status
     * 
     * @return Response
     */
    public function actionStatus()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        try {
            $syncComponent = Yii::$app->magentoSync;
            $stats = $syncComponent ? $syncComponent->getStats() : [];

            return [
                'success' => true,
                'stats' => $stats,
                'module_configured' => Yii::$app->getModule('magento')->isConfigured()
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Error getting sync status: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Manual sync trigger
     * 
     * @return Response
     */
    public function actionSync()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        try {
            $syncComponent = Yii::$app->magentoSync;
            
            if (!$syncComponent) {
                return [
                    'success' => false,
                    'message' => 'Sync component not configured'
                ];
            }

            // Test connection first
            if (!$syncComponent->testConnection()) {
                return [
                    'success' => false,
                    'message' => 'Cannot connect to Magento API'
                ];
            }

            // Trigger a test sync (this would typically sync recent products)
            $results = ['success' => 1, 'failed' => 0]; // Placeholder
            
            return [
                'success' => true,
                'message' => 'Manual sync completed successfully',
                'results' => $results
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Sync error: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Export current configuration
     * 
     * @return Response
     */
    public function actionExport()
    {
        $model = new ConfigForm();
        $model->loadFromParams();

        $config = $model->toArray();
        
        // Remove sensitive data for export
        unset($config['adminPassword']);

        Yii::$app->response->format = Response::FORMAT_JSON;
        Yii::$app->response->headers->set('Content-Disposition', 'attachment; filename="magento-config.json"');

        return $config;
    }

    /**
     * Reset configuration to defaults
     * 
     * @return Response
     */
    public function actionReset()
    {
        try {
            $model = new ConfigForm();
            
            if ($model->resetToDefaults()) {
                Yii::$app->session->setFlash('success', 'Configuration reset to defaults successfully!');
            } else {
                Yii::$app->session->setFlash('error', 'Failed to reset configuration.');
            }

        } catch (\Exception $e) {
            Yii::$app->session->setFlash('error', 'Error resetting configuration: ' . $e->getMessage());
        }

        return $this->redirect(['index']);
    }
}