<?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.3s;
        }
        
        .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: 80mm; /* Lebar kertas thermal 80mm */
            font-family: 'Arial', sans-serif;
            font-size: 12px; /* 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="text-center mb-4">
            <h1 class="display-4 font-weight-bold text-primary">
                <i class="fas fa-cash-register mr-2"></i>Sistem Kasir Modern
            </h1>
            <p class="lead text-muted">Dilengkapi dengan pengecekan stok dan pembayaran digital</p>
        </div>
        
        <!-- Alert untuk stok kosong -->
        <div id="stok-alert" class="alert alert-danger alert-dismissible fade show" style="display:none;">
            <i class="fas fa-exclamation-triangle mr-2"></i>
            <span id="stok-alert-message"></span>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        
        <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>
                        
                        <span id="transaction-id" class="badge badge-light">TRANSAKSI BARU</span>
                    </div>
                    <div class="card-body">
                        <form id="form-add-item">
                            <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" 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> Scan
                                                </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>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label for="satuan"><i class="fas fa-balance-scale mr-1"></i> Satuan</label>
                                        <select class="form-control" id="satuan">
                                            <option value="pcs">Pcs</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">
                                    </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 table-bordered table-cart mb-0">
                                <thead>
                                    <tr>
                                        <th width="5%">No</th>
                                        <th width="30%">Barang</th>
                                        <th width="15%">Harga</th>
                                        <th width="15%">Jumlah</th>
                                        <th width="20%">Total</th>
                                        <th width="15%">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody id="cart-items">
                                    <tr id="empty-cart">
                                        <td colspan="6" class="text-center py-4">
                                            <i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i>
                                            <p class="text-muted">Keranjang belanja kosong</p>
                                        </td>
                                    </tr>
                                </tbody>
                                <tfoot>
                                    <tr class="table-active">
                                        <th colspan="4" class="text-right">Sub Total</th>
                                        <th colspan="2" id="sub-total">Rp 0</th>
                                    </tr>
                                    <tr class="table-active">
                                        <th colspan="4" class="text-right">Total</th>
                                        <th colspan="2" id="cart-total">Rp 0</th>
                                    </tr>
                                </tfoot>
                            </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>
                    <span class="badge badge-light badge-pill py-2 px-3">
                      <i class="fas fa-shopping-bag mr-1"></i>
                      <span id="cart-count">0</span> barang
                    </span>
                  </div>

                  <div class="d-flex justify-content-between align-items-center mb-3">
                    <div class="payment-label">Total Belanja</div>
                    <div class="payment-value" id="total-summary">Rp 0</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-display">Rp 0</div>
                  </div>

                  <div class="d-flex justify-content-between align-items-center">
                    <div class="payment-label">Kembali</div>
                    <div class="payment-value" id="kembali-display">Rp 0</div>
                  </div>
                </div>
                
                <div class="payment-section mb-3">
                    <h4 class="mb-3"><i class="fas fa-credit-card mr-2"></i>Pembayaran</h4>
                    <div class="member-section">
                        
                    
                        
                     
                    <form id="form-payment">
                        <input type="hidden" id="sub_total" name="sub_total" value="0">
                        <input type="hidden" id="total" name="total" value="0">
                        <input type="hidden" id="status" name="status" value="success">
                        <input type="hidden" name="id_admin" id="id_admin" value="<?php echo $id_admin; ?>">
                        <input type="hidden" name="id_kantor" id="id_kantor" value="<?php echo $id_kantor; ?>">
                        <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 $member) : ?>
                                    <option value="<?php echo $member->id_member; ?>">
                                        <?php echo $member->nama_member; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="bayar"><i class="fas fa-money-bill-wave mr-1"></i> Bayar (Rp)</label>
                            <input type="text" class="form-control form-control-currency" id="bayar" name="bayar" required>
                            <small>
                             
                        </small>
                        </div>
                        <div class="form-group">
                            <label for="kembali"><i class="fas fa-exchange-alt mr-1"></i> Kembali (Rp)</label>
                            <input type="text" class="form-control form-control-currency bg-light" id="kembali" name="kembali" readonly>
                        </div>
                        <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>
                        <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 btn-action" id="btn-bayar" disabled>
                            <i class="fas fa-check-circle mr-2"></i> Proses Pembayaran
                        </button>
                    </form>
                </div>
                <div class="mt-4">
                    
                    <button class="btn btn-danger btn-block btn-action py-3" id="btn-cancel">
                        <i class="fas fa-times mr-2"></i> Batalkan Transaksi
                    </button>

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

    <div class="struk-container" id="struk-container">
        <div class="center">
            <img src="<?php echo base_url();?>images/kontak/<?php echo $kontak->logo ;?>" 
            alt="Logo" height="40" width="40">
        </div>
        <h2><?php echo $kontak->nama_toko; ?></h2>
        <div class="center"><?php echo $kontak->alamat; ?></div>
        <div class="center">Telp: <?php echo $kontak->nomor; ?></div>

        <div class="info">
            <strong>ID: </strong><span id="struk-id"></span><br>
            <strong>Tanggal: </strong><span id="struk-tanggal"></span><br>
            <strong>Kasir: </strong> <?php echo $nama_admin; ?> <br> 
            <strong>Member: </strong><span id="struk-member">-</span>
        </div>

        <table>
            <thead>
                <tr>
                    <th align="left">Barang</th>
                    <th align="center">Qty</th>
                    <th align="right">Harga</th>
                    <th align="right">Total</th>
                </tr>
            </thead>
            <tbody id="struk-items">
                <!-- Items will be populated by JS -->
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="2" rowspan="4"></td>
                    <td align="left">Sub Total</td>
                    <td align="right" id="struk-subtotal">0</td>
                </tr>
                <tr>
                    <td align="left">Bayar</td>
                    <td align="right" id="struk-bayar">0</td>
                </tr>
                <tr>
                    <td align="left">Kembali</td>
                    <td align="right" id="struk-kembali">0</td>
                </tr>
                <tr>
                    <td align="left">Metode</td>
                    <td align="right" id="struk-metode">-</td>
                </tr>
            </tfoot>
        </table>

        <div class="text-center">
            <p>-------------------------------</p>
            <p>BARANG YANG SUDAH DIBELI<br>TIDAK DAPAT DIKEMBALIKAN</p>
            <p>* TERIMA KASIH TELAH BERBELANJA *</p>
        </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}`;
        }

        // Init AutoNumeric
        const anBayar = new AutoNumeric('#bayar', {
            digitGroupSeparator: '.',
            decimalCharacter: ',',
            decimalPlaces: 0,
            currencySymbolPlacement: 'p',
            minimumValue: '0'
        });

        const anKembali = new AutoNumeric('#kembali', {
            digitGroupSeparator: '.',
            decimalCharacter: ',',
            decimalPlaces: 0,
            currencySymbolPlacement: 'p',
            minimumValue: '0'
        });

        // 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 class="text-success">Pcs : @${formatRupiah(item.harga)} Dos: ${formatRupiah(item.harga_jual_dos)} </span><br>
                    <small class="text-muted">${grosirInfo.join(' | ')}</small><br>

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

        // Tambah item dengan memperhitungkan grosir dan stok
        $("#form-add-item").submit(function(e) {
            e.preventDefault();
            const barcode = $("#barcode").val().trim();
            const jumlah = parseInt($("#jumlah").val()) || 1;
            // Validasi dasar sebelum request
            if (!barcode) {
                showStokAlert('Silakan scan atau cari barang terlebih dahulu', 'warning');
                $("#barcode").focus();
                return;
            }

            if (jumlah < 1) {
                showStokAlert('Jumlah tidak valid', 'warning');
                $("#jumlah").focus();
                return;
            }

            const satuan = $("#satuan").val();
            $.post("<?php echo site_url('kasirq/get_barang_by_barcode'); ?>", { barcode }, function(response) {
                if (response.status) {
                    const item = response.data;
                    const stokPcs = parseInt(item.stok);
                    
                    if (satuan === 'dos') {
                        // Validasi: barang harus punya isi_dos dan isi_dos > 0
                        if (!item.isi_dos || item.isi_dos <= 0) {
                            showStokAlert('Barang ini tidak dijual per dos', 'warning');
                            return;
                        }
                        
                        // Hitung stok dalam dos
                        const stokDos = Math.floor(stokPcs / item.isi_dos);
                        
                        // Validasi stok dos
                        if (stokDos <= 0) {
                            showStokAlert(`Stok dos untuk "${item.nama}" habis!`, 'danger');
                            return;
                        }
                        if (jumlah > stokDos) {
                            showStokAlert(`Stok dos tidak mencukupi! Hanya tersedia ${stokDos} dos`, 'warning');
                            return;
                        }
                        
                        // Gunakan harga_jual_dos sebagai harga
                        item.harga = item.harga_jual_dos;
                        item.harga_beli = item.harga_beli_dos; // harga beli per dos
                    } else {
                        // Validasi stok pcs
                        if (stokPcs <= 0) {
                            showStokAlert(`Stok barang "${item.nama}" habis!`, 'danger');
                            return;
                        }
                        if (jumlah > stokPcs) {
                            showStokAlert(`Stok tidak mencukupi! Hanya tersedia ${stokPcs} pcs`, 'warning');
                            return;
                        }
                        
                        // Tetap gunakan harga retail (nanti bisa grosir jika jumlah memenuhi)
                    }
                    
                    // Tambahkan ke keranjang
                    addToCart(item, jumlah, satuan);
                    
                    // Reset form
                    $("#barcode").val('').focus();
                    $("#jumlah").val(1);
                    $("#stok-info").hide().removeClass('stok-warning stok-kosong');
                    hideStokAlert();
                    
                } else {
                    showAlert('danger', response.message);
                }
            }, 'json').fail(function(xhr, status, error) {
                showAlert('danger', 'Terjadi kesalahan: ' + error);
            });
        });

        // 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
        }

        // Tambahkan badge grosir jika berlaku
        function getGrosirBadge(item, jumlah) {
            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');
            
            if (min4 > 0 && jumlah >= min4) return '<span class="grosir-badge">Grosir Lv4</span>';
            else if (min3 > 0 && jumlah >= min3) return '<span class="grosir-badge">Grosir Lv3</span>';
            else if (min2 > 0 && jumlah >= min2) return '<span class="grosir-badge">Grosir Lv2</span>';
            else if (min1 > 0 && jumlah >= min1) return '<span class="grosir-badge">Grosir Lv1</span>';
            return '';
        }

        function addToCart(item, jumlah, satuan) {
            // Cari item yang sudah ada di keranjang dengan id dan satuan yang sama
            const existing = cart.find(i => i.id === item.id && i.satuan === satuan);
            
            // Validasi ulang stok (disesuaikan dengan satuan)
            if (satuan === 'dos') {
                // Validasi stok dos
                const stokDos = Math.floor(item.stok / item.isi_dos);
                if (stokDos <= 0) {
                    showStokAlert(`Stok dos untuk "${item.nama}" habis!`, 'danger');
                    return;
                }
                if (jumlah > stokDos) {
                    showStokAlert(`Stok dos tidak mencukupi! Hanya tersedia ${stokDos} dos`, 'warning');
                    return;
                }
            } else {
                // Validasi stok pcs
                if (item.stok <= 0) {
                    showStokAlert(`Stok barang "${item.nama}" habis!`, 'danger');
                    return;
                }
                if (jumlah > item.stok) {
                    showStokAlert(`Stok tidak mencukupi! Hanya tersedia ${item.stok} pcs`, 'warning');
                    return;
                }
            }

            if (existing) {
                // Hitung jumlah baru
                const newJumlah = existing.jumlah + jumlah;
                
                // Validasi ulang stok untuk jumlah baru
                if (satuan === 'dos') {
                    const stokDos = Math.floor(item.stok / item.isi_dos);
                    if (newJumlah > stokDos) {
                        showStokAlert(`Stok dos tidak mencukupi! Hanya tersedia ${stokDos} dos`, 'warning');
                        return;
                    }
                } else {
                    if (newJumlah > item.stok) {
                        showStokAlert(`Stok tidak mencukupi! Hanya tersedia ${item.stok} pcs`, 'warning');
                        return;
                    }
                }
                
                existing.jumlah = newJumlah;
                // Hitung ulang harga berlaku (harga grosir hanya untuk pcs)
                existing.harga_berlaku = hitungHargaGrosir(existing, existing.jumlah);
                existing.total = existing.harga_berlaku * existing.jumlah;
                existing.grosirBadge = getGrosirBadge(existing, existing.jumlah);
            } else {
                // Tentukan harga berlaku
                let harga_berlaku = hitungHargaGrosir({...item, satuan}, jumlah);
                let grosirBadge = getGrosirBadge({...item, satuan}, jumlah);
                
                cart.push({ 
                    ...item,
                    satuan,
                    jumlah, 
                    harga_berlaku,
                    total: harga_berlaku * jumlah,
                    grosirBadge
                });
            }
            updateCartDisplay();
        }

        function updateCartDisplay() {
            const $cartItems = $("#cart-items").empty();
            const $empty = $("#empty-cart").toggle(cart.length === 0);
            let subTotal = 0; // Deklarasi subTotal
            let stokKosongDitemukan = false;

            let stokMasalah = false;
            cart.forEach((item) => {
              if (item.stok <= 0 || item.jumlah > item.stok) {
                stokMasalah = true;
              }
              // PERBAIKAN: Hitung subTotal
              subTotal += item.total;
            });
            
            cart.forEach((item, i) => {
                let stokInfo = '';
                let stokClass = '';
                
                if (item.satuan === 'dos') {
                    const stokDos = Math.floor(item.stok / item.isi_dos);
                    if (stokDos <= 0) {
                        stokClass = 'stok-kosong';
                        stokInfo = '<div class="text-danger"><i class="fas fa-exclamation-circle"></i> Stok dos habis!</div>';
                    } else if (item.jumlah > stokDos) {
                        stokClass = 'stok-kosong';
                        stokInfo = `<div class="text-danger"><i class="fas fa-exclamation-circle"></i> Stok dos hanya ${stokDos}!</div>`;
                    } else if (stokDos <= 2) {
                        stokClass = 'stok-warning';
                        stokInfo = `<div class="text-warning"><i class="fas fa-exclamation-triangle"></i> Stok dos tersisa: ${stokDos}</div>`;
                    }
                } else {
                    if (item.stok <= 0) {
                        stokClass = 'stok-kosong';
                        stokInfo = '<div class="text-danger"><i class="fas fa-exclamation-circle"></i> Stok habis!</div>';
                        stokKosongDitemukan = true;
                    } else if (item.jumlah > item.stok) {
                        stokClass = 'stok-kosong';
                        stokInfo = `<div class="text-danger"><i class="fas fa-exclamation-circle"></i> Stok hanya ${item.stok} pcs!</div>`;
                        stokKosongDitemukan = true;
                    } else if (item.stok <= 5) {
                        stokClass = 'stok-warning';
                        stokInfo = `<div class="text-warning"><i class="fas fa-exclamation-triangle"></i> Stok tersisa: ${item.stok} pcs</div>`;
                    }
                }
                $cartItems.append(`
                    <tr class="item-row ${stokClass}">
                        <td>${i + 1}</td>
                        <td>
                            <div>${item.nama} ${item.grosirBadge} </div>
                            <small class="text-muted">${item.barcode}</small>
                            ${stokInfo}
                        </td>
                        <td class="text-right">${formatRupiah(item.harga_berlaku)} (${item.satuan})</td>
                        <td>
                            <input type="number" class="form-control form-control-sm qty-input qty" 
                                value="${item.jumlah}" min="1" data-index="${i}">
                        </td>
                        <td class="text-right font-weight-bold">${formatRupiah(item.total)}</td>
                        <td class="text-center">
                            <button class="btn btn-sm btn-danger btn-remove" data-index="${i}">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                    <input type="hidden" name="id_barang[]" value="${item.id}">
                    <input type="hidden" name="harga_jual[]" value="${item.harga_berlaku}">
                    <input type="hidden" name="harga_beli[]" value="${item.harga_beli}">
                    <input type="hidden" name="harga_beli_dos[]" value="${item.harga_beli_dos}">
                    <input type="hidden" name="satuan[]" value="${item.satuan}">
                    <input type="hidden" name="isi_dos[]" value="${item.isi_dos}">
                    <input type="hidden" name="jumlah[]" value="${item.jumlah}">
                    <input type="hidden" name="harga_total[]" value="${item.total}">
                `);
            });

            // Tampilkan peringatan jika ada stok kosong
            if (stokKosongDitemukan) {
                showStokAlert('Ada barang dengan stok habis atau tidak mencukupi di keranjang!', 'danger');
            } else {
                hideStokAlert();
            }

            // PERBAIKAN: Update semua nilai terkait total
            $("#sub-total").text(formatRupiah(subTotal));
            $("#cart-total").text(formatRupiah(subTotal));
            $("#total-summary").text(formatRupiah(subTotal));
            $("#sub_total").val(subTotal);
            $("#total").val(subTotal);
            
            anBayar.set(subTotal);
            calculateChange();
            $("#btn-bayar").prop('disabled', cart.length === 0 || stokKosongDitemukan);
            $("#cart-count").text(cart.length);
        }

        $(document).on('change', '.qty', function() {
            const index = $(this).data('index');
            let qty = parseInt($(this).val()) || 1;
            if (qty < 1) qty = 1;
            
            const item = cart[index];
            
            // Cek stok sebelum mengubah jumlah
            if (qty > item.stok) {
                showStokAlert(`Stok tidak mencukupi! Hanya tersedia ${item.stok} unit untuk "${item.nama}"`, 'warning');
                $(this).val(item.stok);
                qty = item.stok;
            }
            
            item.jumlah = qty;
            item.harga_berlaku = hitungHargaGrosir(item, qty);
            item.total = item.harga_berlaku * qty;
            item.grosirBadge = getGrosirBadge(item, qty);
            
            updateCartDisplay();
        });

        $(document).on('click', '.btn-remove', function() {
            cart.splice($(this).data('index'), 1);
            updateCartDisplay();
        });

        $("#bayar").on('input', calculateChange);

        function calculateChange() {
            const bayar = anBayar.getNumber() || 0;
            const total = cart.reduce((sum, item) => sum + item.total, 0);
            const kembali = bayar - total;
            
            anKembali.set(kembali > 0 ? kembali : 0);
            
            // Update payment summary
            $("#bayar-display").text(formatRupiah(bayar));
            $("#kembali-display").text(formatRupiah(kembali > 0 ? kembali : 0));
        }

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

        function cetakStruk(idTransaksi, kasir) {
            // Format tanggal: DD/MM/YYYY HH:MM
            const now = new Date();
            const tanggal = `${now.getDate().toString().padStart(2, '0')}/${(now.getMonth()+1).toString().padStart(2, '0')}/${now.getFullYear()} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
            
            // Isi data struk
            $("#struk-id").text(idTransaksi);
            $("#struk-tanggal").text(tanggal);
            
            // Isi item struk
            const $strukItems = $("#struk-items").empty();
            cart.forEach(item => {
                // Potong nama barang jika terlalu panjang
                const namaBarang = item.nama.length > 20 
                    ? item.nama.substring(0, 17) + '...' 
                    : item.nama;
                    
                $strukItems.append(`
                    <tr>
                        <td>${namaBarang}</td>
                        <td align="center">${item.jumlah} ${item.satuan}</td>
                        <td align="right">${formatRupiah(item.harga_berlaku)}</td>
                        <td align="right">${formatRupiah(item.total)}</td>
                    </tr>
                `);
            });
            
            // Isi total pembayaran
            const total = cart.reduce((sum, item) => sum + item.total, 0);
            const bayar = anBayar.getNumber();
            const kembali = bayar - total;

            // Tambahkan informasi member
            const memberId = $("#id_member").val();
            let memberName = "-";
            if (memberId) {
                memberName = $("#id_member option:selected").text();
            }
            $("#struk-member").text(memberName);
            
            $("#struk-subtotal").text(formatRupiah(total));
            $("#struk-bayar").text(formatRupiah(bayar));
            $("#struk-kembali").text(formatRupiah(kembali > 0 ? kembali : 0));
            $("#struk-metode").text($("#metode_bayar").val().toUpperCase());
            
            // Tampilkan struk sebelum cetak
            $("#struk-container").show();
            
            // Delay cetak untuk memastikan DOM terupdate
            setTimeout(() => {
                window.print();
                
                // Sembunyikan struk setelah cetak
                setTimeout(() => $("#struk-container").hide(), 1000);
            }, 500);
        } 


        $("#form-payment").submit(function(e) {
            e.preventDefault();

            if (cart.length === 0) return showAlert('warning', 'Keranjang belanja kosong');

            const bayar = anBayar.getNumber() || 0;
            const total = cart.reduce((sum, item) => sum + item.total, 0);

            if (bayar < total) return showAlert('warning', 'Jumlah pembayaran kurang');

            // Cek stok terakhir sebelum transaksi
            const stokKosong = cart.some(item => item.jumlah > item.stok);
            if (stokKosong) {
                showStokAlert('Terdapat barang dengan stok tidak mencukupi!', 'danger');
                return;
            }

            const formData = $(this).serializeArray();
            formData.push(
                { name: 'sub_total', value: $("#sub_total").val() },
                { name: 'id_member', value: $("#id_member").val() },
                { name: 'total', value: total },
                { name: 'id_transaksi', value: transactionId }
            );

            $("input[name^='id_barang'], input[name^='harga_jual'], input[name^='harga_beli'], input[name^='jumlah'],input[name^='satuan'], input[name^='isi_dos'], input[name^='harga_total']").each(function() {
                formData.push({ name: $(this).attr('name'), value: $(this).val() });
            });

            $.post("<?php echo site_url('kasirq/proses_transaksi'); ?>", formData, function(response) {
                if (response.status) {
                    showAlert('success', `Transaksi berhasil disimpan. ID: ${response.id_transaksi}`);
                     
                    // PERBAIKAN: TAMBAHKAN PARAMETER KASIR
                    cetakStruk(response.id_transaksi, "<?php echo $user['nama']; ?>");
                    
                    resetTransaction();
                } else {
                    showAlert('danger', 'Gagal menyimpan transaksi: ' + response.message);
                }
            }, 'json').fail(function(xhr, status, error) {
                showAlert('danger', 'Terjadi kesalahan: ' + error);
            });
        });

        $("#btn-cancel").click(function() {
            if (cart.length > 0 && confirm('Batalkan transaksi ini?')) {
                resetTransaction();
            }
        });

        function resetTransaction() {
            cart = [];
            transactionId = generateTransactionId();
            $("#transaction-id").text(transactionId);
            updateCartDisplay();
            $("#form-payment")[0].reset();
            $("#metode_bayar").val('cash').trigger('change');
            anBayar.clear();
            anKembali.clear();
            $("#id_member").val('');
            $("#bayar-display").text('Rp 0');
            $("#kembali-display").text('Rp 0');
            $("#stok-info").hide().removeClass('stok-warning stok-kosong');
            hideStokAlert();
            $("#barcode").focus();
        }

        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;
            }
            
            // 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();
                if (cart.length > 0) {
                    $("#bayar").focus().select();
                } else {
                    showAlert('warning', 'Keranjang kosong, tambahkan barang terlebih dahulu');
                }
                return false;
            }
        });
    });
    </script>

</body>
</html>