@extends('layouts.admin')
@section('title', 'Pengaturan Sistem')

@section('content')

<div class="max-w-3xl mx-auto">

    {{-- Header --}}
    <div class="mb-6">
        <h1 class="text-xl font-bold text-gray-900">Pengaturan Sistem</h1>
        <p class="text-sm text-gray-500 mt-0.5">Konfigurasi identitas perusahaan, nota, dan form</p>
    </div>

    <form method="POST" action="{{ route('admin.settings.update') }}" enctype="multipart/form-data"
          x-data="{ activeTab: '{{ array_key_first($groups) }}' }">
        @csrf @method('PATCH')

        {{-- Tab navigation --}}
        <div class="flex gap-1 bg-gray-100 rounded-2xl p-1 mb-5 flex-wrap">
            @foreach($groups as $groupKey => $group)
            <button type="button"
                    @click="activeTab = '{{ $groupKey }}'"
                    :class="activeTab === '{{ $groupKey }}'
                        ? 'bg-white text-brand-700 shadow-sm font-semibold'
                        : 'text-gray-500 hover:text-gray-700'"
                    class="flex-1 min-w-[120px] inline-flex items-center justify-center gap-2
                           text-sm rounded-xl px-3 py-2 transition">
                <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="{{ $group['icon'] }}"/>
                </svg>
                <span class="hidden sm:inline">{{ $group['label'] }}</span>
            </button>
            @endforeach
        </div>

        @php
        // Kelompokkan rows dari DB berdasarkan group
        $byGroup = $rows->groupBy(fn($r) => $r->group);
        @endphp

        {{-- Tab panels --}}
        @foreach($groups as $groupKey => $group)
        <div x-show="activeTab === '{{ $groupKey }}'" x-transition:enter="transition ease-out duration-150"
             x-transition:enter-start="opacity-0 translate-y-1" x-transition:enter-end="opacity-100 translate-y-0">

            <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-50 bg-gray-50/50">
                    <h2 class="font-semibold text-gray-800 flex items-center gap-2">
                        <svg class="w-4 h-4 text-brand-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="{{ $group['icon'] }}"/>
                        </svg>
                        {{ $group['label'] }}
                    </h2>
                </div>

                <div class="p-6 space-y-5">
                    @forelse($byGroup->get($groupKey, collect()) as $setting)
                    <div>
                        <label for="setting_{{ $setting->key }}"
                               class="block text-sm font-semibold text-gray-700 mb-1.5">
                            {{ $setting->label ?? $setting->key }}
                        </label>

                        @if($setting->type === 'toggle')
                            {{-- Toggle switch --}}
                            <label class="inline-flex items-center gap-3 cursor-pointer" x-data="{ on: {{ old($setting->key, (string) $setting->value) === '1' ? 'true' : 'false' }} }">
                                <input type="hidden" name="{{ $setting->key }}" value="0">
                                <input type="checkbox" name="{{ $setting->key }}" value="1"
                                       id="setting_{{ $setting->key }}"
                                       {{ old($setting->key, (string) $setting->value) === '1' ? 'checked' : '' }}
                                       x-model="on"
                                       class="sr-only peer">
                                <div class="relative w-11 h-6 bg-gray-200 peer-focus:outline-none
                                            peer-focus:ring-2 peer-focus:ring-brand-300
                                            rounded-full peer peer-checked:after:translate-x-full
                                            peer-checked:after:border-white
                                            after:content-[''] after:absolute after:top-[2px] after:left-[2px]
                                            after:bg-white after:rounded-full after:h-5 after:w-5
                                            after:transition-all peer-checked:bg-brand-600 cursor-pointer">
                                </div>
                                <span class="text-sm text-gray-600" x-text="on ? 'Aktif' : 'Nonaktif'"></span>
                            </label>

                        @elseif($setting->type === 'textarea')
                            <textarea name="{{ $setting->key }}" id="setting_{{ $setting->key }}"
                                      rows="3"
                                      placeholder="Kosongkan jika tidak digunakan"
                                      class="w-full rounded-xl border border-gray-200 px-4 py-2.5 text-sm bg-white resize-y
                                             focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">{{ old($setting->key, $setting->value) }}</textarea>

                        @elseif($setting->type === 'color')
                            {{-- Color picker dengan preview --}}
                            <div x-data="{ color: '{{ old($setting->key, $setting->value ?: '#1d4ed8') }}' }" class="flex items-center gap-3">
                                <input type="color"
                                       name="{{ $setting->key }}"
                                       id="setting_{{ $setting->key }}"
                                       x-model="color"
                                       class="h-10 w-16 rounded-lg border border-gray-200 cursor-pointer p-1 bg-white"
                                       value="{{ old($setting->key, $setting->value ?: '#1d4ed8') }}">
                                <div class="flex items-center gap-2">
                                    <div class="w-8 h-8 rounded-full border border-gray-200 shadow-sm" :style="`background:${color}`"></div>
                                    <span class="text-sm font-mono text-gray-600" x-text="color"></span>
                                </div>
                            </div>

                        @elseif($setting->type === 'image_upload')
                            {{-- Upload logo --}}
                            <div class="space-y-3">
                                @if($setting->value)
                                <div class="flex items-center gap-3 p-3 bg-gray-50 rounded-xl border border-gray-100">
                                    <img src="{{ asset('storage/' . $setting->value) }}" alt="Logo" class="h-12 object-contain rounded">
                                    <div class="text-xs text-gray-500 break-all">{{ $setting->value }}</div>
                                </div>
                                @endif
                                <input type="file"
                                       name="logo_upload"
                                       id="setting_{{ $setting->key }}"
                                       accept="image/png,image/jpeg,image/svg+xml,image/webp"
                                       class="block w-full text-sm text-gray-600 file:mr-3 file:py-2 file:px-4
                                              file:rounded-xl file:border-0 file:text-sm file:font-semibold
                                              file:bg-brand-50 file:text-brand-700 hover:file:bg-brand-100">
                                <p class="text-xs text-gray-400">Format: PNG, JPG, SVG, WebP — maksimal 2MB. Kosongkan jika tidak ingin mengubah logo.</p>
                                {{-- hidden input agar key tetap terdaftar --}}
                                <input type="hidden" name="{{ $setting->key }}" value="{{ old($setting->key, $setting->value) }}">
                            </div>

                        @else
                            <input type="{{ $setting->type }}"
                                   name="{{ $setting->key }}"
                                   id="setting_{{ $setting->key }}"
                                   value="{{ old($setting->key, $setting->value) }}"
                                   placeholder="Kosongkan jika tidak digunakan"
                                   class="w-full rounded-xl border border-gray-200 px-4 py-2.5 text-sm bg-white
                                          focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
                        @endif

                        @error($setting->key)
                            <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                        @enderror
                    </div>
                    @empty
                    <p class="text-sm text-gray-400 italic">Belum ada pengaturan di grup ini.</p>
                    @endforelse
                </div>
            </div>

        </div>
        @endforeach

        {{-- Preview nota (khusus tab perusahaan) --}}
        <div x-show="activeTab === 'nota'" class="mt-4">
            <div class="bg-blue-50 border border-blue-100 rounded-2xl px-5 py-4 text-sm text-blue-800">
                <p class="font-semibold mb-1">ℹ️ Pratinjau Nota</p>
                <p>Perubahan akan langsung terlihat pada nota PDF dan halaman nota digital.
                   Buka <a href="{{ route('nota.show', optional(\App\Models\ServiceTicket::latest()->first())->ticket_code ?? '#') }}"
                           class="underline font-medium" target="_blank">nota terakhir</a> untuk melihat hasilnya.</p>
            </div>
        </div>

        {{-- Preview invoice (khusus tab invoice) --}}
        <div x-show="activeTab === 'invoice'" class="mt-4">
            <div class="bg-indigo-50 border border-indigo-100 rounded-2xl px-5 py-4 text-sm text-indigo-800">
                <p class="font-semibold mb-1">ℹ️ Tampilan Invoice</p>
                <p>Perubahan warna, logo, footer, dan QR akan langsung diterapkan ke PDF invoice.
                   @if(\App\Models\Invoice::latest()->first())
                   Buka <a href="{{ route('admin.invoices.pdf', \App\Models\Invoice::latest()->first()) }}"
                           class="underline font-medium" target="_blank">preview PDF invoice terakhir</a> untuk melihat hasilnya.
                   @else
                   Buat invoice terlebih dahulu untuk melihat preview.
                   @endif
                </p>
            </div>
        </div>

        {{-- Save button --}}
        <div class="mt-5 flex items-center justify-between bg-white rounded-2xl border border-gray-100 shadow-sm px-6 py-4">
            <p class="text-sm text-gray-500">Perubahan berlaku langsung setelah disimpan.</p>
            <button type="submit"
                    class="inline-flex items-center gap-2 bg-brand-600 hover:bg-brand-700 text-white
                           font-semibold text-sm rounded-xl px-6 py-2.5 transition shadow-sm">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                </svg>
                Simpan Semua Pengaturan
            </button>
        </div>

    </form>
</div>

@endsection
