<?php
$transaksi = $transaksi ?? [];
$oldBarang = old('barang_items_json');
$oldJasa = old('jasa_items_json');
$barangForJs = $initialBarang ?? [];
$jasaForJs = $initialJasa ?? [];

if (is_string($oldBarang) && $oldBarang !== '') {
    $decodedOldBarang = json_decode($oldBarang, true);

    if (is_array($decodedOldBarang)) {
        $barangForJs = $decodedOldBarang;
    }
}

if (is_string($oldJasa) && $oldJasa !== '') {
    $decodedOldJasa = json_decode($oldJasa, true);

    if (is_array($decodedOldJasa)) {
        $jasaForJs = $decodedOldJasa;
    }
}

$selectedPelanggan = (string) old('pelanggan_id', $transaksi['pelanggan_id'] ?? '');
$selectedTeknisi = (string) old('teknisi_id', $transaksi['teknisi_id'] ?? '');
$tanggalValue = old('tanggal_service', $tanggalService ?? date('Y-m-d'));
$noTransaksiValue = old('no_transaksi', $transaksi['no_transaksi'] ?? ($noTransaksi ?? ''));
$statusValue = old('status_service', $transaksi['status_service'] ?? 'menunggu');
$pajakPersenValue = (int) old('pajak_persen', $pajakPersen ?? ($transaksi['pajak_persen'] ?? 0));
$showInitialPayment = (bool) ($showInitialPayment ?? true);
$initialPaymentRaw = old('jumlah_pembayaran', $initialPayment ?? 0);
$initialPaymentValue = (int) (preg_replace('/\D/', '', (string) $initialPaymentRaw) ?: 0);
$paymentPreviewValue = $showInitialPayment ? $initialPaymentValue : (int) ($totalDibayar ?? 0);
$jasaOptionsForJs = array_map(static fn(array $item): array => [
    'id'        => (int) $item['id'],
    'nama_jasa' => $item['nama_jasa'],
    'biaya'     => (int) ($item['biaya'] ?? 0),
], $jasaOptions ?? []);
?>

<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="serviceForm">
            <?= csrf_field() ?>
            <input type="hidden" name="barang_items_json" id="barangItemsJson" value="<?= esc(json_encode($barangForJs), 'attr') ?>">
            <input type="hidden" name="jasa_items_json" id="jasaItemsJson" value="<?= esc(json_encode($jasaForJs), 'attr') ?>">

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

                <div class="col-12 col-lg-3">
                    <label for="no_transaksi" class="form-label fw-semibold">No. Service</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="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 col-lg-3">
                    <label for="teknisi_id" class="form-label fw-semibold">Teknisi</label>
                    <select class="form-select select2" id="teknisi_id" name="teknisi_id" data-placeholder="Pilih teknisi" required>
                        <option value=""></option>
                        <?php foreach ($teknisi as $item) : ?>
                            <option value="<?= esc($item['id'], 'attr') ?>" <?= $selectedTeknisi === (string) $item['id'] ? 'selected' : '' ?>>
                                <?= esc($item['nama']) ?><?= ! empty($item['kode_teknisi']) ? ' - ' . esc($item['kode_teknisi']) : '' ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12 col-lg-4">
                    <label for="nomor_objek" class="form-label fw-semibold">Nomor Kendaraan/Ponsel/dll</label>
                    <input type="text" class="form-control" id="nomor_objek" name="nomor_objek" value="<?= esc(old('nomor_objek', $transaksi['nomor_objek'] ?? ''), 'attr') ?>" placeholder="Contoh: B 1234 ABC / IMEI / SN">
                </div>

                <div class="col-12 col-lg-5">
                    <label for="merk_tipe" class="form-label fw-semibold">Merk/Tipe/dll</label>
                    <input type="text" class="form-control" id="merk_tipe" name="merk_tipe" value="<?= esc(old('merk_tipe', $transaksi['merk_tipe'] ?? ''), 'attr') ?>" placeholder="Contoh: Vario 150 2025 / iPhone XR / Laptop Toshiba">
                </div>

                <div class="col-12 col-lg-3">
                    <label for="status_service" class="form-label fw-semibold text-primary">Status Service</label>
                    <select class="form-select" id="status_service" name="status_service" required>
                        <?php foreach ($statusLabels as $statusKey => $statusLabel) : ?>
                            <option value="<?= esc($statusKey, 'attr') ?>" <?= $statusValue === $statusKey ? 'selected' : '' ?>>
                                <?= esc($statusLabel) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

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

            <div class="row g-4">
                <div class="col-12 col-xl-12">
                    <div class="panel-subtle border rounded-2 p-3 h-100">
                        <div class="d-flex align-items-center justify-content-between gap-2 mb-3">
                            <div class="fw-bold">Part/Barang Diganti</div>
                           
                        </div>
                        <div class="row">
                            <div class="col-lg-4">
                                <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/isi kode atau pilih dari daftar.</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" readonly>
                                    <input type="hidden" id="selected_barang_id">
                                    <input type="hidden" id="selected_satuan">
                                    <input type="hidden" id="selected_stok">
                                </div>

                                <div class="row g-3">
                                    <div class="col-6">
                                        <label for="jumlah_input" class="form-label fw-semibold">Qty</label>
                                        <input type="number" class="form-control" id="jumlah_input" value="1" min="1">
                                    </div>
                                    <div class="col-6">
                                        <label for="stok_input" 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</label>
                                    <input type="text" class="form-control" id="harga_jual_input" inputmode="numeric" value="0">
                                </div>

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

                            <div class="col-lg-8">

                                <div class="table-responsive">
                                    <table class="table table-hover align-middle mb-0">
                                        <thead>
                                            <tr>
                                                <th>Barang</th>
                                                <th class="text-end">Qty</th>
                                                <th class="text-end">Harga</th>
                                                <th class="text-end">Subtotal</th>
                                                <th class="text-end">Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody id="barangItemsTableBody">
                                            <tr>
                                                <td colspan="5" class="text-center text-secondary py-4">Belum ada part/barang.</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>

                            </div>
                        </div>


                      
                    </div>
                </div>

                <div class="col-12 col-xl-12">
                    <div class="panel-subtle border rounded-2 p-3 h-100">
                        <div class="fw-bold mb-3">Jasa Service</div>

                        <div class="row">
                            <div class="col-lg-4">
                                <div class="mb-3">
                                    <label for="jasa_master_select" class="form-label fw-semibold">Pilih dari Master Jasa</label>
                                    <select class="form-select" id="jasa_master_select">
                                        <option value="">Manual / pilih jasa</option>
                                        <?php foreach ($jasaOptions as $item) : ?>
                                            <option value="<?= esc($item['id'], 'attr') ?>" data-nama="<?= esc($item['nama_jasa'], 'attr') ?>" data-biaya="<?= esc((string) ($item['biaya'] ?? 0), 'attr') ?>">
                                                <?= esc($item['nama_jasa']) ?> - Rp <?= esc(number_format((float) ($item['biaya'] ?? 0), 0, ',', '.')) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="mb-3">
                                    <label for="nama_jasa_input" class="form-label fw-semibold">Nama Jasa</label>
                                    <input type="text" class="form-control" id="nama_jasa_input" placeholder="Contoh: Instal ulang Windows">
                                </div>

                                <div class="my-3">
                                    <label for="biaya_jasa_input" class="form-label fw-semibold">Biaya</label>
                                    <input type="text" class="form-control" id="biaya_jasa_input" inputmode="numeric" value="0">
                                </div>

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

                            <div class="col-lg-8">
                                <div class="table-responsive">
                                    <table class="table table-hover align-middle mb-0">
                                        <thead>
                                            <tr>
                                                <th>Jasa</th>
                                                <th class="text-end">Biaya</th>
                                                <th class="text-end">Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody id="jasaItemsTableBody">
                                            <tr>
                                                <td colspan="3" class="text-center text-secondary py-4">Belum ada jasa.</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row g-4 mt-1">
                <?php if ($showInitialPayment) : ?>
                    <div class="col-12 col-lg-3">
                        <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>
                    </div>
                <?php else : ?>
                    <div class="col-12 col-lg-3">
                        <label class="form-label fw-semibold">Total Dibayar</label>
                        <div class="form-control bg-light">Rp <?= esc(number_format((float) $paymentPreviewValue, 0, ',', '.')) ?></div>
                        <div class="form-text">Ubah lewat halaman cicilan.</div>
                    </div>
                <?php endif; ?>
                <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>
                    <div class="form-text">Mengikuti pengaturan pajak aplikasi.</div>
                </div>
                <div class="col-12 col-lg-6">
                    <div class="table-responsive">
                        <table class="table table-bordere table-sm align-middle">
                            <tbody>
                                <tr>
                                    <th width="35%">Part</th>
                                    <th width="1%">:</th>
                                    <td id="subtotalBarangPreview" class="text-end fw-bold">0</td>
                                </tr>
                                <tr>
                                    <th>Jasa</th>
                                    <th width="1%">:</th>
                                    <td id="subtotalJasaPreview" 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 Service</th>
                                    <th width="1%">:</th>
                                    <td id="totalServicePreview" class="text-end fw-bold">0</td>
                                </tr>
                                <tr>
                                    <th>Sisa Pembayaran</th>
                                    <th width="1%">:</th>
                                    <td id="sisaPembayaranPreview" class="text-end fw-bold text-danger">0</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="d-flex justify-content-end gap-2 mt-4">
                <a href="<?= site_url('admin/service') ?>" 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 barangItemsInput = document.getElementById('barangItemsJson');
        const jasaItemsInput = document.getElementById('jasaItemsJson');
        const barangTableBody = document.getElementById('barangItemsTableBody');
        const jasaTableBody = document.getElementById('jasaItemsTableBody');
        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 barangIdInput = document.getElementById('selected_barang_id');
        const satuanInput = document.getElementById('selected_satuan');
        const selectedStokInput = document.getElementById('selected_stok');
        const lookupMessage = document.getElementById('barangLookupMessage');
        const jasaMasterSelect = document.getElementById('jasa_master_select');
        const namaJasaInput = document.getElementById('nama_jasa_input');
        const biayaJasaInput = document.getElementById('biaya_jasa_input');
        const jumlahPembayaranInput = document.getElementById('jumlah_pembayaran');
        const pajakInput = document.getElementById('pajak_persen');
        const tanggalInput = document.getElementById('tanggal_service');
        const noTransaksiInput = document.getElementById('no_transaksi');
        const subtotalBarangPreview = document.getElementById('subtotalBarangPreview');
        const subtotalJasaPreview = document.getElementById('subtotalJasaPreview');
        const pajakPreview = document.getElementById('pajakPreview');
        const totalServicePreview = document.getElementById('totalServicePreview');
        const sisaPembayaranPreview = document.getElementById('sisaPembayaranPreview');
        let barangItems = <?= json_encode(array_values($barangForJs)) ?>;
        let jasaItems = <?= json_encode(array_values($jasaForJs)) ?>;
        const totalDibayarTersimpan = <?= json_encode((int) $paymentPreviewValue) ?>;
        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 formatNumber = function(value) {
            return normalizeNumber(value).toLocaleString('id-ID', {
                minimumFractionDigits: 0,
                maximumFractionDigits: 0
            });
        };

        const syncItems = function() {
            barangItemsInput.value = JSON.stringify(barangItems);
            jasaItemsInput.value = JSON.stringify(jasaItems);
        };

        const barangSubtotal = function() {
            return barangItems.reduce(function(total, item) {
                return total + ((parseInt(item.jumlah, 10) || 0) * normalizeNumber(item.harga_jual));
            }, 0);
        };

        const jasaSubtotal = function() {
            return jasaItems.reduce(function(total, item) {
                return total + normalizeNumber(item.biaya);
            }, 0);
        };

        const updateSummary = function() {
            const subtotalBarang = barangSubtotal();
            const subtotalJasa = jasaSubtotal();
            const subtotal = subtotalBarang + subtotalJasa;
            const pajak = Math.round(subtotal * (parseInt(pajakInput.value, 10) || 0) / 100);
            const totalService = subtotal + pajak;
            const totalDibayar = jumlahPembayaranInput ? normalizeNumber(jumlahPembayaranInput.value) : totalDibayarTersimpan;

            subtotalBarangPreview.textContent = formatNumber(subtotalBarang);
            subtotalJasaPreview.textContent = formatNumber(subtotalJasa);
            pajakPreview.textContent = formatNumber(pajak);
            totalServicePreview.textContent = formatNumber(totalService);
            sisaPembayaranPreview.textContent = formatNumber(Math.max(0, totalService - totalDibayar));
        };

        const renderBarangItems = function() {
            syncItems();

            if (barangItems.length === 0) {
                barangTableBody.innerHTML = '<tr><td colspan="5" class="text-center text-secondary py-4">Belum ada part/barang.</td></tr>';
                updateSummary();
                return;
            }

            barangTableBody.innerHTML = barangItems.map(function(item, index) {
                const jumlah = Math.max(1, parseInt(item.jumlah, 10) || 1);
                const hargaJual = normalizeNumber(item.harga_jual);
                const subtotal = jumlah * hargaJual;

                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 class="text-end"><input type="number" class="form-control form-control-sm text-end service-part-qty" min="1" max="' + escapeHtml(item.stok_saat_ini || item.stok || 0) + '" value="' + escapeHtml(jumlah) + '" data-index="' + index + '"></td>' +
                    '<td class="text-end"><input type="text" class="form-control form-control-sm text-end service-part-price" inputmode="numeric" value="' + escapeHtml(formatNumber(hargaJual)) + '" data-index="' + index + '"></td>' +
                    '<td class="text-end fw-semibold service-part-subtotal">' + escapeHtml(formatNumber(subtotal)) + '</td>' +
                    '<td class="text-end"><button type="button" class="btn btn-sm btn-danger btn-icon remove-part-btn" data-index="' + index + '" title="Hapus part"><i class="bi bi-trash3"></i></button></td>' +
                    '</tr>';
            }).join('');

            updateSummary();
        };

        const renderJasaItems = function() {
            syncItems();

            if (jasaItems.length === 0) {
                jasaTableBody.innerHTML = '<tr><td colspan="3" class="text-center text-secondary py-4">Belum ada jasa.</td></tr>';
                updateSummary();
                return;
            }

            jasaTableBody.innerHTML = jasaItems.map(function(item, index) {
                return '<tr>' +
                    '<td><input type="text" class="form-control form-control-sm service-jasa-name" value="' + escapeHtml(item.nama_jasa) + '" data-index="' + index + '"></td>' +
                    '<td class="text-end"><input type="text" class="form-control form-control-sm text-end service-jasa-price" inputmode="numeric" value="' + escapeHtml(formatNumber(item.biaya)) + '" data-index="' + index + '"></td>' +
                    '<td class="text-end"><button type="button" class="btn btn-sm btn-danger btn-icon remove-jasa-btn" data-index="' + index + '" title="Hapus jasa"><i class="bi bi-trash3"></i></button></td>' +
                    '</tr>';
            }).join('');

            updateSummary();
        };

        const clearSelectedBarang = function(message, isError) {
            selectedBarang = null;
            barangIdInput.value = '';
            namaInput.value = '';
            satuanInput.value = '';
            selectedStokInput.value = '';
            stokInput.value = '0';
            hargaJualInput.value = '0';
            lookupMessage.textContent = message || 'Scan/isi kode atau pilih dari daftar.';
            lookupMessage.className = isError ? 'form-text text-danger' : 'form-text text-secondary';
        };

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

        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) {
                    if (payload && payload.barang) {
                        setSelectedBarang(payload.barang);
                    }
                })
                .catch(function() {
                    clearSelectedBarang('Barang tidak ditemukan.', true);
                });
        };

        const existingQtyForBarang = function(barangId, excludeIndex) {
            return barangItems.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 addBarangItem = function() {
            if (!selectedBarang) {
                alert('Pilih barang terlebih dahulu.');
                kodeInput.focus();
                return;
            }

            const jumlah = Math.max(1, parseInt(jumlahInput.value, 10) || 1);
            const hargaJual = normalizeNumber(hargaJualInput.value);
            const existingQty = existingQtyForBarang(selectedBarang.id, null);

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

            const existingIndex = barangItems.findIndex(function(item) {
                return parseInt(item.barang_id, 10) === parseInt(selectedBarang.id, 10);
            });

            if (existingIndex >= 0) {
                const currentQty = parseInt(barangItems[existingIndex].jumlah, 10) || 0;
                barangItems[existingIndex].jumlah = currentQty + jumlah;
                barangItems[existingIndex].harga_jual = hargaJual;
            } else {
                barangItems.push({
                    barang_id: selectedBarang.id,
                    kode_barang: selectedBarang.kode_barang,
                    nama_barang: selectedBarang.nama_barang,
                    satuan: selectedBarang.satuan,
                    jumlah: jumlah,
                    harga_jual: hargaJual,
                    stok_saat_ini: selectedBarang.stok
                });
            }

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

        const addJasaItem = function() {
            const namaJasa = namaJasaInput.value.trim();
            const biaya = normalizeNumber(biayaJasaInput.value);

            if (!namaJasa) {
                alert('Nama jasa wajib diisi.');
                namaJasaInput.focus();
                return;
            }

            jasaItems.push({
                jasa_id: jasaMasterSelect.value || null,
                nama_jasa: namaJasa,
                biaya: biaya
            });

            jasaMasterSelect.value = '';
            namaJasaInput.value = '';
            biayaJasaInput.value = '0';
            renderJasaItems();
            namaJasaInput.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();
            }
        });

        hargaJualInput.addEventListener('input', function() {
            hargaJualInput.value = formatNumber(hargaJualInput.value);
        });

        biayaJasaInput.addEventListener('input', function() {
            biayaJasaInput.value = formatNumber(biayaJasaInput.value);
        });

        if (jumlahPembayaranInput) {
            jumlahPembayaranInput.addEventListener('input', function() {
                jumlahPembayaranInput.value = formatNumber(jumlahPembayaranInput.value);
                updateSummary();
            });
        }

        jasaMasterSelect.addEventListener('change', function() {
            const option = jasaMasterSelect.selectedOptions[0];

            if (!option || !option.value) {
                return;
            }

            namaJasaInput.value = option.dataset.nama || option.textContent.trim();
            biayaJasaInput.value = formatNumber(option.dataset.biaya || 0);
        });

        document.getElementById('addBarangButton').addEventListener('click', addBarangItem);
        document.getElementById('addJasaButton').addEventListener('click', addJasaItem);

        barangTableBody.addEventListener('input', function(event) {
            const target = event.target;
            const index = parseInt(target.dataset.index, 10);

            if (Number.isNaN(index) || !barangItems[index]) {
                return;
            }

            if (target.classList.contains('service-part-qty')) {
                const max = normalizeNumber(barangItems[index].stok_saat_ini || barangItems[index].stok || 0);
                const otherQty = existingQtyForBarang(barangItems[index].barang_id, index);
                let jumlah = Math.max(1, parseInt(target.value, 10) || 1);

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

                barangItems[index].jumlah = jumlah;
            }

            if (target.classList.contains('service-part-price')) {
                barangItems[index].harga_jual = normalizeNumber(target.value);
                target.value = formatNumber(barangItems[index].harga_jual);
            }

            renderBarangItems();
        });

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

            if (!button) {
                return;
            }

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

            barangItems.splice(parseInt(button.dataset.index, 10), 1);
            renderBarangItems();
        });

        jasaTableBody.addEventListener('input', function(event) {
            const target = event.target;
            const index = parseInt(target.dataset.index, 10);

            if (Number.isNaN(index) || !jasaItems[index]) {
                return;
            }

            if (target.classList.contains('service-jasa-name')) {
                jasaItems[index].nama_jasa = target.value;
            }

            if (target.classList.contains('service-jasa-price')) {
                jasaItems[index].biaya = normalizeNumber(target.value);
                target.value = formatNumber(jasaItems[index].biaya);
            }

            syncItems();
            updateSummary();
        });

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

            if (!button) {
                return;
            }

            if (!confirm('Hapus jasa ini dari transaksi service?')) {
                return;
            }

            jasaItems.splice(parseInt(button.dataset.index, 10), 1);
            renderJasaItems();
        });

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

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

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

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

        document.getElementById('serviceForm').addEventListener('submit', function() {
            syncItems();
        });

        renderBarangItems();
        renderJasaItems();
        updateSummary();
    });
</script>
