<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Kasir POS</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://cdn.jsdelivr.net/npm/autonumeric@4.5.4"></script>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container mt-4">
  <h3>Transaksi Kasir</h3>
  <form id="form-add-item" class="form-inline mb-3">
    <input type="text" id="barcode" class="form-control mr-2" placeholder="Scan Barcode atau cari nama barang">
    <input type="number" id="jumlah" class="form-control mr-2" value="1" min="1">
    <button type="submit" class="btn btn-primary">Tambah</button>
  </form>

  <table class="table table-bordered">
    <thead>
      <tr>
        <th>#</th>
        <th>Nama Barang</th>
        <th>Harga</th>
        <th>Jumlah</th>
        <th>Total</th>
        <th>Aksi</th>
      </tr>
    </thead>
    <tbody id="cart-items">
      <tr id="empty-cart"><td colspan="6" class="text-center">Belum ada barang</td></tr>
    </tbody>
    <tfoot>
      <tr>
        <th colspan="4" class="text-right">Sub Total</th>
        <th colspan="2" id="sub-total">Rp 0</th>
      </tr>
      <tr>
        <th colspan="4" class="text-right">Total</th>
        <th colspan="2" id="total">Rp 0</th>
      </tr>
    </tfoot>
  </table>

  <form id="form-payment">
    <div class="form-group">
      <label>ID Transaksi</label>
      <input type="text" name="id_transaksi" id="id_transaksi" class="form-control" readonly>
    </div>
    <div class="form-group">
      <label>Total Bayar</label>
      <input type="text" name="total" id="total_bayar" class="form-control" readonly>
    </div>
    <div class="form-group">
      <label>Nominal Bayar</label>
      <input type="text" name="bayar" class="form-control">
    </div>
    <div class="form-group">
      <label>Kembali</label>
      <input type="text" id="kembali" class="form-control" readonly>
    </div>
    <div class="form-group">
      <label>Metode Bayar</label>
      <select name="metode_bayar" id="metode_bayar" class="form-control">
        <option value="cash">Tunai</option>
        <option value="qris">QRIS</option>
        <option value="transfer">Transfer</option>
      </select>
    </div>
    <div class="form-group" id="ket-metode-group" style="display:none">
      <label>Keterangan</label>
      <input type="text" name="ket_metode" class="form-control">
    </div>
    <button type="submit" class="btn btn-success">Simpan Transaksi</button>
  </form>
</div>

<script>
$(function(){
  let cart = [];
  const anBayar = new AutoNumeric('input[name=bayar]', { decimalCharacter: ',', digitGroupSeparator: '.', minimumValue: '0' });
  const anKembali = new AutoNumeric('#kembali', { decimalCharacter: ',', digitGroupSeparator: '.', readOnly: true });

  $.get('<?= site_url('kasirq/generate_id_transaksi') ?>', function(res){
    if(res.status){
      $('#id_transaksi').val(res.id_transaksi);
    }
  }, 'json');

  $("#barcode").autocomplete({
    source: "<?= site_url('kasirq/cari_barang') ?>",
    minLength: 2,
    select: function(e, ui) {
      $("#barcode").val(ui.item.barcode);
      $("#jumlah").focus();
      return false;
    }
  });

  $('#form-add-item').submit(function(e){
    e.preventDefault();
    const barcode = $('#barcode').val().trim();
    const jumlah = parseInt($('#jumlah').val());
    if(!barcode || jumlah < 1) return;
    $.post('<?= site_url('kasirq/get_barang_by_barcode') ?>', { barcode }, function(res){
      if(res.status){
        const b = res.data;
        const idx = cart.findIndex(x => x.id == b.id);
        if(idx >= 0){
          cart[idx].jumlah += jumlah;
        } else {
          cart.push({ id: b.id, nama: b.nama_barang, harga: parseInt(b.harga_jual_ecer), jumlah });
        }
        $('#barcode').val('');
        $('#jumlah').val(1);
        renderCart();
      } else {
        alert(res.message);
      }
    }, 'json');
  });

  function renderCart(){
    let sub = 0;
    const $tbody = $('#cart-items').empty();
    cart.forEach((item, i) => {
      const total = item.harga * item.jumlah;
      sub += total;
      $tbody.append(`
        <tr>
          <td>${i+1}</td>
          <td>${item.nama}</td>
          <td class="text-right">Rp ${item.harga.toLocaleString()}</td>
          <td><input type="number" class="form-control qty" value="${item.jumlah}" data-i="${i}"></td>
          <td class="text-right">Rp ${(total).toLocaleString()}</td>
          <td><button class="btn btn-danger btn-sm remove" data-i="${i}">&times;</button></td>
        </tr>`);
    });
    if(cart.length === 0){
      $('#cart-items').html('<tr id="empty-cart"><td colspan="6" class="text-center">Belum ada barang</td></tr>');
    }
    $('#sub-total, #total').text('Rp ' + sub.toLocaleString());
    $('#total_bayar').val('Rp ' + sub.toLocaleString());
     
  }

  $('#cart-items').on('change', '.qty', function(){
    const i = $(this).data('i');
    cart[i].jumlah = parseInt($(this).val()) || 1;
    renderCart();
  });
  $('#cart-items').on('click', '.remove', function(){
    const i = $(this).data('i');
    cart.splice(i, 1);
    renderCart();
  });

  $('input[name=bayar]').on('input', function(){
    const bayar = anBayar.getNumber();
    const total = parseInt($('#total').text().replace(/[^\d]/g, '')) || 0;
    anKembali.set(bayar - total > 0 ? bayar - total : 0);
  });

  $('#metode_bayar').change(function(){
    $('#ket-metode-group').toggle($(this).val() !== 'cash');
  });

  $('#form-payment').submit(function(e){
    e.preventDefault();
    const bayar = anBayar.getNumber();
    const total = parseInt($('#total').text().replace(/[^\d]/g, ''));
    if(bayar < total){
      alert('Pembayaran kurang!'); return;
    }
    const formData = $(this).serializeArray();
    formData.push({ name: 'sub_total', value: total });
    formData.push({ name: 'total', value: total });
    formData.push({ name: 'kembali', value: bayar - total });
    cart.forEach(item => {
      formData.push({ name: 'id_barang[]', value: item.id });
      formData.push({ name: 'harga_jual[]', value: item.harga });
      formData.push({ name: 'jumlah[]', value: item.jumlah });
      formData.push({ name: 'harga_total[]', value: item.harga * item.jumlah });
    });
    $.post('<?= site_url('kasirq/proses_transaksi') ?>', formData, function(res){
      if(res.status){
        alert('Transaksi berhasil. ID: ' + res.id_trans);
        cart = [];
        renderCart();
        $('#form-payment')[0].reset();
        anBayar.clear();
        anKembali.clear();
        $('#id_transaksi').val(res.id_trans);
      }
    }, 'json');
  });
});
</script>
</body>
</html>
