@extends('admin.layout')

@section('title', 'Dashboard')
@section('page-title', '⚙️ Pengaturan Website')

@section('content')
<div class="tabs">
    <button class="tab-btn active" onclick="switchTab('hero')">🎯 Hero</button>
    <button class="tab-btn" onclick="switchTab('general')">⚙️ Umum</button>
    <button class="tab-btn" onclick="switchTab('about')">🏆 Keunggulan</button>
    <button class="tab-btn" onclick="switchTab('services')">🔧 Layanan</button>
    <button class="tab-btn" onclick="switchTab('footer')">📄 Footer</button>
</div>

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

    {{-- HERO TAB --}}
    <div class="tab-panel active" id="tab-hero">
        <div class="card">
            <div class="card-header">
                <h3>🎯 Hero Section</h3>
                <small style="color:#9CA3AF">Bagian pertama yang dilihat pengunjung</small>
            </div>
            <div class="card-body">
                @php $heroGroup = $settings->get('hero', collect()); @endphp
                
                <div class="form-group">
                    <label>Headline Utama</label>
                    <input type="text" name="hero_headline" class="form-control" 
                           value="{{ $heroGroup->where('key','hero_headline')->first()?->value ?? '' }}">
                </div>
                <div class="form-group">
                    <label>Sub-headline</label>
                    <textarea name="hero_subheadline" class="form-control">{{ $heroGroup->where('key','hero_subheadline')->first()?->value ?? '' }}</textarea>
                </div>
                <div class="form-group">
                    <label>Teks Tombol CTA</label>
                    <input type="text" name="hero_cta_text" class="form-control" 
                           value="{{ $heroGroup->where('key','hero_cta_text')->first()?->value ?? '' }}">
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label>Gambar Hero</label>
                        @php $heroImg = $heroGroup->where('key','hero_image')->first()?->value ?? ''; @endphp
                        <div class="upload-area" onclick="document.getElementById('hero_image_file').click()">
                            @if($heroImg)
                            <img src="{{ $heroImg }}" class="upload-preview" id="hero_image_preview" alt="Preview">
                            @else
                            <div id="hero_image_preview" style="font-size:3rem;margin-bottom:8px">🖼️</div>
                            @endif
                            <p style="font-size:0.82rem;color:#9CA3AF">Klik untuk ganti gambar (JPG, PNG, WEBP)</p>
                        </div>
                        <input type="file" id="hero_image_file" accept="image/*" style="display:none"
                               onchange="previewAndUpload(this, 'hero_image_preview', 'hero_image')">
                        <input type="hidden" name="hero_image" id="hero_image" value="{{ $heroImg }}">
                    </div>
                    
                    <div class="form-group">
                        <label>Video Hero (Opsional)</label>
                        @php $heroVid = $heroGroup->where('key','hero_video')->first()?->value ?? ''; @endphp
                        <div class="upload-area" onclick="document.getElementById('hero_video_file').click()">
                            <div style="font-size:3rem;margin-bottom:8px">🎬</div>
                            <p style="font-size:0.82rem;color:#9CA3AF">{{ $heroVid ? 'Video aktif. Klik untuk ganti.' : 'Klik untuk upload video (MP4)' }}</p>
                        </div>
                        <input type="file" id="hero_video_file" accept="video/*" style="display:none"
                               onchange="previewAndUpload(this, null, 'hero_video')">
                        <input type="hidden" name="hero_video" id="hero_video" value="{{ $heroVid }}">
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- GENERAL TAB --}}
    <div class="tab-panel" id="tab-general">
        <div class="card">
            <div class="card-header"><h3>⚙️ Pengaturan Umum</h3></div>
            <div class="card-body">
                @php $generalGroup = $settings->get('general', collect()); @endphp
                
                <div class="form-group">
                    <label>Logo Bengkel</label>
                    @php $logoVal = $generalGroup->where('key','logo')->first()?->value ?? ''; @endphp
                    <div class="upload-area" onclick="document.getElementById('logo_file').click()">
                        @if($logoVal)
                        <img src="{{ $logoVal }}" class="upload-preview" id="logo_preview" alt="Logo Preview">
                        @else
                        <div id="logo_preview" style="font-size:3rem;margin-bottom:8px">🏷️</div>
                        @endif
                        <p style="font-size:0.82rem;color:#9CA3AF">Klik untuk ganti logo</p>
                    </div>
                    <input type="file" id="logo_file" accept="image/*" style="display:none"
                           onchange="previewAndUpload(this, 'logo_preview', 'logo')">
                    <input type="hidden" name="logo" id="logo" value="{{ $logoVal }}">
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label>Nama Bengkel</label>
                        <input type="text" name="site_name" class="form-control" 
                               value="{{ $generalGroup->where('key','site_name')->first()?->value ?? '' }}">
                    </div>
                    <div class="form-group">
                        <label>Nomor WhatsApp (dengan kode negara)</label>
                        <input type="text" name="whatsapp" class="form-control" 
                               value="{{ $generalGroup->where('key','whatsapp')->first()?->value ?? '' }}"
                               placeholder="628123456789">
                    </div>
                </div>
                
                <div class="form-group">
                    <label>Jam Operasional</label>
                    <input type="text" name="open_hours" class="form-control" 
                           value="{{ $generalGroup->where('key','open_hours')->first()?->value ?? '' }}">
                </div>
                
                <div class="form-group">
                    <label>Alamat Bengkel</label>
                    <textarea name="address" class="form-control">{{ $generalGroup->where('key','address')->first()?->value ?? '' }}</textarea>
                </div>
                
                <div class="form-group">
                    <label>Google Maps Embed URL</label>
                    <input type="text" name="maps_embed" class="form-control" 
                           value="{{ $generalGroup->where('key','maps_embed')->first()?->value ?? '' }}"
                           placeholder="https://www.google.com/maps/embed?pb=...">
                    <small style="color:#9CA3AF;font-size:0.78rem;">Buka Google Maps → Share → Embed a map → salin link dari src="..."</small>
                </div>
            </div>
        </div>
    </div>

    {{-- ABOUT TAB --}}
    <div class="tab-panel" id="tab-about">
        <div class="card">
            <div class="card-header"><h3>🏆 Keunggulan Kami</h3></div>
            <div class="card-body">
                @php 
                    $aboutGroup = $settings->get('about', collect());
                    $featuresRaw = $aboutGroup->where('key','features')->first()?->value ?? '[]';
                    $featuresData = json_decode($featuresRaw, true) ?? [];
                @endphp
                
                <div class="form-grid">
                    <div class="form-group">
                        <label>Judul Section</label>
                        <input type="text" name="about_title" class="form-control" 
                               value="{{ $aboutGroup->where('key','about_title')->first()?->value ?? '' }}">
                    </div>
                    <div class="form-group">
                        <label>Subtitle</label>
                        <input type="text" name="about_subtitle" class="form-control" 
                               value="{{ $aboutGroup->where('key','about_subtitle')->first()?->value ?? '' }}">
                    </div>
                </div>

                <div style="margin-bottom:12px;font-weight:700;font-size:0.9rem;">Daftar Keunggulan:</div>
                <div class="json-items" id="features-list">
                    @foreach($featuresData as $fi => $feat)
                    <div class="json-item" id="feature-item-{{ $fi }}">
                        <div class="json-item-header">
                            <span class="json-item-title">Keunggulan #{{ $fi + 1 }}</span>
                            <button type="button" class="btn btn-danger btn-sm" onclick="removeItem('feature-item-{{ $fi }}')">Hapus</button>
                        </div>
                        <div class="form-grid">
                            <div class="form-group">
                                <label>Icon (Gambar PNG)</label>
                                <div class="upload-area" style="min-height:80px;padding:10px" onclick="document.getElementById('feat_icon_file_{{ $fi }}').click()">
                                    @if(!empty($feat['icon']))
                                    <img src="{{ $feat['icon'] }}" class="upload-preview" id="feat_icon_preview_{{ $fi }}" style="max-height:60px;object-fit:contain;margin-bottom:8px;" alt="Icon">
                                    @else
                                    <div id="feat_icon_preview_{{ $fi }}" style="font-size:2rem;margin-bottom:4px">🖼️</div>
                                    @endif
                                </div>
                                <input type="file" id="feat_icon_file_{{ $fi }}" accept="image/png, image/jpeg, image/webp" style="display:none"
                                       onchange="previewAndUpload(this, 'feat_icon_preview_{{ $fi }}', 'feat_icon_{{ $fi }}')">
                                <input type="hidden" name="feat_icon[]" id="feat_icon_{{ $fi }}" value="{{ $feat['icon'] ?? '' }}">
                            </div>
                            <div class="form-group">
                                <label>Judul</label>
                                <input type="text" name="feat_title[]" class="form-control" value="{{ $feat['title'] ?? '' }}">
                            </div>
                        </div>
                        <div class="form-group">
                            <label>Deskripsi</label>
                            <textarea name="feat_desc[]" class="form-control" style="min-height:70px">{{ $feat['desc'] ?? '' }}</textarea>
                        </div>
                    </div>
                    @endforeach
                </div>
                <button type="button" class="btn btn-primary" onclick="addFeatureItem()" style="margin-top:16px">+ Tambah Keunggulan</button>
                <input type="hidden" name="features" id="features-hidden">
            </div>
        </div>
    </div>

    {{-- SERVICES TAB --}}
    <div class="tab-panel" id="tab-services">
        <div class="card">
            <div class="card-header"><h3>🔧 Layanan Kami</h3></div>
            <div class="card-body">
                @php 
                    $servicesGroup = $settings->get('services', collect());
                    $servicesRaw = $servicesGroup->where('key','services')->first()?->value ?? '[]';
                    $servicesData = json_decode($servicesRaw, true) ?? [];
                @endphp
                
                <div class="form-group">
                    <label>Judul Section Layanan</label>
                    <input type="text" name="services_title" class="form-control" 
                           value="{{ $servicesGroup->where('key','services_title')->first()?->value ?? '' }}">
                </div>

                <div class="json-items" id="services-list">
                    @foreach($servicesData as $si => $svc)
                    <div class="json-item" id="service-item-{{ $si }}">
                        <div class="json-item-header">
                            <span class="json-item-title">Layanan #{{ $si + 1 }}</span>
                            <button type="button" class="btn btn-danger btn-sm" onclick="removeItem('service-item-{{ $si }}')">Hapus</button>
                        </div>
                        <div class="form-grid-3">
                            <div class="form-group">
                                <label>Icon (Gambar PNG)</label>
                                <div class="upload-area" style="min-height:80px;padding:10px" onclick="document.getElementById('svc_icon_file_{{ $si }}').click()">
                                    @if(!empty($svc['icon']))
                                    <img src="{{ $svc['icon'] }}" class="upload-preview" id="svc_icon_preview_{{ $si }}" style="max-height:60px;object-fit:contain;margin-bottom:8px;" alt="Icon">
                                    @else
                                    <div id="svc_icon_preview_{{ $si }}" style="font-size:2rem;margin-bottom:4px">🖼️</div>
                                    @endif
                                </div>
                                <input type="file" id="svc_icon_file_{{ $si }}" accept="image/png, image/jpeg, image/webp" style="display:none"
                                       onchange="previewAndUpload(this, 'svc_icon_preview_{{ $si }}', 'svc_icon_{{ $si }}')">
                                <input type="hidden" name="svc_icon[]" id="svc_icon_{{ $si }}" value="{{ $svc['icon'] ?? '' }}">
                            </div>
                            <div class="form-group">
                                <label>Nama Layanan</label>
                                <input type="text" name="svc_title[]" class="form-control" value="{{ $svc['title'] ?? '' }}">
                            </div>
                            <div class="form-group">
                                <label>Harga</label>
                                <input type="text" name="svc_price[]" class="form-control" value="{{ $svc['price'] ?? '' }}">
                            </div>
                        </div>
                        <div class="form-group">
                            <label>Deskripsi</label>
                            <textarea name="svc_desc[]" class="form-control" style="min-height:70px">{{ $svc['desc'] ?? '' }}</textarea>
                        </div>
                    </div>
                    @endforeach
                </div>
                <button type="button" class="btn btn-primary" onclick="addServiceItem()" style="margin-top:16px">+ Tambah Layanan</button>
                <input type="hidden" name="services" id="services-hidden">
            </div>
        </div>
    </div>

    {{-- FOOTER TAB --}}
    <div class="tab-panel" id="tab-footer">
        <div class="card">
            <div class="card-header"><h3>📄 Footer & CTA</h3></div>
            <div class="card-body">
                @php 
                    $footerGroup = $settings->get('footer', collect());
                    $socialMediaRaw = $settings->flatten()->where('key','social_media')->first()?->value ?? '[]';
                    $socialMediaData = json_decode($socialMediaRaw, true) ?? [];
                @endphp
                <div class="form-group">
                    <label>Judul Footer CTA</label>
                    <input type="text" name="footer_cta_title" class="form-control" 
                           value="{{ $footerGroup->where('key','footer_cta_title')->first()?->value ?? '' }}">
                </div>
                <div class="form-group">
                    <label>Subtitle Footer CTA</label>
                    <textarea name="footer_cta_subtitle" class="form-control">{{ $footerGroup->where('key','footer_cta_subtitle')->first()?->value ?? '' }}</textarea>
                </div>

                <hr style="margin:24px 0; border:0; border-top:1px solid #E5E5E5;">
                <div style="margin-bottom:12px;font-weight:700;font-size:0.9rem;">Ikon Sosial Media:</div>
                <div class="json-items" id="social-list">
                    @foreach($socialMediaData as $smi => $soc)
                    <div class="json-item" id="social-item-{{ $smi }}">
                        <div class="json-item-header">
                            <span class="json-item-title">Sosial Media #{{ $smi + 1 }}</span>
                            <button type="button" class="btn btn-danger btn-sm" onclick="removeItem('social-item-{{ $smi }}')">Hapus</button>
                        </div>
                        <div class="form-grid-3">
                            <div class="form-group">
                                <label>Icon (Gambar/Emoji)</label>
                                <div class="upload-area" style="min-height:80px;padding:10px" onclick="document.getElementById('soc_icon_file_{{ $smi }}').click()">
                                    @if(!empty($soc['icon']) && (str_starts_with($soc['icon'], '/') || str_starts_with($soc['icon'], 'http')))
                                    <img src="{{ $soc['icon'] }}" class="upload-preview" id="soc_icon_preview_{{ $smi }}" style="max-height:60px;object-fit:contain;margin-bottom:8px;" alt="Icon">
                                    @else
                                    <div id="soc_icon_preview_{{ $smi }}" style="font-size:2rem;margin-bottom:4px">{{ $soc['icon'] ?? '🖼️' }}</div>
                                    @endif
                                </div>
                                <input type="file" id="soc_icon_file_{{ $smi }}" accept="image/png, image/jpeg, image/webp" style="display:none"
                                       onchange="previewAndUpload(this, 'soc_icon_preview_{{ $smi }}', 'soc_icon_{{ $smi }}')">
                                <input type="text" name="soc_icon[]" id="soc_icon_{{ $smi }}" value="{{ $soc['icon'] ?? '' }}" class="form-control" placeholder="Atau ketik emoji (cth: 📸)" style="margin-top:8px;">
                            </div>
                            <div class="form-group">
                                <label>Nama Platform</label>
                                <input type="text" name="soc_title[]" class="form-control" value="{{ $soc['title'] ?? '' }}" placeholder="Instagram">
                            </div>
                            <div class="form-group">
                                <label>URL</label>
                                <input type="url" name="soc_url[]" class="form-control" value="{{ $soc['url'] ?? '' }}" placeholder="https://instagram.com/...">
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>
                <button type="button" class="btn btn-primary" onclick="addSocialItem()" style="margin-top:16px">+ Tambah Sosial Media</button>
                <input type="hidden" name="social_media" id="social-hidden">
            </div>
        </div>
    </div>

    <div style="margin-top:24px;display:flex;justify-content:flex-end;">
        <button type="submit" class="btn btn-primary" style="padding:14px 36px;font-size:1rem;">
            💾 Simpan Semua Perubahan
        </button>
    </div>
</form>

<script>
// Tabs
function switchTab(name) {
    document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.getElementById('tab-' + name).classList.add('active');
    event.target.classList.add('active');
}

// File upload with preview
function previewAndUpload(input, previewId, hiddenId) {
    const file = input.files[0];
    if (!file) return;
    
    const formData = new FormData();
    formData.append('file', file);
    formData.append('_token', '{{ csrf_token() }}');

    fetch('{{ route("admin.upload") }}', { method: 'POST', body: formData })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                document.getElementById(hiddenId).value = data.url;
                if (previewId) {
                    const preview = document.getElementById(previewId);
                    if (preview.tagName === 'IMG') {
                        preview.src = data.url;
                    } else {
                        // Create img and replace
                        const img = document.createElement('img');
                        img.src = data.url;
                        img.className = 'upload-preview';
                        img.id = previewId;
                        if(previewId.includes('icon')) {
                            img.style.maxHeight = '60px';
                            img.style.objectFit = 'contain';
                            img.style.marginBottom = '8px';
                        }
                        preview.replaceWith(img);
                    }
                }
                alert('✅ File berhasil diupload!');
            }
        })
        .catch(err => alert('❌ Gagal upload: ' + err));
}

// Dynamic feature items
let featureCount = {{ count($featuresData) }};
function addFeatureItem() {
    const list = document.getElementById('features-list');
    const id = 'feature-item-' + featureCount;
    const div = document.createElement('div');
    div.className = 'json-item';
    div.id = id;
    div.innerHTML = `
        <div class="json-item-header">
            <span class="json-item-title">Keunggulan #${featureCount + 1}</span>
            <button type="button" class="btn btn-danger btn-sm" onclick="removeItem('${id}')">Hapus</button>
        </div>
        <div class="form-grid">
            <div class="form-group">
                <label>Icon (Gambar PNG)</label>
                <div class="upload-area" style="min-height:80px;padding:10px" onclick="document.getElementById('feat_icon_file_${featureCount}').click()">
                    <div id="feat_icon_preview_${featureCount}" style="font-size:2rem;margin-bottom:4px">🖼️</div>
                </div>
                <input type="file" id="feat_icon_file_${featureCount}" accept="image/png, image/jpeg, image/webp" style="display:none" onchange="previewAndUpload(this, 'feat_icon_preview_${featureCount}', 'feat_icon_${featureCount}')">
                <input type="hidden" name="feat_icon[]" id="feat_icon_${featureCount}">
            </div>
            <div class="form-group"><label>Judul</label><input type="text" name="feat_title[]" class="form-control" placeholder="Nama Keunggulan"></div>
        </div>
        <div class="form-group"><label>Deskripsi</label><textarea name="feat_desc[]" class="form-control" style="min-height:70px" placeholder="Deskripsi singkat..."></textarea></div>
    `;
    list.appendChild(div);
    featureCount++;
}

// Dynamic service items
let serviceCount = {{ count($servicesData) }};
function addServiceItem() {
    const list = document.getElementById('services-list');
    const id = 'service-item-' + serviceCount;
    const div = document.createElement('div');
    div.className = 'json-item';
    div.id = id;
    div.innerHTML = `
        <div class="json-item-header">
            <span class="json-item-title">Layanan #${serviceCount + 1}</span>
            <button type="button" class="btn btn-danger btn-sm" onclick="removeItem('${id}')">Hapus</button>
        </div>
        <div class="form-grid-3">
            <div class="form-group">
                <label>Icon (Gambar PNG)</label>
                <div class="upload-area" style="min-height:80px;padding:10px" onclick="document.getElementById('svc_icon_file_${serviceCount}').click()">
                    <div id="svc_icon_preview_${serviceCount}" style="font-size:2rem;margin-bottom:4px">🖼️</div>
                </div>
                <input type="file" id="svc_icon_file_${serviceCount}" accept="image/png, image/jpeg, image/webp" style="display:none" onchange="previewAndUpload(this, 'svc_icon_preview_${serviceCount}', 'svc_icon_${serviceCount}')">
                <input type="hidden" name="svc_icon[]" id="svc_icon_${serviceCount}">
            </div>
            <div class="form-group"><label>Nama Layanan</label><input type="text" name="svc_title[]" class="form-control" placeholder="Nama Layanan"></div>
            <div class="form-group"><label>Harga</label><input type="text" name="svc_price[]" class="form-control" placeholder="Mulai Rp 150.000"></div>
        </div>
        <div class="form-group"><label>Deskripsi</label><textarea name="svc_desc[]" class="form-control" style="min-height:70px"></textarea></div>
    `;
    list.appendChild(div);
    serviceCount++;
}

// Dynamic social items
let socialCount = {{ count($socialMediaData) }};
function addSocialItem() {
    const list = document.getElementById('social-list');
    const id = 'social-item-' + socialCount;
    const div = document.createElement('div');
    div.className = 'json-item';
    div.id = id;
    div.innerHTML = `
        <div class="json-item-header">
            <span class="json-item-title">Sosial Media #${socialCount + 1}</span>
            <button type="button" class="btn btn-danger btn-sm" onclick="removeItem('${id}')">Hapus</button>
        </div>
        <div class="form-grid-3">
            <div class="form-group">
                <label>Icon (Gambar/Emoji)</label>
                <div class="upload-area" style="min-height:80px;padding:10px" onclick="document.getElementById('soc_icon_file_${socialCount}').click()">
                    <div id="soc_icon_preview_${socialCount}" style="font-size:2rem;margin-bottom:4px">🖼️</div>
                </div>
                <input type="file" id="soc_icon_file_${socialCount}" accept="image/png, image/jpeg, image/webp" style="display:none" onchange="previewAndUpload(this, 'soc_icon_preview_${socialCount}', 'soc_icon_${socialCount}')">
                <input type="text" name="soc_icon[]" id="soc_icon_${socialCount}" class="form-control" placeholder="Atau ketik emoji (cth: 📸)" style="margin-top:8px;">
            </div>
            <div class="form-group"><label>Nama Platform</label><input type="text" name="soc_title[]" class="form-control" placeholder="Instagram"></div>
            <div class="form-group"><label>URL</label><input type="url" name="soc_url[]" class="form-control" placeholder="https://instagram.com/..."></div>
        </div>
    `;
    list.appendChild(div);
    socialCount++;
}

function removeItem(id) {
    document.getElementById(id)?.remove();
}

// Before submit: collect JSON data
document.getElementById('settings-form').addEventListener('submit', function(e) {
    // Features JSON
    const featIcons = [...document.querySelectorAll('[name="feat_icon[]"]')].map(el => el.value);
    const featTitles = [...document.querySelectorAll('[name="feat_title[]"]')].map(el => el.value);
    const featDescs = [...document.querySelectorAll('[name="feat_desc[]"]')].map(el => el.value);
    const featJson = featIcons.map((icon, i) => ({ icon, title: featTitles[i], desc: featDescs[i] })).filter(f => f.title);
    document.getElementById('features-hidden').value = JSON.stringify(featJson);

    // Services JSON
    const svcIcons = [...document.querySelectorAll('[name="svc_icon[]"]')].map(el => el.value);
    const svcTitles = [...document.querySelectorAll('[name="svc_title[]"]')].map(el => el.value);
    const svcPrices = [...document.querySelectorAll('[name="svc_price[]"]')].map(el => el.value);
    const svcDescs = [...document.querySelectorAll('[name="svc_desc[]"]')].map(el => el.value);
    const svcJson = svcIcons.map((icon, i) => ({ icon, title: svcTitles[i], price: svcPrices[i], desc: svcDescs[i] })).filter(s => s.title);
    document.getElementById('services-hidden').value = JSON.stringify(svcJson);

    // Social JSON
    const socIcons = [...document.querySelectorAll('[name="soc_icon[]"]')].map(el => el.value);
    const socTitles = [...document.querySelectorAll('[name="soc_title[]"]')].map(el => el.value);
    const socUrls = [...document.querySelectorAll('[name="soc_url[]"]')].map(el => el.value);
    const socJson = socIcons.map((icon, i) => ({ icon, title: socTitles[i], url: socUrls[i] })).filter(s => s.title);
    document.getElementById('social-hidden').value = JSON.stringify(socJson);
});
</script>
@endsection
