

<?php $__env->startSection('title', ($type ?? 'material') === 'sparepart' ? 'Tambah Pembelian Sparepart' : 'Tambah Pembelian Material'); ?>

<?php $__env->startSection('content'); ?>
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
        <div class="flex items-center space-x-3">
        <a href="<?php echo e(route('admin.transaksi.purchases.index')); ?>"
                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>
            <div>
                <h1 class="text-2xl font-bold text-gray-800 dark:text-white">
                    <?php echo e(($type ?? 'material') === 'sparepart' ? 'Tambah Pembelian Sparepart' : 'Tambah Pembelian Material'); ?>

                </h1>
                <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    <?php echo e(($type ?? 'material') === 'sparepart' ? 'Beli sparepart baru atau tambah stok sparepart yang sudah ada' : 'Beli material baru atau tambah stok material yang sudah ada'); ?>

                </p>
            </div>
        </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="<?php echo e(route('admin.transaksi.purchases.store')); ?>" method="POST" enctype="multipart/form-data" id="purchaseForm" class="p-5">
            <?php echo csrf_field(); ?>
            <input type="hidden" name="purchase_type" value="<?php echo e($type ?? 'material'); ?>">
            <?php if(isset($prefillData) && isset($prefillData['item_request_id'])): ?>
            <input type="hidden" name="from_item_request" value="<?php echo e($prefillData['item_request_id']); ?>">
            <?php endif; ?>

            <!-- Header Info -->
            <div class="mb-6 pb-6 border-b border-gray-200 dark:border-gray-700">
                <h2 class="text-lg font-semibold text-gray-800 dark:text-white mb-4">Informasi Pembelian</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Tanggal Pembelian <span class="text-red-500">*</span>
                        </label>
                        <input type="date" name="purchase_date" value="<?php echo e(old('purchase_date', date('Y-m-d'))); ?>" required
                            class="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm">
                        <?php $__errorArgs = ['purchase_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="text-red-500 text-xs mt-1"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Supplier</label>
                        <input type="text" name="supplier_name" value="<?php echo e(old('supplier_name')); ?>"
                            placeholder="Nama supplier" 
                            class="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm">
                        <?php $__errorArgs = ['supplier_name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="text-red-500 text-xs mt-1"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                </div>
                <div class="mt-5">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Catatan</label>
                    <textarea name="notes" rows="2"
                        class="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 resize-none text-sm"
                        placeholder="Catatan tambahan (opsional)"><?php echo e(old('notes')); ?></textarea>
            </div>
                </div>
                
            <!-- Items Container -->
            <div id="itemsContainer" class="space-y-5 mb-6">
                <?php if(old('items') && count(old('items')) > 0): ?>
                    <?php $__currentLoopData = old('items'); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $oldItem): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <?php if(($type ?? 'material') === 'sparepart'): ?>
                            <?php echo $__env->make('admin.transaksi.purchases.partials.sparepart-form', ['index' => $index, 'oldItem' => $oldItem], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                        <?php else: ?>
                            <?php echo $__env->make('admin.transaksi.purchases.partials.material-form', ['index' => $index, 'oldItem' => $oldItem], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                        <?php endif; ?>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                <?php else: ?>
                    <?php if(($type ?? 'material') === 'sparepart'): ?>
                        <?php echo $__env->make('admin.transaksi.purchases.partials.sparepart-form', ['index' => 0], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                    <?php else: ?>
                        <?php echo $__env->make('admin.transaksi.purchases.partials.material-form', ['index' => 0], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                    <?php endif; ?>
                <?php endif; ?>
                    </div>
                    
            <!-- Add Item Button -->
            <div class="flex justify-center my-6">
                <button type="button" id="addItemBtn"
                    class="flex items-center bg-blue-500 hover:bg-blue-600 text-white font-medium px-6 py-3 rounded-lg transition-colors duration-200">
                    <i class="fas fa-plus mr-2"></i>
                    <span><?php echo e(($type ?? 'material') === 'sparepart' ? 'Tambah Sparepart Lain' : 'Tambah Material Lain'); ?></span>
                        </button>
            </div>

            <!-- Action Buttons -->
            <div class="flex justify-end space-x-3 pt-6 border-t border-gray-200 dark:border-gray-700">
                <a href="<?php echo e(route('admin.transaksi.purchases.index')); ?>"
                    class="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="px-6 py-3 bg-blue-500 hover:bg-blue-600 text-white font-medium rounded-lg transition-colors duration-200 flex items-center space-x-2">
                    <i class="fas fa-save"></i>
                    <span>Simpan Pembelian</span>
                </button>
            </div>
        </form>
    </div>

    <?php if($prefillData ?? null): ?>
    <div class="mb-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
        <div class="flex items-center gap-3">
            <div class="w-10 h-10 bg-blue-100 dark:bg-blue-900/40 rounded-lg flex items-center justify-center">
                <i class="fas fa-info-circle text-blue-600 dark:text-blue-400"></i>
            </div>
            <div class="flex-1">
                <h3 class="text-sm font-semibold text-blue-900 dark:text-blue-200">Data dari Item Request</h3>
                <p class="text-xs text-blue-700 dark:text-blue-300 mt-0.5">Form akan diisi otomatis dengan data dari request teknisi</p>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <script>
        const itemType = '<?php echo e($type ?? 'material'); ?>';
        let itemIndex = <?php echo e(old('items') ? count(old('items')) : 1); ?>;
        const materials = <?php echo json_encode($materialsForJs, 15, 512) ?>;
        const spareparts = <?php echo json_encode($sparepartsForJs, 15, 512) ?>;
        const prefillData = <?php echo json_encode($prefillData ?? null, 15, 512) ?>;
        
        // Prefill form jika ada data dari item request
        <?php if($prefillData ?? null): ?>
        document.addEventListener('DOMContentLoaded', function() {
            // Tunggu sebentar untuk memastikan form sudah di-render
            setTimeout(function() {
                // Cari form pertama (form dengan index 0)
                const itemsContainer = document.getElementById('itemsContainer');
                const firstItemForm = itemsContainer ? itemsContainer.querySelector('div.bg-white') : null;
                
                if (firstItemForm && prefillData) {
                    // Set item type radio button jika perlu
                    const purchaseTypeInput = document.querySelector(`input[name="purchase_type"][value="${prefillData.item_type}"]`);
                    if (purchaseTypeInput) {
                        purchaseTypeInput.checked = true;
                    }
                    
                    // Set item select dropdown
                    const itemTypeSelect = firstItemForm.querySelector('select[name*="[item_id]"]');
                    if (itemTypeSelect) {
                        // Jika ada material_id atau sparepart_id, pilih dari dropdown
                        if (prefillData.material_id) {
                            itemTypeSelect.value = prefillData.material_id;
                            // Trigger change event untuk auto-fill data lainnya
                            const changeEvent = new Event('change', { bubbles: true });
                            itemTypeSelect.dispatchEvent(changeEvent);
                        } else if (prefillData.sparepart_id) {
                            itemTypeSelect.value = prefillData.sparepart_id;
                            // Trigger change event untuk auto-fill data lainnya
                            const changeEvent = new Event('change', { bubbles: true });
                            itemTypeSelect.dispatchEvent(changeEvent);
                        } else {
                            // Item baru, tidak pilih dari dropdown (biarkan kosong)
                            itemTypeSelect.value = '';
                        }
                    }
                    
                    // Set item name (untuk item baru atau override jika perlu)
                    const itemNameInput = firstItemForm.querySelector('input[name*="[item_name]"]');
                    if (itemNameInput && prefillData.item_name) {
                        // Jika tidak ada material_id/sparepart_id, berarti item baru, isi nama
                        if (!prefillData.material_id && !prefillData.sparepart_id) {
                            itemNameInput.value = prefillData.item_name;
                        }
                    }
                    
                    // Set quantity (selalu isi, karena ini dari request) - konversi ke integer
                    const quantityInput = firstItemForm.querySelector('input[name*="[quantity]"]');
                    if (quantityInput && prefillData.quantity) {
                        // Konversi ke integer (bulatkan jika desimal)
                        const quantityInt = Math.round(parseFloat(prefillData.quantity) || 1);
                        quantityInput.value = quantityInt;
                    }
                    
                    // Set unit (selalu isi)
                    const unitInput = firstItemForm.querySelector('input[name*="[unit]"]');
                    if (unitInput && prefillData.unit) {
                        unitInput.value = prefillData.unit;
                    }
                    
                    // Set unit price (selalu isi jika ada estimated_price)
                    const unitPriceInput = firstItemForm.querySelector('input[name*="[unit_price]"]');
                    if (unitPriceInput && prefillData.estimated_price) {
                        unitPriceInput.value = prefillData.estimated_price;
                    }
                    
                    // Hidden input for from_item_request sudah ada di form (di-render via Blade)
                    // Tidak perlu menambahkan lagi via JavaScript
                    
                    // Trigger update totals setelah semua field diisi
                    setTimeout(function() {
                        updateTotals();
                    }, 300);
                }
            }, 100);
        });
        <?php endif; ?>
        
        // Initialize totals for old items
        <?php if(old('items')): ?>
        document.addEventListener('DOMContentLoaded', function() {
                setTimeout(function() {
                    updateTotals();
                }, 100);
            });
        <?php endif; ?>

        // Add item button
        document.getElementById('addItemBtn').addEventListener('click', function() {
            const container = document.getElementById('itemsContainer');
            const div = document.createElement('div');
            div.className = "bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-5 relative mb-5";
            
            if (itemType === 'sparepart') {
                div.innerHTML = getSparepartFormHTML(itemIndex);
            } else {
                div.innerHTML = getMaterialFormHTML(itemIndex);
            }
            
            container.appendChild(div);
            updateEvents();
            itemIndex++;

            // Scroll to new item
            div.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        });

        function getMaterialFormHTML(index) {
            const materialsOptions = materials.map(m => 
                `<option value="${m.id}"
                    data-name="${m.name}"
                    data-unit="${m.unit || 'pcs'}"
                    data-code="${m.material_code || ''}"
                    data-category="${m.category || ''}"
                    data-price="${m.price || 0}"
                    data-description="${(m.description || '').replace(/"/g, '&quot;')}"
                    data-image="${m.image || ''}">${m.name}</option>`
            ).join('');

            return `
                <button type="button" class="absolute top-4 right-4 bg-red-500 hover:bg-red-600 text-white rounded-lg w-8 h-8 flex items-center justify-center transition-colors duration-200" onclick="removeItem(this)">
                    <i class="fas fa-times text-sm"></i>
                </button>
                <div class="flex items-center mb-5">
                    <div class="w-10 h-10 bg-green-100 dark:bg-green-900/40 rounded-lg flex items-center justify-center mr-3">
                        <i class="fas fa-cube text-green-600 dark:text-green-400"></i>
                    </div>
                    <h3 class="text-base font-semibold text-gray-800 dark:text-white">Item Material</h3>
                </div>
                <div class="mb-5">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Pilih Material atau Buat Baru <span class="text-red-500">*</span>
                        </label>
                    <select name="items[${index}][item_id]" class="item-select w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm">
                        <option value="">-- Pilih Material atau Buat Baru --</option>
                        ${materialsOptions}
                    </select>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5 mb-5">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Kode Material</label>
                        <input type="text" name="items[${index}][material_code]" class="code-field w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="Jika kosong, otomatis dibuat unik">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Nama Material <span class="text-red-500">*</span></label>
                        <input type="text" name="items[${index}][item_name]" required class="item-name w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="Masukkan nama material">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Kategori</label>
                        <input type="text" name="items[${index}][category]" class="category-field w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="Masukkan kategori material">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-5 mb-5">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Quantity <span class="text-red-500">*</span></label>
                        <input type="number" name="items[${index}][quantity]" min="1" step="1" value="1" required class="quantity w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="1">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Satuan</label>
                        <input type="text" name="items[${index}][unit]" class="unit w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="pcs" value="pcs">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Harga Satuan (Rp) <span class="text-red-500">*</span></label>
                        <input type="number" name="items[${index}][unit_price]" min="0" step="0.01" required class="unit-price w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="0">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Total Harga</label>
                        <input type="text" readonly class="total-price w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700/50 text-gray-900 dark:text-white text-sm font-semibold" value="Rp 0">
                    </div>
                </div>
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-5 mb-5">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Deskripsi</label>
                        <textarea name="items[${index}][description]" rows="3" class="description-field w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 resize-none text-sm" placeholder="Tuliskan deskripsi material jika perlu..."></textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Gambar</label>
                        <div class="space-y-3">
                            <input type="file" name="items[${index}][image]" accept="image/*" onchange="previewImage(this, 'preview-${index}')" class="image-field w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm">
                            <div class="relative w-full max-w-xs">
                                <div id="preview-container-${index}" class="hidden">
                                    <div class="relative border border-gray-200 dark:border-gray-600 rounded-lg p-2 bg-gray-50 dark:bg-gray-700/50">
                                        <img id="preview-${index}" src="" alt="Preview" class="w-full h-48 object-contain rounded" style="background: transparent;">
                                        <button type="button" onclick="removeImage(this, 'preview-${index}')" 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-colors duration-200 shadow-lg">
                                            <i class="fas fa-times text-sm"></i>
                                        </button>
                                    </div>
                                </div>
                                <div id="no-image-${index}" class="text-xs text-gray-500 dark:text-gray-400 italic">
                                    Belum ada gambar yang dipilih
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="flex items-center">
                    <input type="checkbox" name="items[${index}][is_active]" value="1" checked class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700">
                    <label class="ml-3 block text-sm font-medium text-gray-700 dark:text-gray-300">Aktif</label>
                        </div>
                    `;
        }

        function getSparepartFormHTML(index) {
            const sparepartsOptions = spareparts.map(s => 
                `<option value="${s.id}"
                    data-name="${s.name}"
                    data-unit="${s.unit || 'pcs'}"
                    data-code="${s.part_code || ''}"
                    data-brand="${s.brand || ''}"
                    data-type="${s.type || ''}"
                    data-part_number="${s.part_number || ''}"
                    data-price="${s.price || 0}"
                    data-description="${(s.description || '').replace(/"/g, '&quot;')}"
                    data-image="${s.image || ''}">${s.name}</option>`
            ).join('');

            return `
                <button type="button" class="absolute top-4 right-4 bg-red-500 hover:bg-red-600 text-white rounded-lg w-8 h-8 flex items-center justify-center transition-colors duration-200" onclick="removeItem(this)">
                    <i class="fas fa-times text-sm"></i>
                </button>
                <div class="flex items-center mb-5">
                    <div class="w-10 h-10 bg-blue-100 dark:bg-blue-900/40 rounded-lg flex items-center justify-center mr-3">
                        <i class="fas fa-cog text-blue-600 dark:text-blue-400"></i>
                    </div>
                    <h3 class="text-base font-semibold text-gray-800 dark:text-white">Item Sparepart</h3>
                </div>
                <div class="mb-5">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Pilih Sparepart atau Buat Baru <span class="text-red-500">*</span>
                        </label>
                    <select name="items[${index}][item_id]" class="item-select w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm">
                        <option value="">-- Pilih Sparepart atau Buat Baru --</option>
                        ${sparepartsOptions}
                    </select>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5 mb-5">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Kode Sparepart</label>
                        <input type="text" name="items[${index}][part_code]" class="code-field w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="Jika kosong, otomatis dibuat unik">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Nama Sparepart <span class="text-red-500">*</span></label>
                        <input type="text" name="items[${index}][item_name]" required class="item-name w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="Masukkan nama sparepart">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Brand</label>
                        <input type="text" name="items[${index}][brand]" class="brand-field w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="Merk / brand">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5 mb-5">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Tipe</label>
                        <input type="text" name="items[${index}][type]" class="type-field w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="Tipe sparepart">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Part Number</label>
                        <input type="text" name="items[${index}][part_number]" class="part-number-field w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="Nomor part">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Quantity <span class="text-red-500">*</span></label>
                        <input type="number" name="items[${index}][quantity]" min="1" step="1" value="1" required class="quantity w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="1">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-5 mb-5">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Satuan</label>
                        <input type="text" name="items[${index}][unit]" class="unit w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="pcs" value="pcs">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Harga Satuan (Rp) <span class="text-red-500">*</span></label>
                        <input type="number" name="items[${index}][unit_price]" min="0" step="0.01" required class="unit-price w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm" placeholder="0">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Total Harga</label>
                        <input type="text" readonly class="total-price w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700/50 text-gray-900 dark:text-white text-sm font-semibold" value="Rp 0">
                    </div>
                    <div class="flex items-center">
                        <input type="checkbox" name="items[${index}][is_active]" value="1" checked class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700">
                        <label class="ml-3 block text-sm font-medium text-gray-700 dark:text-gray-300">Aktif</label>
                    </div>
                </div>
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-5 mb-5">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Deskripsi</label>
                        <textarea name="items[${index}][description]" rows="3" class="description-field w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 resize-none text-sm" placeholder="Tuliskan deskripsi sparepart jika perlu..."></textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Gambar</label>
                        <div class="space-y-3">
                            <input type="file" name="items[${index}][image]" accept="image/*" onchange="previewImage(this, 'preview-${index}')" class="image-field w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition duration-200 text-sm">
                            <div class="relative w-full max-w-xs">
                                <div id="preview-container-${index}" class="hidden">
                                    <div class="relative border border-gray-200 dark:border-gray-600 rounded-lg p-2 bg-gray-50 dark:bg-gray-700/50">
                                        <img id="preview-${index}" src="" alt="Preview" class="w-full h-48 object-contain rounded" style="background: transparent;">
                                        <button type="button" onclick="removeImage(this, 'preview-${index}')" 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-colors duration-200 shadow-lg">
                                            <i class="fas fa-times text-sm"></i>
                                        </button>
                                    </div>
                                </div>
                                <div id="no-image-${index}" class="text-xs text-gray-500 dark:text-gray-400 italic">
                                    Belum ada gambar yang dipilih
                                </div>
                            </div>
                        </div>
                    </div>
                        </div>
                    `;
                }

        function removeItem(button) {
            Swal.fire({
                title: 'Hapus Item?',
                html: '<p class="text-sm text-gray-600 dark:text-gray-400">Item ini akan dihapus dari daftar pembelian.</p><p class="text-xs text-red-600 dark:text-red-400 mt-2"><i class="fas fa-exclamation-triangle mr-1"></i>Tindakan ini tidak dapat dibatalkan.</p>',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc2626',
                cancelButtonColor: '#6b7280',
                confirmButtonText: '<i class="fas fa-trash mr-2"></i>Ya, Hapus',
                cancelButtonText: '<i class="fas fa-times mr-2"></i>Batal',
                reverseButtons: true,
                customClass: {
                    popup: 'rounded-lg',
                    confirmButton: 'px-4 py-2 rounded-md font-medium',
                    cancelButton: 'px-4 py-2 rounded-md font-medium'
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    button.closest('div.bg-white').remove();
                    updateTotals();
                    
                    // Show success notification
                    Swal.fire({
                        icon: 'success',
                        title: 'Item Dihapus',
                        text: 'Item berhasil dihapus dari daftar pembelian.',
                        timer: 2000,
                        showConfirmButton: false,
                        customClass: {
                            popup: 'rounded-lg'
                        }
                    });
                }
            });
        }

            function updateEvents() {
            // Item select change
                document.querySelectorAll('.item-select').forEach(select => {
                    select.onchange = function() {
                        const option = this.selectedOptions[0];
                    const row = this.closest('div.bg-white');

                        if (option && option.value) {
                            // Set data dasar
                            row.querySelector('.item-name').value = option.dataset.name || '';
                            row.querySelector('.unit').value = option.dataset.unit || 'pcs';
                        row.querySelector('.unit-price').value = parseFloat(option.dataset.price || 0);

                            // Set kode
                            const codeField = row.querySelector('.code-field');
                            if (codeField) codeField.value = option.dataset.code || '';

                            // Set kategori (untuk material)
                            const categoryField = row.querySelector('.category-field');
                            if (categoryField) categoryField.value = option.dataset.category || '';

                            // Set brand (untuk sparepart)
                            const brandField = row.querySelector('.brand-field');
                            if (brandField) brandField.value = option.dataset.brand || '';

                            // Set type (untuk sparepart)
                            const typeField = row.querySelector('.type-field');
                            if (typeField) typeField.value = option.dataset.type || '';

                            // Set part number (untuk sparepart)
                            const partNumberField = row.querySelector('.part-number-field');
                        if (partNumberField) partNumberField.value = option.dataset.part_number || '';

                        // Set deskripsi
                            const descriptionField = row.querySelector('.description-field');
                            if (descriptionField) {
                                descriptionField.value = option.dataset.description || '';
                            }

                        // Handle gambar existing
                        const previewId = row.querySelector('img')?.id || '';
                        const index = previewId.replace('preview-', '');
                        const previewContainer = document.getElementById(`preview-container-${index}`);
                        const noImageDiv = document.getElementById(`no-image-${index}`);
                        const imgPreview = document.getElementById(`preview-${index}`);
                        const removeBtn = row.querySelector('button[onclick*="removeImage"]');

                            if (option.dataset.image && option.dataset.image.trim() !== '') {
                            if (imgPreview) {
                                imgPreview.src = option.dataset.image;
                                imgPreview.classList.remove('hidden');
                            }
                            if (previewContainer) previewContainer.classList.remove('hidden');
                            if (noImageDiv) noImageDiv.classList.add('hidden');
                            if (removeBtn) removeBtn.classList.remove('hidden');
                        } else {
                            if (imgPreview) imgPreview.classList.add('hidden');
                            if (previewContainer) previewContainer.classList.add('hidden');
                            if (noImageDiv) noImageDiv.classList.remove('hidden');
                            if (removeBtn) removeBtn.classList.add('hidden');
                        }
                    } else {
                        // Reset semua field saat pilih "Buat Baru"
                            row.querySelector('.item-name').value = '';
                            row.querySelector('.unit').value = 'pcs';
                            row.querySelector('.unit-price').value = '';
                            const codeField = row.querySelector('.code-field');
                            if (codeField) codeField.value = '';
                            const categoryField = row.querySelector('.category-field');
                            if (categoryField) categoryField.value = '';
                            const brandField = row.querySelector('.brand-field');
                            if (brandField) brandField.value = '';
                            const typeField = row.querySelector('.type-field');
                            if (typeField) typeField.value = '';
                            const partNumberField = row.querySelector('.part-number-field');
                            if (partNumberField) partNumberField.value = '';
                            const descriptionField = row.querySelector('.description-field');
                            if (descriptionField) descriptionField.value = '';
                        const previewId = row.querySelector('img')?.id || '';
                        const index = previewId.replace('preview-', '');
                        const previewContainer = document.getElementById(`preview-container-${index}`);
                        const noImageDiv = document.getElementById(`no-image-${index}`);
                        const imgPreview = document.getElementById(`preview-${index}`);
                        const removeBtn = row.querySelector('button[onclick*="removeImage"]');
                        
                            if (imgPreview) imgPreview.classList.add('hidden');
                        if (previewContainer) previewContainer.classList.add('hidden');
                        if (noImageDiv) noImageDiv.classList.remove('hidden');
                        if (removeBtn) removeBtn.classList.add('hidden');
                        }
                        updateTotals();
                    };
                });

            // Quantity and unit price change
                document.querySelectorAll('.quantity, .unit-price').forEach(input => {
                    if (input.classList.contains('quantity')) {
                        // Pastikan quantity selalu integer saat user input
                        input.addEventListener('input', function() {
                            const value = parseFloat(this.value);
                            if (!isNaN(value)) {
                                this.value = Math.round(value);
                            }
                            updateTotals();
                        });
                        input.addEventListener('blur', function() {
                            const value = parseFloat(this.value);
                            if (!isNaN(value) && value > 0) {
                                this.value = Math.round(value);
                            } else if (this.value === '' || value <= 0) {
                                this.value = 1;
                            }
                            updateTotals();
                        });
                    } else {
                        input.oninput = updateTotals;
                    }
                });
            }

            function updateTotals() {
            document.querySelectorAll('.total-price').forEach(totalInput => {
                const row = totalInput.closest('div.bg-white');
                    const qtyInput = row.querySelector('.quantity');
                    // Pastikan quantity selalu integer
                    if (qtyInput && qtyInput.value) {
                        const qtyValue = parseFloat(qtyInput.value);
                        if (!isNaN(qtyValue)) {
                            qtyInput.value = Math.round(qtyValue);
                        }
                    }
                    const qty = parseInt(qtyInput.value) || 0;
                    const price = parseFloat(row.querySelector('.unit-price').value) || 0;
                    const total = qty * price;
                totalInput.value = 'Rp ' + total.toLocaleString('id-ID');
                });
            }

        function previewImage(input, previewId) {
            const index = previewId.replace('preview-', '');
            const preview = document.getElementById(previewId);
            const previewContainer = document.getElementById(`preview-container-${index}`);
            const noImageDiv = document.getElementById(`no-image-${index}`);
            const file = input.files[0];

            if (file) {
                // Validate file type
                if (!file.type.match('image.*')) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Format Tidak Valid',
                        text: 'Silakan pilih file gambar (JPG, PNG, GIF, dll)',
                        timer: 2000,
                        showConfirmButton: false,
                        customClass: {
                            popup: 'rounded-lg'
                        }
                    });
                    input.value = '';
                    return;
                }

                // Validate file size (max 5MB)
                if (file.size > 5 * 1024 * 1024) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Ukuran File Terlalu Besar',
                        text: 'Ukuran file maksimal 5MB',
                        timer: 2000,
                        showConfirmButton: false,
                        customClass: {
                            popup: 'rounded-lg'
                        }
                    });
                    input.value = '';
                    return;
                }

                const reader = new FileReader();
                reader.onload = function(e) {
                    if (preview) {
                    preview.src = e.target.result;
                    preview.classList.remove('hidden');
                    }
                    if (previewContainer) previewContainer.classList.remove('hidden');
                    if (noImageDiv) noImageDiv.classList.add('hidden');
                };
                reader.readAsDataURL(file);
            }
        }

        function removeImage(button, previewId) {
            const index = previewId.replace('preview-', '');
            const preview = document.getElementById(previewId);
            const previewContainer = document.getElementById(`preview-container-${index}`);
            const noImageDiv = document.getElementById(`no-image-${index}`);
            const input = button.closest('div.space-y-3').querySelector('input[type=file]');
            
            if (input) input.value = '';
            if (preview) {
                preview.src = '';
                preview.classList.add('hidden');
            }
            if (previewContainer) previewContainer.classList.add('hidden');
            if (noImageDiv) noImageDiv.classList.remove('hidden');
            if (button) button.classList.add('hidden');
        }

        // Initialize events
        updateEvents();
        updateTotals();

        // Form validation
        document.getElementById('purchaseForm').addEventListener('submit', function(e) {
            const items = document.querySelectorAll('#itemsContainer > div');
            if (items.length === 0) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Item Kosong',
                    text: 'Tambahkan minimal 1 item untuk melanjutkan pembelian.',
                    confirmButtonText: 'Mengerti',
                    customClass: {
                        popup: 'rounded-lg'
                    }
                });
                return false;
            }
        });
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.admin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/mikr8192/public_html/poljamtech.mikromart.org/poljamtech/resources/views/admin/transaksi/purchases/create.blade.php ENDPATH**/ ?>