<?php
$transaksi = $transaksi ?? [];
$oldItems = old('items_json');
$itemsForJs = $initialItems ?? [];

if (is_string($oldItems) && $oldItems !== '') {
    $decodedOldItems = json_decode($oldItems, true);

    if (is_array($decodedOldItems)) {
        $itemsForJs = $decodedOldItems;
    }
}

$selectedSuplier = (string) old('suplier_id', $transaksi['suplier_id'] ?? '');
$tanggalValue = old('tanggal_pembelian', $tanggalPembelian ?? date('Y-m-d'));
$noTransaksiValue = old('no_transaksi', $noTransaksi ?? '');
$showInitialPayment = (bool) ($showInitialPayment ?? true);
$initialPaymentRaw = old('jumlah_pembayaran', $initialPayment ?? 0);
$initialPaymentValue = (int) (preg_replace('/\D/', '', (string) $initialPaymentRaw) ?: 0);
$paymentPreviewValue = $showInitialPayment ? $initialPaymentValue : (int) ($totalDibayar ?? 0);
$pajakPersenValue = (int) old('pajak_persen', $pajakPersen ?? ($transaksi['pajak_persen'] ?? 11));
?>

<section class="content-area">
    <?php $errors = session()->getFlashdata('errors'); ?>
    <?php if ($errors) : ?>
        <div class="alert alert-danger">
            <?php foreach ($errors as $error) : ?>
                <div><?= esc($error) ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <div class="panel p-4">
        <form action="<?= esc($action, 'attr') ?>" method="post" id="pembelianForm">
            <?= csrf_field() ?>
            <input type="hidden" name="items_json" id="itemsJson" value="<?= esc(json_encode($itemsForJs), 'attr') ?>">

            <div class="alert alert-info d-flex gap-2 align-items-start">
                <i class="bi bi-info-circle-fill mt-1"></i>
                <div>
                    Transaksi pembelian ini menggunakan metode <strong>moving average</strong>.
                    Setiap simpan/edit/hapus pembelian akan menghitung ulang harga beli master barang berdasarkan stok awal dan riwayat pembelian aktif.
                    <div class="mt-2 small">
                        Rumus: <strong>((Stok lama x Harga beli lama) + (Qty pembelian x Harga beli transaksi)) / (Stok lama + Qty pembelian)</strong>.
                    </div>
                </div>
            </div>

            <div class="row g-4 mb-4">
                <div class="col-12 col-lg-2">
                    <label for="tanggal_pembelian" class="form-label fw-semibold">Tanggal Pembelian</label>
                    <input type="date" class="form-control" id="tanggal_pembelian" name="tanggal_pembelian" value="<?= esc($tanggalValue, 'attr') ?>" required>
                </div>

                <div class="col-12 col-lg-3">
                    <label for="no_transaksi" class="form-label fw-semibold">No. Transaksi</label>
                    <input type="text" class="form-control" id="no_transaksi" name="no_transaksi" value="<?= esc($noTransaksiValue, 'attr') ?>" readonly>
                </div>

                <div class="col-12 col-lg-4">
                    <label for="suplier_id" class="form-label fw-semibold">Supplier</label>
                    <select class="form-select select2" id="suplier_id" name="suplier_id" data-placeholder="Pilih supplier" required>
                        <option value=""></option>
                        <?php foreach ($suplier as $item) : ?>
                            <option value="<?= esc($item['id'], 'attr') ?>" <?= $selectedSuplier === (string) $item['id'] ? 'selected' : '' ?>>
                                <?= esc($item['nama']) ?> - <?= esc($item['perusahaan']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12 col-lg-3">
                    <label for="nomor_dokumen" class="form-label fw-semibold">Nomor Dokumen/Nota (Opsional)</label>
                    <input type="text" class="form-control" id="nomor_dokumen" name="nomor_dokumen" value="<?= esc(old('nomor_dokumen', $transaksi['nomor_dokumen'] ?? ''), 'attr') ?>">
                </div>

                <div class="col-12">
                    <label for="catatan" class="form-label fw-semibold">Catatan</label>
                    <textarea class="form-control" id="catatan" name="catatan" rows="2"><?= esc(old('catatan', $transaksi['catatan'] ?? '')) ?></textarea>
                </div>


            </div>

            <div class="row g-4 mb-4">
                <div class="col-12 col-xl-4">
                    <div class="border rounded-2 p-3 h-100">
                        <div class="fw-bold mb-3">Pilih Barang</div>

                        <input type="hidden" id="selected_barang_id">
                        <input type="hidden" id="selected_satuan">

                        <div class="mb-3">
                            <label for="kode_barang_input" class="form-label fw-semibold">Kode Barang</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="kode_barang_input" autocomplete="off" placeholder="Input kode atau scan QR/barcode">
                                <button class="btn btn-outline-dark" type="button" id="openBarangModal">
                                    <i class="bi bi-search"></i>Pilih
                                </button>
                            </div>
                            <div class="form-text" id="barangLookupMessage">Scan QR/barcode akan mengisi kode barang di field ini.</div>
                        </div>

                        <div class="mb-3">
                            <label for="nama_barang_input" class="form-label fw-semibold">Nama Barang</label>
                            <input type="text" class="form-control" id="nama_barang_input" disabled>
                        </div>

                        <div class="mb-3">
                            <label for="jumlah_input" class="form-label fw-semibold">Jumlah</label>
                            <input type="number" class="form-control" id="jumlah_input" min="1" value="1">
                        </div>

                        <div class="mb-3">
                            <label for="harga_beli_input" class="form-label fw-semibold">Harga Beli</label>
                            <input type="text" class="form-control" id="harga_beli_input" inputmode="numeric" value="0">
                            <div class="form-text">Harga beli per satuan untuk transaksi pembelian ini.</div>
                        </div>

                        <div class="border rounded-2 bg-light p-3 mb-3 small" id="movingAveragePreview">
                            <div class="fw-bold mb-1">Simulasi Harga Modal Baru</div>
                            <div class="text-secondary">Pilih barang terlebih dahulu untuk melihat rumus perhitungannya.</div>
                        </div>

                        <button type="button" class="btn btn-dark w-100" id="addItemButton">
                            <i class="bi bi-plus-lg"></i>Tambahkan
                        </button>
                    </div>
                </div>

                <div class="col-12 col-xl-8">
                    <div class="border rounded-2 p-3 h-100">
                        <div class="d-flex align-items-center justify-content-between gap-3 mb-3">
                            <div>
                                <div class="fw-bold">Daftar Item Pembelian</div>
                                <div class="small text-secondary">Estimasi modal memakai stok dan harga beli saat ini. Saat disimpan, sistem menghitung ulang dari riwayat pembelian aktif.</div>
                            </div>
                            <div class="badge text-bg-light border" id="itemCounter">0 item</div>
                        </div>

                        <div class="table-responsive">
                            <table class="table table-sm table-hover align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>Barang</th>
                                        <th style="width:15%">Jumlah</th>
                                        <th style="">Harga Beli</th>
                                        <th class="text-center" style="width: 15%;">Modal Baru</th>
                                        <th class="text-center" style="width: 10%;">Subtotal</th>
                                        <th class="text-center" style="width: 1%;">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody id="itemsTableBody">
                                    <tr>
                                        <td colspan="6" class="text-center text-secondary py-4">Belum ada barang.</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row g-4 mb-4">
                    <div class="col-12 col-lg-4">
                <?php if ($showInitialPayment) : ?>
                        <label for="jumlah_pembayaran" class="form-label fw-semibold">
                            Jumlah Pembayaran
                        </label>
                        <input type="text"
                            class="form-control"
                            id="jumlah_pembayaran"
                            name="jumlah_pembayaran"
                            inputmode="numeric"
                            value="<?= esc(number_format($initialPaymentValue, 0, ',', '.'), 'attr') ?>">

                        <div class="form-text">
                            Pembayaran ini masuk sebagai cicilan/pembayaran pertama.
                        </div>
                <?php endif; ?>
                    </div>

                <div class="col-12 col-lg-2">
                    <label for="pajak_persen" class="form-label fw-semibold">
                        Pajak (%)
                    </label>
                    <input type="number"
                        class="form-control"
                        id="pajak_persen"
                        name="pajak_persen"
                        value="<?= esc((string) $pajakPersenValue, 'attr') ?>"
                        min="0"
                        max="100"
                        step="1"
                        readonly
                        required>

                    <div class="form-text">
                        Mengikuti pengaturan pajak aplikasi.
                    </div>
                </div>

                <div class="col-12 <?= $showInitialPayment ? 'col-lg-6' : 'col-lg-6' ?>">
                    <div class="table-responsive">
                        <table class="table table-bordere table-sm align-middle">
                            <tbody>
                                <tr>
                                    <th width="35%">Subtotal</th>
                                    <th width="1%">:</th>
                                    <td id="subtotalPreview" class="text-end fw-bold">0</td>
                                </tr>
                                <tr>
                                    <th>Pajak</th>
                                    <th width="1%">:</th>
                                    <td id="pajakPreview" class="text-end fw-bold">0</td>
                                </tr>
                                <tr>
                                    <th>Total Pembelian</th>
                                    <th width="1%">:</th>
                                    <td id="totalPembelianPreview" class="text-end fw-bold">0</td>
                                </tr>
                                <tr>
                                    <th>Dibayar</th>
                                    <th width="1%">:</th>
                                    <td id="totalDibayarPreview" class="text-end fw-bold">0</td>
                                </tr>
                                <tr>
                                    <th>Sisa Hutang</th>
                                    <th width="1%">:</th>
                                    <td id="sisaHutangPreview" class="text-end fw-bold text-danger">0</td>
                                </tr>
                                <tr>
                                    <th>Status</th>
                                    <th width="1%">:</th>
                                    <td class="text-end"><span class="badge text-bg-warning text-end" id="statusPembayaranPreview">Hutang</span></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="d-flex justify-content-end gap-2 mt-4">
                <a href="<?= site_url('admin/pembelian') ?>" class="btn btn-light">Batal</a>
                <button type="submit" class="btn btn-dark"><?= esc($submitLabel ?? 'Simpan') ?></button>
            </div>
        </form>
    </div>
</section>

<div class="modal fade" id="barangPickerModal" tabindex="-1" aria-labelledby="barangPickerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="barangPickerModalLabel">Pilih Barang</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle w-100" id="barangPickerTable">
                        <thead>
                            <tr>
                                <th>Kode</th>
                                <th>Nama Barang</th>
                                <th>Kategori</th>
                                <th>Satuan</th>
                                <th>Stok</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const lookupUrl = <?= json_encode($lookupUrl) ?>;
        const datatableUrl = <?= json_encode($datatableUrl) ?>;
        const generateNumberUrl = <?= json_encode($generateNumberUrl) ?>;
        const fixedPaymentAmount = <?= json_encode($paymentPreviewValue) ?>;
        const paymentConflictMessage = <?= json_encode(
                                            $showInitialPayment
                                                ? 'Jumlah pembayaran tidak boleh lebih besar dari total pembelian.'
                                                : 'Total pembayaran yang sudah tercatat tidak boleh lebih besar dari total pembelian. Silakan hapus riwayat pembayaran dulu untuk menyesuaikan jumlah pembayaran pembelian ini.'
                                        ) ?>;
        const itemsInput = document.getElementById('itemsJson');
        const tableBody = document.getElementById('itemsTableBody');
        const itemCounter = document.getElementById('itemCounter');
        const kodeInput = document.getElementById('kode_barang_input');
        const namaInput = document.getElementById('nama_barang_input');
        const jumlahInput = document.getElementById('jumlah_input');
        const hargaBeliInput = document.getElementById('harga_beli_input');
        const jumlahPembayaranInput = document.getElementById('jumlah_pembayaran');
        const pajakInput = document.getElementById('pajak_persen');
        const subtotalPreview = document.getElementById('subtotalPreview');
        const pajakPreview = document.getElementById('pajakPreview');
        const totalPembelianPreview = document.getElementById('totalPembelianPreview');
        const totalDibayarPreview = document.getElementById('totalDibayarPreview');
        const sisaHutangPreview = document.getElementById('sisaHutangPreview');
        const statusPembayaranPreview = document.getElementById('statusPembayaranPreview');
        const barangIdInput = document.getElementById('selected_barang_id');
        const satuanInput = document.getElementById('selected_satuan');
        const lookupMessage = document.getElementById('barangLookupMessage');
        const movingAveragePreview = document.getElementById('movingAveragePreview');
        const tanggalInput = document.getElementById('tanggal_pembelian');
        const noTransaksiInput = document.getElementById('no_transaksi');
        let items = <?= json_encode(array_values($itemsForJs)) ?>;
        let lookupTimer = null;
        let pickerTable = null;
        let selectedBarang = null;

        const escapeHtml = function(value) {
            return String(value ?? '').replace(/[&<>"']/g, function(character) {
                return {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#039;'
                } [character];
            });
        };

        const syncItems = function() {
            itemsInput.value = JSON.stringify(items);
            itemCounter.textContent = items.length + ' item';
        };

        const normalizeNumber = function(value) {
            const digits = String(value ?? '').replace(/\D/g, '');
            const number = parseInt(digits || '0', 10);

            return Number.isFinite(number) && number >= 0 ? number : 0;
        };

        const formatNumber = function(value) {
            return normalizeNumber(value).toLocaleString('id-ID', {
                minimumFractionDigits: 0,
                maximumFractionDigits: 0
            });
        };

        const formatPriceInput = function(input) {
            input.value = formatNumber(input.value);
        };

        const totalItems = function() {
            return items.reduce(function(total, item) {
                const jumlah = Math.max(1, parseInt(item.jumlah, 10) || 1);
                const hargaBeli = normalizeNumber(item.harga_beli);

                return total + (jumlah * hargaBeli);
            }, 0);
        };

        const taxAmount = function(subtotal) {
            const percent = Math.max(0, Math.min(100, parseInt(pajakInput.value, 10) || 0));

            return Math.round(subtotal * percent / 100);
        };

        const totalWithTax = function() {
            const subtotal = totalItems();

            return subtotal + taxAmount(subtotal);
        };

        const updatePaymentPreview = function() {
            const subtotal = totalItems();
            const pajak = taxAmount(subtotal);
            const totalPembelian = subtotal + pajak;
            const totalDibayar = jumlahPembayaranInput ? normalizeNumber(jumlahPembayaranInput.value) : normalizeNumber(fixedPaymentAmount);
            const sisaHutang = Math.max(0, totalPembelian - totalDibayar);
            const isLunas = totalPembelian > 0 && totalDibayar >= totalPembelian;

            subtotalPreview.textContent = formatNumber(subtotal);
            pajakPreview.textContent = formatNumber(pajak);
            totalPembelianPreview.textContent = formatNumber(totalPembelian);
            totalDibayarPreview.textContent = formatNumber(totalDibayar);
            sisaHutangPreview.textContent = formatNumber(sisaHutang);
            statusPembayaranPreview.textContent = isLunas ? 'Lunas' : 'Hutang';
            statusPembayaranPreview.className = isLunas ? 'badge text-bg-success' : 'badge text-bg-warning';
        };

        const movingAveragePreviewData = function(stokLama, hargaLama, qtyPembelian, hargaPembelian) {
            stokLama = normalizeNumber(stokLama);
            hargaLama = normalizeNumber(hargaLama);
            qtyPembelian = Math.max(1, parseInt(qtyPembelian, 10) || 1);
            hargaPembelian = normalizeNumber(hargaPembelian);

            const nilaiLama = stokLama * hargaLama;
            const nilaiPembelian = qtyPembelian * hargaPembelian;
            const totalStok = stokLama + qtyPembelian;
            const hargaBaru = totalStok > 0 ? Math.round((nilaiLama + nilaiPembelian) / totalStok) : hargaPembelian;

            return {
                stokLama: stokLama,
                hargaLama: hargaLama,
                qtyPembelian: qtyPembelian,
                hargaPembelian: hargaPembelian,
                nilaiLama: nilaiLama,
                nilaiPembelian: nilaiPembelian,
                totalStok: totalStok,
                hargaBaru: hargaBaru
            };
        };

        const renderMovingAverageFormula = function(preview) {
            return '<div><span class="text-secondary">Rumus:</span><br> ((Stok lama x Harga lama) + (Qty beli x Harga beli transaksi)) / (Stok lama + Qty beli)</div>' +
                '<div class="mt-1"><span class="text-secondary">Angka:</span><br> ((' + preview.stokLama + ' x ' + formatNumber(preview.hargaLama) + ') + (' + preview.qtyPembelian + ' x ' + formatNumber(preview.hargaPembelian) + ')) / (' + preview.stokLama + ' + ' + preview.qtyPembelian + ')</div>' +
                '<div class="mt-1"><span class="text-secondary">Nilai:</span> (' + formatNumber(preview.nilaiLama) + ' + ' + formatNumber(preview.nilaiPembelian) + ') / ' + preview.totalStok + '</div>' +
                '<div class="mt-2 fw-bold">Modal baru: ' + formatNumber(preview.hargaBaru) + '</div>';
        };

        const updateSelectedMovingAveragePreview = function() {
            if (!selectedBarang) {
                movingAveragePreview.innerHTML = '<div class="fw-bold mb-1">Simulasi Harga Modal Baru</div><div class="text-secondary">Pilih barang terlebih dahulu untuk melihat rumus perhitungannya.</div>';
                return;
            }

            const preview = movingAveragePreviewData(selectedBarang.stok || 0, selectedBarang.harga_beli || 0, jumlahInput.value, hargaBeliInput.value);
            movingAveragePreview.innerHTML = '<div class="fw-bold mb-1">Simulasi Harga Modal Baru</div>' +
                '<div class="mb-2 text-secondary">Perkiraan cepat untuk ' + escapeHtml(selectedBarang.kode_barang) + ' - ' + escapeHtml(selectedBarang.nama_barang) + '.</div>' +
                renderMovingAverageFormula(preview);
        };

        const rowMovingAverageSummary = function(item, jumlah, hargaBeli) {
            const preview = movingAveragePreviewData(item.stok_saat_ini || 0, item.harga_beli_saat_ini || 0, jumlah, hargaBeli);

            return '<span class="fw-semibold">' + escapeHtml(formatNumber(preview.hargaBaru)) + '</span>';
        };

        const renderItems = function() {
            syncItems();

            if (items.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="6" class="text-center text-secondary py-4">Belum ada barang.</td></tr>';
                updatePaymentPreview();
                return;
            }

            tableBody.innerHTML = items.map(function(item, index) {
                const jumlah = Math.max(1, parseInt(item.jumlah, 10) || 1);
                const hargaBeli = normalizeNumber(item.harga_beli);
                const subtotal = jumlah * hargaBeli;

                return '<tr>' +
                    '<td><span class="fw-semibold small d-block">' + escapeHtml(item.kode_barang) + '</span><span class="d-block">' + escapeHtml(item.nama_barang) + '</span><span class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 fw-semibold mt-1">' + escapeHtml(item.satuan) + '</span></td>' +
                    '<td><input type="number" class="form-control form-control-sm item-qty-input" min="1" value="' + escapeHtml(item.jumlah) + '" data-index="' + index + '"></td>' +
                    '<td><input type="text" class="form-control form-control-sm item-price-input" inputmode="numeric" value="' + escapeHtml(formatNumber(hargaBeli)) + '" data-index="' + index + '"></td>' +
                    '<td class="item-average-preview text-center">' + rowMovingAverageSummary(item, jumlah, hargaBeli) + '</td>' +
                    '<td class="text-end fw-semibold item-subtotal">' + escapeHtml(formatNumber(subtotal)) + '</td>' +
                    '<td class="text-end"><button type="button" class="btn btn-sm btn-danger btn-icon remove-item-btn" data-index="' + index + '" title="Hapus item"><i class="bi bi-trash3"></i></button></td>' +
                    '</tr>';
            }).join('');

            updatePaymentPreview();
        };

        const setSelectedBarang = function(barang) {
            barangIdInput.value = barang.id;
            kodeInput.value = barang.kode_barang;
            namaInput.value = barang.nama_barang;
            satuanInput.value = barang.satuan || '';
            hargaBeliInput.value = formatNumber(barang.harga_beli || 0);
            selectedBarang = {
                id: barang.id,
                kode_barang: barang.kode_barang || '',
                nama_barang: barang.nama_barang || '',
                satuan: barang.satuan || '',
                stok: normalizeNumber(barang.stok || 0),
                harga_beli: normalizeNumber(barang.harga_beli || 0)
            };
            lookupMessage.textContent = 'Barang ditemukan.';
            lookupMessage.className = 'form-text text-success';
            updateSelectedMovingAveragePreview();
            jumlahInput.focus();
            jumlahInput.select();
        };

        const clearSelectedBarang = function(message, isError) {
            barangIdInput.value = '';
            namaInput.value = '';
            satuanInput.value = '';
            hargaBeliInput.value = '0';
            selectedBarang = null;
            updateSelectedMovingAveragePreview();
            lookupMessage.textContent = message || 'Scan QR/barcode akan mengisi kode barang di field ini.';
            lookupMessage.className = isError ? 'form-text text-danger' : 'form-text';
        };

        const lookupBarang = function() {
            const kode = kodeInput.value.trim();

            if (kode === '') {
                clearSelectedBarang();
                return;
            }

            fetch(lookupUrl + '?kode_barang=' + encodeURIComponent(kode), {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(function(response) {
                    if (!response.ok) {
                        throw new Error('Barang tidak ditemukan.');
                    }

                    return response.json();
                })
                .then(function(payload) {
                    setSelectedBarang(payload.barang);
                })
                .catch(function() {
                    clearSelectedBarang('Barang tidak ditemukan.', true);
                });
        };

        const addItem = function() {
            const barangId = parseInt(barangIdInput.value, 10);
            const jumlah = parseInt(jumlahInput.value, 10);
            const hargaBeli = normalizeNumber(hargaBeliInput.value);

            if (!barangId || !namaInput.value.trim()) {
                alert('Pilih barang terlebih dahulu.');
                kodeInput.focus();
                return;
            }

            if (!jumlah || jumlah < 1) {
                alert('Jumlah wajib lebih dari 0.');
                jumlahInput.focus();
                return;
            }

            const existing = items.find(function(item) {
                return parseInt(item.barang_id, 10) === barangId;
            });

            if (existing) {
                const oldJumlah = parseInt(existing.jumlah, 10) || 0;
                const newJumlah = oldJumlah + jumlah;
                const oldHargaBeli = normalizeNumber(existing.harga_beli);
                existing.jumlah = newJumlah;
                existing.harga_beli = newJumlah > 0 ? Math.round(((oldJumlah * oldHargaBeli) + (jumlah * hargaBeli)) / newJumlah) : hargaBeli;
            } else {
                items.push({
                    barang_id: barangId,
                    kode_barang: kodeInput.value.trim(),
                    nama_barang: namaInput.value.trim(),
                    satuan: satuanInput.value.trim(),
                    jumlah: jumlah,
                    harga_beli: hargaBeli,
                    stok_saat_ini: selectedBarang ? selectedBarang.stok : 0,
                    harga_beli_saat_ini: selectedBarang ? selectedBarang.harga_beli : hargaBeli
                });
            }

            kodeInput.value = '';
            jumlahInput.value = '1';
            clearSelectedBarang();
            renderItems();
            kodeInput.focus();
        };

        kodeInput.addEventListener('input', function() {
            window.clearTimeout(lookupTimer);
            lookupTimer = window.setTimeout(lookupBarang, 350);
        });

        kodeInput.addEventListener('keydown', function(event) {
            if (event.key === 'Enter') {
                event.preventDefault();
                lookupBarang();
            }
        });

        document.getElementById('addItemButton').addEventListener('click', addItem);
        jumlahInput.addEventListener('input', updateSelectedMovingAveragePreview);
        hargaBeliInput.addEventListener('input', function() {
            formatPriceInput(hargaBeliInput);
            updateSelectedMovingAveragePreview();
        });
        if (jumlahPembayaranInput) {
            jumlahPembayaranInput.addEventListener('input', function() {
                formatPriceInput(jumlahPembayaranInput);
                updatePaymentPreview();
            });
        }

        tableBody.addEventListener('input', function(event) {
            if (!event.target.classList.contains('item-qty-input')) {
                return;
            }

            const index = parseInt(event.target.dataset.index, 10);
            const jumlah = Math.max(1, parseInt(event.target.value, 10) || 1);
            items[index].jumlah = jumlah;
            const subtotalCell = event.target.closest('tr').querySelector('.item-subtotal');

            if (subtotalCell) {
                subtotalCell.textContent = formatNumber(jumlah * normalizeNumber(items[index].harga_beli));
            }

            const averageCell = event.target.closest('tr').querySelector('.item-average-preview');

            if (averageCell) {
                averageCell.innerHTML = rowMovingAverageSummary(items[index], jumlah, normalizeNumber(items[index].harga_beli));
            }

            syncItems();
            updatePaymentPreview();
        });

        tableBody.addEventListener('input', function(event) {
            if (!event.target.classList.contains('item-price-input')) {
                return;
            }

            const index = parseInt(event.target.dataset.index, 10);
            items[index].harga_beli = normalizeNumber(event.target.value);
            event.target.value = formatNumber(items[index].harga_beli);
            const jumlah = Math.max(1, parseInt(items[index].jumlah, 10) || 1);
            const subtotalCell = event.target.closest('tr').querySelector('.item-subtotal');

            if (subtotalCell) {
                subtotalCell.textContent = formatNumber(jumlah * normalizeNumber(items[index].harga_beli));
            }

            const averageCell = event.target.closest('tr').querySelector('.item-average-preview');

            if (averageCell) {
                averageCell.innerHTML = rowMovingAverageSummary(items[index], jumlah, normalizeNumber(items[index].harga_beli));
            }

            syncItems();
            updatePaymentPreview();
        });

        tableBody.addEventListener('click', function(event) {
            const button = event.target.closest('.remove-item-btn');

            if (!button) {
                return;
            }

            if (!confirm('Hapus barang ini dari transaksi pembelian?')) {
                return;
            }

            items.splice(parseInt(button.dataset.index, 10), 1);
            renderItems();
        });

        document.getElementById('pembelianForm').addEventListener('submit', function(event) {
            if (items.length === 0) {
                event.preventDefault();
                alert('Minimal tambahkan 1 item pembelian.');
                return;
            }

            const totalDibayar = jumlahPembayaranInput ? normalizeNumber(jumlahPembayaranInput.value) : normalizeNumber(fixedPaymentAmount);

            if (totalDibayar > totalWithTax()) {
                event.preventDefault();
                alert(paymentConflictMessage);

                if (jumlahPembayaranInput) {
                    jumlahPembayaranInput.focus();
                }
            }
        });

        tanggalInput.addEventListener('change', function() {
            if (!tanggalInput.value) {
                return;
            }

            fetch(generateNumberUrl + '?tanggal_pembelian=' + encodeURIComponent(tanggalInput.value), {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(function(response) {
                    return response.ok ? response.json() : null;
                })
                .then(function(payload) {
                    if (payload && payload.no_transaksi) {
                        noTransaksiInput.value = payload.no_transaksi;
                    }
                });
        });

        document.getElementById('openBarangModal').addEventListener('click', function() {
            const modalElement = document.getElementById('barangPickerModal');
            const modal = new bootstrap.Modal(modalElement);

            modal.show();

            if (!pickerTable && window.jQuery && $.fn.DataTable) {
                pickerTable = $('#barangPickerTable').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: datatableUrl,
                    ordering: false,
                    pageLength: 10,
                    columnDefs: [{
                        targets: -1,
                        searchable: false
                    }],
                    language: {
                        emptyTable: 'Belum ada data.',
                        info: 'Menampilkan _START_ sampai _END_ dari _TOTAL_ data',
                        infoEmpty: 'Menampilkan 0 data',
                        infoFiltered: '(difilter dari _MAX_ total data)',
                        lengthMenu: 'Tampilkan _MENU_ data',
                        loadingRecords: 'Memuat...',
                        processing: 'Memproses...',
                        search: 'Cari:',
                        zeroRecords: 'Data tidak ditemukan',
                        paginate: {
                            first: 'Pertama',
                            last: 'Terakhir',
                            next: 'Berikutnya',
                            previous: 'Sebelumnya'
                        }
                    }
                });
            } else if (pickerTable) {
                pickerTable.ajax.reload(null, false);
            }
        });

        document.getElementById('barangPickerTable').addEventListener('click', function(event) {
            const button = event.target.closest('.pilih-barang-btn');

            if (!button) {
                return;
            }

            setSelectedBarang({
                id: button.dataset.id,
                kode_barang: button.dataset.kode,
                nama_barang: button.dataset.nama,
                satuan: button.dataset.satuan,
                stok: button.dataset.stok || '0',
                harga_beli: button.dataset.hargaBeli || '0'
            });

            const modal = bootstrap.Modal.getInstance(document.getElementById('barangPickerModal'));

            if (modal) {
                modal.hide();
            }
        });

        renderItems();
    });
</script>