<?php

namespace App\Services;

use App\Models\Setting;
use Illuminate\Support\Facades\Schema;
use Throwable;

class PaymentSettings
{
    public const SETTINGS_KEY = 'payments';

    /**
     * @return array<string, mixed>
     */
    public function settings(): array
    {
        try {
            if (! Schema::hasTable('settings')) {
                return $this->defaultSettings();
            }

            return [
                ...$this->defaultSettings(),
                ...(Setting::query()->where('key', self::SETTINGS_KEY)->first()?->value ?? []),
            ];
        } catch (Throwable) {
            return $this->defaultSettings();
        }
    }

    /**
     * @param  array<string, mixed>  $settings
     */
    public function save(array $settings): void
    {
        Setting::query()->updateOrCreate(
            ['key' => self::SETTINGS_KEY],
            ['value' => [
                ...$this->defaultSettings(),
                ...$settings,
            ]],
        );
    }

    /**
     * @return array<string, mixed>
     */
    public function defaultSettings(): array
    {
        return [
            'default_gateway' => 'stripe',
            'default_currency' => 'usd',
            'test_mode' => true,
            'allow_user_subscriptions' => true,
            'trial_days' => 0,
            'invoice_prefix' => 'URL',
            'tax_enabled' => false,
            'tax_rate_percent' => '0',
            'stripe_enabled' => false,
            'stripe_publishable_key' => '',
            'stripe_secret_key' => '',
            'stripe_webhook_secret' => '',
            'stripe_checkout_success_url' => '/dashboard/subscription?payment=success',
            'stripe_checkout_cancel_url' => '/dashboard/subscription?payment=cancelled',
            'stripe_webhook_url' => rtrim(config('app.url'), '/').'/webhooks/stripe',
            'manual_enabled' => false,
            'manual_instructions' => 'Contact support to activate your subscription manually.',
            'admin_notes' => '',
        ];
    }
}
