<?php

namespace portalpeople\stripe\controllers;

use portalpeople\stripe\components\StripeClient;
use portalpeople\stripe\models\ConfigForm;
use RuntimeException;
use Yii;
use yii\web\Controller;

class ConfigController extends Controller
{
    public function actionIndex(): string
    {
        $model = new ConfigForm();
        $model->loadFromParams();

        $result = null;
        $error = null;

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->saveToParams()) {
                Yii::$app->session->setFlash('success', 'Stripe configuration saved successfully.');
                return $this->refresh();
            }
            Yii::$app->session->setFlash('error', 'Failed to save Stripe configuration. Check file permissions.');
        }

        if (Yii::$app->request->isPost && !$model->hasErrors()) {
            $action = (string) Yii::$app->request->post('testAction', '');

            try {
                $client = $model->buildClient();

                if ($action === 'balance') {
                    $result = $client->retrieveBalance();
                } elseif ($action === 'customers') {
                    $result = $client->listCustomers(['limit' => 3]);
                } else {
                    $error = 'Unknown test action.';
                }
            } catch (RuntimeException $e) {
                $error = $e->getMessage();
            }
        }

        return $this->render('index', [
            'model' => $model,
            'result' => $result,
            'error' => $error,
        ]);
    }
}
