<?php foreach($kontak as $kontak) :   endforeach; ?> 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $title; ?></title>
    <link rel="icon" href="<?php echo base_url();?>images/kontak/<?php echo $kontak->logo ;?>" type="image/png" />
    <!-- CDN Links -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body {
            padding-top: 20px;
            background-color: #f5f5f5;
        }
        .form-control-currency {
            text-align: right;
            font-weight: bold;
        }
        .table-cart th {
            background-color: #f8f9fa;
        }
        .btn-barcode {
            cursor: pointer;
        }
        .payment-section {
            background-color: #fff;
            border-radius: 5px;
            padding: 15px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        #barcode-scanner {
            width: 100%;
            height: 300px;
            background: #000;
        }
        .payment-summary {
            background: linear-gradient(135deg, #4361ee 0%, #3a0ca3 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .payment-label {
            font-size: 1.1rem;
            font-weight: 500;
            margin-bottom: 5px;
        }
        
        .payment-value {
            font-size: 1.4rem;
            font-weight: 700;
        }
        
        .keyboard-shortcut {
            background: rgba(255,255,255,0.2);
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.8rem;
            margin-left: 5px;
        }
        
        .grosir-badge {
            background-color: #e83e8c;
            font-size: 0.75rem;
            padding: 2px 6px;
            border-radius: 4px;
            margin-left: 5px;
        }
        
        .item-row {
            transition: background-color 0.10s;
        }
        
        .item-row:hover {
            background-color: rgba(0,123,255,0.05);
        }
        
        .qty-input {
            width: 70px;
            text-align: center;
        }
        
        .btn-action {
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        .btn-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .btn-action:active {
            transform: translateY(0);
        }
        
        
        
        /* Stok warning */
        .stok-warning {
            background-color: #fff3cd;
            border-left: 4px solid #ffc107;
        }
        
        .stok-kosong {
            background-color: #f8d7da;
            border-left: 4px solid #dc3545;
        }
        
        .stok-info {
            font-size: 0.8rem;
            color: #6c757d;
        }
        
        .stok-label {
            font-weight: 600;
        }

         
    </style>
    <style>
         /* Perbaikan Struk Printing Styles */
        .struk-container {
            display: none;
            width: 100%; /* Lebar kertas thermal 80mm */
            font-family: 'Arial', sans-serif;
            font-size: 20px; /* Ukuran lebih kecil */
            padding: 5px;
            margin: 0 auto;
            background: white;
            box-sizing: border-box;
            line-height: 1.3;
        }

        .struk-container h2 {
            font-size: 14px;
            text-align: center;
            margin: 5px 0;
        }

        .struk-container .center {
            text-align: center;
            font-size: 10px;
            margin-bottom: 5px;
        }

        .struk-container .info {
            margin-top: 10px;
            font-size: 10px;
            border-top: 1px dashed #000;
            border-bottom: 1px dashed #000;
            padding: 5px 0;
        }

        .struk-container table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
            font-size: 10px;
        }

        .struk-container table th,
        .struk-container table td {
            padding: 3px 0;
        }

        .struk-container table th {
            border-bottom: 1px dashed #000;
        }

        .struk-container table tfoot td {
            padding-top: 5px;
            border-top: 1px dashed #000;
        }

        .struk-container .text-center {
            text-align: center;
            margin-top: 10px;
            font-size: 10px;
        }

        /* Perbaikan khusus untuk print */
        @media print {
            body * {
                visibility: hidden;
            }
            .struk-container, 
            .struk-container * {
                visibility: visible;
            }
            .struk-container {
                position: absolute;
                left: 0;
                top: 0;
                width: 80mm;
                padding: 0;
                margin: 0;
                box-shadow: none;
            }
        }
        </style>
     
</head>
<body>
    <div class="container">
         
        <div class="row">
            <div class="col-md-8">
                <!-- Product Input Card -->
                <div class="card mb-4">
                    <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                        <h4 class="mb-0"><i class="fas fa-cash-register mr-2"></i>Input Transaksi</h4> <a class="btn btn-warning" href="<?php echo base_url('transaksi');?>" > Data Transaksi </a>
                        <a href="<?php echo base_url('kasir/log_in');?>" class="btn btn-warning  "   >  Kasir Lama </a>
                         <a href="<?php echo base_url('kasir/hold_baru');?>"  class="btn btn-light " onclick="return confirm('Apakah Keranjang ingin di Hold, ? Klik Oke jika Lanjut')"  >  Hold  </a>
                        <a href="<?php echo base_url('kasir/hold_off_baru');?>" class="btn btn-light  " onclick="return confirm('Apakah Keranjang Lepas Hold, ? Klik Oke jika Lanjut')"  >   Off Hold </a>
                         
                    </div>
                    <div class="card-body">
                        <form id="form-add-item" action="<?php echo base_url('kasir/code_simpan_keranjang_baru'); ?>" method="post">
                            <div class="form-row">
                                <div class="col-md-8">
                                    <div class="form-group">
                                        <label for="barcode"><i class="fas fa-barcode mr-1"></i> Barcode / Nama Barang</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="barcode" name="barcode" placeholder="Scan barcode atau cari barang..." autofocus>
                                            <div class="input-group-append">
                                                <button class="btn btn-outline-secondary btn-barcode" type="button" id="btn-scan">
                                                    <i class="fas fa-barcode"></i> Aktifkan Camera
                                                </button>
                                            </div>
                                        </div>
                                        <div class="mt-1 stok-info" id="stok-info" style="display:none;">
                                            <span class="stok-label">Stok tersedia:</span> 
                                            <span id="stok-value"></span>
                                        </div>
                                        <input type="hidden" class="form-control-sm"    name="id_admin" value="<?php echo $id_admin; ?>">
                                        <input type="hidden" class="form-control-sm"    name="id_kantor" value="<?php echo $id_kantor; ?>">
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label for="satuan"><i class="fas fa-balance-scale mr-1"></i> Jenis</label>
                                        <select class="form-control"   name="jenis">
                                            <option value="ecer">ecer</option>
                                            <option value="dos">dos</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label for="jumlah"><i class="fas fa-boxes mr-1"></i> Jumlah</label>
                                        <input type="number" class="form-control" id="jumlah" value="1" min="1" name="jumlah">
                                    </div>
                                </div>
                            </div>

                            <button type="submit" class="btn btn-primary btn-block btn-action">
                                <i class="fas fa-cart-plus mr-2"></i> Tambah ke Keranjang
                            </button>
                            <small>
                                <i class="fas fa-keyboard mr-1"></i>Shortcut: 
                                <span class="keyboard-shortcut">F2</span>: Barcode, 
                                <span class="keyboard-shortcut">F4</span>: Qty,  <!-- Tambah F4 -->
                                <span class="keyboard-shortcut">F8</span>: Scan, 
                                <span class="keyboard-shortcut">F9</span>: Bayar
                            </small>
                        </form>
                    </div>
                </div>

                <!-- Shopping Cart Card -->
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h4 class="mb-0"><i class="fas fa-shopping-cart mr-2"></i>Keranjang Belanja</h4>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table">
                              <thead>
                                <tr>
                                  <th>No</th>
                                  <th>Nama Barang</th>
                                  <th style="text-align: right;">Harga</th>
                                  <th style="text-align: center;">Jumlah</th>

                                  <th style="text-align: right;">Harga</th>
                                  <th style="text-align: right;">Hemat</th>
                                  <th></th>
                                </tr>

                              </thead>
                              <tbody>
                                <?php $no=1; foreach($keranjang as $tampil) :   

                                $id_barang= $tampil->id_barang;
                                $this->db->where('id',$id_barang);
                                $query = $this->db->get('tb_barang');
                                $cek = $query->row();

                                $nama_barang = $cek->nama_barang;




                                ?>

                                <tr>
                                  <td><?php echo $no; ?></td>
                                  <td><?php echo $nama_barang; ?> ( <?php echo $tampil->jenis; ?> )</td>
                                  <td style="text-align: right;">
                                    

                                    <?php 
                                    $cek_ubah=$kontak->edit_harga;
                                     if($cek_ubah == 'tidak' ) { ?>
                                    <?php echo nominal($tampil->harga_jual); ?>

                                      <?php }else{ ?>
                                        <?php if($tampil->jenis =='dos') {
                                        echo nominal($tampil->harga_jual);
                                        } else{ ?>
                                      <form name="ubah" action="<?php echo base_url('kasir/ubah_code_harga_keranjang_baru'); ?>" method="POST">
                                        
                                        <input type="hidden" name="id_nomor" value="<?php echo $tampil->id; ?>"   />   
                                      
                                        <input type="text" style="text-align: center;"   name="harga_ubah" value="<?php echo  $tampil->harga_jual; ?>" size="4" autocomplete="off"  onkeypress="nextfieldBarcode(event)">
                                        <input type="hidden" style="text-align: center;" i name="jumlah_ubah" value="<?php echo  $tampil->jumlah; ?>" size="4" autocomplete="off"  onkeypress="nextfieldBarcode(event)">
                                      </form>
                                    <?php } ?>
                                  <?php } ?>
                                  </td>
                                  <td style="text-align: center;">

                                   <?php if($tampil->jenis =='dos') {
                                     echo $tampil->jumlah; 
                                   } else{ ?>
                                    <form name="ubah" action="<?php echo base_url('kasir/ubah_code_keranjang_baru'); ?>" method="POST">
                                      <input type="hidden" name="id_kantor" value="<?php echo $tampil->id_kantor; ?>" size="5">
                                      <input type="hidden" name="id_barang" value="<?php echo $tampil->id_barang; ?>" size="5">
                                      <input type="hidden" name="id_admin" value="<?php echo $tampil->id_admin; ?>"   />   

                                      <input type="hidden" class="form-control-sm"    name="jenis" value="<?php echo $tampil->jenis; ?>">


                                      <input type="text" style="text-align: center;" id="ada<?php echo $no; ?>" name="jumlah_ubah" value="<?php echo  $tampil->jumlah; ?>" size="4" autocomplete="off"  onkeypress="nextfieldBarcode(event)">
                                    </form>
                                  <?php } ?>
                                  </td>
                                  <td style="text-align: right;"><?php echo  nominal($tampil->harga_total); ?></td>
                                  <td style="text-align: right;"><?php echo  nominal($tampil->total_hemat); ?></td>
                                  <td >

                                  
                                  <a href="" style="color: red;"  type="button"  data-toggle="modal" data-target="#modal-hapus<?php echo $tampil->id; ?>"><i class="fa fa-trash"></i></a>

                                  <form class="form-horizontal" action="<?php echo base_url('kasir/hapus_keranjang_baru'); ?>" method="POST" enctype="multipart/form-data" />  
                                        <div class="modal fade" id="modal-hapus<?php echo $tampil->id; ?>">
                                          <div class="modal-dialog">
                                            <div class="modal-content bg-danger">
                                              <div class="modal-header">
                                                <h4 class="modal-title">Hapus Data </h4>
                                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                  <span aria-hidden="true">&times;</span>
                                                </button>
                                              </div>
                                              <div class="modal-body">
                                                <h4>Apakah Yakin Menghapus item pembelian ini ?</h4>
                                                <!-- id kirim -->
                                                <input type="hidden" name="id" value="<?php echo $tampil->id; ?>">
                                                <input type="password" name="password" placeholder="Masukkan password ">
                                                <input type="hidden" name="password_admin"  value="<?php echo $kontak->password_kasir;?>">


                                              </div>
                                              <div class="modal-footer justify-content-between">
                                                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                                <button type="submit" class="btn btn-primary">Hapus</button>
                                              </div>
                                            </div>
                                            <!-- /.modal-content -->
                                          </div>
                                          <!-- /.modal-dialog -->
                                        </div>
                                      </form>

                                  </td>
                                </tr>
                                <?php $no++; endforeach; ?>
                                <tr>
                                  
                                  <td></td>
                                  <td></td>
                                  <td></td>
                                  <td>Total</td>
                                  <td style="text-align: right;font-weight: bold"><?php echo nominal($sub_total); ?></td>
                                  <td style="text-align: right;font-weight: bold"><?php echo nominal($sub_total_hemat); ?></td>
                                </tr>
                              </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <!-- Payment Summary -->
                <div class="payment-summary mb-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h4 class="mb-0">
                            <i class="fas fa-credit-card mr-2"></i> Pembayaran
                        </h4>
                    </div>

                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div class="payment-label">ID TRANSAKSI</div>
                        <div class="payment-value"><?php echo $id_transaksi; ?></div>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div class="payment-label">TOTAL</div>
                        <div class="payment-value" id="total-text">Rp <?php echo nominal($sub_total); ?></div>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div class="payment-label">BAYAR</div>
                        <div class="payment-value" id="bayar-text">Rp 0</div>
                    </div>  
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div class="payment-label">KEMBALI</div>
                        <div class="payment-value" id="kembali-text">Rp 0</div>
                    </div> 
                </div>
                
                <!-- Payment Form -->
                <div class="payment-section mb-3">
                    <h4 class="mb-3"><i class="fas fa-credit-card mr-2"></i> Pembayaran</h4>

                    <form action="<?php echo base_url('kasir/code_simpan_pembelian'); ?>" 
                          method="POST" target="print_popup" 
                          onsubmit="window.open('about:blank','print_popup','width=600,height=700');">

                        <!-- Hidden fields -->
                        <input type="hidden" name="sub_total" value="<?php echo $sub_total; ?>">
                        <input type="hidden" name="newkode" value="<?php echo $id_transaksi; ?>">
                        <input type="hidden" name="total" value="<?php echo $sub_total; ?>">
                        <input type="hidden" name="status" value="success">
                        <input type="hidden" name="id_admin" value="<?php echo $id_admin; ?>">
                        <input type="hidden" name="id_kantor" value="<?php echo $id_kantor; ?>">

                        <!-- Member -->
                        <div class="form-group">
                            <label for="id_member"><i class="fas fa-user-tag mr-1"></i> Member</label>
                            <select class="form-control" id="id_member" name="id_member">
                                <option value="1">-- Non Member --</option>
                                <?php foreach($member as $m) : ?>
                                    <option value="<?php echo $m->id_member; ?>">
                                        <?php echo $m->nama_member; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Bayar -->
                        <div class="form-group">
                            <label for="bayar-input"><i class="fas fa-money-bill-wave mr-1"></i> Bayar (Rp)</label>
                            <input type="text" class="form-control form-control-currency" id="bayar-input" name="bayar" required>

                            <!-- Tombol nominal cepat -->
                            <div class="mt-2">
                                <button type="button" class="btn btn-outline-primary btn-sm btn-nominal" data-value="50000">50.000</button>
                                <button type="button" class="btn btn-outline-primary btn-sm btn-nominal" data-value="100000">100.000</button>
                                <button type="button" class="btn btn-outline-primary btn-sm btn-nominal" data-value="200000">200.000</button>
                                <button type="button" class="btn btn-outline-primary btn-sm btn-nominal" data-value="500000">500.000</button>
                            </div>
                        </div>

                        <!-- Kembali -->
                        <div class="form-group">
                            <label for="kembali-input"><i class="fas fa-exchange-alt mr-1"></i> Kembali (Rp)</label>
                            <input type="text" class="form-control bg-light text-right" id="kembali-input" name="kembali" readonly>
                        </div>

                        <!-- Metode Bayar -->
                        <div class="form-group">
                            <label for="metode_bayar"><i class="fas fa-wallet mr-1"></i> Metode Pembayaran</label>
                            <select class="form-control" id="metode_bayar" name="metode_bayar" required>
                                <option value="cash">Tunai (Cash)</option>
                                <option value="qris">Qris</option>
                                <option value="transfer">Transfer Bank</option>
                                <option value="debit">Kartu Debit</option>                                                             
                            </select>
                        </div>

                        <!-- Keterangan -->
                        <div class="form-group" id="ket-metode-group" style="display: none;">
                            <label for="ket_metode"><i class="fas fa-info-circle mr-1"></i> Keterangan</label>
                            <input type="text" class="form-control" id="ket_metode" name="ket_metode" placeholder="Contoh: No. Rekening/Nama Bank">
                        </div>

                        <button type="submit" class="btn btn-success btn-block btn-lg" id="btn-bayar" disabled>
                            <i class="fas fa-check-circle mr-2"></i> Proses Pembayaran
                        </button>
                    </form>
                </div>

                 
            </div>
        </div>
    </div>

   

    <!-- Barcode Scanner Modal -->
    <div class="modal fade" id="barcodeModal" tabindex="-1" role="dialog" aria-labelledby="barcodeModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="barcodeModalLabel">Scan Barcode</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body text-center">
                    <div id="barcode-scanner"></div>
                    <p class="mt-2">Arahkan kamera ke barcode barang</p>
                    <div class="form-group mt-3">
                        <label for="manual-barcode">Atau masukkan barcode manual:</label>
                        <input type="text" class="form-control" id="manual-barcode">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript Libraries -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/autonumeric@4.6.0/dist/autoNumeric.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/quagga/dist/quagga.min.js"></script>
    
   <script>
    $(document).ready(function() {
        let cart = [];
        let transactionId = generateTransactionId();

        // Update transaction ID
        $("#transaction-id").text(transactionId);

        // Generate unique transaction ID
        function generateTransactionId() {
            const date = new Date();
            const year = date.getFullYear().toString().substr(-2);
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const randomNum = Math.floor(1000 + Math.random() * 9000);
            return `TRX${year}${month}${day}-${randomNum}`;
        }

        
        // Fungsi untuk menampilkan notifikasi stok
        function showStokAlert(message, type = 'danger') {
            const alert = $("#stok-alert");
            alert.removeClass('alert-danger alert-warning alert-success').addClass(`alert-${type}`);
            $("#stok-alert-message").text(message);
            alert.show();
            
            // Auto hide setelah 5 detik
            setTimeout(hideStokAlert, 5000);
        }

        // Fungsi untuk menyembunyikan notifikasi stok
        function hideStokAlert() {
            $("#stok-alert").hide();
        }

        // Autocomplete dengan informasi grosir dan stok
        $("#barcode").autocomplete({
            source: "<?php echo site_url('kasirq/cari_barang'); ?>",
            minLength: 2,
            select: function(event, ui) {
                $("#barcode").val(ui.item.barcode);
                $("#jumlah").focus();
                
                // Tampilkan info stok
                $("#stok-info").show();
                $("#stok-value").text(ui.item.stok);
                
                // Tampilkan peringatan jika stok rendah
                if (ui.item.stok <= 0) {
                    $("#stok-info").addClass('stok-kosong');
                    showStokAlert(`Stok barang "${ui.item.value}" habis!`, 'danger');
                } else if (ui.item.stok <= 5) {
                    $("#stok-info").addClass('stok-warning');
                    showStokAlert(`Stok barang "${ui.item.value}" hampir habis! (Tersisa: ${ui.item.stok})`, 'warning');
                } else {
                    $("#stok-info").removeClass('stok-warning stok-kosong');
                    hideStokAlert();
                }
                
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            // Tampilkan informasi grosir dan stok di dropdown
            const grosirInfo = [];
            if(item.min_grosir_lv1) grosirInfo.push(`Grosir Lv1: ${item.min_grosir_lv1}@${formatRupiah(item.harga_grosir_lv1)}`);
            if(item.min_grosir_lv2) grosirInfo.push(`Lv2: ${item.min_grosir_lv2}@${formatRupiah(item.harga_grosir_lv2)}`);
            if(item.min_grosir_lv3) grosirInfo.push(`Lv3: ${item.min_grosir_lv3}@${formatRupiah(item.harga_grosir_lv3)}`);
            // if(item.min_grosir_lv4) grosirInfo.push(`Lv4: ${item.min_grosir_lv4}@${formatRupiah(item.harga_grosir_lv4)}`);
            
            // Tentukan kelas stok
            let stokClass = '';
            let stokText = `Stok: ${item.stok}`;
            if (item.stok <= 0) {
                stokClass = 'stok-kosong';
                stokText = 'STOK HABIS';
            } else if (item.stok <= 5) {
                stokClass = 'stok-warning';
                stokText = `Stok: ${item.stok} (Hampir Habis)`;
            }

            return $("<li>").append(
                `<div class="${stokClass} p-2">
                    <strong>${item.value}</strong> (${item.barcode})<br>
                    <span style="color:black;">Pcs : @${formatRupiah(item.harga)} Dos: ${formatRupiah(item.harga_jual_dos)} </span><br>
                    <small style="color:black;">${grosirInfo.join(' | ')}</small><br>

                    <span class="${stokClass}">${stokText}</span>
                </div>`
            ).appendTo(ul);
        };

        
        // Fungsi untuk menentukan harga grosir (hanya untuk satuan pcs)
        function hitungHargaGrosir(item, jumlah) {
            if (item.satuan === 'dos') {
                return item.harga; // untuk dos, tidak ada grosir
            }
            
            // Konversi semua nilai ke integer
            const min1 = parseInt(item.min_grosir_lv1 || '0');
            const min2 = parseInt(item.min_grosir_lv2 || '0');
            const min3 = parseInt(item.min_grosir_lv3 || '0');
            const min4 = parseInt(item.min_grosir_lv4 || '0');
            
            const hrg1 = parseInt(item.harga_grosir_lv1 || item.harga);
            const hrg2 = parseInt(item.harga_grosir_lv2 || item.harga);
            const hrg3 = parseInt(item.harga_grosir_lv3 || item.harga);
            const hrg4 = parseInt(item.harga_grosir_lv4 || item.harga);
            
            // Tentukan harga berdasarkan jumlah (dari level tertinggi ke terendah)
            if (min4 > 0 && jumlah >= min4) return hrg4;
            else if (min3 > 0 && jumlah >= min3) return hrg3;
            else if (min2 > 0 && jumlah >= min2) return hrg2;
            else if (min1 > 0 && jumlah >= min1) return hrg1;
            else return parseInt(item.harga); // Harga retail
        }

         
 

       
        

        

         

        function formatRupiah(nominal) {
            return 'Rp ' + nominal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
        }

        function showAlert(type, message) {
            const alert = `<div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>`;
            $(".container").prepend(alert);
            setTimeout(() => $(".alert").alert('close'), 5000);
        }

        // Barcode scan
        $("#btn-scan").click(function() {
            $("#barcodeModal").modal('show');
            initBarcodeScanner();
        });

        $("#manual-barcode").keypress(function(e) {
            if (e.which === 13) {
                const barcode = $(this).val().trim();
                if (barcode) {
                    $("#barcode").val(barcode);
                    $("#barcodeModal").modal('hide');
                    $("#jumlah").focus();
                }
                $(this).val('');
                return false;
            }
        });

        function initBarcodeScanner() {
            Quagga.init({
                inputStream: {
                    name: "Live",
                    type: "LiveStream",
                    target: document.querySelector('#barcode-scanner'),
                    constraints: {
                        width: 480,
                        height: 320,
                        facingMode: "environment"
                    },
                },
                decoder: {
                    readers: [
                        "ean_reader", "ean_8_reader", "code_128_reader", "code_39_reader",
                        "code_39_vin_reader", "codabar_reader", "upc_reader", "upc_e_reader"
                    ]
                },
            }, function(err) {
                if (err) {
                    console.error(err);
                    showAlert('danger', "Gagal menginisialisasi scanner: " + err);
                    return;
                }
                Quagga.start();
            });

            Quagga.onDetected(function(result) {
                const code = result.codeResult.code;
                $("#barcode").val(code);
                $("#barcodeModal").modal('hide');
                Quagga.stop();
                $("#jumlah").focus();
            });
        }

        $("#barcodeModal").on('hidden.bs.modal', function() {
            Quagga.stop();
            $("#manual-barcode").val('');
        });

        // Keyboard shortcuts
        $(document).keydown(function(e) {
            // F2 - Focus to barcode input
            if (e.key === 'F2') {
                e.preventDefault();
                $("#barcode").focus().select();
                return false;
            }
            if (e.key === 'F4') {
                e.preventDefault();
                // Cari input qty pertama
                 
                return false;
            }
            // F8 - Open scanner modal
            if (e.key === 'F8') {
                e.preventDefault();
                $("#btn-scan").click();
                return false;
            }
            
            // F9 - Focus to bayar input
            if (e.key === 'F9') {
                e.preventDefault();
                return false;
            }
        });
    });
    </script>



    <script>
      $(function(){
        const formatter = new Intl.NumberFormat('id-ID');

        function updateSummary(){
          let total = parseInt(<?php echo $sub_total; ?>);
          let bayar = parseInt($('#bayar-input').val().replace(/\D/g,'') || 0);
          let kembali = bayar - total;
          $('#bayar-text').text('Rp ' + formatter.format(bayar));
          $('#kembali-input').val(formatter.format(Math.max(kembali,0)));
          $('#kembali-text').text('Rp ' + formatter.format(Math.max(kembali,0)));
          $('#btn-bayar').prop('disabled', bayar < total);
        }

        $('.btn-nominal').click(function(){
          let value = $(this).data('value');
          $('#bayar-input').val(value).trigger('input');
        });

        $('#bayar-input').on('input', updateSummary);

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

    </script> 

</body>
</html>