<?php

namespace modules\netsuite\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use modules\netsuite\models\SettingsForm;

/**
 * NetSuite 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'],
                ],
            ],
        ];
    }

    /**
     * Display and handle NetSuite 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', 'NetSuite settings saved successfully.');
                return $this->refresh();
            } else {
                Yii::$app->session->setFlash('error', 'Failed to save NetSuite settings.');
            }
        }
        
        return $this->render('index', [
            'model' => $model,
        ]);
    }

    /**
     * Test NetSuite connection
     * @return \yii\web\Response
     */
    public function actionTestConnection()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $model = new SettingsForm();
        $model->loadFromParams();
        
        try {
            // Test the connection (you can implement actual connection test)
            if (empty($model->account_id) || empty($model->consumer_key) || empty($model->consumer_secret)) {
                return [
                    'success' => false,
                    'message' => 'Please configure all required settings first.',
                ];
            }
            
            // Add your actual connection test logic here
            // For now, just validate that credentials are set
            return [
                'success' => true,
                'message' => 'NetSuite credentials are configured. Connection test would be performed here.',
            ];
            
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Connection failed: ' . $e->getMessage(),
            ];
        }
    }
}
