<?php

namespace PortalPeople\netsuite\controllers;

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

/**
 * 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,
        ]);
    }
    /**
     * AJAX validation for NetSuite 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 NetSuite connection
     * @return \yii\web\Response
     */
    public function actionTestConnection()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $model = new SettingsForm();
        $model->loadFromParams();
        
        try {
            Yii::warning($model->attributes, 'Testing NetSuite connection with settings: ');
            if (empty($model->account_id) || empty($model->consumer_key) || empty($model->consumer_secret)) {
                return [
                    'success' => false,
                    'message' => 'Please configure all required settings first.',
                ];
            }

            // Resolve private key path if it's relative
            $privateKeyPath = $model->private_key_path;
            
            // If path doesn't exist as-is, try prepending document root
            if (!empty($privateKeyPath) && !file_exists($privateKeyPath)) {
                $docRootPath = $_SERVER['DOCUMENT_ROOT'] . $privateKeyPath;
                if (file_exists($docRootPath)) {
                    $privateKeyPath = $docRootPath;
                }
            }
            
            if (!file_exists($privateKeyPath)) {
                return [
                    'success' => false,
                    'message' => 'Private key file not found: ' . $model->private_key_path,
                ];
            }
            
            // Use the working NetSuiteApiAuth implementation
            $oauthClient = new NetSuiteApiAuth([
                'clientId' => $model->consumer_key,
                'clientSecret' => $model->consumer_secret,
            ]);
            
            // Read private key
            $privateKey = file_get_contents($privateKeyPath);
            if ($privateKey === false) {
                return [
                    'success' => false,
                    'message' => 'Could not read private key file',
                ];
            }
            
            // Prepare JWT parameters matching the working implementation
            $jwtParams = [
                'header' => [
                    'alg' => 'ES256',
                    'kid' => $model->certificate_id,
                    'typ' => 'JWT'
                ],
                'signatureKey' => $privateKey,
            ];
            
            // Authenticate using JWT
            $token = $oauthClient->authenticateUserJwt(
                $model->consumer_key,
                null,
                $jwtParams,
                []
            );
            
            if ($token && !empty($token->token)) {
                return [
                    'success' => true,
                    'message' => 'Authentication successful. NetSuite connection is valid.',
                ];
            } else {
                return [
                    'success' => false,
                    'message' => 'Authentication failed: No access token received.',
                ];
            }
        } catch (\Exception $e) {
            Yii::error('NetSuite connection test failed: ' . $e->getMessage(), __CLASS__);
            return [
                'success' => false,
                'message' => 'Connection failed: ' . $e->getMessage(),
            ];
        }
    }
}
