<?php

namespace PortalPeople\netsuite\models;

use Yii;
use yii\base\Model;
use yii\helpers\Json;
use backend\components\Security;

/**
 * NetSuite Settings Form Model
 */
class SettingsForm extends Model
{
    public $enabled;
    public $account_id;
    public $consumer_key;
    public $consumer_secret;
    public $token_id;
    public $token_secret;
    public $environment; // sandbox or production
    public $certificate_id;
    public $private_key_path;
    public $user_id;
    public $base_url;
    public $decryption_key;
    public $cartClass;
    
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['account_id', 'consumer_key', 'consumer_secret', 'token_id', 'token_secret', 'certificate_id', 'private_key_path'], 'required', 'message' => 'This field is required.'],
            [['account_id', 'consumer_key', 'consumer_secret', 'token_id', 'token_secret', 'environment', 'certificate_id', 'private_key_path', 'user_id', 'base_url', 'decryption_key'], 'string'],
            [['enabled'], 'boolean'],
            [['environment'], 'in', 'range' => ['sandbox', 'production']],
            [['account_id'], 'string', 'max' => 50],
            [['consumer_key', 'consumer_secret', 'token_id', 'token_secret', 'certificate_id', 'private_key_path', 'user_id', 'base_url', 'decryption_key'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'enabled' => 'Enable NetSuite Integration',
            'account_id' => 'Account ID',
            'consumer_key' => 'Client ID',
            'consumer_secret' => 'Client Secret',
            'token_id' => 'Token ID',
            'token_secret' => 'Token Secret',
            'environment' => 'Environment',
            'certificate_id' => 'Certificate ID (Key ID)',
            'private_key_path' => 'Private Key Path',
            'user_id' => 'User Internal ID',
            'base_url' => 'Base URL (optional)',
            'decryption_key' => 'Webhook Decryption Key',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeHints()
    {
        return [
            'account_id' => 'Your NetSuite Account ID (e.g., 1234567)',
            'consumer_key' => 'Client ID from NetSuite integration record',
            'consumer_secret' => 'Client Secret from NetSuite integration record',
            'token_id' => 'Token ID from NetSuite Token-Based Authentication (if used)',
            'token_secret' => 'Token Secret from NetSuite Token-Based Authentication (if used)',
            'environment' => 'Select sandbox for testing or production for live environment',
            'certificate_id' => 'Certificate ID (Key ID) from NetSuite',
            'private_key_path' => 'Path to private key file for JWT signing',
            'user_id' => 'NetSuite user internal ID for impersonation',
            'base_url' => 'Override NetSuite REST API base URL (optional)',
            'decryption_key' => 'Separate key used by /netsuite/updateorder to decrypt PP_Order_Change payloads (must match NetSuite API Secret value)',
        ];
    }

    /**
     * Load settings from application params
     */
    public function loadFromParams()
    {
        $settings = Yii::$app->params['netsuite'] ?? [];

        $this->enabled = $settings['enabled'] ?? false;
        $this->account_id = $settings['account_id'] ?? '';
        $this->consumer_key = Security::decryptSensitiveData($settings['consumer_key'] ?? '');
        $this->consumer_secret = Security::decryptSensitiveData($settings['consumer_secret'] ?? '');
        $this->token_id = Security::decryptSensitiveData($settings['token_id'] ?? '');
        $this->token_secret = Security::decryptSensitiveData($settings['token_secret'] ?? '');
        $this->environment = $settings['environment'] ?? 'production';
        $this->certificate_id = Security::decryptSensitiveData($settings['certificate_id'] ?? '');
        $this->private_key_path = $settings['private_key_path'] ?? '';
        $this->user_id = $settings['user_id'] ?? '';
        $this->base_url = $settings['base_url'] ?? '';
        $this->decryption_key = Security::decryptSensitiveData($settings['decryption_key'] ?? '');
        $this->cartClass = $settings['cartClass'] ?? 'backend\models\Cartsbe';
    }

    /**
     * Save settings to config/netsuite/ns.php
     * @return bool
     */
    public function save()
    {
        if (!$this->validate()) {
            return false;
        }

        try {
            $configFile = Yii::getAlias('@config/netsuite/ns.php');
            $configDir = dirname($configFile);
            
            // Create config directory if it doesn't exist
            if (!is_dir($configDir)) {
                if (!mkdir($configDir, 0755, true)) {
                    Yii::error("Failed to create config directory: {$configDir}", __CLASS__);
                    return false;
                }
            }

            // Prepare settings array
            $settings = [
                'enabled' => (bool)$this->enabled,
                'account_id' => $this->account_id,
                'consumer_key' => Security::encryptSensitiveData($this->consumer_key),
                'consumer_secret' => Security::encryptSensitiveData($this->consumer_secret),
                'token_id' => Security::encryptSensitiveData($this->token_id),
                'token_secret' => Security::encryptSensitiveData($this->token_secret),
                'environment' => $this->environment,
                'certificate_id' => Security::encryptSensitiveData($this->certificate_id),
                'private_key_path' => $this->private_key_path,
                'user_id' => $this->user_id,
                'base_url' => $this->base_url,
                'decryption_key' => Security::encryptSensitiveData($this->decryption_key),
                'cartClass' => $this->cartClass,
            ];

            // Generate config file content with encryption notice
            $content = "<?php\n/**\n * NetSuite Configuration\n * \n * This file is auto-generated by the NetSuite settings form.\n * Last updated: " . date('Y-m-d H:i:s') . "\n * \n * Sensitive fields are encrypted when app state is 'live'.\n * Encrypted fields are base64 encoded and prefixed with 'encrypted::'\n */\n\nreturn " . var_export($settings, true) . ";\n";

            // Write to file
            if (file_put_contents($configFile, $content) === false) {
                Yii::error("Failed to write to config file: {$configFile}", __CLASS__);
                return false;
            }

            // Update runtime params with decrypted values
            Yii::$app->params['netsuite'] = $settings;

            return true;

        } catch (\Exception $e) {
            Yii::error("Failed to save NetSuite settings: " . $e->getMessage(), __CLASS__);
            return false;
        }
    }
}
