<?php

namespace Modules\LandingPage\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Str; // Add this line

class ThemeSettingController extends Controller
{
    public function edit()
    {
        $activeTheme = setting('landingpage_active_theme', 'general');
        $siteDirection = setting('site_direction', 'ltr'); // Default to LTR
        $availableThemes = $this->getAvailableThemes();

        // Google Analytics Settings
        $gaEnableTracking = setting('google_analytics_enable_tracking', false);
        $gaTrackingId = setting('google_analytics_tracking_id', ''); // e.g., G-XXXXXXXXXX
        $gaPropertyId = setting('google_analytics_property_id', ''); // e.g., Your GA4 Property ID (numeric)
        $gaCredentialsPath = setting('google_analytics_credentials_path', '');
        $topBarTagline = setting('top_bar_tagline', 'Your Expert Digital Partner');

        // Theme Color Settings with defaults
        $colorSettings = [
            'top_bar_bg_light' => setting('top_bar_bg_light', '#f3f4f6'), // gray-100
            'top_bar_text_light' => setting('top_bar_text_light', '#374151'), // gray-700
            'top_bar_bg_dark' => setting('top_bar_bg_dark', '#111827'), // gray-900
            'top_bar_text_dark' => setting('top_bar_text_dark', '#d1d5db'), // gray-300
            'header_bg_light' => setting('header_bg_light', '#ffffff'), // white
            'header_text_light' => setting('header_text_light', '#374151'), // gray-700
            'header_bg_dark' => setting('header_bg_dark', '#1f2937'), // gray-800 (solid, for /95 use rgba in input)
            'header_text_dark' => setting('header_text_dark', '#d1d5db'), // gray-300
            'accent_color_light' => setting('accent_color_light', '#7c3aed'), // purple-600
            'accent_color_dark' => setting('accent_color_dark', '#a78bfa'), // purple-400
            // Contact & Social Settings
            'contact_email' => setting('contact_email', ''),
            'whatsapp_number' => setting('whatsapp_number', ''),
            'whatsapp_default_message' => setting('whatsapp_default_message', 'Hello! I have a question.'),
            'social_facebook_url' => setting('social_facebook_url', ''),
            'social_linkedin_url' => setting('social_linkedin_url', ''),
            'social_youtube_url' => setting('social_youtube_url', ''),
            'social_twitter_url' => setting('social_twitter_url', ''),
            'social_tiktok_url' => setting('social_tiktok_url', ''),
            'social_instagram_url' => setting('social_instagram_url', ''),
        ];
        // Here you could load theme-specific settings if you implement them
        // For now, we only manage the active theme.

        return view('landingpage::admin.theme_settings.edit', compact(
            'activeTheme', 'siteDirection',
            'availableThemes', 
            'gaEnableTracking', 'gaTrackingId', 'gaPropertyId', 'gaCredentialsPath',
            'topBarTagline',
            'colorSettings'
        ));
    }

    public function update(Request $request)
    {
        $request->validate([
            'landingpage_active_theme' => 'required|string',
            'site_direction' => 'required|in:ltr,rtl',
            // Add validation for other theme-specific settings here
            'top_bar_tagline' => 'nullable|string|max:255',
            'google_analytics_enable_tracking' => 'nullable|boolean',
            'google_analytics_tracking_id' => 'nullable|string|max:255',
            'google_analytics_property_id' => 'nullable|string|max:255',
            'google_analytics_credentials_path' => 'nullable|string|max:2048',
            // Color settings validation (hex or rgba)
            'top_bar_bg_light' => 'nullable|string|max:25',
            'top_bar_text_light' => 'nullable|string|max:25',
            'top_bar_bg_dark' => 'nullable|string|max:25',
            'top_bar_text_dark' => 'nullable|string|max:25',
            'header_bg_light' => 'nullable|string|max:25',
            'header_text_light' => 'nullable|string|max:25',
            'header_bg_dark' => 'nullable|string|max:25',
            'header_text_dark' => 'nullable|string|max:25',
            'accent_color_light' => 'nullable|string|max:25',
            'accent_color_dark' => 'nullable|string|max:25',
            // Contact & Social Validation
            'site_name' => 'nullable|string|max:255',
            'contact_email' => 'nullable|email|max:255',
            'whatsapp_number' => 'nullable|string|max:25',
            'whatsapp_default_message' => 'nullable|string|max:500',
            'social_facebook_url' => 'nullable|url|max:255',
            'social_linkedin_url' => 'nullable|url|max:255',
            'social_youtube_url' => 'nullable|url|max:255',
            'social_twitter_url' => 'nullable|url|max:255',
            'social_tiktok_url' => 'nullable|url|max:255',
            'social_instagram_url' => 'nullable|url|max:255',
        ]);

        Setting::updateOrCreate(
            ['key' => 'landingpage_active_theme'],
            [
                'name' => 'Landing Page Active Theme', // Human-readable name
                'value' => $request->input('landingpage_active_theme')
            ]
        );

        Setting::updateOrCreate(
            ['key' => 'site_direction'],
            [
                'name' => 'Site Text Direction',
                'value' => $request->input('site_direction', 'ltr')
            ]
        );


        Setting::updateOrCreate(
            ['key' => 'site_name'],
            [
                'name' => 'Site Name',
                'value' => $request->input('site_name', config('app.name'))
            ]
        );

        Setting::updateOrCreate(
            ['key' => 'top_bar_tagline'],
            [
                'name' => 'Top Bar Tagline',
                'value' => $request->input('top_bar_tagline', '')
            ]
        );

        // Google Analytics Settings
        Setting::updateOrCreate(
            ['key' => 'google_analytics_enable_tracking'],
            [
                'name' => 'Enable Google Analytics Tracking',
                'value' => $request->has('google_analytics_enable_tracking') ? '1' : '0'
            ]
        );
        Setting::updateOrCreate(
            ['key' => 'google_analytics_tracking_id'],
            [
                'name' => 'Google Analytics Tracking ID',
                'value' => $request->input('google_analytics_tracking_id', '')
            ]
        );
        Setting::updateOrCreate(
            ['key' => 'google_analytics_property_id'],
            [
                'name' => 'Google Analytics Property ID',
                'value' => $request->input('google_analytics_property_id', '')
            ]
        );
        Setting::updateOrCreate(
            ['key' => 'google_analytics_credentials_path'],
            [
                'name' => 'Google Analytics Credentials Path',
                'value' => $request->input('google_analytics_credentials_path', '')
            ]
        );
        
        // Contact & Social Settings
        $contactSocialKeys = [
            'contact_email' => 'Contact Email',
            'whatsapp_number' => 'WhatsApp Number',
            'whatsapp_default_message' => 'WhatsApp Default Message',
            'social_facebook_url' => 'Facebook URL',
            'social_linkedin_url' => 'LinkedIn URL',
            'social_youtube_url' => 'YouTube URL',
            'social_twitter_url' => 'Twitter (X) URL',
            'social_tiktok_url' => 'TikTok URL',
            'social_instagram_url' => 'Instagram URL',
        ];
        foreach ($contactSocialKeys as $key => $name) {
            Setting::updateOrCreate(
                ['key' => $key], 
                [
                    'name' => $name,
                    'value' => $request->input($key, ($key === 'whatsapp_default_message' ? 'Hello! I have a question.' : ''))
                    // Provide a specific default for whatsapp_default_message if it's empty
                ]
            );
        }

        // Save Color Settings
        $colorKeys = [
            'top_bar_bg_light', 'top_bar_text_light', 'top_bar_bg_dark', 'top_bar_text_dark',
            'header_bg_light', 'header_text_light', 'header_bg_dark', 'header_text_dark',
            'accent_color_light', 'accent_color_dark',
        ];

        foreach ($colorKeys as $colorKey) {
            if ($request->has($colorKey)) {
                Setting::updateOrCreate(
                    ['key' => $colorKey], 
                    [
                        'name' => Str::title(str_replace('_', ' ', $colorKey)), // Generate a name from the key
                        'value' => $request->input($colorKey)
                    ]
                );
            }
        }


        // Save other theme-specific settings here

        Artisan::call('cache:clear');
        Artisan::call('config:clear'); // Clear config cache as settings might be cached

        return redirect()->back()->with('success', 'Theme settings updated successfully.');
    }

    protected function getAvailableThemes(): array
    {
        $themes = [];
        $themePath = module_path('LandingPage', 'Resources/views/themes');

        if (File::isDirectory($themePath)) {
            $directories = File::directories($themePath);
            foreach ($directories as $directory) {
                $themeName = basename($directory);
                // You could read a theme.json file here for more theme details (name, author, screenshot)
                $themes[$themeName] = ucfirst(str_replace('_', ' ', $themeName));
            }
        }
        return $themes;
    }
}