@extends('layouts.dashboard')

@section('title', 'System Settings')

@section('content')
<div class="container mx-auto px-4 py-6">
    <!-- Header -->
    <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-8">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">System Settings</h1>
            <p class="text-gray-600 mt-1">Configure your system preferences and options</p>
        </div>
        <div class="flex flex-wrap items-center gap-3 mt-4 md:mt-0">
            <form action="{{ route('settings.clear-cache') }}" method="POST" class="inline">
                @csrf
                <button type="submit" 
                        class="inline-flex items-center px-4 py-2.5 bg-gray-600 hover:bg-gray-700 text-white font-medium rounded-lg transition duration-200">
                    <i class="fas fa-sync-alt mr-2"></i> Clear Cache
                </button>
            </form>
            <form action="{{ route('settings.seed') }}" method="POST" class="inline">
                @csrf
                <button type="submit" 
                        class="inline-flex items-center px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-medium rounded-lg transition duration-200">
                    <i class="fas fa-database mr-2"></i> Seed Defaults
                </button>
            </form>
        </div>
    </div>

    <!-- Settings Tabs -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden mb-8">
        <!-- Tabs Navigation -->
        <div class="border-b border-gray-200 bg-gradient-to-r from-gray-50 to-gray-100">
            <nav class="flex flex-wrap -mb-px">
                <a href="#general" 
                   class="tab-link active py-4 px-6 text-sm font-medium text-center border-b-2 border-blue-600 text-blue-600">
                    <i class="fas fa-cog mr-2"></i> General
                </a>
                <a href="#appearance" 
                   class="tab-link py-4 px-6 text-sm font-medium text-center border-b-2 border-transparent text-gray-600 hover:text-blue-600 hover:border-blue-300 transition duration-200">
                    <i class="fas fa-palette mr-2"></i> Appearance
                </a>
                <a href="#email" 
                   class="tab-link py-4 px-6 text-sm font-medium text-center border-b-2 border-transparent text-gray-600 hover:text-blue-600 hover:border-blue-300 transition duration-200">
                    <i class="fas fa-envelope mr-2"></i> Email
                </a>
                <a href="#map" 
                   class="tab-link py-4 px-6 text-sm font-medium text-center border-b-2 border-transparent text-gray-600 hover:text-blue-600 hover:border-blue-300 transition duration-200">
                    <i class="fas fa-map-marked-alt mr-2"></i> Map & GPS
                </a>
                <a href="#security" 
                   class="tab-link py-4 px-6 text-sm font-medium text-center border-b-2 border-transparent text-gray-600 hover:text-blue-600 hover:border-blue-300 transition duration-200">
                    <i class="fas fa-shield-alt mr-2"></i> Security
                </a>
                <a href="#payment" 
                   class="tab-link py-4 px-6 text-sm font-medium text-center border-b-2 border-transparent text-gray-600 hover:text-blue-600 hover:border-blue-300 transition duration-200">
                    <i class="fas fa-money-bill-wave mr-2"></i> Payment
                </a>
                <a href="#notification" 
                   class="tab-link py-4 px-6 text-sm font-medium text-center border-b-2 border-transparent text-gray-600 hover:text-blue-600 hover:border-blue-300 transition duration-200">
                    <i class="fas fa-bell mr-2"></i> Notifications
                </a>
            </nav>
        </div>

        <form action="{{ route('settings.update') }}" method="POST" enctype="multipart/form-data" id="settingsForm">
            @csrf
            @method('PUT')

            <!-- General Settings -->
            <div id="general" class="tab-content p-6 active">
                <div class="mb-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                        <i class="fas fa-cog mr-3 text-blue-500"></i>General Settings
                    </h3>
                    <p class="text-sm text-gray-600 mb-6">Configure basic system settings and preferences</p>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    @php
                        $generalSettings = $settings['general'] ?? collect();
                    @endphp
                    
                    @forelse($generalSettings as $setting)
                    <div class="space-y-2">
                        <div class="flex items-center justify-between">
                            <label class="block text-sm font-medium text-gray-700">{{ $setting->label }}</label>
                            @if($setting->is_required)
                            <span class="text-xs text-red-500">Required</span>
                            @endif
                        </div>
                        
                        @if($setting->description)
                        <p class="text-xs text-gray-500">{{ $setting->description }}</p>
                        @endif
                        
                        @if($setting->type == 'text')
                        <input type="text" 
                               name="{{ $setting->key }}" 
                               value="{{ old($setting->key, $setting->value) }}"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                               {{ $setting->is_required ? 'required' : '' }}>
                        
                        @elseif($setting->type == 'textarea')
                        <textarea name="{{ $setting->key }}" 
                                  rows="3"
                                  class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                                  {{ $setting->is_required ? 'required' : '' }}>{{ old($setting->key, $setting->value) }}</textarea>
                        
                        @elseif($setting->type == 'email')
                        <input type="email" 
                               name="{{ $setting->key }}" 
                               value="{{ old($setting->key, $setting->value) }}"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                               {{ $setting->is_required ? 'required' : '' }}>
                        
                        @elseif($setting->type == 'number')
                        <input type="number" 
                               name="{{ $setting->key }}" 
                               value="{{ old($setting->key, $setting->value) }}"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                               {{ $setting->is_required ? 'required' : '' }}>
                        
                        @elseif($setting->type == 'select')
                        <select name="{{ $setting->key }}" 
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                                {{ $setting->is_required ? 'required' : '' }}>
                            <option value="">Select Option</option>
                            @foreach(json_decode($setting->options, true) as $value => $label)
                            <option value="{{ $value }}" {{ old($setting->key, $setting->value) == $value ? 'selected' : '' }}>
                                {{ $label }}
                            </option>
                            @endforeach
                        </select>
                        @endif
                    </div>
                    @empty
                    <div class="md:col-span-2 text-center py-12">
                        <div class="w-20 h-20 mx-auto mb-4 text-gray-300">
                            <i class="fas fa-cog text-5xl"></i>
                        </div>
                        <h4 class="text-lg font-semibold text-gray-700 mb-2">No Settings Found</h4>
                        <p class="text-gray-500 mb-6 max-w-md mx-auto">No general settings configured. Please seed default settings.</p>
                        <form action="{{ route('settings.seed') }}" method="POST" class="inline">
                            @csrf
                            <button type="submit" 
                                    class="inline-flex items-center px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition duration-200">
                                <i class="fas fa-database mr-2"></i> Seed Default Settings
                            </button>
                        </form>
                    </div>
                    @endforelse
                </div>
            </div>

            <!-- Appearance Settings -->
            <div id="appearance" class="tab-content hidden p-6">
                <div class="mb-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                        <i class="fas fa-palette mr-3 text-purple-500"></i>Appearance Settings
                    </h3>
                    <p class="text-sm text-gray-600 mb-6">Customize the look and feel of your application</p>
                </div>
                
                <div class="space-y-8">
                    <!-- Logo Upload -->
                    <div class="bg-gradient-to-r from-purple-50 to-purple-100 rounded-xl p-5 border border-purple-200">
                        <div class="flex items-center mb-4">
                            <div class="w-10 h-10 rounded-lg bg-purple-100 text-purple-600 flex items-center justify-center mr-3">
                                <i class="fas fa-image"></i>
                            </div>
                            <h4 class="font-semibold text-purple-800">Logo & Images</h4>
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <!-- Logo -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Logo</label>
                                <p class="text-xs text-gray-500 mb-3">Upload your company logo (Recommended: 200x60px, PNG/SVG)</p>
                                <div class="space-y-4">
                                    @php
                                        $logoSetting = ($settings['appearance'] ?? collect())->where('key', 'logo')->first();
                                        $logoValue = $logoSetting->value ?? null;
                                    @endphp
                                    
                                    @if($logoValue)
                                    <div class="flex items-center justify-center p-4 bg-white rounded-lg border border-gray-200">
                                        <img src="{{ Storage::url($logoValue) }}" 
                                             alt="Logo" 
                                             class="max-w-[200px] max-h-[60px]">
                                    </div>
                                    @endif
                                    
                                    <div class="relative">
                                        <input type="file" 
                                               name="logo" 
                                               accept="image/*"
                                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                                    </div>
                                </div>
                            </div>

                            <!-- Favicon -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Favicon</label>
                                <p class="text-xs text-gray-500 mb-3">Upload favicon (Recommended: 32x32px, ICO/PNG)</p>
                                <div class="space-y-4">
                                    @php
                                        $faviconSetting = ($settings['appearance'] ?? collect())->where('key', 'favicon')->first();
                                        $faviconValue = $faviconSetting->value ?? null;
                                    @endphp
                                    
                                    @if($faviconValue)
                                    <div class="flex items-center justify-center p-4 bg-white rounded-lg border border-gray-200">
                                        <img src="{{ Storage::url($faviconValue) }}" 
                                             alt="Favicon" 
                                             class="max-w-[32px] max-h-[32px]">
                                    </div>
                                    @endif
                                    
                                    <div class="relative">
                                        <input type="file" 
                                               name="favicon" 
                                               accept="image/*"
                                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Theme Settings -->
                    @php
                        $appearanceSettings = $settings['appearance'] ?? collect();
                        $themeSettings = $appearanceSettings->whereNotIn('key', ['logo', 'favicon', 'login_background']);
                    @endphp
                    
                    @if($themeSettings->isNotEmpty())
                    <div class="bg-gradient-to-r from-blue-50 to-blue-100 rounded-xl p-5 border border-blue-200">
                        <div class="flex items-center mb-4">
                            <div class="w-10 h-10 rounded-lg bg-blue-100 text-blue-600 flex items-center justify-center mr-3">
                                <i class="fas fa-paint-brush"></i>
                            </div>
                            <h4 class="font-semibold text-blue-800">Theme Settings</h4>
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            @foreach($themeSettings as $setting)
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">{{ $setting->label }}</label>
                                @if($setting->description)
                                <p class="text-xs text-gray-500 mb-3">{{ $setting->description }}</p>
                                @endif
                                
                                @if($setting->type == 'select')
                                <select name="{{ $setting->key }}" 
                                        class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200">
                                    @foreach(json_decode($setting->options, true) as $value => $label)
                                    <option value="{{ $value }}" {{ old($setting->key, $setting->value) == $value ? 'selected' : '' }}>
                                        {{ $label }}
                                    </option>
                                    @endforeach
                                </select>
                                
                                @elseif($setting->type == 'color')
                                <div class="flex items-center space-x-3">
                                    <div class="relative">
                                        <input type="color" 
                                               name="{{ $setting->key }}_color" 
                                               value="{{ old($setting->key . '_color', $setting->value) }}"
                                               class="w-12 h-12 p-1 border border-gray-300 rounded-lg cursor-pointer">
                                    </div>
                                    <div class="flex-1">
                                        <input type="text" 
                                               name="{{ $setting->key }}" 
                                               value="{{ old($setting->key, $setting->value) }}"
                                               placeholder="#000000"
                                               pattern="^#[0-9A-F]{6}$"
                                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200">
                                    </div>
                                </div>
                                @endif
                            </div>
                            @endforeach
                        </div>
                    </div>
                    @endif
                    
                    @if($appearanceSettings->isEmpty())
                    <div class="text-center py-12">
                        <div class="w-20 h-20 mx-auto mb-4 text-gray-300">
                            <i class="fas fa-palette text-5xl"></i>
                        </div>
                        <h4 class="text-lg font-semibold text-gray-700 mb-2">No Appearance Settings</h4>
                        <p class="text-gray-500 mb-6 max-w-md mx-auto">No appearance settings configured. Please seed default settings.</p>
                    </div>
                    @endif
                </div>
            </div>

            <!-- Email Settings -->
            <div id="email" class="tab-content hidden p-6">
                <div class="mb-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                        <i class="fas fa-envelope mr-3 text-emerald-500"></i>Email Settings
                    </h3>
                    <p class="text-sm text-gray-600 mb-6">Configure email server and notification settings</p>
                </div>
                
                <div class="space-y-6">
                    @php
                        $emailSettings = $settings['email'] ?? collect();
                    @endphp
                    
                    @forelse($emailSettings as $setting)
                    <div>
                        <div class="flex items-center justify-between mb-2">
                            <label class="block text-sm font-medium text-gray-700">{{ $setting->label }}</label>
                            @if($setting->is_required)
                            <span class="text-xs text-red-500">Required</span>
                            @endif
                        </div>
                        
                        @if($setting->description)
                        <p class="text-xs text-gray-500 mb-3">{{ $setting->description }}</p>
                        @endif
                        
                        @if($setting->type == 'password')
                        <div class="relative">
                            <input type="password" 
                                   name="{{ $setting->key }}" 
                                   value="{{ old($setting->key, $setting->value) }}"
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                                   autocomplete="new-password"
                                   {{ $setting->is_required ? 'required' : '' }}>
                            <button type="button" 
                                    class="absolute right-3 top-3 text-gray-400 hover:text-gray-600 toggle-password"
                                    onclick="togglePassword(this)">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        
                        @elseif($setting->type == 'select')
                        <select name="{{ $setting->key }}" 
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                                {{ $setting->is_required ? 'required' : '' }}>
                            <option value="">Select Option</option>
                            @foreach(json_decode($setting->options, true) as $value => $label)
                            <option value="{{ $value }}" {{ old($setting->key, $setting->value) == $value ? 'selected' : '' }}>
                                {{ $label }}
                            </option>
                            @endforeach
                        </select>
                        
                        @else
                        <input type="{{ $setting->type }}" 
                               name="{{ $setting->key }}" 
                               value="{{ old($setting->key, $setting->value) }}"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                               {{ $setting->is_required ? 'required' : '' }}>
                        @endif
                    </div>
                    @empty
                    <div class="text-center py-12">
                        <div class="w-20 h-20 mx-auto mb-4 text-gray-300">
                            <i class="fas fa-envelope text-5xl"></i>
                        </div>
                        <h4 class="text-lg font-semibold text-gray-700 mb-2">No Email Settings</h4>
                        <p class="text-gray-500 mb-6 max-w-md mx-auto">No email settings configured. Please seed default settings.</p>
                    </div>
                    @endforelse
                </div>
                
                @if($emailSettings->isNotEmpty())
                <div class="mt-8 pt-6 border-t border-gray-200">
                    <button type="button" 
                            onclick="testEmail()" 
                            class="inline-flex items-center px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-medium rounded-lg transition duration-200">
                        <i class="fas fa-paper-plane mr-2"></i> Test Email Configuration
                    </button>
                    <p class="text-xs text-gray-500 mt-2">Send a test email to verify your configuration</p>
                </div>
                @endif
            </div>

            <!-- Map & GPS Settings -->
            <div id="map" class="tab-content hidden p-6">
                <div class="mb-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                        <i class="fas fa-map-marked-alt mr-3 text-blue-500"></i>Map & GPS Settings
                    </h3>
                    <p class="text-sm text-gray-600 mb-6">Configure map providers and GPS tracking settings</p>
                </div>
                
                <div class="space-y-6">
                    @php
                        $mapSettings = $settings['map'] ?? collect();
                    @endphp
                    
                    @forelse($mapSettings as $setting)
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">{{ $setting->label }}</label>
                        @if($setting->description)
                        <p class="text-xs text-gray-500 mb-3">{{ $setting->description }}</p>
                        @endif
                        
                        @if($setting->type == 'select')
                        <select name="{{ $setting->key }}" 
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200">
                            @foreach(json_decode($setting->options, true) as $value => $label)
                            <option value="{{ $value }}" {{ old($setting->key, $setting->value) == $value ? 'selected' : '' }}>
                                {{ $label }}
                            </option>
                            @endforeach
                        </select>
                        
                        @else
                        <input type="{{ $setting->type }}" 
                               name="{{ $setting->key }}" 
                               value="{{ old($setting->key, $setting->value) }}"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200">
                        @endif
                    </div>
                    @empty
                    <div class="text-center py-12">
                        <div class="w-20 h-20 mx-auto mb-4 text-gray-300">
                            <i class="fas fa-map-marked-alt text-5xl"></i>
                        </div>
                        <h4 class="text-lg font-semibold text-gray-700 mb-2">No Map Settings</h4>
                        <p class="text-gray-500 mb-6 max-w-md mx-auto">No map settings configured. Please seed default settings.</p>
                    </div>
                    @endforelse
                </div>
                
                <!-- Map Preview -->
                @if($mapSettings->isNotEmpty())
                <div class="mt-8 pt-6 border-t border-gray-200">
                    <div class="flex items-center mb-4">
                        <div class="w-8 h-8 rounded-lg bg-blue-100 text-blue-600 flex items-center justify-center mr-3">
                            <i class="fas fa-map"></i>
                        </div>
                        <h4 class="font-semibold text-gray-700">Map Preview</h4>
                    </div>
                    
                    <div id="mapPreview" class="h-80 bg-gradient-to-br from-gray-50 to-gray-100 rounded-xl border-2 border-gray-300 border-dashed">
                        <div class="flex flex-col items-center justify-center h-full text-gray-500 p-6">
                            <i class="fas fa-map-marked-alt text-5xl mb-4"></i>
                            <p class="text-lg font-medium text-gray-600 mb-2">Map Preview</p>
                            <p class="text-sm text-gray-500 mb-4">Configure your map settings and save to see preview</p>
                            <button type="button" 
                                    onclick="initializeMapPreview()" 
                                    class="inline-flex items-center px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition duration-200">
                                <i class="fas fa-map mr-2"></i> Load Map Preview
                            </button>
                        </div>
                    </div>
                </div>
                @endif
            </div>

            <!-- Security Settings -->
            <div id="security" class="tab-content hidden p-6">
                <div class="mb-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                        <i class="fas fa-shield-alt mr-3 text-red-500"></i>Security Settings
                    </h3>
                    <p class="text-sm text-gray-600 mb-6">Configure security policies and authentication settings</p>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    @php
                        $securitySettings = $settings['security'] ?? collect();
                    @endphp
                    
                    @forelse($securitySettings as $setting)
                    <div class="bg-gradient-to-br from-gray-50 to-white rounded-xl p-5 border border-gray-200">
                        <div class="flex items-center justify-between mb-3">
                            <label class="block text-sm font-medium text-gray-700">{{ $setting->label }}</label>
                            @if($setting->is_required)
                            <span class="text-xs text-red-500">Required</span>
                            @endif
                        </div>
                        
                        @if($setting->description)
                        <p class="text-xs text-gray-500 mb-4">{{ $setting->description }}</p>
                        @endif
                        
                        @if($setting->type == 'checkbox')
                        <label class="flex items-center cursor-pointer">
                            <div class="relative">
                                <input type="hidden" name="{{ $setting->key }}" value="0">
                                <input type="checkbox" 
                                       name="{{ $setting->key }}" 
                                       value="1"
                                       {{ old($setting->key, $setting->value) == '1' ? 'checked' : '' }}
                                       class="sr-only">
                                <div class="block bg-gray-300 w-10 h-6 rounded-full toggle-bg"></div>
                                <div class="dot absolute left-1 top-1 bg-white w-4 h-4 rounded-full transition"></div>
                            </div>
                            <span class="ml-3 text-sm font-medium text-gray-700">
                                {{ old($setting->key, $setting->value) == '1' ? 'Enabled' : 'Disabled' }}
                            </span>
                        </label>
                        
                        @else
                        <input type="{{ $setting->type }}" 
                               name="{{ $setting->key }}" 
                               value="{{ old($setting->key, $setting->value) }}"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                               {{ $setting->is_required ? 'required' : '' }}>
                        @endif
                    </div>
                    @empty
                    <div class="md:col-span-2 text-center py-12">
                        <div class="w-20 h-20 mx-auto mb-4 text-gray-300">
                            <i class="fas fa-shield-alt text-5xl"></i>
                        </div>
                        <h4 class="text-lg font-semibold text-gray-700 mb-2">No Security Settings</h4>
                        <p class="text-gray-500 mb-6 max-w-md mx-auto">No security settings configured. Please seed default settings.</p>
                    </div>
                    @endforelse
                </div>
            </div>

            <!-- Payment Settings -->
            <div id="payment" class="tab-content hidden p-6">
                <div class="mb-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                        <i class="fas fa-money-bill-wave mr-3 text-purple-500"></i>Payment Settings
                    </h3>
                    <p class="text-sm text-gray-600 mb-6">Configure payment gateway and transaction settings</p>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    @php
                        $paymentSettings = $settings['payment'] ?? collect();
                    @endphp
                    
                    @forelse($paymentSettings as $setting)
                    <div>
                        <div class="flex items-center justify-between mb-2">
                            <label class="block text-sm font-medium text-gray-700">{{ $setting->label }}</label>
                            @if($setting->is_required)
                            <span class="text-xs text-red-500">Required</span>
                            @endif
                        </div>
                        
                        @if($setting->description)
                        <p class="text-xs text-gray-500 mb-3">{{ $setting->description }}</p>
                        @endif
                        
                        @if($setting->type == 'select')
                        <select name="{{ $setting->key }}" 
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                                {{ $setting->is_required ? 'required' : '' }}>
                            <option value="">Select Option</option>
                            @foreach(json_decode($setting->options, true) as $value => $label)
                            <option value="{{ $value }}" {{ old($setting->key, $setting->value) == $value ? 'selected' : '' }}>
                                {{ $label }}
                            </option>
                            @endforeach
                        </select>
                        
                        @elseif($setting->type == 'password')
                        <div class="relative">
                            <input type="password" 
                                   name="{{ $setting->key }}" 
                                   value="{{ old($setting->key, $setting->value) }}"
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                                   autocomplete="new-payment"
                                   {{ $setting->is_required ? 'required' : '' }}>
                            <button type="button" 
                                    class="absolute right-3 top-3 text-gray-400 hover:text-gray-600 toggle-payment"
                                    onclick="togglePayment(this)">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        
                        @else
                        <input type="{{ $setting->type }}" 
                               name="{{ $setting->key }}" 
                               value="{{ old($setting->key, $setting->value) }}"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                               {{ $setting->is_required ? 'required' : '' }}>
                        @endif
                    </div>
                    @empty
                    <div class="md:col-span-2 text-center py-12">
                        <div class="w-20 h-20 mx-auto mb-4 text-gray-300">
                            <i class="fas fa-money-bill-wave text-5xl"></i>
                        </div>
                        <h4 class="text-lg font-semibold text-gray-700 mb-2">No Payment Settings</h4>
                        <p class="text-gray-500 mb-6 max-w-md mx-auto">No payment settings configured. Please seed default settings.</p>
                    </div>
                    @endforelse
                </div>
            </div>

            <!-- Notification Settings -->
            <div id="notification" class="tab-content hidden p-6">
                <div class="mb-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                        <i class="fas fa-bell mr-3 text-amber-500"></i>Notification Settings
                    </h3>
                    <p class="text-sm text-gray-600 mb-6">Configure notification preferences and delivery methods</p>
                </div>
                
                <div class="space-y-6">
                    @php
                        $notificationSettings = $settings['notification'] ?? collect();
                    @endphp
                    
                    @forelse($notificationSettings as $setting)
                    <div class="bg-gradient-to-br from-gray-50 to-white rounded-xl p-5 border border-gray-200">
                        <div class="flex items-center justify-between mb-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ $setting->label }}</label>
                                @if($setting->description)
                                <p class="text-xs text-gray-500 mt-1">{{ $setting->description }}</p>
                                @endif
                            </div>
                            <label class="flex items-center cursor-pointer">
                                <div class="relative">
                                    <input type="hidden" name="{{ $setting->key }}" value="0">
                                    <input type="checkbox" 
                                           name="{{ $setting->key }}" 
                                           value="1"
                                           {{ old($setting->key, $setting->value) == '1' ? 'checked' : '' }}
                                           class="sr-only notification-toggle">
                                    <div class="block bg-gray-300 w-10 h-6 rounded-full toggle-bg"></div>
                                    <div class="dot absolute left-1 top-1 bg-white w-4 h-4 rounded-full transition"></div>
                                </div>
                                <span class="ml-3 text-sm font-medium text-gray-700">
                                    {{ old($setting->key, $setting->value) == '1' ? 'Enabled' : 'Disabled' }}
                                </span>
                            </label>
                        </div>
                    </div>
                    @empty
                    <div class="text-center py-12">
                        <div class="w-20 h-20 mx-auto mb-4 text-gray-300">
                            <i class="fas fa-bell text-5xl"></i>
                        </div>
                        <h4 class="text-lg font-semibold text-gray-700 mb-2">No Notification Settings</h4>
                        <p class="text-gray-500 mb-6 max-w-md mx-auto">No notification settings configured. Please seed default settings.</p>
                    </div>
                    @endforelse
                </div>
            </div>

            <!-- Form Actions -->
            <div class="px-6 py-5 border-t border-gray-200 bg-gradient-to-r from-gray-50 to-gray-100">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                    <div class="mb-4 md:mb-0">
                        <p class="text-sm text-gray-600 flex items-center">
                            <i class="fas fa-info-circle mr-2 text-blue-500"></i> Changes may require cache clearing to take effect
                        </p>
                    </div>
                    <div class="flex items-center space-x-3">
                        <button type="reset" 
                                class="px-5 py-3 border border-gray-300 text-gray-700 font-medium rounded-lg hover:bg-gray-50 transition duration-200">
                            <i class="fas fa-redo mr-2"></i> Reset
                        </button>
                        <button type="submit" 
                                class="px-5 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition duration-200 shadow-sm hover:shadow-md">
                            <i class="fas fa-save mr-2"></i> Save Settings
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- System Information -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <!-- Section Header -->
        <div class="px-6 py-5 border-b border-gray-200 bg-gradient-to-r from-gray-50 to-gray-100">
            <h3 class="text-lg font-semibold text-gray-900">System Information</h3>
            <p class="text-sm text-gray-600 mt-1">View system status and technical details</p>
        </div>
        
        <div class="p-6">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
                <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-5 border border-blue-200">
                    <div class="flex items-center mb-3">
                        <div class="w-10 h-10 rounded-lg bg-blue-100 text-blue-600 flex items-center justify-center mr-3">
                            <i class="fab fa-php"></i>
                        </div>
                        <div>
                            <div class="text-sm text-gray-600">PHP Version</div>
                            <div class="text-xl font-bold text-gray-900">{{ phpversion() }}</div>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-red-50 to-red-100 rounded-xl p-5 border border-red-200">
                    <div class="flex items-center mb-3">
                        <div class="w-10 h-10 rounded-lg bg-red-100 text-red-600 flex items-center justify-center mr-3">
                            <i class="fab fa-laravel"></i>
                        </div>
                        <div>
                            <div class="text-sm text-gray-600">Laravel Version</div>
                            <div class="text-xl font-bold text-gray-900">{{ app()->version() }}</div>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-emerald-50 to-emerald-100 rounded-xl p-5 border border-emerald-200">
                    <div class="flex items-center mb-3">
                        <div class="w-10 h-10 rounded-lg bg-emerald-100 text-emerald-600 flex items-center justify-center mr-3">
                            <i class="fas fa-server"></i>
                        </div>
                        <div>
                            <div class="text-sm text-gray-600">Environment</div>
                            <div class="text-xl font-bold text-gray-900">{{ app()->environment() }}</div>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-5 border border-purple-200">
                    <div class="flex items-center mb-3">
                        <div class="w-10 h-10 rounded-lg bg-purple-100 text-purple-600 flex items-center justify-center mr-3">
                            <i class="fas fa-database"></i>
                        </div>
                        <div>
                            <div class="text-sm text-gray-600">Database</div>
                            <div class="text-xl font-bold text-gray-900">{{ \DB::connection()->getDatabaseName() }}</div>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-amber-50 to-amber-100 rounded-xl p-5 border border-amber-200">
                    <div class="flex items-center mb-3">
                        <div class="w-10 h-10 rounded-lg bg-amber-100 text-amber-600 flex items-center justify-center mr-3">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div>
                            <div class="text-sm text-gray-600">Timezone</div>
                            <div class="text-xl font-bold text-gray-900">{{ config('app.timezone') }}</div>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-gray-50 to-gray-100 rounded-xl p-5 border border-gray-200">
                    <div class="flex items-center mb-3">
                        <div class="w-10 h-10 rounded-lg bg-gray-100 text-gray-600 flex items-center justify-center mr-3">
                            <i class="fas fa-hdd"></i>
                        </div>
                        <div>
                            <div class="text-sm text-gray-600">Storage</div>
                            <div class="text-xl font-bold text-gray-900">
                                @php
                                    $free = disk_free_space('/');
                                    $total = disk_total_space('/');
                                    $used = $total - $free;
                                    $percentage = ($used / $total) * 100;
                                @endphp
                                {{ number_format($percentage, 1) }}% used
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Leaflet for Map Preview -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<script>
// Tab functionality
document.addEventListener('DOMContentLoaded', function() {
    // Initialize tabs
    const tabLinks = document.querySelectorAll('.tab-link');
    const tabContents = document.querySelectorAll('.tab-content');
    
    tabLinks.forEach(tab => {
        tab.addEventListener('click', function(e) {
            e.preventDefault();
            
            // Remove active class from all tabs
            tabLinks.forEach(t => {
                t.classList.remove('active', 'border-blue-600', 'text-blue-600');
                t.classList.add('text-gray-600', 'border-transparent');
            });
            
            // Add active class to clicked tab
            this.classList.add('active', 'border-blue-600', 'text-blue-600');
            this.classList.remove('text-gray-600', 'border-transparent');
            
            // Hide all tab contents
            tabContents.forEach(content => {
                content.classList.add('hidden');
                content.classList.remove('active');
            });
            
            // Show clicked tab content
            const tabId = this.getAttribute('href');
            const tabContent = document.querySelector(tabId);
            if (tabContent) {
                tabContent.classList.remove('hidden');
                tabContent.classList.add('active');
                
                // Initialize map preview when map tab is clicked
                if (tabId === '#map') {
                    // We'll load map on button click instead
                }
            }
        });
    });
    
    // Toggle password visibility
    function togglePassword(button) {
        const input = button.previousElementSibling;
        const icon = button.querySelector('i');
        
        if (input.type === 'password') {
            input.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            input.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
    }
    
    // Toggle payment visibility
    function togglePayment(button) {
        const input = button.previousElementSibling;
        const icon = button.querySelector('i');
        
        if (input.type === 'password') {
            input.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            input.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
    }
    
    // Color picker synchronization
    document.querySelectorAll('input[type="color"]').forEach(colorPicker => {
        const textInput = colorPicker.parentElement.nextElementSibling?.querySelector('input[type="text"]');
        
        if (textInput) {
            colorPicker.addEventListener('input', function() {
                textInput.value = this.value;
            });
            
            textInput.addEventListener('input', function() {
                if (this.value.match(/^#[0-9A-F]{6}$/i)) {
                    colorPicker.value = this.value;
                }
            });
            
            // Initialize color picker with text input value
            if (textInput.value && textInput.value.match(/^#[0-9A-F]{6}$/i)) {
                colorPicker.value = textInput.value;
            }
        }
    });
    
    // Toggle switch functionality
    document.querySelectorAll('input[type="checkbox"].sr-only').forEach(checkbox => {
        const container = checkbox.closest('label');
        if (!container) return;
        
        const toggleBg = container.querySelector('.toggle-bg');
        const dot = container.querySelector('.dot');
        const statusText = container.querySelector('span.text-gray-700');
        
        if (!toggleBg || !dot || !statusText) return;
        
        checkbox.addEventListener('change', function() {
            if (this.checked) {
                toggleBg.classList.remove('bg-gray-300');
                toggleBg.classList.add('bg-green-500');
                dot.classList.remove('left-1');
                dot.classList.add('left-5');
                statusText.textContent = 'Enabled';
            } else {
                toggleBg.classList.remove('bg-green-500');
                toggleBg.classList.add('bg-gray-300');
                dot.classList.remove('left-5');
                dot.classList.add('left-1');
                statusText.textContent = 'Disabled';
            }
        });
        
        // Initialize toggle state
        if (checkbox.checked) {
            toggleBg.classList.add('bg-green-500');
            dot.classList.add('left-5');
            statusText.textContent = 'Enabled';
        } else {
            toggleBg.classList.add('bg-gray-300');
            dot.classList.add('left-1');
            statusText.textContent = 'Disabled';
        }
    });
});

// Test email configuration
function testEmail() {
    const userEmail = '{{ auth()->user()->email ?? "admin@example.com" }}';
    
    if (confirm('Send test email to ' + userEmail + '?')) {
        const button = event.target;
        const originalText = button.innerHTML;
        button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Sending...';
        button.disabled = true;
        
        fetch('{{ route("settings.test-email") }}', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            // Show success message
            showNotification('success', data.message || 'Test email sent successfully!');
        })
        .catch(error => {
            console.error('Error sending test email:', error);
            showNotification('error', 'Error sending test email. Please check your configuration.');
        })
        .finally(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        });
    }
}

// Initialize map preview
function initializeMapPreview() {
    const mapContainer = document.getElementById('mapPreview');
    if (!mapContainer) return;
    
    // Clear existing content and show loading
    mapContainer.innerHTML = `
        <div class="flex flex-col items-center justify-center h-full text-gray-500 p-6">
            <div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mb-4"></div>
            <p class="text-lg font-medium text-gray-600 mb-2">Loading Map...</p>
            <p class="text-sm text-gray-500">Please wait while we load the map preview</p>
        </div>
    `;
    
    // Get map settings values with defaults
    const latInput = document.querySelector('input[name="default_latitude"]');
    const lngInput = document.querySelector('input[name="default_longitude"]');
    const zoomInput = document.querySelector('input[name="default_zoom"]');
    
    const lat = parseFloat(latInput?.value || 30.0444);
    const lng = parseFloat(lngInput?.value || 31.2357);
    const zoom = parseInt(zoomInput?.value || 12);
    
    // Use setTimeout to ensure DOM is updated before creating map
    setTimeout(() => {
        mapContainer.innerHTML = '';
        
        try {
            const map = L.map(mapContainer).setView([lat, lng], zoom);
            
            // Use OpenStreetMap
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
                maxZoom: 19
            }).addTo(map);
            
            // Add marker with custom icon
            const customIcon = L.divIcon({
                className: 'custom-marker',
                html: '<div class="w-8 h-8 bg-blue-600 rounded-full border-4 border-white shadow-lg flex items-center justify-center"><i class="fas fa-map-marker-alt text-white"></i></div>',
                iconSize: [32, 32],
                iconAnchor: [16, 32]
            });
            
            const marker = L.marker([lat, lng], { icon: customIcon }).addTo(map);
            
            // Add popup
            marker.bindPopup(`
                <div class="p-2">
                    <div class="font-semibold text-gray-900">Default Location</div>
                    <div class="text-sm text-gray-600 mt-1">
                        Latitude: ${lat}<br>
                        Longitude: ${lng}<br>
                        Zoom: ${zoom}
                    </div>
                </div>
            `).openPopup();
            
            // Add scale control
            L.control.scale().addTo(map);
            
        } catch (error) {
            console.error('Error creating map:', error);
            mapContainer.innerHTML = `
                <div class="flex flex-col items-center justify-center h-full text-red-500 p-6">
                    <i class="fas fa-exclamation-triangle text-5xl mb-4"></i>
                    <p class="text-lg font-medium mb-2">Failed to load map</p>
                    <p class="text-sm">Please check your map settings and try again</p>
                </div>
            `;
        }
    }, 100);
}

// Form validation
document.getElementById('settingsForm')?.addEventListener('submit', function(e) {
    // Validate email settings
    const mailDriver = document.querySelector('select[name="mail_driver"]');
    if (mailDriver && mailDriver.value !== '') {
        const requiredFields = ['mail_host', 'mail_port', 'mail_username', 'mail_password'];
        let isValid = true;
        let errorMessage = '';
        
        requiredFields.forEach(field => {
            const input = document.querySelector(`[name="${field}"]`);
            if (input && !input.value.trim()) {
                isValid = false;
                errorMessage = `Please fill in ${field.replace('_', ' ')}`;
            }
        });
        
        if (!isValid) {
            e.preventDefault();
            showNotification('error', errorMessage || 'Please fill in all required email settings');
            return false;
        }
    }
    
    // Validate color fields
    const colorTextInputs = document.querySelectorAll('input[type="text"][name*="color"]');
    colorTextInputs.forEach(input => {
        if (input.value && !input.value.match(/^#[0-9A-F]{6}$/i)) {
            e.preventDefault();
            showNotification('error', `Invalid color format for ${input.name.replace('_', ' ')}. Use hex format (#RRGGBB)`);
            return false;
        }
    });
    
    // Show saving state
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Saving...';
    submitBtn.disabled = true;
    
    // Re-enable button after 5 seconds if still disabled
    setTimeout(() => {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    }, 5000);
    
    return true;
});

// Notification function
function showNotification(type, message) {
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 transform transition-transform duration-300 translate-x-full`;
    
    if (type === 'success') {
        notification.className += ' bg-emerald-50 border border-emerald-200 text-emerald-800';
        notification.innerHTML = `
            <div class="flex items-center">
                <i class="fas fa-check-circle text-emerald-500 text-xl mr-3"></i>
                <div>
                    <div class="font-semibold">Success</div>
                    <div class="text-sm">${message}</div>
                </div>
            </div>
        `;
    } else {
        notification.className += ' bg-red-50 border border-red-200 text-red-800';
        notification.innerHTML = `
            <div class="flex items-center">
                <i class="fas fa-exclamation-triangle text-red-500 text-xl mr-3"></i>
                <div>
                    <div class="font-semibold">Error</div>
                    <div class="text-sm">${message}</div>
                </div>
            </div>
        `;
    }
    
    document.body.appendChild(notification);
    
    // Animate in
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
    }, 10);
    
    // Remove after 5 seconds
    setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 5000);
}
</script>

<style>
/* Custom styles */
.tab-link.active {
    border-bottom-color: #3b82f6;
    color: #3b82f6;
}

.tab-content {
    display: none;
}

.tab-content.active {
    display: block;
}

/* Toggle switch styles */
.toggle-bg {
    transition: background-color 0.3s;
}

.dot {
    transition: transform 0.3s;
}

input[type="checkbox"]:checked ~ .toggle-bg {
    background-color: #10b981;
}

input[type="checkbox"]:checked ~ .dot {
    transform: translateX(100%);
}

/* Custom marker styles */
.custom-marker {
    background: transparent;
    border: none;
}

/* File input styling */
input[type="file"]::-webkit-file-upload-button {
    color: #1e40af;
    background: #eff6ff;
    border: 0;
    padding: 0.5rem 1rem;
    border-radius: 0.375rem;
    cursor: pointer;
}

input[type="file"]::-webkit-file-upload-button:hover {
    background: #dbeafe;
}

/* Smooth transitions */
* {
    transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform;
    transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
    transition-duration: 200ms;
}
</style>
@endsection