<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;

class SettingController extends Controller
{
    public function index()
    {
        $settings = Setting::first();

        if (!$settings) {
            // Create default settings if none exist
            $settings = new Setting([
                'site_name' => 'Lic',
                'site_description' => '',
                'site_logo' => '',
                'support_email' => '',
                'avg_response_time' => 24,
                'support_phone' => '',
                'timezone' => 'UTC',
                'maintenance_mode' => false,
                'envato_personal_token' => '',
                'envato_api_key' => '',
                'envato_auth_enabled' => false,
                'envato_username' => '',
                'envato_client_id' => '',
                'envato_client_secret' => '',
                'envato_redirect_uri' => config('app.url') . '/auth/envato/callback',
                'envato_oauth_enabled' => false,
                'auto_generate_license' => true,
                'default_license_length' => 32,
                'license_max_attempts' => 5,
                'license_lockout_minutes' => 15,
                // Preloader defaults
                'preloader_enabled' => true,
                'preloader_type' => 'spinner',
                'preloader_color' => '#3b82f6',
                'preloader_background_color' => '#ffffff',
                'preloader_duration' => 800,
                'preloader_custom_css' => null,
                // Logo defaults
                'site_logo_dark' => null,
                'logo_width' => 150,
                'logo_height' => 50,
                'logo_show_text' => true,
                'logo_text' => config('app.name'),
                'logo_text_color' => '#1f2937',
                'logo_text_font_size' => '24px',
                // License API Token default
                'license_api_token' => 'a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456',
            ]);
            $settings->save();
        }

        // Convert to array for backward compatibility
        $settingsArray = $settings->toArray();
        $currentTimezone = old('timezone', $settings->timezone ?? 'UTC');

        return view('admin.settings.index', compact('settings', 'settingsArray', 'currentTimezone'));
    }

    public function update(Request $request)
    {

        $validated = $request->validate([
            'site_name' => 'required|string|max:255',
            'site_description' => 'nullable|string|max:500',
            'site_logo' => 'nullable|mimes:jpeg,png,jpg,gif,svg,webp|max:5120',
            'support_email' => 'nullable|email',
            'avg_response_time' => 'nullable|integer|min:1|max:168',
            'support_phone' => 'nullable|string|max:20',
            'timezone' => 'nullable|string',
            'maintenance_mode' => 'boolean',
            // SEO
            'seo_site_title' => 'nullable|string|max:255',
            'seo_site_description' => 'nullable|string|max:500',
            'seo_og_image' => 'nullable|mimes:jpeg,png,jpg,gif,svg,webp|max:5120',
            'seo_kb_title' => 'nullable|string|max:255',
            'seo_kb_description' => 'nullable|string|max:500',
            'seo_tickets_title' => 'nullable|string|max:255',
            'seo_tickets_description' => 'nullable|string|max:500',
            'envato_personal_token' => 'nullable|string',
            'envato_api_key' => 'nullable|string',
            'envato_auth_enabled' => 'boolean',
            'envato_username' => 'nullable|string',
            'envato_client_id' => 'nullable|string',
            'envato_client_secret' => 'nullable|string',
            'envato_redirect_uri' => 'nullable|string',
            'envato_oauth_enabled' => 'boolean',
            'license_api_token' => 'required|string|min:32|max:128',
            'license_max_attempts' => 'nullable|integer|min:1',
            'license_lockout_minutes' => 'nullable|integer|min:1',
            // Advanced License Settings
            'license_verify_envato' => 'boolean',
            'license_fallback_internal' => 'boolean',
            'license_cache_verification' => 'boolean',
            'license_cache_duration' => 'nullable|integer|min:1|max:1440',
            'license_allow_offline' => 'boolean',
            'license_grace_period' => 'nullable|integer|min:0|max:30',
            'license_allow_localhost' => 'boolean',
            'license_allow_ip_addresses' => 'boolean',
            'license_allow_wildcards' => 'boolean',
            'license_validate_ssl' => 'boolean',
            'license_auto_approve_subdomains' => 'boolean',
            'license_auto_register_domains' => 'boolean',
            'license_max_domains' => 'nullable|integer|min:1|max:100',
            'license_domain_cooldown' => 'nullable|integer|min:1|max:168',
            'license_default_duration' => 'nullable|integer|min:1|max:3650',
            'license_support_duration' => 'nullable|integer|min:1|max:3650',
            'license_renewal_reminder' => 'nullable|integer|min:1|max:365',
            'license_expiration_grace' => 'nullable|integer|min:0|max:30',
            'license_auto_suspend' => 'boolean',
            'license_allow_expired_verification' => 'boolean',
            'license_encrypt_data' => 'boolean',
            'license_secure_tokens' => 'boolean',
            'license_validate_signatures' => 'boolean',
            'license_prevent_sharing' => 'boolean',
            'license_detect_suspicious' => 'boolean',
            'license_block_vpn' => 'boolean',
            'license_require_https' => 'boolean',
            'license_notify_verification' => 'boolean',
            'license_notify_expiration' => 'boolean',
            'license_notify_domain_change' => 'boolean',
            'license_notify_suspicious' => 'boolean',
            'license_notification_email' => 'nullable|email',
            'license_use_slack' => 'boolean',
            'license_slack_webhook' => 'nullable|url',
            'license_enable_caching' => 'boolean',
            'license_cache_driver' => 'nullable|string|in:file,database,redis,memcached',
            'license_optimize_queries' => 'boolean',
            'license_batch_size' => 'nullable|integer|min:1|max:1000',
            'license_use_indexes' => 'boolean',
            'license_compress_responses' => 'boolean',
            'license_allow_test' => 'boolean',
            'license_test_prefix' => 'nullable|string|max:10',
            'license_bypass_testing' => 'boolean',
            'license_mock_envato' => 'boolean',
            'license_generate_fake_data' => 'boolean',
            // Preloader settings
            'preloader_enabled' => 'boolean',
            'preloader_type' => 'nullable|string|in:spinner,dots,bars,pulse,progress,custom',
            'preloader_color' => 'nullable|string|max:7',
            'preloader_background_color' => 'nullable|string|max:7',
            'preloader_duration' => 'nullable|integer|min:500|max:10000',
            'preloader_custom_css' => 'nullable|string',
            // Logo settings
            'site_logo_dark' => 'nullable|mimes:jpeg,png,jpg,gif,svg,webp|max:5120',
            'logo_width' => 'nullable|integer|min:50|max:500',
            'logo_height' => 'nullable|integer|min:20|max:200',
            'logo_show_text' => 'boolean',
            'logo_text' => 'nullable|string|max:255',
            'logo_text_color' => 'nullable|string|max:7',
            'logo_text_font_size' => 'nullable|string|max:10',
            // Anti-spam / captcha settings
            'enable_captcha' => 'boolean',
            'captcha_site_key' => 'nullable|string|max:255',
            'captcha_secret_key' => 'nullable|string|max:255',
            'enable_human_question' => 'boolean',
            // Accept either a JSON string or an array of question/answer pairs from the dynamic UI
            'human_questions' => 'nullable',
            'human_questions.*.question' => 'required_with:human_questions|string|max:255',
            'human_questions.*.answer' => 'required_with:human_questions|string|max:255',
        ]);

        // Handle logo upload
        if ($request->hasFile('site_logo')) {
            $logoFile = $request->file('site_logo');
            if ($logoFile->isValid()) {
                $logoPath = $logoFile->store('logos', 'public');
                $validated['site_logo'] = $logoPath;
            }
        }

        // Handle OG image upload
        if ($request->hasFile('seo_og_image')) {
            $ogFile = $request->file('seo_og_image');
            if ($ogFile->isValid()) {
                $ogPath = $ogFile->store('seo', 'public');
                $validated['seo_og_image'] = $ogPath;
            }
        }

        // Handle dark logo upload
        if ($request->hasFile('site_logo_dark')) {
            $darkLogoFile = $request->file('site_logo_dark');
            if ($darkLogoFile->isValid()) {
                $darkLogoPath = $darkLogoFile->store('logos', 'public');
                $validated['site_logo_dark'] = $darkLogoPath;
            }
        }

        // Set defaults for required fields if not provided
        $validated['license_max_attempts'] = $validated['license_max_attempts'] ?? 5;
        $validated['license_lockout_minutes'] = $validated['license_lockout_minutes'] ?? 15;
        $validated['timezone'] = $validated['timezone'] ?? 'UTC';
        if (!$request->has('maintenance_mode')) {
            $validated['maintenance_mode'] = 0;
        }
        if (!$request->has('preloader_enabled')) {
            $validated['preloader_enabled'] = 0;
        }
        if (!$request->has('logo_show_text')) {
            $validated['logo_show_text'] = 0;
        }

        // Update settings
        $setting = Setting::firstOrCreate([]);
        foreach ($validated as $key => $value) {
            // If human_questions, validate JSON and save as string
            if ($key === 'human_questions') {
                // Accept array input (from dynamic UI) or JSON string
                if (is_array($value)) {
                    $decoded = $value;
                } elseif (!empty($value)) {
                    try {
                        $decoded = json_decode($value, true, 512, JSON_THROW_ON_ERROR);
                    } catch (\JsonException $e) {
                        return back()->withErrors(['human_questions' => 'Invalid JSON: ' . $e->getMessage()])->withInput();
                    }
                } else {
                    $setting->human_questions = null;
                    continue;
                }

                if (!is_array($decoded)) {
                    return back()->withErrors(['human_questions' => 'Human questions must be an array'])->withInput();
                }

                // Normalize: keep only question & answer strings
                $normalized = [];
                foreach ($decoded as $entry) {
                    if (!is_array($entry)) continue;
                    $q = trim((string)($entry['question'] ?? ''));
                    $a = trim((string)($entry['answer'] ?? ''));
                    if ($q === '' || $a === '') continue;
                    $normalized[] = ['question' => $q, 'answer' => $a];
                }

                $setting->human_questions = !empty($normalized) ? json_encode($normalized) : null;
                continue;
            }

            $setting->$key = $value;
        }
        $saved = $setting->save();

        // Clear cache
        Setting::clearCache();

        return back()->with('success', 'Settings updated successfully.');
    }

    public function testApi(Request $request)
    {
        $request->validate([
            'token' => 'required|string'
        ]);

        try {
            $envatoService = app('App\Services\EnvatoService');

            // Test API by calling testToken method
            $isValid = $envatoService->testToken($request->token);

            if ($isValid) {
                return response()->json([
                    'success' => true,
                    'message' => 'API connection successful! Your token is valid.'
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid token or API connection failed. Please check your token and try again.'
                ]);
            }
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'API test failed: ' . $e->getMessage()
            ]);
        }
    }

    public function envatoGuide()
    {
        return view('admin.settings.envato-guide');
    }
}