<?php

namespace App\Helpers;

use App\Models\Setting;
use Illuminate\Support\Facades\Cache;

class ConfigHelper
{
    /**
     * Get setting value from database with fallback to config/env
     * 
     * @param string $key The setting key
     * @param mixed $default Default value if not found
     * @param string $configKey Optional config key for fallback
     * @return mixed
     */
    public static function getSetting(string $key, $default = null, string $configKey = null)
    {
        try {
            // Try single-row settings first
            $setting = Setting::first();
            if ($setting && isset($setting->$key) && !empty($setting->$key)) {
                return $setting->$key;
            }

            // Fallback to key/value rows (some installations store settings as rows with 'key' and 'value')
            $kv = Setting::where('key', $key)->first();
            if ($kv && isset($kv->value) && $kv->value !== null && $kv->value !== '') {
                return $kv->value;
            }

            // Fallback to config if provided
            if ($configKey) {
                return config($configKey, $default);
            }

            return $default;
        } catch (\Exception $e) {
            // If database is not available, fallback to config/env
            if ($configKey) {
                return config($configKey, $default);
            }
            return $default;
        }
    }

    /**
     * Get multiple settings at once
     * 
     * @param array $keys Array of setting keys
     * @return array
     */
    public static function getSettings(array $keys): array
    {
        $settings = [];
        
        try {
            // Try single-row settings
            $setting = Setting::first();

            foreach ($keys as $key) {
                if ($setting && isset($setting->$key) && !empty($setting->$key)) {
                    $settings[$key] = $setting->$key;
                    continue;
                }

                // Fallback to key/value row
                $kv = Setting::where('key', $key)->first();
                $settings[$key] = $kv && isset($kv->value) ? $kv->value : null;
            }
        } catch (\Exception $e) {
            // Return empty array if database is not available
            foreach ($keys as $key) {
                $settings[$key] = null;
            }
        }
        
        return $settings;
    }

    /**
     * Get license-related settings
     * 
     * @return array
     */
    public static function getLicenseSettings(): array
    {
        return self::getSettings([
            'license_api_token',
            'envato_personal_token',
            'envato_client_id',
            'envato_client_secret',
            'envato_redirect_uri',
            'auto_generate_license',
            'default_license_length',
            'license_max_attempts',
            'license_lockout_minutes',
            // License verification settings
            'license_verify_envato',
            'license_fallback_internal',
            'license_cache_verification',
            'license_cache_duration',
            'license_allow_offline',
            'license_grace_period',
            // Domain management settings
            'license_allow_localhost',
            'license_allow_ip_addresses',
            'license_allow_wildcards',
            'license_validate_ssl',
            'license_auto_approve_subdomains',
            'license_max_domains',
            'license_domain_cooldown',
            // License expiration settings
            'license_default_duration',
            'license_support_duration',
            'license_renewal_reminder',
            'license_expiration_grace',
            'license_auto_suspend',
            'license_allow_expired_verification',
            // Security settings
            'license_encrypt_data',
            'license_secure_tokens',
            'license_validate_signatures',
            'license_prevent_sharing',
            'license_detect_suspicious',
            'license_block_vpn',
            'license_require_https',
            // Notification settings
            'license_notify_verification',
            'license_notify_expiration',
            'license_notify_domain_change',
            'license_notify_suspicious',
            'license_notification_email',
            'license_use_slack',
            'license_slack_webhook',
            // Performance settings
            'license_enable_caching',
            'license_cache_driver',
            'license_optimize_queries',
            'license_batch_size',
            'license_use_indexes',
            'license_compress_responses',
            // Testing settings
            'license_allow_test',
            'license_test_prefix',
            'license_bypass_testing',
            'license_mock_envato',
            'license_generate_fake_data',
        ]);
    }

    /**
     * Get Envato-related settings
     * 
     * @return array
     */
    public static function getEnvatoSettings(): array
    {
        return self::getSettings([
            'envato_personal_token',
            'envato_client_id',
            'envato_client_secret',
            'envato_redirect_uri',
            'envato_auth_enabled',
            'envato_oauth_enabled',
            'envato_username',
        ]);
    }
}