<?php

namespace portalpeople\stripe\controllers;

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

class ConfigController extends Controller
{
    public function actionIndex(): string
    {
        /** @var Module $module */
        $module = $this->module;

        $result = null;
        $error = null;

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

            try {
                $client = StripeClient::fromModule($module);

                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', [
            'config' => [
                'moduleId' => $module->moduleId,
                'apiBaseUrl' => $module->apiBaseUrl,
                'stripeVersion' => $module->stripeVersion,
                'timeout' => $module->timeout,
                'webhookTolerance' => $module->webhookTolerance,
                'secretKeyConfigured' => $module->secretKey !== '',
                'webhookSecretConfigured' => $module->webhookSigningSecret !== '',
                'debug' => $module->debug,
            ],
            'result' => $result,
            'error' => $error,
        ]);
    }
}
