<?php
/**
 * Configuration Form Model 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\models;

use Yii;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use PortalPeople\magento\components\MagentoClient;

/**
 * Configuration Form Model
 * 
 * Handles Magento module configuration form data and persistence
 */
class ConfigForm extends Model
{
    /**
     * @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 string Price fields to sync (comma-separated)
     */
    public $priceFields = 'price1,price2,price3';

    /**
     * @var bool Enable debug logging
     */
    public $debug = false;

    /**
     * @var bool Use queue for async processing
     */
    public $useQueue = true;

    /**
     * @var int Request timeout in seconds
     */
    public $timeout = 30;

    /**
     * @var string Authentication method (token|credentials)
     */
    public $authMethod = 'token';

    /**
     * @var string Field mapping JSON
     */
    public $fieldMapping;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['apiUrl'], 'required'],
            [['accessToken'], 'required', 'when' => function($model) {
                return $model->authMethod === 'token';
            }, 'whenClient' => "function (attribute, value) {
                return $('#configform-authmethod').val() === 'token';
            }"],
            [['adminUsername', 'adminPassword'], 'required', 'when' => function($model) {
                return $model->authMethod === 'credentials';
            }, 'whenClient' => "function (attribute, value) {
                return $('#configform-authmethod').val() === 'credentials';
            }"],
            [['apiUrl'], 'url'],
            [['apiUrl', 'accessToken', 'adminUsername', 'adminPassword', 'storeCode', 'priceFields', 'fieldMapping', 'authMethod'], 'string'],
            [['apiUrl'], 'string', 'max' => 255],
            [['accessToken'], 'string', 'max' => 500],
            [['adminUsername', 'adminPassword'], 'string', 'max' => 100],
            [['storeCode'], 'string', 'max' => 50],
            [['priceFields'], 'string', 'max' => 500],
            [['autoSync', 'debug', 'useQueue'], 'boolean'],
            [['timeout'], 'integer', 'min' => 5, 'max' => 300],
            [['authMethod'], 'in', 'range' => ['token', 'credentials']],
            [['fieldMapping'], 'validateFieldMapping'],
            [['apiUrl'], 'validateApiUrl'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'apiUrl' => 'Magento API URL',
            'accessToken' => 'API Access Token',
            'authMethod' => 'Authentication Method',
            'adminUsername' => 'Admin Username',
            'adminPassword' => 'Admin Password',
            'storeCode' => 'Store Code',
            'autoSync' => 'Enable Auto Sync',
            'priceFields' => 'Price Fields to Sync',
            'debug' => 'Enable Debug Logging',
            'useQueue' => 'Use Queue for Async Processing',
            'timeout' => 'Request Timeout (seconds)',
            'fieldMapping' => 'Field Mapping (JSON)',
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeHints()
    {
        return [
            'apiUrl' => 'Full URL to your Magento installation (e.g., https://yourstore.com)',
            'accessToken' => 'Magento API access token (recommended for security)',
            'authMethod' => 'Choose between using an access token or admin credentials',
            'adminUsername' => 'Magento admin user with API access (only needed for credentials method)',
            'adminPassword' => 'Password for the admin user (only needed for credentials method)',
            'storeCode' => 'Magento store view code (default: "default")',
            'priceFields' => 'Comma-separated list of price fields to monitor (e.g., price1,price2,price3)',
            'fieldMapping' => 'JSON mapping of local fields to Magento fields (optional)',
            'timeout' => 'HTTP request timeout in seconds',
        ];
    }

    /**
     * Validate API URL format
     * 
     * @param string $attribute
     * @param array $params
     */
    public function validateApiUrl($attribute, $params)
    {
        if (!empty($this->$attribute)) {
            $url = rtrim($this->$attribute, '/');
            
            // Check if URL is reachable (basic check)
            if (!filter_var($url, FILTER_VALIDATE_URL)) {
                $this->addError($attribute, 'Please enter a valid URL');
                return;
            }

            // Ensure it's HTTPS for security
            if (strpos($url, 'https://') !== 0) {
                $this->addError($attribute, 'HTTPS is recommended for API security');
            }
        }
    }

    /**
     * Validate field mapping JSON
     * 
     * @param string $attribute
     * @param array $params
     */
    public function validateFieldMapping($attribute, $params)
    {
        if (!empty($this->$attribute)) {
            $decoded = json_decode($this->$attribute, true);
            
            if (json_last_error() !== JSON_ERROR_NONE) {
                $this->addError($attribute, 'Invalid JSON format: ' . json_last_error_msg());
            }
        }
    }

    /**
     * Load configuration from params file
     * 
     * @return bool
     */
    public function loadFromParams()
    {
        $params = Yii::$app->params;
        
        if (isset($params['plugins']['magento'])) {
            $config = $params['plugins']['magento'];
            
            $this->apiUrl = $config['apiUrl'] ?? '';
            $this->accessToken = $config['accessToken'] ?? '';
            $this->authMethod = $config['authMethod'] ?? 'token';
            $this->adminUsername = $config['adminUsername'] ?? '';
            $this->adminPassword = $config['adminPassword'] ?? '';
            $this->storeCode = $config['storeCode'] ?? 'default';
            $this->autoSync = $config['autoSync'] ?? true;
            $this->debug = $config['debug'] ?? false;
            $this->useQueue = $config['useQueue'] ?? true;
            $this->timeout = $config['timeout'] ?? 30;
            
            // Convert array to comma-separated string
            if (isset($config['priceFields']) && is_array($config['priceFields'])) {
                $this->priceFields = implode(',', $config['priceFields']);
            } else {
                $this->priceFields = $config['priceFields'] ?? 'price1,price2,price3';
            }
            
            // Convert field mapping to JSON
            if (isset($config['fieldMapping']) && is_array($config['fieldMapping'])) {
                $this->fieldMapping = json_encode($config['fieldMapping'], JSON_PRETTY_PRINT);
            } else {
                $this->fieldMapping = $config['fieldMapping'] ?? '';
            }
            
            return true;
        }
        
        return false;
    }

    /**
     * Save configuration to params file
     * 
     * @return bool
     */
    public function saveToParams()
    {
        try {
            $paramsFile = Yii::getAlias('@backend/config/params-local.php');
            
            // Load existing params
            $params = [];
            if (file_exists($paramsFile)) {
                $params = include $paramsFile;
            }

            // Initialize plugins section if it doesn't exist
            if (!isset($params['plugins'])) {
                $params['plugins'] = [];
            }
            if (!isset($params['plugins']['magento'])) {
                $params['plugins']['magento'] = [];
            }

            // Prepare Magento configuration
            $magentoConfig = [
                'enabled' => 1, // Enable the plugin
                'apiUrl' => $this->apiUrl,
                'authMethod' => $this->authMethod,
                'storeCode' => $this->storeCode,
                'autoSync' => (bool)$this->autoSync,
                'debug' => (bool)$this->debug,
                'useQueue' => (bool)$this->useQueue,
                'timeout' => (int)$this->timeout,
            ];

            // Add authentication details based on method
            if ($this->authMethod === 'token') {
                $magentoConfig['accessToken'] = $this->accessToken;
            } else {
                $magentoConfig['adminUsername'] = $this->adminUsername;
                $magentoConfig['adminPassword'] = $this->adminPassword;
            }

            // Convert comma-separated string to array
            if (!empty($this->priceFields)) {
                $magentoConfig['priceFields'] = array_map('trim', explode(',', $this->priceFields));
            } else {
                $magentoConfig['priceFields'] = ['price1', 'price2', 'price3'];
            }

            // Convert JSON to array
            if (!empty($this->fieldMapping)) {
                $fieldMapping = json_decode($this->fieldMapping, true);
                if ($fieldMapping !== null) {
                    $magentoConfig['fieldMapping'] = $fieldMapping;
                }
            }

            // Update params
            $params['plugins']['magento'] = $magentoConfig;

            // Write to file
            $content = "<?php \n\treturn " . var_export($params, true) . ";\n";
            
            $result = file_put_contents($paramsFile, $content);
            
            return $result !== false;

        } catch (\Exception $e) {
            Yii::error('Failed to save Magento configuration: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Test connection to Magento API
     * 
     * @return array
     */
    public function testConnection()
    {
        try {
            // Create temporary client with current settings
            $client = new MagentoClient([
                'apiUrl' => $this->apiUrl,
                'accessToken' => $this->authMethod === 'token' ? $this->accessToken : null,
                'adminUsername' => $this->authMethod === 'credentials' ? $this->adminUsername : null,
                'adminPassword' => $this->authMethod === 'credentials' ? $this->adminPassword : null,
                'storeCode' => $this->storeCode,
                'debug' => false // Disable debug for testing
            ]);

            $success = $client->testConnection();

            if ($success) {
                return [
                    'success' => true,
                    'message' => 'Successfully connected to Magento API!',
                    'details' => 'API URL: ' . $this->apiUrl . ', Store: ' . $this->storeCode
                ];
            } else {
                return [
                    'success' => false,
                    'message' => 'Failed to connect to Magento API. Please check your credentials and URL.',
                ];
            }

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

    /**
     * Reset configuration to defaults
     * 
     * @return bool
     */
    public function resetToDefaults()
    {
        try {
            $paramsFile = Yii::getAlias('@backend/config/params-local.php');
            
            // Load existing params
            $params = [];
            if (file_exists($paramsFile)) {
                $params = require $paramsFile;
            }

            // Reset Magento configuration to disabled state
            if (!isset($params['plugins'])) {
                $params['plugins'] = [];
            }
            $params['plugins']['magento'] = ['enabled' => 0];

            // Write updated params
            $content = "<?php \n\treturn " . var_export($params, true) . ";\n";
            
            return file_put_contents($paramsFile, $content) !== false;

        } catch (\Exception $e) {
            Yii::error('Failed to reset Magento configuration: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Get default field mapping
     * 
     * @return array
     */
    public function getDefaultFieldMapping()
    {
        return [
            'sku' => 'sku',
            'name' => 'name',
            'price1' => 'price',
            'price2' => 'special_price',
            'description' => 'description',
            'short_description' => 'short_description',
            'weight' => 'weight',
            'status' => 'status'
        ];
    }
}