<?php

namespace modules\netsuite\models;

use Yii;
use yii\base\Model;
use yii\helpers\Json;

/**
 * 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
    
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['account_id', 'consumer_key', 'consumer_secret', 'token_id', 'token_secret'], 'required', 'message' => 'This field is required.'],
            [['account_id', 'consumer_key', 'consumer_secret', 'token_id', 'token_secret', 'environment'], 'string'],
            [['enabled'], 'boolean'],
            [['environment'], 'in', 'range' => ['sandbox', 'production']],
            [['account_id'], 'string', 'max' => 50],
            [['consumer_key', 'consumer_secret', 'token_id', 'token_secret'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'enabled' => 'Enable NetSuite Integration',
            'account_id' => 'Account ID',
            'consumer_key' => 'Consumer Key',
            'consumer_secret' => 'Consumer Secret',
            'token_id' => 'Token ID',
            'token_secret' => 'Token Secret',
            'environment' => 'Environment',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeHints()
    {
        return [
            'account_id' => 'Your NetSuite Account ID (e.g., 1234567)',
            'consumer_key' => 'OAuth 1.0 Consumer Key from NetSuite Integration',
            'consumer_secret' => 'OAuth 1.0 Consumer Secret from NetSuite Integration',
            'token_id' => 'Token ID from NetSuite Token-Based Authentication',
            'token_secret' => 'Token Secret from NetSuite Token-Based Authentication',
            'environment' => 'Select sandbox for testing or production for live environment',
        ];
    }

    /**
     * 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 = $settings['consumer_key'] ?? '';
        $this->consumer_secret = $settings['consumer_secret'] ?? '';
        $this->token_id = $settings['token_id'] ?? '';
        $this->token_secret = $settings['token_secret'] ?? '';
        $this->environment = $settings['environment'] ?? 'production';
    }

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

        try {
            $configFile = Yii::getAlias('@modules/netsuite/config/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' => $this->consumer_key,
                'consumer_secret' => $this->consumer_secret,
                'token_id' => $this->token_id,
                'token_secret' => $this->token_secret,
                'environment' => $this->environment,
            ];

            // Generate config file content
            $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\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
            Yii::$app->params['netsuite'] = $settings;

            return true;

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