<?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;
    }
}

$selectedPelanggan = (string) old('pelanggan_id', $transaksi['pelanggan_id'] ?? '');
$tanggalValue = old('tanggal_penjualan', $tanggalPenjualan ?? 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) round((float) 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="penjualanForm">
            <?= csrf_field() ?>
            <input type="hidden" name="items_json" id="itemsJson" value="<?= esc(json_encode($itemsForJs), 'attr') ?>">

            <div class="row g-4 mb-4">
                <div class="col-12 col-lg-2">
                    <label for="tanggal_penjualan" class="form-label fw-semibold">Tanggal Penjualan</label>
                    <input type="date" class="form-control" id="tanggal_penjualan" name="tanggal_penjualan" 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-7">
                    <label for="pelanggan_id" class="form-label fw-semibold">Pelanggan</label>
                    <select class="form-select select2" id="pelanggan_id" name="pelanggan_id" data-placeholder="Pilih pelanggan" required>
                        <option value=""></option>
                        <?php foreach ($pelanggan as $item) : ?>
                            <option value="<?= esc($item['id'], 'attr') ?>" <?= $selectedPelanggan === (string) $item['id'] ? 'selected' : '' ?>>
                                <?= esc($item['nama']) ?><?= ! empty($item['kode_pelanggan']) ? ' - ' . esc($item['kode_pelanggan']) : '' ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </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">
                        <input type="hidden" id="selected_stok">

                        <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="row g-3">
                            <div class="col-6">
                                <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="col-6">
                                <label class="form-label fw-semibold">Stok</label>
                                <input type="text" class="form-control" id="stok_input" value="0" disabled>
                            </div>
                        </div>

                        <div class="my-3">
                            <label for="harga_jual_input" class="form-label fw-semibold">Harga Jual</label>
                            <input type="text" class="form-control" id="harga_jual_input" inputmode="numeric" value="0">
                            <div class="form-text text-danger d-none" id="hargaJualWarning"></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 Penjualan</div>
                                <div class="small text-secondary">Qty tidak boleh melebihi stok barang saat transaksi disimpan.</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="width:20%">Harga Jual</th>
                                        <th class="text-end" style="width:18%">Subtotal</th>
                                        <th class="text-center" style="width:1%">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody id="itemsTableBody">
                                    <tr>
                                        <td colspan="5" 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-3">
                        <?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 pembayaran pertama.</div>
                        <?php endif; ?>
                    </div>

                <div class="col-12 col-lg-3">
                    <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 Penjualan</th>
                                    <th width="1%">:</th>
                                    <td id="totalPenjualanPreview" 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 Piutang</th>
                                    <th width="1%">:</th>
                                    <td id="sisaPiutangPreview" 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" id="statusPembayaranPreview">Piutang</span></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="d-flex justify-content-end gap-2 mt-4">
                <a href="<?= site_url('admin/penjualan') ?>" 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>Harga Jual</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 penjualan.'
            : 'Jumlah pembayaran tidak boleh lebih besar dari jumlah penjualan. Silakan hapus riwayat pembayaran dulu untuk menyesuaikan jumlah pembayaran penjualan 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 stokInput = document.getElementById('stok_input');
        const hargaJualInput = document.getElementById('harga_jual_input');
        const hargaJualWarning = document.getElementById('hargaJualWarning');
        const jumlahPembayaranInput = document.getElementById('jumlah_pembayaran');
        const pajakInput = document.getElementById('pajak_persen');
        const subtotalPreview = document.getElementById('subtotalPreview');
        const pajakPreview = document.getElementById('pajakPreview');
        const totalPenjualanPreview = document.getElementById('totalPenjualanPreview');
        const totalDibayarPreview = document.getElementById('totalDibayarPreview');
        const sisaPiutangPreview = document.getElementById('sisaPiutangPreview');
        const statusPembayaranPreview = document.getElementById('statusPembayaranPreview');
        const barangIdInput = document.getElementById('selected_barang_id');
        const satuanInput = document.getElementById('selected_satuan');
        const selectedStokInput = document.getElementById('selected_stok');
        const lookupMessage = document.getElementById('barangLookupMessage');
        const tanggalInput = document.getElementById('tanggal_penjualan');
        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 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 normalizePercent = function (value) {
            const number = Math.round(parseFloat(String(value ?? '0').replace(',', '.')));
            return Number.isFinite(number) && number >= 0 ? Math.min(100, 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 belowCostMessage = function (item) {
            const hargaBeli = normalizeNumber(item && item.harga_beli);
            const hargaJual = normalizeNumber(item && item.harga_jual);

            return hargaBeli > 0 && hargaJual < hargaBeli
                ? 'Harga jual tidak boleh lebih kecil dari modal Rp ' + formatNumber(hargaBeli) + '.'
                : '';
        };

        const updateMainPriceWarning = function () {
            if (! selectedBarang) {
                hargaJualInput.classList.remove('is-invalid');
                hargaJualWarning.classList.add('d-none');
                hargaJualWarning.textContent = '';
                return '';
            }

            const message = belowCostMessage({
                harga_jual: normalizeNumber(hargaJualInput.value),
                harga_beli: selectedBarang.harga_beli
            });

            hargaJualInput.classList.toggle('is-invalid', message !== '');
            hargaJualWarning.classList.toggle('d-none', message === '');
            hargaJualWarning.textContent = message;

            return message;
        };

        const belowCostItems = function () {
            return items.filter(function (item) {
                return belowCostMessage(item) !== '';
            });
        };

        const totalItems = function () {
            return items.reduce(function (total, item) {
                const jumlah = Math.max(1, parseInt(item.jumlah, 10) || 1);
                const hargaJual = normalizeNumber(item.harga_jual);
                return total + (jumlah * hargaJual);
            }, 0);
        };

        const totalQtyForBarang = function (barangId, excludeIndex) {
            return items.reduce(function (total, item, index) {
                if (index === excludeIndex || parseInt(item.barang_id, 10) !== parseInt(barangId, 10)) {
                    return total;
                }
                return total + (parseInt(item.jumlah, 10) || 0);
            }, 0);
        };

        const updatePaymentPreview = function () {
            const subtotal = totalItems();
            const pajak = Math.round(subtotal * normalizePercent(pajakInput.value) / 100);
            const totalPenjualan = subtotal + pajak;
            const totalDibayar = jumlahPembayaranInput ? normalizeNumber(jumlahPembayaranInput.value) : normalizeNumber(fixedPaymentAmount);
            const sisaPiutang = Math.max(0, totalPenjualan - totalDibayar);
            const isLunas = totalPenjualan > 0 && totalDibayar >= totalPenjualan;

            subtotalPreview.textContent = formatNumber(subtotal);
            pajakPreview.textContent = formatNumber(pajak);
            totalPenjualanPreview.textContent = formatNumber(totalPenjualan);
            totalDibayarPreview.textContent = formatNumber(totalDibayar);
            sisaPiutangPreview.textContent = formatNumber(sisaPiutang);
            statusPembayaranPreview.textContent = isLunas ? 'Lunas' : 'Piutang';
            statusPembayaranPreview.className = isLunas ? 'badge text-bg-success' : 'badge text-bg-warning';
        };

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

        const renderItems = function () {
            syncItems();

            if (items.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="5" 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 hargaJual = normalizeNumber(item.harga_jual);
                const subtotal = jumlah * hargaJual;
                const priceWarning = belowCostMessage(item);
                const priceInputClass = priceWarning
                    ? 'form-control form-control-sm item-price-input is-invalid'
                    : 'form-control form-control-sm item-price-input';

                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="small text-secondary d-block mt-1">Stok: ' + escapeHtml(item.stok_saat_ini ?? 0) + ' <span class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 fw-semibold">' + escapeHtml(item.satuan) + '</span></span></td>'
                    + '<td><input type="number" class="form-control form-control-sm item-qty-input" min="1" max="' + escapeHtml(item.stok_saat_ini ?? 0) + '" value="' + escapeHtml(item.jumlah) + '" data-index="' + index + '"></td>'
                    + '<td><input type="text" class="' + priceInputClass + '" inputmode="numeric" value="' + escapeHtml(formatNumber(hargaJual)) + '" data-index="' + index + '">'
                    + (priceWarning ? '<div class="form-text text-danger">' + escapeHtml(priceWarning) + '</div>' : '') + '</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 || '';
            selectedStokInput.value = barang.stok || '0';
            stokInput.value = barang.stok || '0';
            hargaJualInput.value = formatNumber(barang.harga_jual || 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),
                harga_jual: normalizeNumber(barang.harga_jual || 0)
            };
            lookupMessage.textContent = selectedBarang.stok > 0 ? 'Barang ditemukan.' : 'Stok barang kosong.';
            lookupMessage.className = selectedBarang.stok > 0 ? 'form-text text-success' : 'form-text text-danger';
            updateMainPriceWarning();
            jumlahInput.focus();
            jumlahInput.select();
        };

        const clearSelectedBarang = function (message, isError) {
            barangIdInput.value = '';
            namaInput.value = '';
            satuanInput.value = '';
            selectedStokInput.value = '0';
            stokInput.value = '0';
            hargaJualInput.value = '0';
            selectedBarang = null;
            updateMainPriceWarning();
            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 hargaJual = normalizeNumber(hargaJualInput.value);

            if (! barangId || ! namaInput.value.trim() || ! selectedBarang) {
                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;
            });
            const currentQty = existing ? parseInt(existing.jumlah, 10) || 0 : 0;

            if ((currentQty + jumlah) > selectedBarang.stok) {
                alert('Jumlah penjualan melebihi stok tersedia.');
                jumlahInput.focus();
                return;
            }

            const priceMessage = updateMainPriceWarning();

            if (priceMessage !== '') {
                alert(priceMessage);
                hargaJualInput.focus();
                return;
            }

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

            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);
        hargaJualInput.addEventListener('input', function () {
            formatPriceInput(hargaJualInput);
            updateMainPriceWarning();
        });
        pajakInput.addEventListener('input', updatePaymentPreview);
        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 barangId = items[index].barang_id;
            const stock = normalizeNumber(items[index].stok_saat_ini);
            let jumlah = Math.max(1, parseInt(event.target.value, 10) || 1);
            const otherQty = totalQtyForBarang(barangId, index);

            if ((otherQty + jumlah) > stock) {
                jumlah = Math.max(1, stock - otherQty);
                event.target.value = jumlah;
            }

            items[index].jumlah = jumlah;
            const subtotalCell = event.target.closest('tr').querySelector('.item-subtotal');

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

            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_jual = normalizeNumber(event.target.value);
            event.target.value = formatNumber(items[index].harga_jual);
            const jumlah = Math.max(1, parseInt(items[index].jumlah, 10) || 1);
            const warning = belowCostMessage(items[index]);
            const cell = event.target.closest('td');
            const subtotalCell = event.target.closest('tr').querySelector('.item-subtotal');

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

            event.target.classList.toggle('is-invalid', warning !== '');

            if (cell) {
                let warningElement = cell.querySelector('.form-text.text-danger');

                if (warning !== '') {
                    if (! warningElement) {
                        warningElement = document.createElement('div');
                        warningElement.className = 'form-text text-danger';
                        cell.appendChild(warningElement);
                    }

                    warningElement.textContent = warning;
                } else if (warningElement) {
                    warningElement.remove();
                }
            }

            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 penjualan?')) {
                return;
            }

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

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

            const totalPenjualan = totalItems() + Math.round(totalItems() * normalizePercent(pajakInput.value) / 100);
            const totalDibayar = jumlahPembayaranInput ? normalizeNumber(jumlahPembayaranInput.value) : normalizeNumber(fixedPaymentAmount);

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

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

                return;
            }

            const invalidPriceItems = belowCostItems();

            if (invalidPriceItems.length > 0) {
                event.preventDefault();
                alert('Ada harga jual yang lebih kecil dari modal barang. Silakan sesuaikan harga jual terlebih dahulu.');
                renderItems();

                const invalidInput = tableBody.querySelector('.item-price-input.is-invalid');

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

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

            fetch(generateNumberUrl + '?tanggal_penjualan=' + 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',
                harga_jual: button.dataset.hargaJual || '0'
            });

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

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

        renderItems();
    });
</script>
