@extends('layouts.app')

@section('title', 'Pengaturan Sistem')

@section('content')
<div class="container mx-auto px-4 py-6">
    <div class="flex flex-col md:flex-row gap-6">
        <!-- Sidebar Navigasi Pengaturan -->
        <div class="w-full md:w-1/4">
            <div class="bg-white rounded-lg shadow-sm overflow-hidden">
                <div class="bg-blue-600 text-white px-4 py-3">
                    <h5 class="font-medium">Kategori Pengaturan</h5>
                </div>
                <div class="p-0">
                    <div class="p-3">
                        <div class="relative">
                            <input type="text" id="settingSearch" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50" placeholder="Cari pengaturan...">
                            <div class="absolute inset-y-0 right-0 flex items-center pr-3">
                                <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                </svg>
                            </div>
                        </div>
                    </div>
                    <div class="divide-y divide-gray-200">
                        @foreach($groups as $groupKey => $groupData)
                            <a href="{{ route('settings.index', ['group' => $groupKey]) }}" 
                               class="flex items-center px-4 py-3 hover:bg-gray-50 {{ $currentGroup == $groupKey ? 'bg-blue-50 text-blue-600' : 'text-gray-700' }}">
                                <i class="{{ $groupData['icon'] }} mr-2"></i>
                                <span>{{ $groupData['name'] }}</span>
                            </a>
                        @endforeach
                    </div>
                </div>
                <div class="border-t border-gray-200 px-4 py-3">
                    <div class="flex justify-between">
                        <button type="button" id="exportSettings" class="inline-flex items-center px-3 py-1.5 border border-blue-600 text-blue-600 rounded-md text-sm hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            <svg class="-ml-1 mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
                            </svg>
                            Ekspor
                        </button>
                        <button type="button" id="importSettings" class="inline-flex items-center px-3 py-1.5 border border-green-600 text-green-600 rounded-md text-sm hover:bg-green-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                            <svg class="-ml-1 mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"></path>
                            </svg>
                            Impor
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Konten Pengaturan -->
        <div class="w-full md:w-3/4">
            <div class="bg-white rounded-lg shadow-sm overflow-hidden">
                <div class="bg-blue-600 text-white px-4 py-3 flex justify-between items-center">
                    <h4 class="font-medium">{{ $groups[$currentGroup]['name'] }}</h4>
                    <button type="button" id="resetSettings" class="inline-flex items-center px-3 py-1.5 border border-white text-white rounded-md text-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <svg class="-ml-1 mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                        </svg>
                        Reset
                    </button>
                </div>
                <div class="p-6">
                    @if (session('success'))
                        <div class="bg-green-50 border-l-4 border-green-400 p-4 mb-6">
                            <div class="flex">
                                <div class="flex-shrink-0">
                                    <svg class="h-5 w-5 text-green-400" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
                                    </svg>
                                </div>
                                <div class="ml-3">
                                    <p class="text-sm text-green-700">{{ session('success') }}</p>
                                </div>
                            </div>
                        </div>
                    @endif
                    @if ($errors->any())
                        <div class="bg-red-50 border-l-4 border-red-400 p-4 mb-6">
                            <div class="flex">
                                <div class="flex-shrink-0">
                                    <svg class="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/>
                                    </svg>
                                </div>
                                <div class="ml-3">
                                    <ul class="list-disc pl-5 space-y-1">
                                        @foreach ($errors->all() as $error)
                                            <li class="text-sm text-red-700">{{ $error }}</li>
                                        @endforeach
                                    </ul>
                                </div>
                            </div>
                        </div>
                    @endif
                    
                    <form method="POST" action="{{ route('settings.update') }}" enctype="multipart/form-data" id="settingsForm">
                        @csrf
                        @method('POST')
                        <input type="hidden" name="group" value="{{ $currentGroup }}">
                        
                        <div class="space-y-6" id="settingItems">
                            @foreach($settings as $setting)
                                <div class="setting-item p-4 border border-gray-200 rounded-lg hover:shadow-md transition-all duration-200 transform hover:-translate-y-1" data-setting-key="{{ $setting->key }}" data-setting-name="{{ $setting->description }}">
                                    <div class="flex justify-between items-center mb-2">
                                        <label for="{{ $setting->key }}" class="block text-sm font-medium text-gray-700">{{ $setting->description }}</label>
                                        @if($setting->type == 'boolean')
                                            <div class="relative inline-block w-10 mr-2 align-middle select-none">
                                                <input type="checkbox" id="{{ $setting->key }}" name="{{ $setting->key }}" 
                                                    {{ old($setting->key, $setting->value) ? 'checked' : '' }}
                                                    class="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 appearance-none cursor-pointer focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-transform duration-200 ease-in-out"/>
                                                <label for="{{ $setting->key }}" class="toggle-label block overflow-hidden h-6 rounded-full bg-gray-300 cursor-pointer"></label>
                                                <span class="setting-status ml-2 text-sm text-gray-500">{{ old($setting->key, $setting->value) ? 'Aktif' : 'Nonaktif' }}</span>
                                            </div>
                                        @endif
                                    </div>
                                    
                                    @if($setting->help_text)
                                        <p class="text-sm text-gray-500 mb-2">{{ $setting->help_text }}</p>
                                    @endif
                                    
                                    @if($setting->type == 'textarea')
                                        <textarea class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50" id="{{ $setting->key }}" name="{{ $setting->key }}" rows="3">{{ old($setting->key, $setting->value) }}</textarea>
                                    @elseif($setting->type == 'select' && isset($setting->options))
                                        <select class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50" id="{{ $setting->key }}" name="{{ $setting->key }}">
                                            @foreach(json_decode($setting->options, true) as $optionKey => $optionValue)
                                                <option value="{{ $optionKey }}" {{ old($setting->key, $setting->value) == $optionKey ? 'selected' : '' }}>{{ $optionValue }}</option>
                                            @endforeach
                                        </select>
                                    @elseif($setting->type == 'file')
                                        <div class="mt-1 flex items-center">
                                            <input type="file" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100" id="{{ $setting->key }}" name="{{ $setting->key }}">
                                        </div>
                                        @if(!empty($setting->value))
                                            <div class="mt-2">
                                                <img src="{{ asset('storage/' . $setting->value) }}" alt="{{ $setting->description }}" class="h-12 w-auto object-contain">
                                            </div>
                                        @endif
                                    @elseif($setting->type == 'boolean')
                                        <input type="hidden" name="{{ $setting->key }}" value="0">
                                    @else
                                        <input type="{{ $setting->type == 'number' ? 'number' : 'text' }}" 
                                               class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50" 
                                               id="{{ $setting->key }}" 
                                               name="{{ $setting->key }}" 
                                               value="{{ old($setting->key, $setting->value) }}" 
                                               {{ $setting->key == 'app_name' ? 'required' : '' }}>
                                    @endif
                                </div>
                            @endforeach
                        </div>
                        
                        <div class="flex justify-end mt-6">
                            <button type="submit" class="inline-flex items-center px-4 py-2 bg-blue-600 border border-transparent rounded-md font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                <svg class="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"></path>
                                </svg>
                                Simpan Pengaturan
                            </button>
                            
                            @if($currentGroup == 'email')
                            <button type="button" id="testEmailBtn" class="ml-3 inline-flex items-center px-4 py-2 bg-green-600 border border-transparent rounded-md font-medium text-white hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                                <svg class="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                                </svg>
                                Test Email
                            </button>
                            @endif
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    /* Toggle switch styling */
    .toggle-checkbox:checked {
        transform: translateX(100%);
        border-color: #3b82f6;
    }
    .toggle-checkbox:checked + .toggle-label {
        background-color: #3b82f6;
    }
    .toggle-label {
        transition: background-color 0.2s ease-in-out;
    }
</style>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Pencarian pengaturan
        const searchInput = document.getElementById('settingSearch');
        const settingItems = document.querySelectorAll('.setting-item');
        
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                
                settingItems.forEach(item => {
                    const key = item.dataset.settingKey.toLowerCase();
                    const name = item.dataset.settingName.toLowerCase();
                    
                    if (key.includes(searchTerm) || name.includes(searchTerm)) {
                        item.style.display = '';
                    } else {
                        item.style.display = 'none';
                    }
                });
            });
        }
        
        // Toggle status label untuk boolean settings
        const toggleSwitches = document.querySelectorAll('input[type="checkbox"]');
        toggleSwitches.forEach(toggle => {
            toggle.addEventListener('change', function() {
                const statusLabel = this.parentNode.querySelector('.setting-status') || 
                                    this.parentNode.parentNode.querySelector('.setting-status');
                if (statusLabel) {
                    statusLabel.textContent = this.checked ? 'Aktif' : 'Nonaktif';
                }
            });
        });
        
        // Reset settings
        const resetButton = document.getElementById('resetSettings');
        if (resetButton) {
            resetButton.addEventListener('click', function() {
                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        title: 'Konfirmasi Reset',
                        text: 'Apakah Anda yakin ingin mereset semua pengaturan ke nilai default?',
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#d33',
                        cancelButtonColor: '#3085d6',
                        confirmButtonText: 'Ya, Reset!',
                        cancelButtonText: 'Batal'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = '{{ route("settings.reset", ["group" => $currentGroup]) }}';
                        }
                    });
                } else {
                    if (confirm('Apakah Anda yakin ingin mereset semua pengaturan ke nilai default?')) {
                        window.location.href = '{{ route("settings.reset", ["group" => $currentGroup]) }}';
                    }
                }
            });
        }
        
        // Ekspor settings
        const exportButton = document.getElementById('exportSettings');
        if (exportButton) {
            exportButton.addEventListener('click', function() {
                fetch('{{ route("settings.export") }}')
                    .then(response => response.json())
                    .then(data => {
                        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = 'settings-export-' + new Date().toISOString().slice(0, 10) + '.json';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        URL.revokeObjectURL(url);
                        
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                title: 'Berhasil!',
                                text: 'Pengaturan berhasil diekspor',
                                icon: 'success',
                                timer: 2000,
                                showConfirmButton: false
                            });
                        } else {
                            alert('Pengaturan berhasil diekspor');
                        }
                    })
                    .catch(error => {
                        console.error('Error exporting settings:', error);
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                title: 'Error!',
                                text: 'Gagal mengekspor pengaturan',
                                icon: 'error'
                            });
                        } else {
                            alert('Gagal mengekspor pengaturan');
                        }
                    });
            });
        }
        
        // Impor settings
        const importButton = document.getElementById('importSettings');
        if (importButton) {
            importButton.addEventListener('click', function() {
                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        title: 'Impor Pengaturan',
                        html: `
                            <div class="mb-3">
                                <label for="importFile" class="block text-sm font-medium text-gray-700 mb-1">Pilih file JSON pengaturan</label>
                                <input type="file" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100" id="importFile" accept=".json">
                            </div>
                        `,
                        showCancelButton: true,
                        confirmButtonText: 'Impor',
                        cancelButtonText: 'Batal',
                        preConfirm: () => {
                            const fileInput = Swal.getPopup().querySelector('#importFile');
                            if (!fileInput.files.length) {
                                Swal.showValidationMessage('Silakan pilih file JSON');
                                return false;
                            }
                            return fileInput.files[0];
                        }
                    }).then((result) => {
                        if (result.isConfirmed) {
                            const file = result.value;
                            const reader = new FileReader();
                            
                            reader.onload = function(e) {
                                try {
                                    const settings = e.target.result;
                                    
                                    // Kirim data ke server
                                    fetch('{{ route("settings.import") }}', {
                                        method: 'POST',
                                        headers: {
                                            'Content-Type': 'application/json',
                                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                                        },
                                        body: JSON.stringify({ settings })
                                    })
                                    .then(response => response.json())
                                    .then(data => {
                                        if (data.success) {
                                            Swal.fire({
                                                title: 'Berhasil!',
                                                text: data.message || 'Pengaturan berhasil diimpor',
                                                icon: 'success'
                                            }).then(() => {
                                                window.location.reload();
                                            });
                                        } else {
                                            Swal.fire({
                                                title: 'Error!',
                                                text: data.message || 'Gagal mengimpor pengaturan',
                                                icon: 'error'
                                            });
                                        }
                                    })
                                    .catch(error => {
                                        console.error('Error importing settings:', error);
                                        Swal.fire({
                                            title: 'Error!',
                                            text: 'Terjadi kesalahan saat mengimpor pengaturan',
                                            icon: 'error'
                                        });
                                    });
                                } catch (error) {
                                    console.error('Error parsing JSON:', error);
                                    Swal.fire({
                                        title: 'Error!',
                                        text: 'Format file JSON tidak valid',
                                        icon: 'error'
                                    });
                                }
                            };
                            
                            reader.readAsText(file);
                        }
                    });
                } else {
                    alert('Fitur impor membutuhkan SweetAlert2 yang tidak tersedia. Silakan tambahkan SweetAlert2 ke proyek Anda.');
                }
            });
        }
        
        // Form validation
        const form = document.getElementById('settingsForm');
        if (form) {
            form.addEventListener('submit', function(event) {
                let hasError = false;
                const requiredInputs = form.querySelectorAll('input[required]');
                
                requiredInputs.forEach(input => {
                    if (!input.value.trim()) {
                        input.classList.add('border-red-500', 'ring-red-200');
                        input.classList.remove('border-gray-300', 'focus:border-blue-300', 'focus:ring-blue-200');
                        
                        const errorElement = input.nextElementSibling;
                        if (!errorElement || !errorElement.classList.contains('text-red-500')) {
                            const feedback = document.createElement('p');
                            feedback.classList.add('mt-1', 'text-sm', 'text-red-500');
                            feedback.textContent = 'Bidang ini wajib diisi';
                            input.parentNode.insertBefore(feedback, input.nextSibling);
                        }
                        hasError = true;
                    } else {
                        input.classList.remove('border-red-500', 'ring-red-200');
                        input.classList.add('border-gray-300', 'focus:border-blue-300', 'focus:ring-blue-200');
                        
                        const errorElement = input.nextElementSibling;
                        if (errorElement && errorElement.classList.contains('text-red-500')) {
                            errorElement.remove();
                        }
                    }
                });
                
                if (hasError) {
                    event.preventDefault();
                    event.stopPropagation();
                }
            });
        }
    });
</script>

<script>
// Test Email functionality
if (document.getElementById('testEmailBtn')) {
    document.getElementById('testEmailBtn').addEventListener('click', function() {
        Swal.fire({
            title: 'Test Email',
            html: `
                <div class="mb-3">
                    <label for="testEmailInput" class="block text-sm font-medium text-gray-700 mb-1">Masukkan alamat email untuk test:</label>
                    <input type="email" id="testEmailInput" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" placeholder="email@example.com" required>
                </div>
            `,
            showCancelButton: true,
            confirmButtonText: 'Kirim Test Email',
            cancelButtonText: 'Batal',
            showLoaderOnConfirm: true,
            preConfirm: () => {
                const testEmail = document.getElementById('testEmailInput').value;
                if (!testEmail) {
                    Swal.showValidationMessage('Alamat email diperlukan');
                    return false;
                }
                
                return fetch('{{ route("settings.test-email") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    body: JSON.stringify({ test_email: testEmail })
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.message);
                    }
                    return data;
                })
                .catch(error => {
                    Swal.showValidationMessage(`Request failed: ${error.message || error}`);
                });
            },
            allowOutsideClick: () => !Swal.isLoading()
        }).then((result) => {
            if (result.isConfirmed && result.value) {
                Swal.fire({
                    title: 'Berhasil!',
                    text: result.value.message,
                    icon: 'success'
                });
            }
        });
    });
}
</script>
@endpush
@endsection