@extends('layouts.admin')

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

@section('content')
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
        <div class="flex items-center space-x-3">
            <a href="{{ route('admin.master.products.index', isset($queryParams) ? $queryParams : []) }}" 
                class="flex items-center justify-center w-10 h-10 text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors duration-200">
                <i class="fas fa-arrow-left text-lg"></i>
            </a>
            <h1 class="text-2xl font-bold text-gray-800 dark:text-white">Edit Produk Jasa</h1>
        </div>
    </div>

    <!-- Form Container -->
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 transition-colors duration-300">
        <form action="{{ route('admin.master.products.update', $product->id) }}" method="POST" enctype="multipart/form-data" class="p-5" onsubmit="return validateForm()">
            @csrf
            @method('PUT')
            
            <!-- Hidden inputs untuk menyimpan query parameters -->
            @if(isset($queryParams))
                @foreach($queryParams as $key => $value)
                    @if($value)
                        <input type="hidden" name="{{ $key }}" value="{{ $value }}">
                    @endif
                @endforeach
            @endif
            
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Kiri: Data Produk & Relasi (2 kolom) -->
                <div class="lg:col-span-2 space-y-5">
                    <!-- Informasi Dasar Produk -->
                    <div class="bg-gray-50 dark:bg-gray-800/50 p-5 rounded-lg border border-gray-200 dark:border-gray-700 transition-colors duration-300">
                        <h3 class="text-base font-semibold text-gray-800 dark:text-gray-200 mb-4 flex items-center">
                            <i class="fas fa-info-circle mr-2 text-blue-600 dark:text-blue-400"></i>
                            Informasi Dasar Produk
                        </h3>
                        
                        <!-- Nama Produk -->
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Nama Produk <span class="text-red-500">*</span></label>
                            <input type="text" name="product_title" value="{{ old('product_title', $product->product_title) }}" required
                                class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors duration-200 @error('product_title') border-red-500 dark:border-red-500 @enderror"
                                placeholder="Masukkan nama produk">
                            @error('product_title')
                                <p class="mt-2 text-sm text-red-600 dark:text-red-400">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- Deskripsi -->
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Deskripsi Produk</label>
                            <textarea name="product_description" rows="4"
                                class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors duration-200 @error('product_description') border-red-500 dark:border-red-500 @enderror"
                                placeholder="Tuliskan deskripsi produk">{{ old('product_description', $product->product_description) }}</textarea>
                            @error('product_description')
                                <p class="mt-2 text-sm text-red-600 dark:text-red-400">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- Kategori -->
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Kategori Produk <span class="text-red-500">*</span></label>
                            <select name="category_id" required
                                class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors duration-200 @error('category_id') border-red-500 dark:border-red-500 @enderror">
                                <option value="">Pilih Kategori</option>
                                @foreach ($categories as $category)
                                    <option value="{{ $category->id }}"
                                        {{ old('category_id', $product->category_id ?? null) == $category->id ? 'selected' : '' }}>
                                        {{ $category->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('category_id')
                                <p class="mt-2 text-sm text-red-600 dark:text-red-400">{{ $message }}</p>
                            @enderror
                        </div>


                        <!-- Lama Pengerjaan & Garansi -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Lama Pengerjaan</label>
                                <input type="text" name="product_work_duration" value="{{ old('product_work_duration', $product->product_work_duration) }}"
                                    class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors duration-200 @error('product_work_duration') border-red-500 dark:border-red-500 @enderror"
                                    placeholder="cth: 7 hari kerja">
                                @error('product_work_duration')
                                    <p class="mt-2 text-sm text-red-600 dark:text-red-400">{{ $message }}</p>
                                @enderror
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Garansi</label>
                                <input type="text" name="product_garansi" value="{{ old('product_garansi', $product->product_garansi) }}"
                                    class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors duration-200 @error('product_garansi') border-red-500 dark:border-red-500 @enderror"
                                    placeholder="cth: 1 tahun">
                                @error('product_garansi')
                                    <p class="mt-2 text-sm text-red-600 dark:text-red-400">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>

                        <!-- Status Aktif Produk -->
                        <div class="mt-4">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Status Produk</label>
                            <div class="flex items-center">
                                <label for="is_active" class="flex items-center cursor-pointer select-none">
                                    <input type="checkbox" name="is_active" id="is_active" value="1"
                                           {{ old('is_active', $product->is_active) ? 'checked' : '' }}
                                           class="sr-only peer">
                                    <div class="w-12 h-6 bg-gray-300 dark:bg-gray-600 rounded-full relative transition 
                                                peer-checked:bg-green-500">
                                        <span class="absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow transition-all 
                                                     peer-checked:left-6"></span>
                                    </div>
                                    <span class="ml-3 text-sm text-gray-700 dark:text-gray-300 peer-checked:text-green-600">Aktif</span>
                                </label>
                                <span class="ml-3 text-xs text-gray-500 dark:text-gray-400">Nonaktif akan menyembunyikan produk dari daftar.</span>
                            </div>
                        </div>
                    </div>

                    <!-- Materials Dinamis -->
                    <div class="bg-gray-50 dark:bg-gray-800/50 p-5 rounded-lg border border-gray-200 dark:border-gray-700 transition-colors duration-300">
                        <label class="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-2 flex items-center">
                            <i class="fas fa-hammer mr-2 text-blue-600 dark:text-blue-400"></i>
                            Bahan yang Digunakan
                        </label>
                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-4">Tambahkan bahan yang diperlukan untuk produk ini. Anda bisa mengisi nama bahan bebas.</p>
                        <div id="materialsContainer" class="space-y-3">
                            @php $materialIndex = 0; @endphp
                            @forelse(($product->materials ?? []) as $selectedMaterial)
                                <div class="material-item bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700 transition-colors duration-300">
                                    <div class="flex items-start gap-3">
                                        <div class="flex-1 grid grid-cols-1 md:grid-cols-3 gap-3">
                                            <div class="md:col-span-2">
                                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Nama Bahan</label>
                                                <input type="text" name="product_materials[{{ $materialIndex }}][name]" placeholder="Contoh: Plat Baja, Stainless Steel, dll" required
                                                    class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors duration-200"
                                                    value="{{ old('product_materials.' . $materialIndex . '.name', $selectedMaterial->name ?? '') }}">
                                                <input type="hidden" name="product_materials[{{ $materialIndex }}][type]" value="material">
                                            </div>
                                            <div>
                                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Jumlah</label>
                                                <input type="number" name="product_materials[{{ $materialIndex }}][quantity]" placeholder="0" min="1" required
                                                    class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors duration-200"
                                                    value="{{ old('product_materials.' . $materialIndex . '.quantity', $selectedMaterial->quantity ?? 1) }}">
                                            </div>
                                            <div>
                                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Satuan</label>
                                                <input type="text" name="product_materials[{{ $materialIndex }}][unit]" placeholder="cth: pcs, kg, meter, dll" required
                                                    class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors duration-200"
                                                    value="{{ old('product_materials.' . $materialIndex . '.unit', $selectedMaterial->unit ?? '') }}">
                                            </div>
                                        </div>
                                        <button type="button" onclick="removeRow(this)" 
                                            class="mt-6 bg-red-500 hover:bg-red-600 text-white rounded-lg w-8 h-8 flex items-center justify-center transition-colors duration-200 flex-shrink-0">
                                            <i class="fas fa-times text-sm"></i>
                                        </button>
                                    </div>
                                </div>
                                @php $materialIndex++; @endphp
                            @empty
                                <!-- Tidak ada bahan awal -->
                            @endforelse
                        </div>
                        <button type="button" onclick="addMaterial()"
                            class="mt-4 bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg transition-colors duration-200 flex items-center font-medium">
                            <i class="fas fa-plus mr-2"></i>Tambah Bahan
                        </button>
                    </div>

                    <!-- Spareparts Dinamis -->
                    <div class="bg-gray-50 dark:bg-gray-800/50 p-5 rounded-lg border border-gray-200 dark:border-gray-700 transition-colors duration-300">
                        <label class="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-2 flex items-center">
                            <i class="fas fa-cogs mr-2 text-green-600 dark:text-green-400"></i>
                            Sparepart yang Digunakan
                        </label>
                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-4">Tambahkan sparepart yang diperlukan untuk produk ini. Anda bisa mengisi nama sparepart bebas.</p>
                        <div id="sparepartsContainer" class="space-y-3">
                            @php $sparepartIndexPrefill = 0; @endphp
                            @forelse(($product->spareparts ?? []) as $selectedSparepart)
                                <div class="sparepart-item bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700 transition-colors duration-300">
                                    <div class="flex items-start gap-3">
                                        <div class="flex-1 grid grid-cols-1 md:grid-cols-3 gap-3">
                                            <div class="md:col-span-2">
                                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Nama Sparepart</label>
                                                <input type="text" name="product_spareparts[{{ $sparepartIndexPrefill }}][name]" placeholder="Contoh: Baut M8, Bearing, dll" required
                                                    class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 dark:bg-gray-700 dark:text-white transition-colors duration-200"
                                                    value="{{ old('product_spareparts.' . $sparepartIndexPrefill . '.name', $selectedSparepart->name ?? '') }}">
                                                <input type="hidden" name="product_spareparts[{{ $sparepartIndexPrefill }}][type]" value="sparepart">
                                            </div>
                                            <div>
                                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Jumlah</label>
                                                <input type="number" name="product_spareparts[{{ $sparepartIndexPrefill }}][quantity]" placeholder="0" min="1" required
                                                    class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 dark:bg-gray-700 dark:text-white transition-colors duration-200"
                                                    value="{{ old('product_spareparts.' . $sparepartIndexPrefill . '.quantity', $selectedSparepart->quantity ?? 1) }}">
                                            </div>
                                            <div>
                                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Satuan</label>
                                                <input type="text" name="product_spareparts[{{ $sparepartIndexPrefill }}][unit]" placeholder="cth: pcs, kg, meter, dll" required
                                                    class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 dark:bg-gray-700 dark:text-white transition-colors duration-200"
                                                    value="{{ old('product_spareparts.' . $sparepartIndexPrefill . '.unit', $selectedSparepart->unit ?? '') }}">
                                            </div>
                                        </div>
                                        <button type="button" onclick="removeRow(this)" 
                                            class="mt-6 bg-red-500 hover:bg-red-600 text-white rounded-lg w-8 h-8 flex items-center justify-center transition-colors duration-200 flex-shrink-0">
                                            <i class="fas fa-times text-sm"></i>
                                        </button>
                                    </div>
                                </div>
                                @php $sparepartIndexPrefill++; @endphp
                            @empty
                                <!-- Tidak ada sparepart awal -->
                            @endforelse
                        </div>
                        <button type="button" onclick="addSparepart()"
                            class="mt-4 bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors duration-200 flex items-center font-medium">
                            <i class="fas fa-plus mr-2"></i>Tambah Sparepart
                        </button>
                    </div>

                    <!-- Specifications Dinamis -->
                    <div class="bg-gray-50 dark:bg-gray-800/50 p-5 rounded-lg border border-gray-200 dark:border-gray-700 transition-colors duration-300">
                        <label class="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-4 flex items-center">
                            <i class="fas fa-list-alt mr-2 text-orange-600 dark:text-orange-400"></i>
                            Spesifikasi Produk (Opsional)
                        </label>
                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-4">Tambahkan spesifikasi seperti dimensi, kapasitas, dll.</p>
                        
                        <div id="specificationsContainer" class="space-y-4">
                            @php $specIndexPrefill = 0; @endphp
                            @forelse(($product->specifications ?? []) as $spec)
                                <div class="space-y-3 spec-item bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700 transition-colors duration-300">
                                    <div class="grid grid-cols-2 gap-3">
                                        <input type="text" name="product_specifications[{{ $specIndexPrefill }}][key]" placeholder="Nama spesifikasi (cth: Panjang)"
                                            class="px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 dark:bg-gray-700 dark:text-white transition-colors duration-200"
                                            value="{{ old('product_specifications.' . $specIndexPrefill . '.key', $spec->key) }}">
                                        <input type="text" name="product_specifications[{{ $specIndexPrefill }}][value]" placeholder="Nilai (cth: 150 cm)"
                                            class="px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 dark:bg-gray-700 dark:text-white transition-colors duration-200"
                                            value="{{ old('product_specifications.' . $specIndexPrefill . '.value', $spec->value) }}">
                                    </div>
                                    <div class="flex justify-end">
                                        <button type="button" onclick="removeRow(this)"
                                            class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg transition duration-200 shadow-sm">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                </div>
                                @php $specIndexPrefill++; @endphp
                            @empty
                                <!-- Tidak ada spesifikasi awal -->
                            @endforelse
                        </div>
                        
                        <button type="button" onclick="addSpecification()"
                            class="mt-4 bg-orange-500 hover:bg-orange-600 text-white px-4 py-2 rounded-lg transition-colors duration-200 flex items-center font-medium">
                            <i class="fas fa-plus mr-2"></i>Tambah Spesifikasi
                        </button>
                    </div>

                    <!-- Kalkulasi Biaya -->
                    <div class="bg-gray-50 dark:bg-gray-800/50 p-5 rounded-lg border border-gray-200 dark:border-gray-700 transition-colors duration-300">
                        <h3 class="text-base font-semibold text-gray-800 dark:text-gray-200 mb-4 flex items-center">
                            <i class="fas fa-calculator mr-2 text-purple-600 dark:text-purple-400"></i>
                            Kalkulasi Biaya Produk
                        </h3>
                        
                        <!-- Harga Produk -->
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Harga Produk (Rp) <span class="text-red-500">*</span></label>
                            <input type="number" name="product_prices" id="product_prices" placeholder="Harga jual produk" min="1" value="{{ old('product_prices', $product->product_prices) }}"
                                class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 dark:bg-gray-700 dark:text-white transition-colors duration-200 @error('product_prices') border-red-500 dark:border-red-500 @enderror"
                                onchange="calculateProfit()" required>
                            @error('product_prices')
                                <p class="mt-2 text-sm text-red-600 dark:text-red-400">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- Upah Jasa -->
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Upah Jasa Pengerjaan (Rp)</label>
                            <input type="number" name="service_fee" id="service_fee" placeholder="Upah jasa" min="0" value="{{ old('service_fee', $product->service_fee) }}"
                                class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 dark:bg-gray-700 dark:text-white transition-colors duration-200 @if(isset($mismatchedProductions) && $mismatchedProductions->count() > 0) border-orange-500 dark:border-orange-500 @endif"
                                onchange="calculateProfit()">
                            
                            @if(isset($mismatchedProductions) && $mismatchedProductions->count() > 0)
                                <div class="mt-3 bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-700 rounded-lg p-4">
                                    <div class="flex items-start">
                                        <div class="flex-shrink-0">
                                            <i class="fas fa-exclamation-triangle text-orange-600 dark:text-orange-400 text-lg"></i>
                                        </div>
                                        <div class="ml-3 flex-1">
                                            <h4 class="text-sm font-semibold text-orange-800 dark:text-orange-200 mb-2">
                                                Peringatan: Ada {{ $mismatchedProductions->count() }} produksi dengan labor cost berbeda!
                                            </h4>
                                            <p class="text-xs text-orange-700 dark:text-orange-300 mb-3">
                                                Upah jasa yang Anda input (Rp {{ number_format($product->service_fee ?? 0, 0, ',', '.') }}) tidak sesuai dengan labor cost yang diinput teknisi pada beberapa produksi. Pertimbangkan untuk memperbarui nilai ini.
                                            </p>
                                            <div class="mt-3 space-y-2 max-h-48 overflow-y-auto">
                                                @foreach($mismatchedProductions->take(5) as $production)
                                                    <div class="bg-white dark:bg-gray-800 rounded p-2 text-xs border border-orange-200 dark:border-orange-700">
                                                        <div class="flex justify-between items-center">
                                                            <div>
                                                                <span class="font-medium text-gray-900 dark:text-gray-100">
                                                                    Production #{{ $production->id }}
                                                                </span>
                                                                @if($production->order)
                                                                    <span class="text-gray-600 dark:text-gray-400">
                                                                        - Order #{{ $production->order->order_number ?? $production->order->id }}
                                                                    </span>
                                                                @endif
                                                            </div>
                                                            <span class="font-semibold {{ $production->labor_cost > ($product->service_fee ?? 0) ? 'text-red-600 dark:text-red-400' : 'text-green-600 dark:text-green-400' }}">
                                                                Rp {{ number_format($production->labor_cost, 0, ',', '.') }}
                                                            </span>
                                                        </div>
                                                        <div class="mt-1 text-gray-600 dark:text-gray-400">
                                                            <span class="text-gray-500">Default: Rp {{ number_format($product->service_fee ?? 0, 0, ',', '.') }}</span>
                                                            <span class="mx-2">•</span>
                                                            <span class="{{ $production->labor_cost > ($product->service_fee ?? 0) ? 'text-red-600' : 'text-green-600' }}">
                                                                Selisih: {{ $production->labor_cost > ($product->service_fee ?? 0) ? '+' : '' }}Rp {{ number_format(abs($production->labor_cost - ($product->service_fee ?? 0)), 0, ',', '.') }}
                                                            </span>
                                                            @if($production->notes)
                                                                <div class="mt-1 text-gray-500 italic">
                                                                    <i class="fas fa-comment"></i> {{ Str::limit($production->notes, 50) }}
                                                                </div>
                                                            @endif
                                                        </div>
                                                    </div>
                                                @endforeach
                                                @if($mismatchedProductions->count() > 5)
                                                    <p class="text-xs text-orange-600 dark:text-orange-400 text-center italic">
                                                        ... dan {{ $mismatchedProductions->count() - 5 }} produksi lainnya
                                                    </p>
                                                @endif
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            @endif
                        </div>

                        <!-- Summary Biaya -->
                        <div class="bg-white dark:bg-gray-700/50 p-4 rounded-lg border border-gray-200 dark:border-gray-600">
                            <h4 class="font-semibold text-gray-800 dark:text-gray-200 mb-3">Ringkasan Biaya & Keuntungan:</h4>
                            <div class="space-y-2 text-sm">
                                <div class="flex justify-between">
                                    <span class="text-gray-600 dark:text-gray-400">Upah Jasa:</span>
                                    <span id="service_fee_display" class="font-semibold text-purple-600 dark:text-purple-400">Rp 0</span>
                                </div>
                                <hr class="border-gray-300 dark:border-gray-700">
                                <div class="flex justify-between text-lg font-bold">
                                    <span class="text-gray-800 dark:text-gray-200">Harga Jual Produk:</span>
                                    <span id="product_price_display" class="text-blue-600 dark:text-blue-400">Rp 0</span>
                                </div>
                                <hr class="border-gray-300 dark:border-gray-700">
                                <div class="flex justify-between text-xl font-bold">
                                    <span class="text-gray-800 dark:text-gray-200">Keuntungan:</span>
                                    <span id="profit_amount" class="text-green-600 dark:text-green-400">Rp 0</span>
                                </div>
                                <div class="flex justify-between text-sm">
                                    <span class="text-gray-600 dark:text-gray-400">Persentase Keuntungan:</span>
                                    <span id="profit_percentage" class="font-semibold text-green-600 dark:text-green-400">0%</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Kanan: Gambar (1 kolom) -->
                <div class="space-y-5">
                    <!-- Gambar Utama -->
                    <div class="bg-gray-50 dark:bg-gray-800/50 p-5 rounded-lg border border-gray-200 dark:border-gray-700 transition-colors duration-300">
                        <label class="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-4 flex items-center">
                            <i class="fas fa-image mr-2 text-orange-600 dark:text-orange-400"></i>
                            Gambar Utama
                        </label>
                        <div class="relative">
                            <input type="file" name="product_image" id="product_image" accept="image/*"
                                class="hidden" onchange="previewMainImage(event)">
                            <label for="product_image"
                                class="flex items-center justify-center w-full h-24 bg-gray-50 dark:bg-gray-800 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer hover:border-gray-400 dark:hover:border-gray-500 transition duration-300">
                                <i class="fas fa-cloud-upload-alt text-2xl text-orange-400 dark:text-orange-500 mr-2"></i>
                                <span class="text-sm text-gray-600 dark:text-gray-300 font-medium">Upload gambar utama</span>
                            </label>
                            <p class="mt-2 text-xs text-gray-500 dark:text-gray-400">Unggah minimal 1 gambar (jpg, jpeg, png, max 2MB).</p>
                            @error('product_image')
                                <p class="mt-2 text-sm text-red-600 dark:text-red-400">{{ $message }}</p>
                            @enderror

                            <!-- Preview Gambar Utama -->
                            <input type="hidden" name="remove_main_image" id="remove_main_image" value="0">
                            <div id="mainImagePreviewContainer" style="{{ ($product->product_image && file_exists(public_path('uploads/products/' . $product->product_image))) ? '' : 'display:none;' }}"
                                class="relative mt-4 w-full h-64 bg-gray-50 dark:bg-gray-700/50 rounded-lg border-2 {{ ($product->product_image && file_exists(public_path('uploads/products/' . $product->product_image))) ? 'border-solid border-gray-200 dark:border-gray-600' : 'border-dashed border-gray-300 dark:border-gray-600' }} overflow-hidden transition-colors duration-300">
                                <img id="previewImage" class="w-full h-full object-contain" 
                                     @if ($product->product_image && file_exists(public_path('uploads/products/' . $product->product_image)))
                                         src="{{ asset('uploads/products/' . $product->product_image) }}"
                                         style="background: transparent;"
                                     @else
                                         style="background: transparent;"
                                     @endif>
                                <button type="button" id="removeMainImage"
                                    class="absolute top-2 right-2 bg-red-500 hover:bg-red-600 text-white rounded-lg w-8 h-8 flex items-center justify-center transition">
                                    <i class="fas fa-times text-sm"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Gambar Tambahan -->
                    <div class="bg-gray-50 dark:bg-gray-800/50 p-5 rounded-lg border border-gray-200 dark:border-gray-700 transition-colors duration-300">
                        <label class="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-4 flex items-center">
                            <i class="fas fa-images mr-2 text-cyan-600 dark:text-cyan-400"></i>
                            Gambar Tambahan
                        </label>
                        
                        <!-- Upload Area -->
                        <div class="relative mb-4">
                            <input type="file" name="product_images[]" accept="image/*" id="product_images" multiple
                                class="hidden" onchange="previewAdditionalImages(event)">
                            <label for="product_images"
                                class="flex items-center justify-center w-full h-32 bg-gray-50 dark:bg-gray-800 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer hover:border-gray-400 dark:hover:border-gray-500 transition duration-300">
                                <div class="text-center">
                                    <i class="fas fa-cloud-upload-alt text-3xl text-cyan-400 dark:text-cyan-500 mb-2"></i>
                                    <p class="text-sm text-gray-600 dark:text-gray-300 font-medium">Klik untuk upload gambar (bisa pilih banyak)</p>
                                    <p class="text-xs text-gray-500 dark:text-gray-400">Maksimal 5 gambar (jpg, jpeg, png, max 2MB)</p>
                                </div>
                            </label>
                        </div>

                        <!-- Gambar Tersimpan -->
                        @if($product->images && $product->images->count() > 0)
                            <input type="hidden" name="remove_images" id="remove_images" value="">
                            <div class="mb-4">
                                <label class="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-2 flex items-center">
                                    <i class="fas fa-photo-video mr-2 text-cyan-600 dark:text-cyan-400"></i>
                                    Gambar Tersimpan
                                </label>
                                <div id="existingImagesContainer" class="grid grid-cols-2 gap-3">
                                    @foreach($product->images as $img)
                                        <div class="relative border border-gray-200 dark:border-gray-600 rounded-lg overflow-hidden bg-gray-50 dark:bg-gray-700/50" data-image-id="{{ $img->id }}">
                                            <img src="{{ asset('uploads/products/' . $img->image_path) }}" alt="Gambar" class="w-full h-32 object-contain p-2" style="background: transparent;">
                                            <button type="button" onclick="removeExistingImage({{ $img->id }}, this)"
                                                class="absolute top-2 right-2 bg-red-500 hover:bg-red-600 text-white rounded-lg w-8 h-8 flex items-center justify-center transition">
                                                <i class="fas fa-times text-sm"></i>
                                            </button>
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        @endif

                        <!-- Upload Satu per Satu -->
                        <div class="mb-4">
                            <button type="button" onclick="addSingleImageUpload()"
                                class="w-full bg-cyan-500 hover:bg-cyan-600 text-white font-medium py-2 px-4 rounded-lg transition-colors duration-200 flex items-center justify-center">
                                <i class="fas fa-plus mr-2"></i>
                                Tambah Gambar Satu per Satu
                            </button>
                        </div>

                        <!-- Container untuk upload satu per satu -->
                        <div id="singleImageUploads" class="space-y-3"></div>

                        <!-- Preview Container -->
                        <div id="additionalImagesPreview" class="mt-4 grid grid-cols-2 gap-3"></div>
                    </div>
                </div>
            </div>

            <!-- Tombol Submit dan Cancel -->
            <div class="flex flex-col sm:flex-row justify-end space-y-3 sm:space-y-0 sm:space-x-3 pt-6 mt-6 border-t border-gray-200 dark:border-gray-700">
                <a href="{{ route('admin.master.products.index', isset($queryParams) ? $queryParams : []) }}"
                    class="flex items-center justify-center px-6 py-3 text-gray-600 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors duration-200 font-medium">
                    Batal
                </a>
                <button type="submit"
                    class="flex items-center justify-center bg-blue-500 hover:bg-blue-600 text-white font-medium py-3 px-6 rounded-lg transition-colors duration-200">
                    <i class="fas fa-save mr-2"></i>
                    <span>Perbarui Produk</span>
                </button>
            </div>
        </form>
    </div>

    <script>
        let materialIndex = {{ isset($product) && isset($product->materials) ? $product->materials->count() : 0 }};
        let sparepartIndex = {{ isset($product) && isset($product->spareparts) ? $product->spareparts->count() : 0 }};
        let specIndex = {{ isset($product) && isset($product->specifications) ? $product->specifications->count() : 0 }};
        let extraFiles = [];
        let singleImageIndex = 0;
        let removeImageIds = [];

        // Preview Gambar Utama
        const mainImageInput = document.getElementById('product_image');
        const previewImage = document.getElementById('previewImage');
        const mainImagePreviewContainer = document.getElementById('mainImagePreviewContainer');
        const removeMainImageBtn = document.getElementById('removeMainImage');

        mainImageInput.addEventListener('change', function(event) {
            const file = event.target.files[0];

            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImage.src = e.target.result;
                    previewImage.style.background = 'transparent';
                    mainImagePreviewContainer.style.display = 'block';
                    mainImagePreviewContainer.classList.remove('border-dashed');
                    mainImagePreviewContainer.classList.add('border-solid');
                };
                reader.readAsDataURL(file);
            }
        });

        removeMainImageBtn.addEventListener('click', function() {
            mainImageInput.value = '';
            previewImage.src = '';
            previewImage.style.background = '';
            mainImagePreviewContainer.style.display = 'none';
            mainImagePreviewContainer.classList.add('border-dashed');
            mainImagePreviewContainer.classList.remove('border-solid');
            const rm = document.getElementById('remove_main_image');
            if (rm) rm.value = '1';
        });

        // Preview gambar tambahan dengan remove button
        function previewAdditionalImages(event) {
            const previewContainer = document.getElementById('additionalImagesPreview');
            const input = event.target;
            previewContainer.innerHTML = '';
            extraFiles = Array.from(input.files).slice(0, 5);

            extraFiles.forEach((file, index) => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const div = document.createElement('div');
                    div.className = 'relative';
                    div.innerHTML = `
                        <img src="${e.target.result}" class="w-full h-32 object-contain rounded border border-gray-200 dark:border-gray-600" style="background: transparent;">
                        <button type="button" onclick="removeExtraImage(${index})"
                            class="absolute -top-1 -right-1 bg-red-500 hover:bg-red-600 text-white rounded-full w-6 h-6 flex items-center justify-center transition-colors duration-200">
                            <i class="fas fa-times text-xs"></i>
                        </button>
                    `;
                    previewContainer.appendChild(div);
                };
                reader.readAsDataURL(file);
            });
        }

        function removeExtraImage(index) {
            extraFiles.splice(index, 1);
            const dataTransfer = new DataTransfer();
            extraFiles.forEach(file => dataTransfer.items.add(file));
            document.getElementById('product_images').files = dataTransfer.files;

            // Re-render preview
            const event = new Event('change', {
                bubbles: true
            });
            document.getElementById('product_images').dispatchEvent(event);
        }

        // Upload gambar satu per satu
        function addSingleImageUpload() {
            const container = document.getElementById('singleImageUploads');
            const div = document.createElement('div');
            div.className = 'single-image-upload bg-white dark:bg-gray-600 p-4 rounded-lg border border-cyan-200 dark:border-cyan-600 transition-colors duration-300';
                    div.innerHTML = `
                <div class="flex items-center space-x-3">
                    <input type="file" name="product_images[]" accept="image/*" id="single_image_${singleImageIndex}" 
                        class="hidden" onchange="previewSingleImage(this, ${singleImageIndex})">
                    <label for="single_image_${singleImageIndex}" 
                        class="flex-1 flex items-center justify-center h-20 bg-gray-50 dark:bg-gray-800 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer hover:border-gray-400 dark:hover:border-gray-500 transition duration-300">
                        <div class="text-center">
                            <i class="fas fa-image text-lg text-cyan-400 dark:text-cyan-500 mr-2"></i>
                            <span class="text-sm text-gray-600 dark:text-gray-300">Pilih Gambar</span>
                        </div>
                    </label>
                    <button type="button" onclick="removeSingleImageUpload(this)" 
                        class="bg-red-500 hover:bg-red-600 text-white rounded-lg w-8 h-8 flex items-center justify-center transition duration-200">
                        <i class="fas fa-times text-sm"></i>
                    </button>
                </div>
                <div id="single_preview_${singleImageIndex}" class="mt-3 hidden">
                    <img id="single_img_${singleImageIndex}" class="w-full h-32 object-contain rounded border border-gray-200 dark:border-gray-600" style="background: transparent;">
                </div>
            `;
            container.appendChild(div);
            singleImageIndex++;
        }

        // Preview gambar satu per satu
        function previewSingleImage(input, index) {
            const file = input.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const previewImg = document.getElementById(`single_img_${index}`);
                    const previewDiv = document.getElementById(`single_preview_${index}`);
                    previewImg.src = e.target.result;
                    previewDiv.classList.remove('hidden');
                };
                reader.readAsDataURL(file);
            }
        }

        // Hapus gambar tersimpan langsung
        function removeExistingImage(id, btn) {
            // Tambahkan ID ke array untuk dikirim ke server
            if (removeImageIds.indexOf(id) === -1) {
                removeImageIds.push(id);
            }
            
            // Update hidden input
            const hidden = document.getElementById('remove_images');
            if (hidden) hidden.value = removeImageIds.join(',');
            
            // Hapus elemen gambar dari DOM langsung
            const imageContainer = btn.closest('[data-image-id]');
            if (imageContainer) {
                imageContainer.remove();
            }
            
            // Cek jika tidak ada gambar tersisa, sembunyikan container
            const container = document.getElementById('existingImagesContainer');
            if (container && container.children.length === 0) {
                container.closest('.mb-4').style.display = 'none';
            }
        }

        // Hapus upload gambar satu per satu
        function removeSingleImageUpload(button) {
            const container = button.closest('.single-image-upload');
            container.remove();
        }

        // Tambah Material
        function addMaterial() {
            const container = document.getElementById('materialsContainer');
            const div = document.createElement('div');
            div.className = 'material-item bg-white dark:bg-gray-700/50 p-4 rounded-lg border border-gray-200 dark:border-gray-600 transition-colors duration-300';
            div.innerHTML = `
                <div class="flex items-start gap-3">
                    <div class="flex-1 grid grid-cols-1 md:grid-cols-3 gap-3">
                        <div class="md:col-span-2">
                            <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Nama Bahan</label>
                            <input type="text" name="product_materials[${materialIndex}][name]" placeholder="Contoh: Plat Baja, Stainless Steel, dll" required
                                class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors duration-200">
                            <input type="hidden" name="product_materials[${materialIndex}][type]" value="material">
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Jumlah</label>
                            <input type="number" name="product_materials[${materialIndex}][quantity]" placeholder="0" min="1" required
                                class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors duration-200">
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Satuan</label>
                            <input type="text" name="product_materials[${materialIndex}][unit]" placeholder="cth: pcs, kg, meter, dll" required
                                class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors duration-200">
                        </div>
                    </div>
                    <button type="button" onclick="removeRow(this)" 
                        class="mt-6 bg-red-500 hover:bg-red-600 text-white rounded-lg w-8 h-8 flex items-center justify-center transition-colors duration-200 flex-shrink-0">
                        <i class="fas fa-times text-sm"></i>
                    </button>
                </div>
            `;
            container.appendChild(div);
            materialIndex++;
        }

        // Tambah Sparepart
        function addSparepart() {
            const container = document.getElementById('sparepartsContainer');
            const div = document.createElement('div');
            div.className = 'sparepart-item bg-white dark:bg-gray-700/50 p-4 rounded-lg border border-gray-200 dark:border-gray-600 transition-colors duration-300';
            div.innerHTML = `
                <div class="flex items-start gap-3">
                    <div class="flex-1 grid grid-cols-1 md:grid-cols-3 gap-3">
                        <div class="md:col-span-2">
                            <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Nama Sparepart</label>
                            <input type="text" name="product_spareparts[${sparepartIndex}][name]" placeholder="Contoh: Baut M8, Bearing, dll" required
                                class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 dark:bg-gray-700 dark:text-white transition-colors duration-200">
                            <input type="hidden" name="product_spareparts[${sparepartIndex}][type]" value="sparepart">
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Jumlah</label>
                            <input type="number" name="product_spareparts[${sparepartIndex}][quantity]" placeholder="0" min="1" required
                                class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 dark:bg-gray-700 dark:text-white transition-colors duration-200">
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Satuan</label>
                            <input type="text" name="product_spareparts[${sparepartIndex}][unit]" placeholder="cth: pcs, kg, meter, dll" required
                                class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 dark:bg-gray-700 dark:text-white transition-colors duration-200">
                        </div>
                    </div>
                    <button type="button" onclick="removeRow(this)" 
                        class="mt-6 bg-red-500 hover:bg-red-600 text-white rounded-lg w-8 h-8 flex items-center justify-center transition-colors duration-200 flex-shrink-0">
                        <i class="fas fa-times text-sm"></i>
                    </button>
                </div>
            `;
            container.appendChild(div);
            sparepartIndex++;
        }

        // Tambah Spesifikasi
        function addSpecification() {
            const container = document.getElementById('specificationsContainer');
            const div = document.createElement('div');
            div.className = 'space-y-3 spec-item bg-white dark:bg-gray-700/50 p-4 rounded-lg border border-gray-200 dark:border-gray-600 transition-colors duration-300';
            div.innerHTML = `
                <div class="grid grid-cols-2 gap-3">
                    <input type="text" name="product_specifications[${specIndex}][key]" placeholder="Nama spesifikasi (cth: Panjang)"
                        class="px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 dark:bg-gray-700 dark:text-white transition-colors duration-200">
                    <input type="text" name="product_specifications[${specIndex}][value]" placeholder="Nilai (cth: 150 cm)"
                        class="px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 dark:bg-gray-700 dark:text-white transition-colors duration-200">
                </div>
                <div class="flex justify-end">
                    <button type="button" onclick="removeRow(this)"
                        class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg transition-colors duration-200 font-medium">
                        <i class="fas fa-times mr-1"></i>Hapus
                    </button>
                </div>
            `;
            container.appendChild(div);
            specIndex++;
        }

        // Remove row universal (untuk materials dan spareparts)
        function removeRow(button) {
            const parent = button.closest('.material-item, .sparepart-item, .spec-item');
            if (parent) {
                parent.remove();
            }
        }

        // Kalkulasi keuntungan
        function calculateProfit() {
            let serviceFee = parseFloat(document.getElementById('service_fee').value) || 0;
            let productPrice = parseFloat(document.getElementById('product_prices').value) || 0;

            const totalProductionCost = serviceFee;
            const profit = productPrice - totalProductionCost;
            const profitPercentage = totalProductionCost > 0 ? ((profit / totalProductionCost) * 100) : 0;

            // Update display
            document.getElementById('service_fee_display').textContent = 'Rp ' + serviceFee.toLocaleString('id-ID');
            document.getElementById('product_price_display').textContent = 'Rp ' + productPrice.toLocaleString('id-ID');
            
            // Update profit display
            const profitElement = document.getElementById('profit_amount');
            const percentageElement = document.getElementById('profit_percentage');
            
            if (profit >= 0) {
                profitElement.textContent = 'Rp ' + profit.toLocaleString('id-ID');
                profitElement.className = 'text-green-600 dark:text-green-400 text-xl font-bold';
                percentageElement.textContent = profitPercentage.toFixed(1) + '%';
                percentageElement.className = 'font-semibold text-green-600 dark:text-green-400';
            } else {
                profitElement.textContent = 'Rp ' + Math.abs(profit).toLocaleString('id-ID');
                profitElement.className = 'text-red-600 dark:text-red-400 text-xl font-bold';
                percentageElement.textContent = '-' + Math.abs(profitPercentage).toFixed(1) + '%';
                percentageElement.className = 'font-semibold text-red-600 dark:text-red-400';
            }
        }


        // Validasi form sebelum submit
        function validateForm() {
            console.log('Form validation started...');
            
            // Cek field required
            const productTitle = document.querySelector('input[name="product_title"]');
            const productPrices = document.querySelector('input[name="product_prices"]');
            const categoryId = document.querySelector('select[name="category_id"]');
            
            if (!productTitle.value.trim()) {
                alert('Nama Produk harus diisi!');
                productTitle.focus();
                return false;
            }
            
            if (!productPrices.value || productPrices.value <= 0) {
                alert('Harga Produk harus diisi dan lebih dari 0!');
                productPrices.focus();
                return false;
            }
            
            if (!categoryId.value) {
                alert('Kategori Produk harus dipilih!');
                categoryId.focus();
                return false;
            }
            
            console.log('Form validation passed, submitting...');
            return true;
        }

        // Debug form submission
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.querySelector('form');
            if (form) {
                form.addEventListener('submit', function(e) {
                    console.log('Form submit event triggered');
                    console.log('Form action:', form.action);
                    console.log('Form method:', form.method);
                    console.log('Form data:', new FormData(form));
                });
            }
            // Hitung ringkasan biaya saat halaman dibuka
            calculateProfit();
        });
    </script>
@endsection