<?php

namespace PortalPeople\paygate\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use PortalPeople\paygate\models\SettingsForm;

/**
 * PayGate Settings Controller
 */
class SettingsController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'save' => ['post'],
                    'test-connection' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Display and handle PayGate settings
     * @return string
     */
    public function actionIndex()
    {
        $model = new SettingsForm();
        
        // Load current settings
        $model->loadFromParams();
        
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'PayGate settings saved successfully.');
                return $this->refresh();
            } else {
                Yii::$app->session->setFlash('error', 'Failed to save PayGate settings.');
            }
        }
        
        return $this->render('index', [
            'model' => $model,
        ]);
    }

    /**
     * AJAX validation for PayGate settings form
     */
    public function actionValidate()
    {
        $model = new SettingsForm();
        if ($model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\widgets\ActiveForm::validate($model);
        }
        throw new \yii\web\BadRequestHttpException('Invalid request');
    }

    /**
     * Test PayGate connection
     * @return \yii\web\Response
     */
    public function actionTestConnection()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $model = new SettingsForm();
        
        // Load posted data or current settings
        if (Yii::$app->request->post()) {
            $model->load(Yii::$app->request->post());
        } else {
            $model->loadFromParams();
        }
        
        try {
            if (empty($model->merchant_code) || empty($model->secret_key)) {
                return [
                    'success' => false,
                    'message' => 'Please configure merchant code and secret key first.',
                ];
            }

            // Determine the API URL based on environment
            $apiUrl = $model->environment === 'sandbox' 
                ? \PortalPeople\paygate\models\Paygate::sandboxUrl
                : \PortalPeople\paygate\models\Paygate::productionUrl;

            // Test basic configuration validity
            if (!filter_var($apiUrl, FILTER_VALIDATE_URL)) {
                return [
                    'success' => false,
                    'message' => 'Invalid PayGate API URL configuration.',
                ];
            }

            // Validate merchant code format (9 digits)
            if (!preg_match('/^\d{1,9}$/', $model->merchant_code)) {
                return [
                    'success' => false,
                    'message' => 'Merchant code should be numeric (max 9 digits).',
                ];
            }

            // Validate terminal format (typically 3 digits)
            if (!preg_match('/^\d{1,3}$/', $model->terminal)) {
                return [
                    'success' => false,
                    'message' => 'Terminal number should be numeric (max 3 digits).',
                ];
            }

            // Validate currency code (3 digits)
            if (!preg_match('/^\d{3}$/', $model->currency)) {
                return [
                    'success' => false,
                    'message' => 'Currency code should be 3 digits (e.g., 978 for EUR).',
                ];
            }

            // Check if secret key appears to be Base64 encoded (typical for Redsys)
            if (strlen($model->secret_key) < 20) {
                return [
                    'success' => false,
                    'message' => 'Secret key appears to be too short. Please verify your key.',
                ];
            }

            return [
                'success' => true,
                'message' => 'PayGate configuration is valid. Environment: ' . ucfirst($model->environment) . 
                            ', Merchant: ' . $model->merchant_code . 
                            ', Terminal: ' . $model->terminal,
                'details' => [
                    'environment' => $model->environment,
                    'api_url' => $apiUrl,
                    'merchant_code' => $model->merchant_code,
                    'terminal' => $model->terminal,
                    'currency' => $model->currency,
                ]
            ];
            
        } catch (\Exception $e) {
            Yii::error('PayGate connection test error: ' . $e->getMessage(), __METHOD__);
            return [
                'success' => false,
                'message' => 'Error testing connection: ' . $e->getMessage(),
            ];
        }
    }
}
