@extends('layouts.admin')

@section('title', 'Edit Produk')

@section('content')
<div class="max-w-6xl mx-auto space-y-6">

    <!-- Header -->
    <div class="flex items-center justify-between">
        <div>
            <h2 class="text-2xl font-bold text-gray-800">Edit Produk</h2>
            <p class="text-gray-500 mt-1">Perbarui informasi produk</p>
        </div>
        <a href="{{ route('produks.index') }}" 
           class="inline-flex items-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-xl hover:bg-gray-50 transition">
            <i class="bi bi-arrow-left"></i>
            Kembali
        </a>
    </div>

    <!-- Error -->
    @if ($errors->any())
        <div class="px-5 py-4 bg-red-50 border border-red-200 rounded-xl text-red-700">
            <ul class="list-disc list-inside text-sm space-y-1">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form action="{{ route('produks.update', $produk->id) }}" method="POST" enctype="multipart/form-data" class="space-y-6">
        @csrf
        @method('PUT')

        <!-- Informasi Produk -->
        <div class="bg-white border border-gray-200 rounded-2xl shadow-sm p-6 space-y-5">
            <h3 class="font-semibold text-gray-800">Informasi Dasar Produk</h3>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Nama Produk</label>
                <input type="text" name="nama"
                       value="{{ old('nama', $produk->nama) }}"
                       class="w-full px-4 py-2.5 border rounded-xl focus:ring-2 focus:ring-emerald-500 outline-none">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Deskripsi</label>
                <textarea name="deskripsi"
                          class="w-full px-4 py-2.5 border rounded-xl focus:ring-2 focus:ring-emerald-500 outline-none"
                          rows="3">{{ old('deskripsi', $produk->deskripsi) }}</textarea>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Kategori</label>
                <select name="kategori_id"
                        class="w-full px-4 py-2.5 border rounded-xl focus:ring-2 focus:ring-emerald-500 outline-none">
                    <option value="">-- Pilih Kategori --</option>
                    @foreach($kategoris as $kategori)
                        <option value="{{ $kategori->id }}"
                            {{ old('kategori_id', $produk->kategori_id) == $kategori->id ? 'selected' : '' }}>
                            {{ $kategori->nama }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Foto Utama</label>

                @if($produk->foto)
                    <div class="mb-3">
                        <img src="{{ asset('storage/' . $produk->foto) }}" 
                             class="rounded-xl w-32 h-32 object-cover border">
                    </div>
                @endif

                <input type="file" name="foto"
                       class="w-full border rounded-xl px-3 py-2">
                <p class="text-xs text-gray-500 mt-1">Format: jpg, png, webp. Maks 2MB</p>
            </div>
        </div>

        <!-- Varian -->
        <div class="bg-white border border-gray-200 rounded-2xl shadow-sm p-6">
            
            <div class="flex items-center justify-between mb-4">
                <h3 class="font-semibold text-gray-800">Varian Produk</h3>
                <button type="button" onclick="addVarian()"
                    class="inline-flex items-center gap-2 px-4 py-2 bg-emerald-500 text-white rounded-xl hover:bg-emerald-600 transition">
                    <i class="bi bi-plus"></i>
                    Tambah Varian
                </button>
            </div>

            <div id="varian-container" class="space-y-4"></div>
            
            <div class="mt-4 p-3 bg-yellow-50 rounded-lg border border-yellow-200">
                <p class="text-sm text-yellow-700">
                    <i class="bi bi-info-circle"></i>
                    Untuk menghapus foto varian, klik tombol <strong class="text-red-600">×</strong> pada foto. 
                    Untuk menambah foto baru, pilih file foto pada kolom "Tambah Foto Varian".
                </p>
            </div>
        </div>

        <!-- Submit -->
        <div class="flex justify-end gap-3">
            <a href="{{ route('produks.index') }}" 
               class="px-5 py-2.5 border border-gray-300 rounded-xl text-gray-700 hover:bg-gray-50">
                Batal
            </a>

            <button type="submit"
                class="px-5 py-2.5 bg-gradient-to-r from-emerald-500 to-teal-600 text-white rounded-xl shadow hover:scale-[1.02] transition">
                Simpan Perubahan
            </button>
        </div>

    </form>
</div>

<!-- TEMPLATE VARIAN -->
<template id="varian-template">
    <div class="varian-item border border-gray-200 rounded-xl p-4 bg-gray-50">
        <input type="hidden" name="varians[INDEX][id]" class="varian-id">

        <div class="grid grid-cols-1 md:grid-cols-5 gap-3">
            <div>
                <label class="block text-xs text-gray-600 mb-1">Ukuran</label>
                <input type="text" name="varians[INDEX][ukuran]" placeholder="S, M, L, XL"
                    class="w-full px-3 py-2 border rounded-lg">
            </div>
            <div>
                <label class="block text-xs text-gray-600 mb-1">Warna</label>
                <input type="text" name="varians[INDEX][warna]" placeholder="Merah, Biru, Hitam"
                    class="w-full px-3 py-2 border rounded-lg">
            </div>
            <div>
                <label class="block text-xs text-gray-600 mb-1">Harga</label>
                <input type="number" name="varians[INDEX][harga]" placeholder="Harga"
                    class="w-full px-3 py-2 border rounded-lg">
            </div>
            <div>
                <label class="block text-xs text-gray-600 mb-1">Stok</label>
                <input type="number" name="varians[INDEX][stok]" placeholder="Stok"
                    class="w-full px-3 py-2 border rounded-lg">
            </div>
            <div>
                <label class="block text-xs text-gray-600 mb-1">SKU (Opsional)</label>
                <input type="text" name="varians[INDEX][sku]" placeholder="SKU-001"
                    class="w-full px-3 py-2 border rounded-lg">
            </div>
        </div>

        <!-- Foto existing -->
        <div class="mt-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">Foto Varian Saat Ini</label>
            <div class="varian-existing-photos mt-2 flex gap-3 flex-wrap"></div>
        </div>

        <!-- Upload foto baru -->
        <div class="mt-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">Tambah Foto Varian Baru</label>
            <input type="file" name="varians[INDEX][photos][]" multiple 
                   class="varian-photos-input w-full border rounded-lg px-3 py-2" 
                   accept="image/*">
            <p class="text-xs text-gray-500 mt-1">Bisa pilih lebih dari satu file (JPG, PNG, maks 2MB)</p>
        </div>

        <!-- Preview foto baru -->
        <div class="varian-new-photos-preview mt-3 flex gap-2 flex-wrap"></div>

        <div class="mt-4 text-right pt-3 border-t border-gray-200">
            <button type="button" onclick="removeVarian(this)"
                class="px-4 py-2 text-sm bg-red-500 text-white rounded-lg hover:bg-red-600 transition">
                <i class="bi bi-trash"></i> Hapus Varian
            </button>
        </div>
    </div>
</template>

<script>
let varianIndex = 0;
let existingVarians = @json($produk->varians->load('photos'));

function addVarian(data = null) {
    const container = document.getElementById('varian-container');
    const template = document.getElementById('varian-template').innerHTML;
    const currentIndex = varianIndex;
    const newHtml = template.replace(/INDEX/g, currentIndex);
    const temp = document.createElement('div');
    temp.innerHTML = newHtml;
    const el = temp.firstElementChild;

    if (data) {
        // Isi data varian
        el.querySelector('.varian-id').value = data.id || '';
        el.querySelector('[name*="[ukuran]"]').value = data.ukuran || '';
        el.querySelector('[name*="[warna]"]').value = data.warna || '';
        el.querySelector('[name*="[harga]"]').value = data.harga || '';
        el.querySelector('[name*="[stok]"]').value = data.stok || '';
        el.querySelector('[name*="[sku]"]').value = data.sku || '';

        // Tampilkan foto existing
        const photoBox = el.querySelector('.varian-existing-photos');
        if (data.photos && data.photos.length) {
            data.photos.forEach(photo => {
                const div = document.createElement('div');
                div.className = 'relative group';
                div.innerHTML = `
                    <img src="/storage/${photo.foto}" class="w-20 h-20 object-cover rounded-lg border shadow-sm">
                    <input type="hidden" name="varians[${currentIndex}][existing_photos][]" value="${photo.id}">
                    <button type="button" onclick="removeExistingPhoto(this)" 
                        class="absolute -top-2 -right-2 bg-red-500 text-white text-xs w-5 h-5 rounded-full hover:bg-red-600 transition flex items-center justify-center">
                        ×
                    </button>
                `;
                photoBox.appendChild(div);
            });
        } else {
            photoBox.innerHTML = '<p class="text-sm text-gray-400 italic">Belum ada foto</p>';
        }
    }

    // Setup event listener untuk preview foto baru
    const fileInput = el.querySelector('.varian-photos-input');
    if (fileInput) {
        fileInput.addEventListener('change', function(e) {
            const previewContainer = el.querySelector('.varian-new-photos-preview');
            previewContainer.innerHTML = '';
            Array.from(this.files).forEach(file => {
                const reader = new FileReader();
                reader.onload = function(ev) {
                    const img = document.createElement('img');
                    img.src = ev.target.result;
                    img.className = 'w-20 h-20 object-cover rounded-lg border shadow-sm';
                    previewContainer.appendChild(img);
                };
                reader.readAsDataURL(file);
            });
        });
    }

    container.appendChild(el);
    varianIndex++;
}

function removeVarian(btn) {
    if (confirm('Yakin ingin menghapus varian ini? Semua foto varian juga akan dihapus.')) {
        btn.closest('.varian-item').remove();

        if (!document.getElementById('varian-container').children.length) {
            addVarian();
        }
    }
}

function removeExistingPhoto(btn) {
    if (confirm('Hapus foto ini?')) {
        const wrapper = btn.parentElement;
        const input = wrapper.querySelector('input');
        if (input && input.value) {
            const hiddenInput = document.createElement('input');
            hiddenInput.type = 'hidden';
            hiddenInput.name = 'delete_photos[]';
            hiddenInput.value = input.value;
            document.getElementById('varian-container').appendChild(hiddenInput);
        }
        wrapper.remove();
        
        // Tampilkan pesan jika tidak ada foto lagi
        const photoBox = wrapper.closest('.varian-item').querySelector('.varian-existing-photos');
        if (photoBox && photoBox.children.length === 0) {
            photoBox.innerHTML = '<p class="text-sm text-gray-400 italic">Belum ada foto</p>';
        }
    }
}

document.addEventListener('DOMContentLoaded', () => {
    if (existingVarians.length) {
        existingVarians.forEach(v => addVarian(v));
    } else {
        addVarian();
    }
});
</script>

@endsection