<?php

namespace PortalPeople\paygate\models;

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

/**
 * PayGate (Redsys) Settings Form Model
 */
class SettingsForm extends Model
{
    public $enabled;
    public $environment; // sandbox or production
    public $merchant_code;
    public $terminal;
    public $currency;
    public $transaction_type;
    public $secret_key;
    public $auto_capture;
    public $debug;
    public $notification_url;
    public $success_url;
    public $error_url;
    
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['merchant_code', 'terminal', 'currency', 'secret_key'], 'required', 'message' => 'This field is required.'],
            [['merchant_code', 'terminal', 'currency', 'transaction_type', 'secret_key', 'notification_url', 'success_url', 'error_url'], 'string'],
            [['enabled', 'auto_capture', 'debug'], 'boolean'],
            [['environment'], 'in', 'range' => ['sandbox', 'production']],
            [['merchant_code'], 'string', 'max' => 9],
            [['terminal'], 'string', 'max' => 3],
            [['currency'], 'string', 'max' => 3],
            [['transaction_type'], 'string', 'max' => 1],
            [['secret_key'], 'string', 'max' => 255],
            [['notification_url', 'success_url', 'error_url'], 'url'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'enabled' => 'Enable PayGate Integration',
            'environment' => 'Environment',
            'merchant_code' => 'Merchant Code (FUC)',
            'terminal' => 'Terminal Number',
            'currency' => 'Currency Code',
            'transaction_type' => 'Transaction Type',
            'secret_key' => 'Secret Key (SHA-256)',
            'auto_capture' => 'Auto Capture Payments',
            'debug' => 'Enable Debug Logging',
            'notification_url' => 'Notification URL',
            'success_url' => 'Success Return URL',
            'error_url' => 'Error Return URL',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeHints()
    {
        return [
            'merchant_code' => 'Your PayGate/Redsys merchant identification code (FUC)',
            'terminal' => 'Terminal number assigned by your bank (usually 001)',
            'currency' => 'Currency code (978 for EUR, 826 for GBP, 840 for USD)',
            'transaction_type' => '0 = Authorization, A = Pre-authorization, 1 = Pre-authorization confirmation',
            'secret_key' => 'Secret key (SHA-256) provided by your bank',
            'environment' => 'Select sandbox for testing or production for live payments',
            'auto_capture' => 'Automatically capture authorized payments',
            'debug' => 'Enable detailed logging for troubleshooting',
            'notification_url' => 'URL for payment notifications (webhooks)',
            'success_url' => 'URL to redirect customers after successful payment',
            'error_url' => 'URL to redirect customers after payment failure',
        ];
    }

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

        $this->enabled = $settings['enabled'] ?? false;
        $this->environment = $settings['environment'] ?? 'production';
        $this->merchant_code = $settings['merchant_code'] ?? '';
        $this->terminal = $settings['terminal'] ?? '1';
        $this->currency = $settings['currency'] ?? '978';
        $this->transaction_type = $settings['transaction_type'] ?? '0';
        $this->secret_key = Security::decryptSensitiveData($settings['secret_key'] ?? '');
        $this->auto_capture = $settings['auto_capture'] ?? true;
        $this->debug = $settings['debug'] ?? false;
        $this->notification_url = $settings['notification_url'] ?? '';
        $this->success_url = $settings['success_url'] ?? '';
        $this->error_url = $settings['error_url'] ?? '';
    }

    /**
     * Save settings to application params
     * @return bool
     */
    public function save()
    {
        if (!$this->validate()) {
            return false;
        }

        try {
            $paramsFile = Yii::getAlias('@common/config/params.php');
            
            if (!file_exists($paramsFile)) {
                Yii::error("Params file not found: $paramsFile", __METHOD__);
                return false;
            }

            $params = require $paramsFile;

            // Encrypt sensitive data
            $params['paygate'] = [
                'enabled' => (bool)$this->enabled,
                'environment' => $this->environment,
                'merchant_code' => $this->merchant_code,
                'terminal' => $this->terminal,
                'currency' => $this->currency,
                'transaction_type' => $this->transaction_type,
                'secret_key' => Security::encryptSensitiveData($this->secret_key),
                'auto_capture' => (bool)$this->auto_capture,
                'debug' => (bool)$this->debug,
                'notification_url' => $this->notification_url,
                'success_url' => $this->success_url,
                'error_url' => $this->error_url,
            ];

            // Save back to file
            $content = "<?php\nreturn " . var_export($params, true) . ";\n";
            
            if (file_put_contents($paramsFile, $content) === false) {
                Yii::error("Failed to write params file: $paramsFile", __METHOD__);
                return false;
            }

            // Reload params
            Yii::$app->params = $params;

            return true;
        } catch (\Exception $e) {
            Yii::error("Error saving PayGate settings: " . $e->getMessage(), __METHOD__);
            return false;
        }
    }

    /**
     * Save settings to params file
     * @return bool
     */
    public function saveToParams()
    {
        return $this->save();
    }
}
