

<?php $__env->startSection('title', 'Buat Stock Opname'); ?>

<?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.backoffice.stock-opname.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"
                title="Kembali">
                <i class="fas fa-arrow-left text-lg"></i>
            </a>
            <div>
                <h1 class="text-2xl font-bold text-gray-800 dark:text-white">Buat Stock Opname</h1>
                <p class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                    Input data stock opname baru untuk pengecekan stok barang
                </p>
            </div>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <?php if(session('error')): ?>
        <div class="mb-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200 px-4 py-3 rounded-lg text-sm">
            <i class="fas fa-exclamation-circle mr-2"></i><?php echo e(session('error')); ?>

        </div>
    <?php endif; ?>

    <?php if($errors->any()): ?>
        <div class="mb-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200 px-4 py-3 rounded-lg text-sm">
            <div class="font-medium mb-2">Terdapat kesalahan:</div>
            <ul class="list-disc list-inside space-y-1 text-xs">
                <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <li><?php echo e($error); ?></li>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </ul>
        </div>
    <?php endif; ?>

    <!-- 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.backoffice.stock-opname.store')); ?>" method="POST" id="stockOpnameForm" class="p-5">
            <?php echo csrf_field(); ?>

            <!-- Header Info -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-5 mb-6">
                <!-- Tanggal Opname -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Tanggal Opname <span class="text-red-500">*</span>
                    </label>
                    <input type="date" name="opname_date" value="<?php echo e(old('opname_date', date('Y-m-d'))); ?>" required
                        max="<?php echo e(date('Y-m-d')); ?>"
                        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 transition-colors duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm <?php $__errorArgs = ['opname_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>">
                    <?php $__errorArgs = ['opname_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-600 dark:text-red-400 text-xs mt-1"><?php echo e($message); ?></p>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                <!-- Catatan -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Catatan
                    </label>
                    <input type="text" name="notes" value="<?php echo e(old('notes')); ?>"
                        placeholder="Catatan tambahan (opsional)..."
                        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 transition-colors duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm <?php $__errorArgs = ['notes'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>">
                    <?php $__errorArgs = ['notes'];
$__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-600 dark:text-red-400 text-xs mt-1"><?php echo e($message); ?></p>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>
            </div>

            <!-- Items Section -->
            <div class="mb-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-base font-semibold text-gray-800 dark:text-white">
                        <i class="fas fa-list-ul mr-2 text-blue-600 dark:text-blue-400"></i>Daftar Item
                    </h3>
                    <button type="button" onclick="addItemRow()"
                        class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors duration-200 text-sm flex items-center space-x-2">
                        <i class="fas fa-plus text-xs"></i>
                        <span>Tambah Item</span>
                    </button>
                </div>

                <div class="overflow-x-auto border border-gray-300 dark:border-gray-600 rounded-lg">
                    <table class="w-full" id="itemsTable">
                        <thead class="bg-gray-50 dark:bg-gray-700">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 dark:text-gray-200">Tipe</th>
                                <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 dark:text-gray-200">Item</th>
                                <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 dark:text-gray-200">Kode</th>
                                <th class="px-4 py-3 text-right text-xs font-semibold text-gray-700 dark:text-gray-200">Stok Sistem</th>
                                <th class="px-4 py-3 text-right text-xs font-semibold text-gray-700 dark:text-gray-200">Stok Fisik</th>
                                <th class="px-4 py-3 text-right text-xs font-semibold text-gray-700 dark:text-gray-200">Selisih</th>
                                <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 dark:text-gray-200">Alasan</th>
                                <th class="px-4 py-3 text-center text-xs font-semibold text-gray-700 dark:text-gray-200">Aksi</th>
                            </tr>
                        </thead>
                        <tbody id="itemsTableBody" class="divide-y divide-gray-200 dark:divide-gray-600">
                            <!-- Rows will be added dynamically -->
                        </tbody>
                    </table>
                </div>

                <p id="emptyMessage" class="text-sm text-gray-500 dark:text-gray-400 mt-3 flex items-center">
                    <i class="fas fa-info-circle mr-2"></i>
                    Belum ada item. Klik tombol "Tambah Item" untuk menambahkan.
                </p>
            </div>

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

    <script>
        let rowIndex = 0;
        const materials = <?php echo json_encode($materials, 15, 512) ?>;
        const spareparts = <?php echo json_encode($spareparts, 15, 512) ?>;

        function addItemRow() {
            const tbody = document.getElementById('itemsTableBody');
            const emptyMessage = document.getElementById('emptyMessage');

            const row = document.createElement('tr');
            row.className = 'bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors duration-200';
            row.id = `row-${rowIndex}`;

            row.innerHTML = `
        <td class="px-4 py-3">
            <select name="items[${rowIndex}][type]" 
                    class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs focus:ring-2 focus:ring-blue-500 transition-colors duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    onchange="updateItemOptions(${rowIndex})" required>
                <option value="">Pilih Tipe</option>
                <option value="material">Material</option>
                <option value="sparepart">Sparepart</option>
            </select>
        </td>
        <td class="px-4 py-3">
            <select name="items[${rowIndex}][item_select]" 
                    id="item-${rowIndex}"
                    class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs focus:ring-2 focus:ring-blue-500 transition-colors duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    onchange="loadItemData(${rowIndex})" required disabled>
                <option value="">Pilih tipe dulu</option>
            </select>
        </td>
        <td class="px-4 py-3">
            <input type="text" id="code-${rowIndex}" readonly
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs bg-gray-100 dark:bg-gray-600 text-gray-900 dark:text-white">
        </td>
        <td class="px-4 py-3">
            <input type="text" id="system-${rowIndex}" readonly
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs text-right bg-gray-100 dark:bg-gray-600 font-medium text-gray-900 dark:text-white">
        </td>
        <td class="px-4 py-3">
            <input type="number" name="items[${rowIndex}][physical_qty]" step="1" min="0"
                id="physical-${rowIndex}" required
                oninput="calculateDifference(${rowIndex})"
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs text-right focus:ring-2 focus:ring-blue-500 transition-colors duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
        </td>
        <td class="px-4 py-3">
            <input type="text" id="difference-${rowIndex}" readonly
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs text-right font-semibold bg-gray-100 dark:bg-gray-600 text-gray-900 dark:text-white">
        </td>
        <td class="px-4 py-3">
            <input type="text" name="items[${rowIndex}][reason]" placeholder="Alasan selisih..."
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs focus:ring-2 focus:ring-blue-500 transition-colors duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
        </td>
        <td class="px-4 py-3 text-center">
            <button type="button" onclick="removeItemRow(${rowIndex})"
                    class="w-8 h-8 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors duration-200 flex items-center justify-center">
                <i class="fas fa-trash text-xs"></i>
            </button>
        </td>
        
        <input type="hidden" name="items[${rowIndex}][itemable_type]" id="itemable-type-${rowIndex}">
        <input type="hidden" name="items[${rowIndex}][itemable_id]" id="itemable-id-${rowIndex}">
        `;

            tbody.appendChild(row);
            emptyMessage.style.display = 'none';
            rowIndex++;
        }

        function updateItemOptions(index) {
            const typeSelect = document.querySelector(`select[name="items[${index}][type]"]`);
            const itemSelect = document.getElementById(`item-${index}`);
            const type = typeSelect.value;

            // Reset semua field
            itemSelect.innerHTML = '<option value="">-- Pilih Item --</option>';
            itemSelect.disabled = !type;

            ['code', 'system', 'physical', 'difference'].forEach(field => {
                const el = document.getElementById(`${field}-${index}`);
                if (el) el.value = '';
            });

            // Reset hidden inputs
            document.getElementById(`itemable-type-${index}`).value = '';
            document.getElementById(`itemable-id-${index}`).value = '';

            if (!type) return;

            // Populate dropdown berdasarkan tipe
            const list = type === 'material' ? materials : spareparts;
            list.forEach(item => {
                const option = document.createElement('option');
                option.value = item.id;
                option.textContent = `${item.name} (Stok: ${item.stock} ${item.unit})`;
                option.dataset.item = JSON.stringify(item);
                itemSelect.appendChild(option);
            });

            // Set itemable_type
            const itemableType = type === 'material' ? 'App\\Models\\Material' : 'App\\Models\\Sparepart';
            document.getElementById(`itemable-type-${index}`).value = itemableType;
        }

        function loadItemData(index) {
            const itemSelect = document.getElementById(`item-${index}`);
            const selectedOption = itemSelect.options[itemSelect.selectedIndex];

            if (!selectedOption || !selectedOption.dataset.item) {
                return;
            }

            const item = JSON.parse(selectedOption.dataset.item);

            // Set semua data item
            document.getElementById(`code-${index}`).value = item.code || '-';

            const systemEl = document.getElementById(`system-${index}`);
            systemEl.value = `${item.stock} ${item.unit}`;
            systemEl.dataset.qty = item.stock;
            systemEl.dataset.unit = item.unit;

            // Set itemable_id
            document.getElementById(`itemable-id-${index}`).value = item.id;

            // Reset physical qty dan difference
            document.getElementById(`physical-${index}`).value = '';
            document.getElementById(`difference-${index}`).value = '';
        }

        function calculateDifference(index) {
            const systemEl = document.getElementById(`system-${index}`);
            const physicalInput = document.getElementById(`physical-${index}`);

            const physicalQty = parseFloat(physicalInput.value);
            const systemQty = parseFloat(systemEl.dataset.qty);
            const unit = systemEl.dataset.unit || '';

            if (isNaN(physicalQty) || isNaN(systemQty)) {
                document.getElementById(`difference-${index}`).value = '';
                return;
            }

            // Hitung selisih: Fisik - Sistem
            const diff = physicalQty - systemQty;

            const diffEl = document.getElementById(`difference-${index}`);
            diffEl.value = (diff >= 0 ? '+' : '') + Math.round(diff) + ' ' + unit;

            // Styling berdasarkan selisih
            if (diff > 0) {
                diffEl.className =
                    'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs text-right font-semibold bg-green-50 dark:bg-green-900/40 text-green-600 dark:text-green-300';
            } else if (diff < 0) {
                diffEl.className =
                    'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs text-right font-semibold bg-red-50 dark:bg-red-900/40 text-red-600 dark:text-red-300';
            } else {
                diffEl.className =
                    'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs text-right font-semibold bg-gray-100 dark:bg-gray-600 text-gray-600 dark:text-gray-200';
            }
        }

        function removeItemRow(index) {
            const row = document.getElementById(`row-${index}`);
            if (row) {
                row.remove();
            }

            const tbody = document.getElementById('itemsTableBody');
            const emptyMessage = document.getElementById('emptyMessage');

            if (tbody.children.length === 0) {
                emptyMessage.style.display = 'flex';
            }
        }

        // Validasi sebelum submit
        document.getElementById('stockOpnameForm').addEventListener('submit', function(e) {
            const tbody = document.getElementById('itemsTableBody');

            if (tbody.children.length === 0) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Item Kosong',
                    text: 'Tambahkan minimal 1 item untuk stock opname!',
                    confirmButtonColor: '#3b82f6'
                });
                return false;
            }

            // Validasi setiap item sudah lengkap
            let isValid = true;
            const rows = tbody.querySelectorAll('tr');

            rows.forEach((row, idx) => {
                const typeSelect = row.querySelector('select[name*="[type]"]');
                const itemSelect = row.querySelector('select[name*="[item_select]"]');
                const physicalInput = row.querySelector('input[name*="[physical_qty]"]');

                if (!typeSelect.value || !itemSelect.value || !physicalInput.value) {
                    isValid = false;
                }
            });

            if (!isValid) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Data Tidak Lengkap',
                    text: 'Lengkapi semua data item sebelum menyimpan!',
                    confirmButtonColor: '#3b82f6'
                });
                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/backoffice/stock-opname/create.blade.php ENDPATH**/ ?>