<?php

namespace portalpeople\stripe\models;

use portalpeople\stripe\components\StripeClient;
use RuntimeException;
use Yii;
use yii\base\Model;

class ConfigForm extends Model
{
    public bool $enabled = true;
    public string $secretKey = '';
    public string $webhookSigningSecret = '';
    public string $apiBaseUrl = 'https://api.stripe.com/v1';
    public ?string $stripeVersion = null;
    public int $timeout = 30;
    public int $webhookTolerance = 300;
    public bool $debug = false;

    public function rules(): array
    {
        return [
            [['apiBaseUrl'], 'required'],
            [['apiBaseUrl'], 'url'],
            [['secretKey', 'webhookSigningSecret', 'apiBaseUrl'], 'string', 'max' => 255],
            [['stripeVersion'], 'string', 'max' => 64],
            [['timeout'], 'integer', 'min' => 5, 'max' => 300],
            [['webhookTolerance'], 'integer', 'min' => 0, 'max' => 86400],
            [['enabled', 'debug'], 'boolean'],
        ];
    }

    public function attributeLabels(): array
    {
        return [
            'enabled' => 'Enable Stripe Module',
            'secretKey' => 'Stripe Secret Key',
            'webhookSigningSecret' => 'Webhook Signing Secret',
            'apiBaseUrl' => 'Stripe API Base URL',
            'stripeVersion' => 'Stripe API Version (optional)',
            'timeout' => 'Request Timeout (seconds)',
            'webhookTolerance' => 'Webhook Tolerance (seconds)',
            'debug' => 'Enable Debug Logging',
        ];
    }

    public function loadFromParams(): void
    {
        $config = Yii::$app->params['plugins']['stripe'] ?? [];
        if (!is_array($config)) {
            return;
        }

        $this->enabled = (bool) ($config['enabled'] ?? $this->enabled);
        $this->secretKey = (string) ($config['secretKey'] ?? $this->secretKey);
        $this->webhookSigningSecret = (string) ($config['webhookSigningSecret'] ?? $this->webhookSigningSecret);
        $this->apiBaseUrl = (string) ($config['apiBaseUrl'] ?? $this->apiBaseUrl);
        $this->stripeVersion = $config['stripeVersion'] ?? $this->stripeVersion;
        $this->timeout = (int) ($config['timeout'] ?? $this->timeout);
        $this->webhookTolerance = (int) ($config['webhookTolerance'] ?? $this->webhookTolerance);
        $this->debug = (bool) ($config['debug'] ?? $this->debug);
    }

    public function saveToParams(): bool
    {
        $paramsFile = Yii::getAlias('@backend/config/params-local.php');

        try {
            $params = [];
            if (file_exists($paramsFile)) {
                $params = include $paramsFile;
            }

            if (!isset($params['plugins']) || !is_array($params['plugins'])) {
                $params['plugins'] = [];
            }

            $params['plugins']['stripe'] = [
                'enabled' => (bool) $this->enabled,
                'secretKey' => trim($this->secretKey),
                'webhookSigningSecret' => trim($this->webhookSigningSecret),
                'apiBaseUrl' => trim($this->apiBaseUrl),
                'stripeVersion' => $this->stripeVersion !== null && $this->stripeVersion !== ''
                    ? trim($this->stripeVersion)
                    : null,
                'timeout' => (int) $this->timeout,
                'webhookTolerance' => (int) $this->webhookTolerance,
                'debug' => (bool) $this->debug,
            ];

            $content = "<?php\n\nreturn " . var_export($params, true) . ";\n";
            return file_put_contents($paramsFile, $content) !== false;
        } catch (RuntimeException $e) {
            Yii::error('Failed to save Stripe configuration: ' . $e->getMessage(), __METHOD__);
            return false;
        }
    }

    public function buildClient(): StripeClient
    {
        if (!$this->enabled) {
            throw new RuntimeException('Stripe plugin is disabled.');
        }

        if ($this->secretKey === '') {
            throw new RuntimeException('Stripe secret key is required.');
        }

        return new StripeClient(
            $this->secretKey,
            $this->apiBaseUrl,
            $this->timeout,
            $this->debug,
            $this->stripeVersion
        );
    }
}
