<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<h4>Edit Transaksi</h4>

<form action="<?= base_url('admin/report/sales/update/' . $sales['id']) ?>" method="post">
    <div class="table-responsive mb-3">
        <table class="table table-sm table-bordered" id="item-table">
            <thead>
                <tr>
                    <th>Nama Item</th>
                    <th>Qty</th>
                    <th>Harga</th>
                    <th>Subtotal</th>
                    <th><button type="button" class="btn btn-sm btn-success" onclick="addRow()">+</button></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($details as $index => $item): ?>
                    <tr>
                        <td>
                            <input type="hidden" name="items[<?= $index ?>][id]" value="<?= $item['id'] ?>">
                            <select name="items[<?= $index ?>][item_id]" class="form-control item-select" data-index="<?= $index ?>">
                                <option value="">Pilih Item</option>
                                <?php foreach ($items as $i): ?>
                                    <option value="<?= $i['id'] ?>" data-harga="<?= $i['harga'] ?>" <?= $i['id'] == $item['item_id'] ? 'selected' : '' ?>>
                                        <?= esc($i['barcode']) ?> - <?= esc($i['nama']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td><input type="number" name="items[<?= $index ?>][qty]" value="<?= $item['qty'] ?>" class="form-control qty" data-index="<?= $index ?>" min="1"></td>
                        <td><input type="number" name="items[<?= $index ?>][harga]" value="<?= $item['harga'] ?>" class="form-control harga" data-index="<?= $index ?>" min="0" readonly></td>
                        <td><input type="number" name="items[<?= $index ?>][subtotal]" value="<?= $item['subtotal'] ?>" class="form-control subtotal-input" id="subtotal-input-<?= $index ?>" readonly></td>
                        <td><button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">-</button></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <div class="row">
        <div class="col-md-6">
            <div class="mb-2">
                <label>Tanggal:</label>
                <input type="text" class="form-control" value="<?= date('d-m-Y H:i', strtotime($sales['tanggal'])) ?>" readonly>
            </div>
            <div class="mb-2">
                <label for="customer_id">Pelanggan:</label>
                <select name="customer_id" id="customer_id" class="form-control">
                    <option value="">Umum</option>
                    <?php foreach ($customers as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= $c['id'] == $sales['customer_id'] ? 'selected' : '' ?>>
                            <?= esc($c['nama']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mb-2">
                <label>Kasir:</label>
                <input type="text" class="form-control" value="<?= esc($sales['user_name']) ?>" readonly>
            </div>
            <div class="mb-2">
                <label>Kode Transaksi:</label>
                <input type="text" class="form-control" value="<?= esc($sales['kode']) ?>" readonly>
            </div>
            <div class="mb-2">
                <label>Jenis Pesan:</label>
                <select name="jenis_pesan" id="jenis_pesan" class="form-control" onchange="toggleMeja()">
                    <option value="take_away" <?= $sales['jenis_pesan'] === 'take_away' ? 'selected' : '' ?>>Take Away</option>
                    <option value="dine_in" <?= $sales['jenis_pesan'] === 'dine_in' ? 'selected' : '' ?>>Dine In</option>
                </select>
            </div>
            <div class="mb-2" id="no_meja_group" style="display: <?= $sales['jenis_pesan'] === 'dine_in' ? 'block' : 'none' ?>;">
                <label>No. Meja:</label>
                <input type="text" name="no_meja" class="form-control" value="<?= esc($sales['no_meja']) ?>">
            </div>
            <?php if (isset($tax)): ?>
                <div class="mb-2">
                    <label>Status Pajak:</label>
                    <input type="text" class="form-control" value="<?= $tax['aktif'] ? 'Aktif (' . $tax['persen'] . '%)' : 'Tidak Aktif' ?>" readonly>
                </div>
            <?php endif; ?>
        </div>

        <div class="col-md-6">
            <div class="mb-2">
                <label>Bayar:</label>
                <input type="number" name="dibayar" id="dibayar" value="<?= $sales['dibayar'] ?>" class="form-control">
            </div>
            <div class="mb-2">
                <label>Kembalian:</label>
                <input type="number" name="kembalian" id="kembalian" value="<?= $sales['kembalian'] ?>" class="form-control" readonly>
            </div>
            <div class="mb-2">
                <label>Grand Total (Termasuk Pajak):</label>
                <p class="form-control-plaintext"><strong id="total-display"><?= number_format($sales['total_bayar'], 0, ',', '.') ?></strong></p>
            </div>
        </div>
    </div>

    <input type="hidden" name="total" id="total-hidden" value="<?= $sales['total'] ?>">
    <input type="hidden" name="pajak_nominal" id="pajak-nominal" value="<?= $sales['pajak_nominal'] ?>">
    <input type="hidden" name="grand_total" id="grand-total" value="<?= $sales['total_bayar'] ?>">
    <input type="hidden" id="pajak-persen" value="<?= ($tax && $tax['aktif']) ? $tax['persen'] : 0 ?>">

    <div class="text-end mt-3">
        <button type="submit" class="btn btn-primary">Simpan</button>
        <a href="<?= base_url('admin/report/sales') ?>" class="btn btn-secondary">Batal</a>
    </div>
</form>


<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
const itemList = <?= json_encode($items) ?>;

document.addEventListener('DOMContentLoaded', () => {
    function updateSubtotal(index) {
        const qty = parseInt(document.querySelector(`.qty[data-index="${index}"]`)?.value || 0);
        const harga = parseInt(document.querySelector(`.harga[data-index="${index}"]`)?.value || 0);
        const subtotal = qty * harga;
        document.getElementById(`subtotal-input-${index}`).value = subtotal;
        updateTotal();
    }

    function updateTotal() {
        let total = 0;
        document.querySelectorAll('.subtotal-input').forEach(input => {
            total += parseInt(input.value) || 0;
        });

        const pajakPersen = parseFloat(document.getElementById('pajak-persen').value || 0);
        const pajak = Math.round(total * pajakPersen / 100);
        const grandTotal = total + pajak;

        document.getElementById('total-display').textContent = grandTotal.toLocaleString('id-ID');
        document.getElementById('total-hidden').value = total;
        document.getElementById('pajak-nominal').value = pajak;
        document.getElementById('grand-total').value = grandTotal;
        updateKembalian();
    }

    function updateKembalian() {
        const dibayar = parseInt(document.getElementById('dibayar').value) || 0;
        const grandTotal = parseInt(document.getElementById('grand-total').value) || 0;
        document.getElementById('kembalian').value = dibayar - grandTotal;
    }

    function bindRowEvents(index) {
        document.querySelector(`.qty[data-index="${index}"]`)?.addEventListener('input', () => updateSubtotal(index));

        const select = document.querySelector(`.item-select[data-index="${index}"]`);
        if (select) {
            select.addEventListener('change', function () {
                const selected = itemList.find(i => i.id == this.value);
                const hargaInput = document.querySelector(`.harga[data-index="${index}"]`);
                if (selected) {
                    hargaInput.value = selected.harga;
                    updateSubtotal(index);
                }
            });

            $(select).select2({ width: 'resolve', placeholder: 'Cari nama/barcode item' });
        }
    }

    document.querySelectorAll('.item-select').forEach((el, i) => bindRowEvents(i));
    document.getElementById('dibayar').addEventListener('input', updateKembalian);

    window.toggleMeja = function () {
        const jenis = document.getElementById('jenis_pesan').value;
        document.getElementById('no_meja_group').style.display = jenis === 'dine_in' ? 'block' : 'none';
    };

    window.addRow = function () {
        const tbody = document.querySelector('#item-table tbody');
        const index = tbody.querySelectorAll('tr').length;
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>
                <select name="items[${index}][item_id]" class="form-control item-select" data-index="${index}">
                    <option value="">Pilih Item</option>
                    ${itemList.map(i => `<option value="${i.id}" data-harga="${i.harga}">${i.barcode} - ${i.nama}</option>`).join('')}
                </select>
            </td>
            <td><input type="number" name="items[${index}][qty]" value="1" class="form-control qty" data-index="${index}" min="1"></td>
            <td><input type="number" name="items[${index}][harga]" value="0" class="form-control harga" data-index="${index}" readonly></td>
            <td><input type="number" name="items[${index}][subtotal]" value="0" class="form-control subtotal-input" id="subtotal-input-${index}" readonly></td>
            <td><button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">-</button></td>
        `;
        tbody.appendChild(row);
        bindRowEvents(index);
    };

    window.removeRow = function (btn) {
        btn.closest('tr').remove();
        updateTotal();
    };

    updateTotal();
});
</script>

<?= $this->endSection() ?>
