<?php

namespace App\Helpers;

use App\Models\SystemConfiguration;

class ConfigHelper
{
    /**
     * Get configuration value by key
     *
     * @param string $key Configuration key (e.g., 'payment.stripe.enabled')
     * @param mixed $default Default value if not found
     * @return mixed Configuration value
     */
    public static function get($key, $default = null)
    {
        try {
            $config = SystemConfiguration::where('key', $key)->first();

            if (!$config) {
                return $default;
            }

            $value = $config->value;

            // Try to decode JSON if it looks like JSON
            if (is_string($value) && in_array($value[0] ?? null, ['{', '['])) {
                $decoded = json_decode($value, true);
                return $decoded !== null ? $decoded : $value;
            }

            // Convert '1'/'0' to boolean for enabled/disabled configs
            if (in_array($key, [
                'payment.stripe.enabled',
                'payment.paypal.enabled',
                'payment.test_mode',
            ])) {
                return $value === '1' || $value === 1 || $value === true;
            }

            return $value;
        } catch (\Exception $e) {
            \Log::error('Error getting configuration: ' . $e->getMessage());
            return $default;
        }
    }

    /**
     * Check if payment method is enabled
     *
     * @param string $method Payment method (stripe, paypal)
     * @return bool
     */
    public static function isPaymentMethodEnabled($method)
    {
        return self::get("payment.{$method}.enabled", false) === true ||
               self::get("payment.{$method}.enabled", false) === '1';
    }

    /**
     * Get all payment configuration
     *
     * @return array
     */
    public static function getPaymentConfig()
    {
        return [
            'stripe' => [
                'enabled' => self::isPaymentMethodEnabled('stripe'),
                'public_key' => self::get('payment.stripe.public_key', ''),
                'secret_key' => self::get('payment.stripe.secret_key', ''),
            ],
            'paypal' => [
                'enabled' => self::isPaymentMethodEnabled('paypal'),
                'client_id' => self::get('payment.paypal.client_id', ''),
                'secret' => self::get('payment.paypal.secret', ''),
            ],
        ];
    }
}

