<?php
if (!empty($proses)) {
    if (!function_exists('keranjang_harga_format')) {
        function keranjang_harga_format($value) {
            $value = (float) $value;
            if (abs($value - round($value)) < 0.00001) {
                return number_format($value, 0, ',', '.');
            }
            return rtrim(rtrim(number_format($value, 4, ',', '.'), '0'), ',');
        }
    }
?>
<div class="keranjang" id="container">
    <?php
        if ($id > 0) {
            $kon = pilih('konsumen', 'id', $proses['id_konsumen']);
            $iduser = $this->session->idu;
            $id_invoice = $id;
            $pos = $proses['pos'];
            $oto = $proses['oto'];
            $pajak = $proses['pajak'];
            $potongan_harga = $proses['potongan_harga'];
            $id_konsumen = $proses['id_konsumen'];

            if (!empty($kon['panggilan'])) {
                $nama = $kon['panggilan'].'. '.$kon['nama'];
            }

            $cek_member      = cek_member($id_konsumen);
            $jenis_member    = member($cek_member);
            $idmember        = $cek_member;

            if ($kon['tampil'] == 1) {
                $nick   = '';
                $nama   = $kon['perusahaan'];
                $telp   = $kon['no_telp'];
                $alamat = $kon['alamat_lembaga'];
            } else {
                $nick   = $kon['panggilan'];
                $nama   = $kon['nama'];
                $telp   = phone_number($kon['no_hp']);
                $alamat = $kon['alamat'];
            }

            $disabled      = '';
            $fa            = 'times-rectangle';
            $tgl_trx_timestamp = !empty($proses['tgl_trx']) && $proses['tgl_trx'] !== '0000-00-00 00:00:00'
                ? strtotime($proses['tgl_trx'])
                : false;
            $tgl_ambil_timestamp = !empty($proses['tgl_ambil']) && $proses['tgl_ambil'] !== '0000-00-00 00:00:00'
                ? strtotime($proses['tgl_ambil'])
                : false;
            $jam_order_timestamp = !empty($proses['jam_order']) && $proses['jam_order'] !== '00:00:00'
                ? strtotime(date('Y-m-d', $tgl_trx_timestamp !== false ? $tgl_trx_timestamp : time()) . ' ' . $proses['jam_order'])
                : false;

            $order_datetime_timestamp = $jam_order_timestamp !== false ? $jam_order_timestamp : time();

            // Draft versi lama mengisi deadline sama dengan waktu order.
            // Koreksi hanya nilai bawaan tersebut; deadline yang sudah dipilih
            // manual oleh pengguna tetap dipertahankan.
            $is_legacy_default_deadline = $tgl_ambil_timestamp !== false
                && ($proses['status'] ?? '') === 'baru'
                && abs($tgl_ambil_timestamp - $order_datetime_timestamp) <= 60;
            if ($tgl_ambil_timestamp === false || $is_legacy_default_deadline) {
                $tgl_ambil_timestamp = strtotime('+4 hours', $order_datetime_timestamp);
            }

            // Zero-date MySQL bersifat non-kosong, tetapi tidak boleh diberikan
            // ke date()/datepicker karena menghasilkan tanggal -0001.
            $tgl_invoice   = $tgl_trx_timestamp !== false ? date('d/m/Y', $tgl_trx_timestamp) : date('d/m/Y');
            $tomorrow      = date('Y-m-d', strtotime('+1 day', $tgl_ambil_timestamp !== false ? $tgl_ambil_timestamp : time()));
            $tgl_ambil     = $tgl_ambil_timestamp !== false ? date('d/m/Y', $tgl_ambil_timestamp) : date('d/m/Y');
            $jam_ambil     = $tgl_ambil_timestamp !== false ? date('H:i', $tgl_ambil_timestamp) : '17:00';
            $jam_order     = date('H:i:s', $order_datetime_timestamp);
            $marketing     = $proses['id_marketing'];
            $total_bayar   = $proses['total_bayar'];
            $auto_number   = $proses['id_transaksi'];
            $lunas         = $proses['lunas'];
            $button_1      = ''; // pelanggan
            $button_2      = ''; // tgl_order
            $readonly      = '';
            $readonlym     = '';
            $button_lunas  = '';
            $status        = $proses['status'];

            if ($status == 'baru' and $this->session->level == 'desain') {
                $readonlym = 'readonly';
            }

            $jenis_dropship = '';
            if (!empty($proses['id_dropshiper'])) {
                $jenis_dropship = '[DROPSHIP]';
            }

            if ($status == 'simpan') {
                $readonly     = 'readonly';
                $disabled     = 'disabled';
                $button_1     = 'disabled';
                $button_2     = 'readonly';
                $fa           = 'lock';
            }

        } else {
            $iduser          = 0;
            $id_invoice      = 0;
            $pos             = 'N';
            $oto             = 0;
            $pajak           = 0;
            $potongan_harga  = 0;
            $id_konsumen     = 0;
            $idmember        = '-';
            $nick            = '-';
            $nama            = '-';
            $disabled        = '';
            $telp            = '-';
            $alamat          = '-';
            $readonly        = '';
            $button_1        = '';
            $button_2        = '';
            $tgl_invoice     = '-';
            $tgl_ambil       = '-';
            $jam_ambil       = '-';
            $jam_order       = date('H:i:s');
            $marketing       = '-';
            $total_bayar     = 0;
            $status          = 'baru';
            $auto_number     = $autonumber;
            $lunas           = 0;
        }

        $komisi_sales_aktif = !isset($komisi_sales_aktif) || (int) $komisi_sales_aktif === 1;
        $dropshipper_aktif = !isset($dropshipper_aktif) || (int) $dropshipper_aktif === 1;
        $sales_users = isset($sales_users) && is_array($sales_users) ? $sales_users : [];
        $sales_komisi = isset($proses['id_sales_komisi']) ? (int) $proses['id_sales_komisi'] : 0;
		$komisi_penjualan_aktif = isset($komisi_penjualan_aktif) && (int)$komisi_penjualan_aktif === 1;
		$sales_penjualan_users = isset($sales_penjualan_users) && is_array($sales_penjualan_users) ? $sales_penjualan_users : [];
		$sales_penjualan = isset($proses['id_sales_penjualan']) ? (int)$proses['id_sales_penjualan'] : 0;
        $totbayar = 0;
        if ($diskon->num_rows() > 0) {
            $rows     = $diskon->row();
            $totbayar = $rows->totbayar;
            if ($rows->jdiskon > 0) {
                $tdiskon  = ($totbayar * 10) / 100;
                $tdiskon  = ($totbayar - $rows->jdiskon) / $totbayar * 100;
                $tdiskon  = 100 - $tdiskon;
                $totbayar = rp($totbayar - $rows->jdiskon);
            }
        } else {
            $tdiskon  = 0;
            $totbayar = 0;
        }

        if ($oto == 6 OR $lunas == 1) {
            $disabled = 'disabled';
            $script0 = <<< JS
            $("#pending,#bayarin").prop("disabled",true);
            JS;
            echo "<script>{$script0}</script>";
        }

        if ($oto == 5) {
            $disabled = 'disabled';
            $script1 = <<< JS
            $("#print,#pending,#bayarin,#simpan").prop("disabled",true);
            JS;
            echo "<script>{$script1}</script>";
        }

        if ($oto == 1) {
            $script2 = <<< JS
            $("#pending,#bayarin,#simpan").prop("disabled",false);
            JS;
            echo "<script>{$script2}</script>";
        }

        if ($oto == 3) {
            $button_1 = 'disabled';
            $button_2 = 'readonly';

            $script3 = <<< JS
            $("#pending,#bayarin,#simpan").prop("disabled",false);
            JS;
            echo "<script>{$script3}</script>";
        }

        if ($totbayar + $potongan_harga > 0) {
            $script4 = <<< JS
            $("#pending").prop("disabled",true);
            JS;
            echo "<script>{$script4}</script>";
        }

        if ($cdetail == ($totbayar + $potongan_harga) and $pos == 'Y' and $lunas == 1 and $oto != 3) {
            $readonly     = 'readonly';
            $disabled     = 'disabled';
            $button_lunas = 'disabled';
            $button_1     = 'disabled';
            $button_2     = 'readonly';
            $script5 = <<< JS
            $("#pending").prop("disabled",true);
            JS;
            echo "<script>{$script5}</script>";
        }

        if ($status == 'pending') {
            $script2 = <<< JS
            $("#pending").hide();
            JS;
            echo "<script>{$script2}</script>";
        }

        if ($type == 'edit' && $status != 'simpan') {
            $readonly     = '';
            $disabled     = '';
            $button_lunas = '';
        } elseif ($type == 'lunas') {
            $readonly = 'readonly';
            $button_1 = 'disabled';
        } elseif ($type == 'pelunasan') {
            $readonly = 'readonly';
            $button_1 = 'disabled';
        } elseif ($type == 'pending') {
            $readonly = 'readonly';
        } elseif ($type == 'view') {
            $readonly     = 'readonly';
            $button_1     = 'disabled';
            $button_lunas = 'disabled';
        } elseif ($type == 'batal') {
            $readonly = 'disabled';
            $button_2 = 'disabled';
        }

        if ($status == 'pending') {
            $readonly = '';
        }

        if ($id_konsumen == 1) {
            $button_1 = '';
        }

        $none  = '';
        $nonee = '';
        if ($this->session->level == 'op') {
            $none  = 'style="display:none"';
            $nonee = 'display:none';
            $script6 = <<< JS
            $("#print").hide();
            $("#pending").hide();
            $("#bayarin").hide();
            $("#cetak_spk").show();
            $(".pending").attr("disabled",false);
            JS;
            echo "<script>{$script6}</script>";
        }
    ?>

    <!-- hidden inputs -->
    <input type="hidden" name="id_transaksi" id="id_transaksi" value="<?php echo $auto_number; ?>">
    <input type="hidden" name="id_invoice" id="id_invoice" value="<?php echo $id_invoice; ?>">
    <input type="hidden" name="id_konsumen" id="id_konsumen" value="<?php echo $id_konsumen; ?>">
    <input type="hidden" name="idmember" id="idmember" value="<?php echo $idmember; ?>">
    <input type="hidden" name="iduser" id="iduser" value="<?php echo $iduser; ?>">
    <input type='hidden' id='idsesi' value="<?php echo $idsesi; ?>" />
    <input type='hidden' id='idlunas' value="<?php echo $lunas; ?>" />
    <input type='hidden' id='status' value="<?php echo $status; ?>" />

    <!-- ========================= -->
<!-- BLOK INFO (3 kolom -> stack di mobile) -->
<!-- ========================= -->
<div class="row simple-section">
    <!-- PELANGGAN -->
    <div class="col-md-4 col-12">
        <div class="simple-card cust-card">

            <div class="cart-card-heading">
                <span class="cart-card-icon"><i class="fa fa-user-o"></i></span>
                <span>Informasi Pelanggan</span>
            </div>

            <!-- NAMA PELANGGAN -->
            <div class="cust-header mb-2 cart-customer-content">
                <strong class="text-main d-block text-truncate" id="namanya">
                    <?php echo ucwords($nama); ?>
                </strong>
            </div>

            <!-- status pelanggan -->
            <div class="info-line cart-customer-content">
                <span class="info-label">Status</span>
                <span class="info-value">
                    <span id="jenis_member"><?php echo $jenis_member; ?></span>
                    <span id="jenis_dropship"><?php echo $jenis_dropship; ?></span>
                </span>
            </div>

            <div class="info-line cart-customer-content">
                <span class="info-label">Telp</span>
                <span class="info-value" id="tlpnya"><?php echo $telp; ?></span>
            </div>

            <!-- TOMBOL AKSI PELANGGAN -->
            <div class="cust-actions mt-auto <?php echo $dropshipper_aktif ? '' : 'cust-actions-no-dropship'; ?>">
                <button type="button"
                        data-id="<?php echo $id_invoice; ?>"
                        class="btn cari"
                        data-toggle='tooltip'
                        title="Cari pelanggan"
                        <?php echo $button_1; ?>>
                    <i class="fa fa-search"></i>
                    <span>Cari Pelanggan (F2)</span>
                </button>

                <button type="button"
                        data-id="<?php echo $id_invoice; ?>"
                        class="btn tambah"
                        id="tambah"
                        data-toggle='tooltip'
                        title="Tambah pelanggan"
                        <?php echo $button_1; ?>>
                    <i class="fa fa-user-plus"></i>
                    <span>Tambah Pelanggan (F3)</span>
                </button>

                <?php if ($dropshipper_aktif): ?>
                    <button type="button"
                            data-id="<?php echo $id_invoice; ?>"
                            class="btn cari_dropship"
                            id="tambah"
                            data-toggle='tooltip'
                            title="Tambah dropship"
                            <?php echo $button_1; ?>>
                        <i class="fa fa-truck"></i>
                        <span>Dropship</span>
                    </button>
                <?php endif; ?>
            </div>

        </div>
    </div>

    <!-- TANGGAL & KASIR -->
    <div class="col-md-4 col-12">
        <div class="simple-card order-card">
            <div class="cart-card-heading">
                <span class="cart-card-icon"><i class="fa fa-calendar-o"></i></span>
                <span>Informasi Order</span>
            </div>
            <div class="order-date-row">
            <div class="mb-2 order-date-field">
                <label class="mini-label">Tanggal Order</label>
                <div class="input-group input-group-sm flex-nowrap order-time-wrap">
                    <input type="text"
                           class="form-control text-center tgl_invoice modern-date-input"
                           id="tgl_invoice"
                           value="<?php echo $tgl_invoice; ?>"
                           data-today="<?php echo date('d/m/Y'); ?>"
                           data-lock-today="<?php echo $status === 'baru' ? '1' : '0'; ?>"
                           autocomplete="off"
                           <?php echo $button_2; ?>>
                    <span class="input-group-text simple-addon modern-picker-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"></circle><path d="M12 7.5v5l3.2 1.9"></path></svg></span>
                    <input type="text"
                           class="form-control text-center"
                           id="jam_order"
                           value="<?php echo $jam_order; ?>"
                           data-timezone="<?php echo html_escape(date_default_timezone_get()); ?>"
                           aria-label="Jam order realtime"
                           readonly>
                </div>
            </div>

            <div class="mb-2 order-date-field">
                <label class="mini-label">Tanggal Deadline</label>
                <div class="input-group input-group-sm flex-nowrap selesai-wrap">
                    <input type="text"
                           class="form-control text-center modern-date-input"
                           id="tgl_ambil"
                           value="<?php echo $tgl_ambil; ?>"
                           autocomplete="off">

                    <span class="input-group-text simple-addon modern-picker-icon deadline-clock-trigger" onclick="openDeadlineClockPicker(event)" title="Pilih jam deadline" aria-label="Pilih jam deadline"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"></circle><path d="M12 7.5v5l3.2 1.9"></path></svg></span>

                    <input type="time"
                           class="form-control text-center jam modern-time-input"
                           id="jam_ambil"
                           value="<?php echo $jam_ambil; ?>"
                           placeholder="HH:mm"
                           step="60"
                           autocomplete="off"
                           onclick="openDeadlineClockPicker(event)"
                           aria-label="Jam deadline">
                </div>
            </div>
            </div>

            <div class="mb-0">
                <?php
                    $pilih = pilih('tb_users', 'id_user', $marketing);
                    $namamarketing = $pilih['nama_lengkap'];
                    $id_user       = $pilih['id_user'];
                ?>
                <input type="hidden" id="marketing" value="<?php echo $marketing; ?>">

                <label class="mini-label">Kasir</label>
                <div class="input-group input-group-sm">
                    <input type="text"
                           class="form-control"
                           onchange="save_invoice()"
                           id="namamarketing"
                           value="<?php echo $namamarketing; ?>"
                           <?php echo $readonlym; ?>
                           required
                           <?php echo $button_2; ?>>
                </div>
            </div>

            <?php if ($komisi_sales_aktif || $komisi_penjualan_aktif): ?>
            <div class="commission-inline-row">
            <?php endif; ?>
            <?php if ($komisi_sales_aktif): ?>
            <div class="mb-0 komisi-desain-wrap commission-inline-field" id="komisi_desain_wrap">
                <label class="mini-label komisi-desain-label" for="sales_komisi">
                    <span>Komisi Desain</span>
                </label>
                <div class="input-group input-group-sm komisi-desain-control">
                    <div class="input-group-prepend">
                        <span class="input-group-text komisi-desain-icon"><i class="fa fa-user"></i></span>
                    </div>
                    <select class="form-control"
                            id="sales_komisi"
                            onchange="save_invoice()"
                            <?php echo $disabled; ?>>
                        <option value="0">Pilih Desainer / Karyawan</option>
                        <?php foreach ($sales_users as $sales_row): ?>
                            <option value="<?= (int) $sales_row['id_user']; ?>" <?= ((int) $sales_row['id_user'] === $sales_komisi) ? 'selected' : ''; ?>>
                                <?= htmlspecialchars($sales_row['nama_lengkap'], ENT_QUOTES, 'UTF-8'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="komisi-desain-hint" id="komisi_desain_hint">Wajib pilih karyawan sebelum bayar atau cetak order</div>
            </div>
            <?php endif; ?>
			<?php if ($komisi_penjualan_aktif): ?>
			<div class="mb-0 komisi-desain-wrap commission-inline-field" id="komisi_penjualan_wrap">
				<label class="mini-label komisi-desain-label" for="sales_penjualan"><span>Komisi Penjualan</span></label>
				<div class="input-group input-group-sm komisi-desain-control"><div class="input-group-prepend"><span class="input-group-text komisi-desain-icon"><i class="fa fa-user"></i></span></div>
				<select class="form-control" id="sales_penjualan" <?php echo $disabled; ?>><option value="0">Pilih Karyawan Penjualan</option><?php foreach($sales_penjualan_users as $u): ?><option value="<?=(int)$u['id_user'];?>" <?=((int)$u['id_user']===$sales_penjualan)?'selected':'';?>><?=htmlspecialchars($u['nama_lengkap'],ENT_QUOTES,'UTF-8');?></option><?php endforeach;?></select></div>
				<div class="komisi-desain-hint" id="komisi_penjualan_hint"></div>
			</div>
			<?php endif; ?>
            <?php if ($komisi_sales_aktif || $komisi_penjualan_aktif): ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- RINGKASAN PEMBAYARAN -->
    <div class="col-md-4 col-12" <?php echo $none; ?>>
        <div class="simple-card pay-card">
            <div class="cart-card-heading">
                <span class="cart-card-icon"><i class="fa fa-credit-card"></i></span>
                <span>Ringkasan Pembayaran</span>
            </div>

            <div class="cart-summary-list">
                <div class="cart-payment-total cart-payment-total-order">
                    <span class="cart-payment-icon"><i class="fa fa-shopping-cart"></i></span>
                    <span class="cart-payment-label">Total Order</span>
                    <input type="text" id="totalSum" name="totalSum" readonly="readonly">
                    <input type="hidden" id="sum_total_order" name="sum_total_order" readonly="readonly">
                </div>

                <div class="cart-payment-total cart-payment-tax cart-summary-optional"
                     <?php echo ((float) $pajak > 0) ? '' : 'hidden'; ?>>
                    <span class="cart-payment-icon"><i class="fa fa-percent"></i></span>
                    <span class="cart-payment-label">Pajak</span>
                    <span class="cart-tax-value">
                        <input type="text" id="pajaksum" value="<?php echo $pajak; ?>" readonly="readonly">
                        <span>%</span>
                    </span>
                </div>

                <div class="cart-payment-total cart-payment-discount cart-summary-optional"
                     <?php echo ((float) $potongan_harga > 0) ? '' : 'hidden'; ?>>
                    <span class="cart-payment-icon"><i class="fa fa-tag"></i></span>
                    <span class="cart-payment-label">Diskon</span>
                    <input type="text"
                           id="potongan_harga_diskon"
                           value="<?php echo ((float) $potongan_harga > 0) ? 'Rp.'.keranjang_harga_format($potongan_harga) : 'Rp.0'; ?>"
                           readonly="readonly">
                </div>

                <div class="cart-payment-total cart-payment-paid">
                    <span class="cart-payment-icon"><i class="fa fa-check-circle-o"></i></span>
                    <span class="cart-payment-label">Sudah Dibayar</span>
                    <input type="text" id="uangmuka" value="<?php echo $totbayar; ?>" readonly="readonly">
                </div>

                <div class="cart-payment-total cart-payment-due">
                    <span class="cart-payment-icon"><i class="fa fa-credit-card-alt"></i></span>
                    <span class="cart-payment-label">Sisa / Piutang</span>
                    <input type="text" id="sisaSum" value="0" readonly="readonly">
                </div>
            </div>

            <input type="hidden" id="potongan_harga" value="<?php echo $potongan_harga; ?>" readonly="readonly">
        </div>
    </div>
</div>
<!-- /row simple-section -->


    <!-- ========================= -->
    <!-- TABEL ITEM -->
    <!-- ========================= -->
    <div class="row mt-3">
        <div class="col-12">
            <div class="simple-card cart-items-card">
                <form id="formcheckin" class="cart-product-toolbar">
                    <div class="input-group input-group-sm flex-grow-1">
                        <div class="cart-product-search">
                            <i class="fa fa-search"></i>
                            <input type="text"
                                   name="cari_produk"
                                   id="cari_produk"
                                   class="form-control"
                                   placeholder="Cari produk / barcode"
                                   <?php echo $button_lunas; ?>>
                        </div>

                        <input type="hidden" name="invoice_add" id="invoice_add" value="<?php echo $id_invoice; ?>">
                        <input type="hidden" name="idmember_add" id="idmember_add" value="<?php echo $idmember; ?>">
                        <input type="hidden" name="kodeproduk" id="kodeproduk">
                        <input type="hidden" name="id_produk" id="id_produk">
                        <input type="hidden" name="harga" id="harga">
                        <input type="hidden" name="jenis_cetakan" id="jenis_cetakan">
                        <input type="hidden" name="bahan" id="bahan">
                        <input type="hidden" name="id_jenis" id="id_jenis">
                        <input type="hidden" name="id_bahan" id="id_bahan">
                        <input type="hidden" name="type_harga" id="type_harga">
                        <input type="hidden" name="status_hitung" id="status_hitung">
                        <input type="hidden" name="satuan" id="satuan_add">
                        <input type="hidden" name="ukuran" id="ukuran">
                        <input type="hidden" name="jumlah" id="jumlah">
                        <input type="hidden" name="lock" id="lock">
                        <input type="hidden" name="id_konsumen_cari" id="id_konsumen_cari" value="<?php echo $id_konsumen; ?>">

                        <div class="input-group-append produk-aksi">
                            <button class="btn btn-outline-secondary show_qr" type="button" <?php echo $button_lunas; ?>>
                                <i class="fa fa-barcode" aria-hidden="true"></i>
                                Scan Barcode
                            </button>
                            <button class="btn btn-outline-secondary show_harga" type="button" <?php echo $button_lunas; ?>>
                                <i class="fa fa-list" aria-hidden="true"></i>
                                Daftar Bahan &amp; Harga
                            </button>
                        </div>
                    </div>
                </form>

                <div class="table-responsive">
                    <table class="table table-striped table-sm mb-0" id="tablein">
                        <thead class="simple-thead">
                            <tr>
                                <td width="55" class="align-middle text-center">
                                    <button class="btn btn-primary btn-xs flat addmore"
                                            type="button"
                                            id="addmore"
                                            readonly>
                                        <i class="fa fa-plus"></i>
                                    </button>
                                    No
                                </td>
                                <td>Produk</td>
                                <td>Keterangan</td>
                                <td>Merk / Bahan</td>
                                <td style="width:90px!important">Satuan</td>
                                <td style="width:140px!important">Ukuran</td>
                                <td class="text-center" style="width:110px!important">Qty</td>
                                <td style="width:170px!important;<?php echo $nonee; ?>">@ Harga</td>
                                <td class="text-right" <?php echo $none; ?>>Sub Total</td>
                                <td class="text-center cart-action-head">Aksi</td>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $no = 0;
                            $ni = 1;
                            $lock_harga = '';
                            $komposisiVariantOptions = isset($komposisi_variant_options) && is_array($komposisi_variant_options) ? $komposisi_variant_options : [];
                            foreach ($detail as $val) {
                                $kunci = kunci_harga($val['id_produk']);
                                if ($kunci == 'Y' AND $this->session->level!='admin') {
                                    $lock_harga = 'readonly';
                                }
                                if ($val['status_hitung'] == 2) {
                                    $lock_status = '';
                                } else {
                                    $lock_status = 'readonly';
                                }
                                if (empty($val['keterangan']) or empty($val['ukuran'])) {
                                    $readonly = '';
                                }
                                $status_hitung   = cek_hitung($val['idbahan']);
                                $cek_type_harga  = cek_type_harga($val['idbahan']);
                                $rowKomposisiVariantOptions = isset($komposisiVariantOptions[(int) $val['idbahan']]) ? $komposisiVariantOptions[(int) $val['idbahan']] : [];
                                $currentKeterangan = (string) $val['keterangan'];
                            ?>
                            <tr id='rowCount<?php echo $no; ?>' class="rowCount">
                                <td align="center" class="cart-row-number"><?php echo $ni; ?></td>
                                <td>
                                    <div class="form-group p-0 m-0">
                                        <input type='hidden'
                                               id='id_rincianinvoice_<?php echo $no; ?>'
                                               value="<?php echo $val['id_rincianinvoice']; ?>" />
                                        <input class="form-control form-control-sm input next"
                                               type='text'
                                               id='kodeproduk_<?php echo $no; ?>'
                                               onchange="doMath()"
                                               value="<?php echo $val['title']; ?>"
                                               onfocusout="sav(<?php echo $no; ?>)"
                                               <?php echo $readonly; ?> />
                                        <input type='hidden'
                                               id='id_produk_<?php echo $no; ?>'
                                               value="<?php echo $val['id']; ?>" />
                                        <input type="hidden"
                                               class="form-control form-control-sm input next"
                                               value="<?php echo $val['jenis']; ?>"
                                               id="jenis_cetakan_<?php echo $no; ?>"
                                               placeholder="jenis"
                                               onfocusout="sav(<?php echo $no; ?>)"
                                               <?php echo $readonly; ?> readonly>
                                        <input type='hidden'
                                               id='id_jenis_<?php echo $no; ?>'
                                               value="<?php echo $val['id_jenis']; ?>" />
                                        <input type='hidden'
                                               class="input"
                                               id='status_hitung_<?php echo $no; ?>'
                                               value="<?php echo $status_hitung; ?>" />
                                        <input type='hidden'
                                               class="input"
                                               id='type_harga_<?php echo $no; ?>'
                                               value="<?php echo $cek_type_harga; ?>" />
                                    </div>
                                </td>
                                <td>
                                    <div class="form-group p-0 m-0">
                                        <?php if (!empty($rowKomposisiVariantOptions)) { ?>
                                            <select class="form-control form-control-sm input next komposisi-variant-ket bootstrap-select"
                                                    id="ket_<?php echo $no; ?>"
                                                    name="ket"
                                                    title="Pilih varian"
                                                    data-live-search="true"
                                                    data-size="6"
                                                    data-width="100%"
                                                    data-container="body"
                                                    data-none-results-text="Varian tidak ditemukan {0}"
                                                    onchange="cartKomposisiVariantChanged(<?php echo $no; ?>)"
                                                    <?php echo $readonly; ?>
                                                    required>
                                                <option value="">Pilih varian</option>
                                                <?php
                                                    $currentInOptions = false;
                                                    foreach ($rowKomposisiVariantOptions as $option) {
                                                        $optionValue = isset($option['value']) ? (string) $option['value'] : '';
                                                        $optionUkuran = isset($option['ukuran']) ? (string) $option['ukuran'] : '';
                                                        if ($optionValue === $currentKeterangan) {
                                                            $currentInOptions = true;
                                                        }
                                                ?>
                                                    <option value="<?php echo htmlspecialchars($optionValue, ENT_QUOTES, 'UTF-8'); ?>"
                                                            data-ukuran="<?php echo htmlspecialchars($optionUkuran, ENT_QUOTES, 'UTF-8'); ?>"
                                                            <?php echo ($optionValue === $currentKeterangan) ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars(isset($option['label']) ? (string) $option['label'] : $optionValue, ENT_QUOTES, 'UTF-8'); ?>
                                                    </option>
                                                <?php } ?>
                                                <?php if ($currentKeterangan !== '' && $currentKeterangan !== '-' && !$currentInOptions) { ?>
                                                    <option value="<?php echo htmlspecialchars($currentKeterangan, ENT_QUOTES, 'UTF-8'); ?>" selected>
                                                        <?php echo htmlspecialchars($currentKeterangan, ENT_QUOTES, 'UTF-8'); ?>
                                                    </option>
                                                <?php } ?>
                                            </select>
                                        <?php } else { ?>
                                            <input type="text"
                                                   class="form-control form-control-sm input next"
                                                   id='ket_<?php echo $no; ?>'
                                                   name='ket'
                                                   value="<?php echo $val['keterangan']; ?>"
                                                   onfocusout="sav(<?php echo $no; ?>)"
                                                   <?php echo $readonly; ?>
                                                   required />
                                        <?php } ?>
                                    </div>
                                </td>
                                <td>
                                    <div class="form-group p-0 m-0">
                                        <input type="text"
                                               class="form-control form-control-sm input next"
                                               placeholder="bahan"
                                               onchange="sav(<?php echo $no; ?>);hitflexi(<?php echo $no; ?>);doMath();"
                                               id="bahan_<?php echo $no; ?>"
                                               placeholder="0"
                                               value="<?php echo $val['nbahan']; ?>"
                                               <?php echo $readonly; ?> />
                                        <input type='hidden'
                                               id='id_bahan_<?php echo $no; ?>'
                                               value="<?php echo $val['idbahan']; ?>"
                                               onfocusout="sav(<?php echo $no; ?>)" />
                                    </div>
                                </td>
                                <td>
                                    <div class="form-group p-0 m-0">
                                        <select name="satuan_<?php echo $no; ?>"
                                                id="satuan_<?php echo $no; ?>"
                                                class="form-control form-control-sm rounded-0 next"
                                                data-valueKey="id"
                                                data-displayKey="name"
                                                required
                                                <?php echo $readonly; ?>>
                                        </select>
                                        <input type="hidden"
                                               class="form-control form-control-sm input"
                                               value="<?php echo $val['id_satuan']; ?>"
                                               onchange="sav(<?php echo $no; ?>)"
                                               id="id_satuan_<?php echo $no; ?>"
                                               required
                                               readonly />
                                    </div>
                                </td>
                                <td>
                                    <div class="form-group p-0 m-0">
                                        <input type="text"
                                               value="<?php echo $val['ukuran']; ?>"
                                               class="form-control form-control-sm ukur pilih next"
                                               onchange="hitflexi(<?php echo $no; ?>);doMath();sav(<?php echo $no; ?>);"
                                               id="ukuran_<?php echo $no; ?>"
                                               onclick="show_modal_ukuan(<?php echo $status_hitung; ?>)"
                                               <?php echo $readonly; ?> />
                                        <input type='hidden'
                                               id='totukuran_<?php echo $no; ?>'
                                               value="<?php echo $val['tot_ukuran']; ?>" />
                                        <input type='hidden'
                                               id='harga_satuan_<?php echo $no; ?>'
                                               value="<?php echo $val['harga_satuan']; ?>" />
                                        <input type='hidden'
                                               id='ukuran_hitung_<?php echo $no; ?>'
                                               value="<?php echo $val['ukuran_hitung']; ?>" />
                                    </div>
                                </td>
                                <td>
                                    <div class="form-group p-0 m-0">
                                        <input type="number"
                                               class="form-control form-control-sm pilih ukur text-center next"
                                               value="<?php echo $val['jumlah']; ?>"
                                               onchange="harga_range(<?php echo $no; ?>);hitflexi(<?php echo $no; ?>);sav(<?php echo $no; ?>);doMath()"
                                               onclick="harga_range(<?php echo $no; ?>);hitflexi(<?php echo $no; ?>);doMath();sav(<?php echo $no; ?>);"
                                               onkeyup='formatNumber(this)'
                                               id="jumlah_<?php echo $no; ?>"
                                               placeholder="0"
                                               min="1"
                                               max="50000"
                                               <?php echo $readonly; ?> />
                                    </div>
                                </td>
                                <td <?php echo $none; ?>>
                                    <div class="form-group p-0 m-0">
                                        <input type="text"
                                               class="form-control form-control-sm input next text-right"
                                               value="<?php echo keranjang_harga_format($val['harga']); ?>"
                                               onchange="doMath();sav(<?php echo $no; ?>)"
                                               oninput='hargaKeranjangInputDecimal(this)'
                                               id="harga_<?php echo $no; ?>"
                                               placeholder="0"
                                               <?php echo $readonly; ?>
                                               <?php echo $lock_harga; ?> />
                                        <input class="form-control text-center form-control-sm input"
                                               type="hidden"
                                               id="diskon_<?php echo $no; ?>"
                                               value="<?php echo $val['diskon']; ?>"
                                               onchange="sav(<?php echo $no; ?>)"
                                               min="0"
                                               max="99"
                                               <?php echo $readonly; ?>>
                                    </div>
                                </td>
                                <td class="text-right" <?php echo $none; ?>>
                                    <div class="form-group p-0 m-0">
                                        <input type="text"
                                               class="form-control form-control-sm totalsz text-right"
                                               id="total_<?php echo $no; ?>"
                                               placeholder="0"
                                               readonly />
                                    </div>
                                </td>
                                <td class="cart-action-cell">
                                    <div class="cart-row-actions">
                                        <button type="button"
                                                id="duplikat_<?php echo $no; ?>"
                                                data-id="<?php echo $val['id_rincianinvoice']; ?>"
                                                data-inv="<?php echo $id_invoice; ?>"
                                                data-no='<?php echo $no; ?>'
                                                class='btn btn-success btn-sm flat duplikat cart-action-btn cart-duplicate-btn'
                                                data-toggle='tooltip'
                                                title="Duplikat"
                                                <?php echo $disabled; ?>>
                                            <i class="fa fa-copy"></i>
                                        </button>

                                        <button type="button"
                                                id='button_<?php echo $no; ?>'
                                                class='btn btn-warning btn-sm flat cart-action-btn cart-note-btn'
                                                data-toggle='tooltip'
                                                title="Finishing/Catatan"
                                                onclick="getproduk(<?php echo $no; ?>)"
                                                <?php echo ($status == 'simpan') ? '' : $disabled; ?>>
                                            <i class="fa fa-pencil-square-o"></i>
                                            <span class="note-label">Finishing/Catatan</span>
                                        </button>

                                        <button type="button"
                                                data-no='<?php echo $no; ?>'
                                                class='btn btn-danger btn-sm flat btnDelete cart-action-btn cart-delete-btn'
                                                data-id="<?php echo $val['id_rincianinvoice']; ?>"
                                                data-toggle='tooltip'
                                                title="Hapus"
                                                <?php echo $disabled; ?>>
                                            <i class="fa fa-<?php echo $fa === 'lock' ? 'lock' : 'trash-o'; ?>"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php
                                ++$no;
                                ++$ni;
                            } ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="7" class="cart-items-total">Total Item: <strong id="cart-total-items"><?php echo $no; ?></strong></td>
                                <td colspan="3" class="cart-subtotal-total">Total Sub Total <strong id="cart-total-subtotal">Rp.0</strong></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>

</div><!-- /.keranjang -->

<input type="hidden" name="baris" id="baris" value="<?php echo $no; ?>">
<input type="hidden" name="idnya" id="idnya" value="<?php echo $id_invoice; ?>">

<?php
    $active_printer_options = [];
    if (isset($active_printers) && is_array($active_printers)) {
        foreach ($active_printers as $printer) {
            $active_printer_options[] = [
                'id' => isset($printer['id']) ? (int) $printer['id'] : 0,
                'name' => isset($printer['name']) ? (string) $printer['name'] : '',
                'shared_name' => isset($printer['shared_name']) ? (string) $printer['shared_name'] : '',
                'slug' => isset($printer['slug']) ? (string) $printer['slug'] : '',
                'ukuran_kertas' => isset($printer['ukuran_kertas']) ? (string) $printer['ukuran_kertas'] : '',
                'posisi' => isset($printer['posisi']) ? (string) $printer['posisi'] : '',
            ];
        }
    }
    $active_printer_json = json_encode($active_printer_options, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
?>

<input type="hidden" id="active-cart-printers" value="<?php echo htmlspecialchars($active_printer_json, ENT_QUOTES, 'UTF-8'); ?>">

<script>
    window.activeCartPrinters = <?php echo $active_printer_json; ?>;
    window.cartKomposisiVariantOptions = <?php echo json_encode($komposisiVariantOptions, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE); ?>;

    function syncCartVisualSummary() {
        var itemCount = $('#tablein > tbody > tr').length;
        var subtotal = 0;

        $('#tablein > tbody > tr').each(function(index) {
            var $numberCell = $(this).find('.cart-row-number').first();
            if (!$numberCell.length) {
                return;
            }

            $numberCell.contents().filter(function() {
                return this.nodeType === 3;
            }).remove();
            $numberCell.append(document.createTextNode(index + 1));
        });

        $('#tablein > tbody .totalsz').each(function() {
            subtotal += parseInt(angka($(this).val()), 10) || 0;
        });

        $('#cart-total-items').text(itemCount);
        $('#cart-total-subtotal').text(formatMoney(subtotal, 0, 'Rp.'));

        var taxValue = parseFloat(angka($('#pajaksum').val())) || 0;
        var discountValue = parseFloat(angka($('#potongan_harga').val())) || 0;
        $('.cart-payment-tax').prop('hidden', taxValue <= 0);
        $('.cart-payment-discount').prop('hidden', discountValue <= 0);
    }

    clearInterval(window.cartVisualSummaryTimer);
    window.cartVisualSummaryTimer = setInterval(syncCartVisualSummary, 250);
    syncCartVisualSummary();
    $(document).off('.cartVisualSummary').on('input.cartVisualSummary change.cartVisualSummary', '#tablein input, #tablein select', syncCartVisualSummary);

    function cartKetEscape(value) {
        return String(value == null ? '' : value).replace(/[&<>"']/g, function(match) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            }[match];
        });
    }

    function cartKetInputHtml(row, value) {
        return '<input type="text" class="form-control form-control-sm input next" id="ket_' + row + '" name="ket" value="' + cartKetEscape(value || '-') + '" onfocusout="sav(' + row + ')" required />';
    }

    function cartInitKomposisiVariantSelect(scope) {
        if (typeof $.fn.selectpicker !== 'function') {
            return;
        }

        var $selects = scope ? $(scope).find('.komposisi-variant-ket') : $('.komposisi-variant-ket');
        if ($(scope).is && $(scope).is('.komposisi-variant-ket')) {
            $selects = $selects.add(scope);
        }

        $selects.each(function() {
            var $select = $(this);
            if ($select.data('selectpicker')) {
                $select.selectpicker('refresh');
            } else {
                $select.selectpicker();
            }
        });
    }

    function cartKetSelectHtml(row, options, selected) {
        var selectedValue = String(selected == null ? '' : selected);
        var selectedInOptions = false;
        var html = '<select class="form-control form-control-sm input next komposisi-variant-ket bootstrap-select" id="ket_' + row + '" name="ket" title="Pilih varian" data-live-search="true" data-size="6" data-width="100%" data-container="body" data-none-results-text="Varian tidak ditemukan {0}" onchange="cartKomposisiVariantChanged(' + row + ')" required>';
        html += '<option value="">Pilih varian</option>';

        $.each(options || [], function(idx, option) {
            var value = String((option && option.value) || '');
            var label = String((option && option.label) || value);
            var ukuran = String((option && option.ukuran) || '');
            var isSelected = value === selectedValue;
            if (isSelected) {
                selectedInOptions = true;
            }
            html += '<option value="' + cartKetEscape(value) + '" data-ukuran="' + cartKetEscape(ukuran) + '"' + (isSelected ? ' selected' : '') + '>' + cartKetEscape(label) + '</option>';
        });

        if (selectedValue !== '' && selectedValue !== '-' && !selectedInOptions) {
            html += '<option value="' + cartKetEscape(selectedValue) + '" selected>' + cartKetEscape(selectedValue) + '</option>';
        }

        html += '</select>';
        return html;
    }

    function cartSyncKomposisiVariantUkuran(row, persist) {
        var $ket = $('#ket_' + row);
        var $ukuran = $('#ukuran_' + row);
        if (!$ket.length || !$ukuran.length || !$ket.is('select')) {
            return;
        }

        var $selected = $ket.find('option:selected');
        var ukuran = String($selected.data('ukuran') || '');
        if (ukuran === '' || String($ket.val() || '') === '') {
            return;
        }

        if (String($ukuran.val() || '') !== ukuran) {
            $ukuran.val(ukuran);
            if (typeof ukuranKeranjangSinkronSatuan === 'function') {
                ukuranKeranjangSinkronSatuan(row, ukuran, false);
            }
            if (typeof hitflexi === 'function') {
                hitflexi(row);
            }
            if (typeof doMath === 'function') {
                doMath();
            }
            if (persist && !$ket.is(':disabled') && typeof sav === 'function') {
                sav(row);
            }
        }
    }

    window.cartKomposisiVariantChanged = function(row) {
        cartSyncKomposisiVariantUkuran(row, false);
        if (typeof sav === 'function') {
            sav(row);
        }
    };

    function renderKomposisiVariantKeterangan(row, options, selected) {
        var $ket = $('#ket_' + row);
        if (!$ket.length) {
            return;
        }

        var value = selected;
        if (typeof value === 'undefined' || value === null) {
            value = $ket.val();
        }

        if ($.isArray(options) && options.length > 0) {
            var $group = $ket.closest('.form-group');
            $group.html(cartKetSelectHtml(row, options, value));
            cartInitKomposisiVariantSelect($group);
            cartSyncKomposisiVariantUkuran(row, true);
        } else if ($ket.is('select')) {
            $ket.closest('.form-group').html(cartKetInputHtml(row, value));
        }
    }

    window.refreshKomposisiVariantKeterangan = function(row, idBahan, selected) {
        idBahan = parseInt(idBahan || 0, 10);
        if (!row && row !== 0) {
            return;
        }

        if (idBahan <= 0) {
            renderKomposisiVariantKeterangan(row, [], selected);
            return;
        }

        if (window.cartKomposisiVariantOptions && window.cartKomposisiVariantOptions[idBahan]) {
            renderKomposisiVariantKeterangan(row, window.cartKomposisiVariantOptions[idBahan], selected);
            return;
        }

        $.ajax({
            url: base_url + 'penjualan/komposisi_variant_options',
            type: 'POST',
            dataType: 'json',
            data: { id_bahan: idBahan },
            success: function(response) {
                var options = response && $.isArray(response.options) ? response.options : [];
                window.cartKomposisiVariantOptions = window.cartKomposisiVariantOptions || {};
                if (options.length > 0) {
                    window.cartKomposisiVariantOptions[idBahan] = options;
                }
                renderKomposisiVariantKeterangan(row, options, selected);
            },
            error: function() {
                renderKomposisiVariantKeterangan(row, [], selected);
            }
        });
    };

    $(function() {
        cartInitKomposisiVariantSelect();
        setTimeout(function() {
            $('.komposisi-variant-ket').each(function() {
                var row = String(this.id || '').replace('ket_', '');
                cartSyncKomposisiVariantUkuran(row, true);
            });
        }, 0);
    });

    (function() {
        function escPrinterText(value) {
            return String(value == null ? '' : value).replace(/[&<>"']/g, function(match) {
                return {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#039;'
                }[match];
            });
        }

        function isInvoicePrinter(printer) {
            var slug = String((printer && printer.slug) || '').toLowerCase();
            return slug === 'in' || slug === 'dotmatrix';
        }

        function loadActivePrinters(callback) {
            $.ajax({
                type: 'GET',
                url: base_url + 'produk/active_printers',
                dataType: 'json',
                cache: false,
                data: { _: Date.now() },
                success: function(response) {
                    window.activeCartPrinters = response && $.isArray(response.printers) ? response.printers : [];
                    callback(window.activeCartPrinters);
                },
                error: function() {
                    var printers = $.isArray(window.activeCartPrinters) ? window.activeCartPrinters : [];
                    callback(printers);
                }
            });
        }

        function printUrl(params, printer) {
            var query = printer && printer.id ? '?printer_id=' + encodeURIComponent(printer.id) : '';
            if (isInvoicePrinter(printer)) {
                return base_url + 'produk/print_invoice_html/' + params.encrypt_url + query;
            }
            return base_url + 'produk/print_thermal_raw/' + params.encrypt_url + query;
        }

        function openSelectedPrinter(params, printer) {
            $('#OpenCart-1').modal('hide');
            if (typeof searchFilter === 'function') {
                searchFilter();
            }
            window.open(printUrl(params, printer), '_blank');
        }

        window.showCartPrinterOptions = function(params, printers) {
            var html = '<div class="cart-printer-options">';
            $.each(printers, function(idx, printer) {
                var shared = printer.shared_name || '';
                var paper = printer.ukuran_kertas ? 'Kertas ' + printer.ukuran_kertas : '';
                var position = printer.posisi ? ' - ' + printer.posisi : '';
                var label = isInvoicePrinter(printer) ? 'Cetak invoice' : 'Cetak struk invoice';
                var icon = isInvoicePrinter(printer) ? 'fa-file-text-o' : 'fa-print';

                html += '<button type="button" class="cart-printer-option" data-printer-id="' + escPrinterText(printer.id) + '">' +
                    '<strong><i class="fa ' + icon + '"></i> ' + escPrinterText(printer.name || shared || 'Printer') + '</strong>' +
                    '<small>' + escPrinterText(label) + (shared ? ' - ' + escPrinterText(shared) : '') + (paper ? ' - ' + escPrinterText(paper + position) : '') + '</small>' +
                    '</button>';
            });
            html += '</div>';
            window.pendingCartPrintParams = params;

            Swal.fire({
                title: 'Pilih printer aktif',
                html: html,
                showConfirmButton: false,
                showCloseButton: true,
                allowOutsideClick: false,
                width: 520
            });
        };

        $(document).off('click.cartPrinterOption').on('click.cartPrinterOption', '.cart-printer-option', function() {
            var printerId = String($(this).data('printer-id'));
            var params = window.pendingCartPrintParams;
            var printers = $.isArray(window.activeCartPrinters) ? window.activeCartPrinters : [];
            var selected = null;

            $.each(printers, function(idx, printer) {
                if (String(printer.id) === printerId) {
                    selected = printer;
                    return false;
                }
            });

            Swal.close();
            if (params && selected) {
                openSelectedPrinter(params, selected);
            }
        });

        window.handlePrintOrderRaw = function(params) {
            if (!params || params.status != 200) {
                if ($('body').loading) $('body').loading('stop');
                return;
            }

            loadActivePrinters(function(printers) {
                if (printers.length > 1) {
                    window.showCartPrinterOptions(params, printers);
                } else if (printers.length === 1) {
                    openSelectedPrinter(params, printers[0]);
                } else {
                    Swal.fire('Printer belum aktif', 'Aktifkan minimal satu printer di Pengaturan printer.', 'warning');
                }
                if ($('body').loading) $('body').loading('stop');
            });
        };

        window.cetak_invoice = function(invoiceId) {
            $.ajax({
                type: 'POST',
                url: base_url + 'produk/print_cek',
                data: { id: invoiceId },
                dataType: 'json',
                cache: false,
                beforeSend: function() {
                    if ($('body').loading) $('body').loading();
                },
                success: window.handlePrintOrderRaw,
                error: function(res, status, httpMessage) {
                    sweet('Peringatan!!!', httpMessage, 'warning', 'warning');
                    if ($('body').loading) $('body').loading('stop');
                }
            });
        };
    })();

    var komisiSalesAktif = <?= $komisi_sales_aktif ? 'true' : 'false'; ?>;
	var komisiPenjualanAktif = <?= $komisi_penjualan_aktif ? 'true' : 'false'; ?>;
	function saveKomisiPenjualan(){ if(!komisiPenjualanAktif)return; var id=$('#idnya').val(); if(!id)return; $.post(base_url+'penjualan/save-komisi-penjualan-invoice',{id:id,sales_penjualan:$('#sales_penjualan').val()||0}); }
	$(document).on('change','#sales_penjualan',saveKomisiPenjualan);

    function komisiSalesPayload() {
		var result = {};
		if (komisiSalesAktif) result.sales_komisi = $('#sales_komisi').length ? $('#sales_komisi').val() : 0;
		if (komisiPenjualanAktif) result.sales_penjualan = $('#sales_penjualan').length ? $('#sales_penjualan').val() : 0;
		return result;
    }

    function save_komisi_invoice() {
        if (!komisiSalesAktif) {
            return;
        }

        var id = $('#idnya').val();
        if (!id || parseInt(id, 10) <= 0) {
            return;
        }

        $.ajax({
            url: base_url + 'penjualan/save-komisi-invoice',
            type: 'POST',
            dataType: 'json',
            data: $.extend({ id: id }, komisiSalesPayload())
        });
    }

    if (!window.__komisiSalesAjaxPatch && typeof $ !== 'undefined' && $.ajaxPrefilter) {
        window.__komisiSalesAjaxPatch = true;

        $.ajaxPrefilter(function(options, originalOptions) {
            var url = options && options.url ? String(options.url) : '';
            var isKomisiRequest =
                url.indexOf('penjualan/update_data') !== -1 ||
                url.indexOf('penjualan/save_bayar') !== -1 ||
                url.indexOf('penjualan/save_bayar_piutang') !== -1;

            if (!isKomisiRequest) {
                return;
            }
            if (!komisiSalesAktif && !komisiPenjualanAktif) {
                return;
            }

            var komisiPayload = komisiSalesPayload();
            var data = originalOptions && typeof originalOptions.data !== 'undefined'
                ? originalOptions.data
                : options.data;

            if (window.FormData && data instanceof FormData) {
                if (typeof data.set === 'function') {
                    data.set('sales_komisi', komisiPayload.sales_komisi);
                } else {
                    data.append('sales_komisi', komisiPayload.sales_komisi);
                }
                options.data = data;
                return;
            }

            if ($.isPlainObject(data)) {
                options.data = $.param($.extend({}, data, komisiPayload));
                return;
            }

            var extra = $.param(komisiPayload);

            if (typeof data === 'string' && data !== '') {
                options.data = data + '&' + extra;
            } else {
                options.data = extra;
            }
        });
    }

    function save_invoice() {
        var id = $('#idnya').val();
        if (!id || parseInt(id, 10) <= 0) {
            return;
        }

        function toIsoDate(value) {
            var parts = String(value || '').split('/');
            return parts.length === 3 ? parts[2] + '-' + parts[1] + '-' + parts[0] : value;
        }

        var payload = {
            id: id,
            tglin: toIsoDate($('#tgl_invoice').val()),
            tgla: toIsoDate($('#tgl_ambil').val()),
            jam: $('#jam_ambil').val(),
            marketing: $('#marketing').val()
        };
        payload = $.extend(payload, komisiSalesPayload());

        if ($('#referal').length) {
            payload.referal = $('#referal').val();
        }

        $.ajax({
            url: base_url + 'penjualan/auto_save_invoice',
            type: 'POST',
            dataType: 'json',
            data: payload
        });

        save_komisi_invoice();
    }

    function cektgl() {
        save_invoice();
    }

    function cektglpesan() {
        save_invoice();
    }

    $(document).on('change blur', '#sales_komisi', function() {
        updateKomisiDesainState();
        save_komisi_invoice();
    });

    var komisiDesainItemRequired = null;

    function refreshKomisiDesainRequirement(callback) {
        if (!komisiSalesAktif) {
            komisiDesainItemRequired = false;
            updateKomisiDesainState();
            if (typeof callback === 'function') {
                callback(false);
            }
            return;
        }

        var id = $('#idnya').val();
        if (!id || parseInt(id, 10) <= 0) {
            komisiDesainItemRequired = false;
            updateKomisiDesainState();
            if (typeof callback === 'function') {
                callback(false);
            }
            return;
        }

        $.ajax({
            url: base_url + 'penjualan/komisi_desain_required',
            type: 'POST',
            dataType: 'json',
            data: { id: id },
            success: function(response) {
                komisiDesainItemRequired = !!(response && response.required);
                updateKomisiDesainState();
                if (typeof callback === 'function') {
                    callback(komisiDesainItemRequired);
                }
            },
            error: function() {
                komisiDesainItemRequired = true;
                updateKomisiDesainState();
                if (typeof callback === 'function') {
                    callback(true);
                }
            }
        });
    }

    function komisiDesainIsFilled() {
        if (!komisiSalesAktif || !$('#sales_komisi').length || $('#sales_komisi').is(':disabled')) {
            return true;
        }

        return parseInt($('#sales_komisi').val() || 0, 10) > 0;
    }

    function updateKomisiDesainState() {
        var required = komisiDesainItemRequired === true;
        var filled = komisiDesainIsFilled();
        $('#komisi_desain_wrap').toggleClass('komisi-desain-missing', required && !filled);
        $('#komisi_desain_wrap').toggleClass('komisi-desain-filled', required && filled);
        $('#komisi_desain_wrap').toggleClass('komisi-desain-not-required', !required);
        $('#komisi_desain_hint').text(required ? 'Wajib pilih karyawan sebelum bayar atau cetak order' : ' ');
    }

    function showKomisiDesainReminder() {
        updateKomisiDesainState();
        if (typeof Swal !== 'undefined' && Swal.fire) {
            Swal.fire('Komisi Desain belum dipilih', 'Pilih nama karyawan pada kolom Komisi Desain sebelum melanjutkan.', 'warning');
        } else if (typeof sweet === 'function') {
            sweet('Peringatan!!!', 'Pilih nama karyawan pada kolom Komisi Desain sebelum melanjutkan.', 'warning', 'warning');
        } else if (typeof showNotif === 'function') {
            showNotif('top-center', 'Komisi Desain', 'Pilih nama karyawan terlebih dahulu', 'warning');
        } else {
            alert('Pilih nama karyawan pada kolom Komisi Desain sebelum melanjutkan.');
        }

        setTimeout(function() {
            $('#sales_komisi').focus();
        }, 250);
    }

    refreshKomisiDesainRequirement();
    window.__komisiDesainGuardReminder = showKomisiDesainReminder;

    if (!window.__komisiDesainRequiredGuard) {
        window.__komisiDesainRequiredGuard = true;
        window.__komisiDesainGuardBypass = false;
        function blockKomisiDesainAction(target, event) {
            event.preventDefault();
            event.stopPropagation();
            if (typeof event.stopImmediatePropagation === 'function') {
                event.stopImmediatePropagation();
            }
            refreshKomisiDesainRequirement(function(required) {
                if (required && !komisiDesainIsFilled()) {
                    if (typeof window.__komisiDesainGuardReminder === 'function') {
                        window.__komisiDesainGuardReminder();
                    }
                    return;
                }

                window.__komisiDesainGuardBypass = true;
                target.click();
            });
        }

        document.addEventListener('click', function(event) {
            var target = event.target && event.target.closest ? event.target.closest('#bayarin, .bayarin, #print, .print') : null;
            if (!target || target.disabled) {
                return;
            }
            if (window.__komisiDesainGuardBypass) {
                window.__komisiDesainGuardBypass = false;
                return;
            }
            if (!komisiSalesAktif || komisiDesainIsFilled()) {
                return;
            }

            blockKomisiDesainAction(target, event);
        }, true);

        document.addEventListener('keydown', function(event) {
            if (!event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) {
                return;
            }

            var key = String(event.key || '').toLowerCase();
            if (key !== 'b' && key !== 'p') {
                return;
            }
            if (!komisiSalesAktif || komisiDesainIsFilled()) {
                return;
            }

            var target = key === 'b'
                ? document.querySelector('#bayarin, .bayarin')
                : document.querySelector('#print, .print');

            if (!target || target.disabled) {
                return;
            }

            blockKomisiDesainAction(target, event);
        }, true);
    }

	if (komisiPenjualanAktif && !window.__komisiPenjualanGuard) {
		window.__komisiPenjualanGuard = true;
		window.__komisiPenjualanBypass = false;
		document.addEventListener('click', function(event){
			var target=event.target&&event.target.closest?event.target.closest('#bayarin, .bayarin, #print, .print'):null;
			if(!target||target.disabled||window.__komisiPenjualanBypass){ window.__komisiPenjualanBypass=false; return; }
			var id=$('#idnya').val(); if(!id)return;
			event.preventDefault(); event.stopPropagation(); if(event.stopImmediatePropagation)event.stopImmediatePropagation();
			$.post(base_url+'penjualan/komisi-penjualan-required',{id:id},function(resp){
				var required=!!(resp&&resp.required), filled=parseInt($('#sales_penjualan').val()||0,10)>0;
				$('#komisi_penjualan_wrap').toggleClass('komisi-desain-missing',required&&!filled);
				$('#komisi_penjualan_hint').text(required?'Wajib pilih karyawan penjualan sebelum bayar atau cetak order':'');
				if(required&&!filled){ if(typeof Swal!=='undefined'&&Swal.fire)Swal.fire('Komisi Penjualan belum dipilih','Pilih nama karyawan untuk komisi penjualan sebelum melanjutkan.','warning'); $('#sales_penjualan').focus(); return; }
				window.__komisiPenjualanBypass=true; target.click();
			},'json');
		},true);
	}

    // Date picker dan time picker khusus agar konsisten di semua browser.
    var $cartDateInputs = $('#tgl_invoice, #tgl_ambil');
    $cartDateInputs.each(function () {
        if ($(this).data('datepicker')) $(this).datepicker('destroy');
    });
    var cartDatePickerOptions = {
        format: 'dd/mm/yyyy',
        language: 'id',
        autoclose: true,
        todayHighlight: true,
        enableOnReadonly: false,
        container: '#OpenCart-1 .cart-modal-content',
        orientation: 'bottom auto'
    };

    var $orderDateInput = $('#tgl_invoice');
    var orderDateLockedToToday = $orderDateInput.attr('data-lock-today') === '1';
    var orderDateToday = String($orderDateInput.attr('data-today') || '');
    var orderDatePickerOptions = $.extend({}, cartDatePickerOptions);
    if (orderDateLockedToToday) {
        orderDatePickerOptions.startDate = orderDateToday;
        orderDatePickerOptions.endDate = orderDateToday;
    }

    function showOrderDateWarning() {
        if (typeof sweet === 'function') {
            sweet('Tanggal order tidak sesuai', 'Tanggal order harus menggunakan tanggal hari ini.', 'warning', 'warning');
        }
    }

    function validateOrderDate(showWarning) {
        if (!orderDateLockedToToday || String($orderDateInput.val() || '') === orderDateToday) {
            return true;
        }
        $orderDateInput.val(orderDateToday);
        if ($orderDateInput.data('datepicker')) {
            $orderDateInput.datepicker('update', orderDateToday);
        }
        window.setTimeout(function () {
            $orderDateInput.val(orderDateToday);
        }, 0);
        if (showWarning) {
            showOrderDateWarning();
        }
        return false;
    }

    function normalizeCartDateDisplay($field) {
        var value = String($field.val() || '');
        var isoMatch = value.match(/^(\d{4})-(\d{2})-(\d{2})$/);
        if (isoMatch) {
            $field.val(isoMatch[3] + '/' + isoMatch[2] + '/' + isoMatch[1]);
        }
    }

    function initializeCartDatePicker($field) {
        normalizeCartDateDisplay($field);
        if (!$field.data('datepicker')) {
            $field.datepicker($field.is('#tgl_invoice') ? orderDatePickerOptions : cartDatePickerOptions);
        }
    }

    function bindDisabledOrderDateWarnings() {
        if (!orderDateLockedToToday || !$activeCartDateField.is('#tgl_invoice')) {
            return;
        }
        $('.datepicker-dropdown:visible .datepicker-days td.day.disabled')
            .off('.orderDateDisabled')
            .on('mousedown.orderDateDisabled touchstart.orderDateDisabled', function (event) {
                event.preventDefault();
                event.stopImmediatePropagation();
                $orderDateInput.val(orderDateToday);
                showOrderDateWarning();
                return false;
            });
    }

    var $activeCartDateField = $();
    $cartDateInputs.off('.cartDatePicker');
    initializeCartDatePicker($('#tgl_invoice'));
    initializeCartDatePicker($('#tgl_ambil'));
    $cartDateInputs
        .on('changeDate.cartDatePicker', function (event) {
            event.stopPropagation();
            if ($(this).is('#tgl_invoice') && !validateOrderDate(true)) {
                return;
            }
            save_invoice();
        })
        .on('change.cartDatePicker', function (event) {
            // changeDate di atas adalah satu-satunya pemicu autosave tanggal.
            // Cegah event change buatan plugin merambat ke handler halaman.
            event.stopPropagation();
            if ($(this).is('#tgl_invoice')) {
                validateOrderDate(true);
            }
        })
        .on('click.cartDatePicker', function () {
            var $field = $(this);
            $activeCartDateField = $field;
            initializeCartDatePicker($field);
            $field.datepicker('show');
            window.setTimeout(bindDisabledOrderDateWarnings, 0);
        });

    $(document)
        .off('change.deadlineNativeTime', '#jam_ambil')
        .on('change.deadlineNativeTime', '#jam_ambil', function (event) {
            event.stopPropagation();
            save_invoice();
        });

    var $deadlineClockInput = $('#jam_ambil');
    if ($deadlineClockInput.data('clockpicker')) {
        $deadlineClockInput.clockpicker('remove');
        $deadlineClockInput.removeData('clockpicker');
    }

    var deadlineClockOptions = {
        autoclose: true,
        placement: 'bottom',
        align: 'right',
        donetext: 'Pilih',
        twelvehour: false,
        afterDone: function () {
            cektgl();
        }
    };

    function initializeDeadlineClock($field) {
        $field = $field && $field.length ? $field : $('#jam_ambil');
        if (!$field.data('clockpicker')) {
            $field.clockpicker(deadlineClockOptions);
        }
        return $field;
    }

    window.openDeadlineClockPicker = function (event) {
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }

        var $field = $('#jam_ambil');
        var field = $field.get(0);
        if (field && typeof field.showPicker === 'function') {
            field.showPicker();
            return;
        }

        if (field && $field.attr('type') === 'time') {
            field.focus();
            return;
        }

        if ($field.data('clockpicker')) {
            $field.clockpicker('remove');
            $field.removeData('clockpicker');
        }

        initializeDeadlineClock($field).clockpicker('show');
    };

    $deadlineClockInput.off('.cartClockPicker');
    if ($deadlineClockInput.attr('type') !== 'time') {
        initializeDeadlineClock($deadlineClockInput);
    }

    $(document)
        .off('click.cartClockPicker', '.deadline-clock-trigger')
        .on('click.cartClockPicker', '.deadline-clock-trigger', function (event) {
            event.preventDefault();
            event.stopPropagation();
            initializeDeadlineClock($('#jam_ambil')).clockpicker('show');
        })
        .off('focusin.cartClockPicker click.cartClockPicker', '#jam_ambil')
        .on('focusin.cartClockPicker click.cartClockPicker', '#jam_ambil', function (event) {
            event.stopPropagation();
            initializeDeadlineClock($(this)).clockpicker('show');
        });

    // Popup picker adalah bagian dari keranjang; jangan biarkan kliknya
    // diteruskan sebagai klik backdrop modal.
    $(document)
        .off('mousedown.cartPicker click.cartPicker', '.datepicker-dropdown, .clockpicker-popover')
        .on('mousedown.cartPicker click.cartPicker', '.datepicker-dropdown, .clockpicker-popover', function (event) {
            event.stopPropagation();
        });

    $('#OpenCart-1')
        .off('hidden.bs.modal.cartPickers')
        .on('hidden.bs.modal.cartPickers', function () {
            $cartDateInputs.each(function () {
                if ($(this).data('datepicker')) $(this).datepicker('destroy');
            });
            var $currentDeadlineClock = $('#jam_ambil');
            if ($currentDeadlineClock.data('clockpicker')) {
                $currentDeadlineClock.clockpicker('remove');
                $currentDeadlineClock.removeData('clockpicker');
            }
            $('.datepicker-dropdown, .clockpicker-popover').remove();
        });

    // Keranjang baru menampilkan jam berjalan sampai disimpan. Saat transaksi
    // lama dibuka kembali, tampilkan jam_order tersimpan tanpa mengubahnya.
    (function() {
        var jamOrder = document.getElementById('jam_order');
        if (!jamOrder) return;

        var isPersistedOrderView = <?php echo isset($echo) && (int) $echo === 0 ? 'true' : 'false'; ?>;
        if (isPersistedOrderView) return;

        function setNow(){
            var timezone = jamOrder.getAttribute('data-timezone') || 'Asia/Jakarta';
            try {
                jamOrder.value = new Intl.DateTimeFormat('id-ID', {
                    timeZone: timezone,
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                }).format(new Date()).replace(/\./g, ':');
            } catch (error) {
                // Pertahankan nilai dari server jika browser tidak mendukung timezone IANA.
            }
        }

        setNow();
        setInterval(setNow, 1000);
    })();


    function applyFinishingLabel() {
        $('#tablein tbody tr').each(function() {
            var $btn = $(this).find("button[id^='button_']");
            if ($btn.length) {
                $btn.addClass('cart-action-btn cart-note-btn').attr('title', 'Finishing/Catatan').attr('data-toggle', 'tooltip');
                var rawText = $.trim($btn.text());
                if (rawText === '' || rawText === '...' || rawText === '…' || rawText === 'Isi Catatan') {
                    $btn.html('<i class="fa fa-pencil-square-o"></i><span class="note-label">Finishing/Catatan</span>');
                }
            }
        });
    }

    function onScanSuccess(decodedText, decodedResult) {
        $("#cari_produk").val(decodedText);
        $("#formcheckin").submit();
        $("#button-qr").modal('hide');
        html5QrcodeScanner.clear();
    }

    $(document).on('click', '.show_qr', function(e) {
        e.preventDefault();
        $('#cari_qr').val('');
        var html5QrcodeScanner = new Html5QrcodeScanner(
            "qr-reader",
            { fps: 10, qrbox: 250 }
        );

        html5QrcodeScanner.render(onScanSuccess);
        $('#button-qr').modal({
            backdrop: 'static',
            keyboard: false
        });
    });

    setTimeout(function() {
        $("#cari_produk").focus();
    }, 500);

    applyFinishingLabel();

    $('#formcheckin').submit(function(e) {
        e.preventDefault();
        e.stopPropagation();

        if ($("#cari_produk").val() == '') {
            $("#cari_produk").addClass('form-control-warning');
            showNotif('top-center', 'Input Data', 'Harus diisi', 'warning');
            $("#cari_produk").focus();
            return;
        }
        var id_detail = $('#tablein > tbody tr').length;
        const maindata = $('#formcheckin').serializeArray().concat({
            name: "id_detail",
            value: id_detail
        });

        $.ajax({
            url: base_url + "penjualan/cek_harga_type",
            type: "POST",
            data: maindata,
            dataType: "json",
            success: handleMember
        });
    });

    function handleMember(response) {
        if (response.status == 'qr') {

            var id            = response.id;
            var id_detail     = response.iddetail;
            var id_bahan      = response.id_bahan;
            var status_hitung = response.status_hitung;
            var ukuran        = response.ukuran;
            var harga         = response.harga;

            add_more(id, id_detail, id_bahan, status_hitung, ukuran, harga)

            $("#id_rincianinvoice_" + id_detail).val(response.id);
            $('#kodeproduk_' + id_detail).val(response.kodeproduk).attr('disabled', true);
            $('#id_produk_' + id_detail).val(response.id_produk);
            $('#harga_satuan_' + id_detail).val(hargaKeranjangNumber(response.harga));
            $('#harga_' + id_detail).val(hargaKeranjangFormat(response.harga));
            $('#diskon_' + id_detail).val(0);
            $('#jenis_cetakan_' + id_detail).val(response.jenis_cetakan);
            $('#bahan_' + id_detail).val(response.bahan).attr('disabled', true);
            $('#id_bahan_' + id_detail).val(response.id_bahan);
            load_satuan(id_detail, response.id_satuan);
            $('#id_jenis_' + id_detail).val(response.id_jenis);
            $('#status_hitung_' + id_detail).val(response.status_hitung);
            $('#type_harga_' + id_detail).val(response.type_harga);
            $('#id_satuan_' + id_detail).val(response.id_satuan);
            $('#ukuran_' + id_detail).val(response.ukuran).attr('disabled', true);
            $('#ket_' + id_detail).val('-').attr('disabled', true);
            if (typeof refreshKomposisiVariantKeterangan === 'function') {
                refreshKomposisiVariantKeterangan(id_detail, response.id_bahan, '');
            }
            $('#jumlah_' + id_detail).val(response.jumlah).attr('disabled', true);
            $('#lock_' + id_detail).val(response.lock_harga);
            $('#satuan_' + id_detail).val(response.id_satuan).attr('disabled', true);

            $('#satuan_' + id_detail.toString() + '  option[value="' + response.id_satuan + '"]').prop("selected", true);

            if (response.lock_harga == 'Y') {
                $('#harga_' + id_detail).attr('readonly', true);
            }
            if (type_harga == 2 || type_harga == 6) {
                $('#satuan_' + id_detail).prop('disabled', false).attr('readonly', false);
            }
            $('#duplikat_' + id_detail).attr('disabled', true);

            doMath();
            setTimeout(function() {
                saved(id_detail)
            }, 1000);

        } else if (response.status == false) {
            $("#cari_produk").focus();
            showNotif('top-center', 'Input Data', response.msg, 'warning');
        } else {
            var id_produk       = $("#id_produk").val();
            var kodeproduk_     = $("#kodeproduk").val();
            var harga_          = $("#harga").val();
            var jenis_cetakan_  = $("#jenis_cetakan").val();
            var bahan_          = $("#bahan").val();
            var id_jenis_       = $("#id_jenis").val();
            var id_bahan_       = $("#id_bahan").val();
            var status_hitung   = $("#status_hitung").val();
            var type_harga      = $("#type_harga").val();
            var satuan_add      = parseInt($("#satuan_add").val());
            var ukuran_         = $("#ukuran").val();
            var jumlah_         = $("#jumlah").val();
            var lock_           = $("#lock").val();

            id_detail = $('#tablein > tbody tr').length;
            $(".addmore").click();

            $('#kodeproduk_' + id_detail).val(kodeproduk_);
            $('#id_produk_' + id_detail).val(id_produk);
            $('#ket_' + id_detail).val('-');
            $('#harga_satuan_' + id_detail).val(hargaKeranjangNumber(response.harga));
            $('#harga_' + id_detail).val(hargaKeranjangFormat(response.harga));
            $('#diskon_' + id_detail).val(0);
            $('#jenis_cetakan_' + id_detail).val(jenis_cetakan_);
            $('#bahan_' + id_detail).val(bahan_);
            $('#id_jenis_' + id_detail).val(id_jenis_);
            $('#id_bahan_' + id_detail).val(id_bahan_);
            load_satuan(id_detail, satuan_add);
            $('#status_hitung_' + id_detail).val(status_hitung);
            $('#type_harga_' + id_detail).val(type_harga);
            $('#id_satuan_' + id_detail).val(satuan_add);
            $('#ukuran_' + id_detail).val(ukuran_);
            if (typeof refreshKomposisiVariantKeterangan === 'function') {
                refreshKomposisiVariantKeterangan(id_detail, id_bahan_, '');
            }
            $('#jumlah_' + id_detail).val(jumlah_);
            $('#lock_' + id_detail).val(lock_);
            $('#satuan_' + id_detail).val(satuan_add);

            $('#satuan_' + id_detail.toString() + '  option[value="' + satuan_add + '"]').prop("selected", true);

            if (lock_ == 'Y') {
                $('#harga_' + id_detail).attr('readonly', true);
            }
            if (type_harga == 2 || type_harga == 6) {
                $('#satuan_' + id_detail).prop('disabled', false).attr('readonly', false);
            }
            doMath();
            setTimeout(function() {
                saved(id_detail)
            }, 3000);
        }

        applyFinishingLabel();
        reset_input()
    }

    function reset_input() {
        $('#cari_produk').val('');
        $('#kodeproduk').val('');
        $('#id_produk').val('');
        $('#harga').val(0);
        $('#harga_satuan_').val(0);
        $('#jenis_cetakan').val('');
        $('#bahan').val('');
        $('#id_jenis').val('');
        $('#id_bahan').val('');
        $('#type_harga').val('');
        $('#status_hitung').val('');
        $('#satuan').val('');
        $('#ukuran').val('');
        $('#jumlah').val('');
        $('#lock').val('');
    }

    doMath();
    window.onload = doMath;

    $(function() {
        $('[data-toggle="tooltip"]').tooltip()
    });

    $(document).fcs(".next");

</script>

<?php } else {
    echo 'error';
} ?>

<style>
/* =========================================================
   TARGET PERBAIKAN (AREA MERAH):
   - PC normal: tetap 1 baris (input + 3 tombol)
   - Laptop Windows scale 150%: tampilannya mirip iPad (input full, tombol grid)
   - iPad & Smartphone: pertahankan rules lama (tidak berubah)
   ========================================================= */

:root{
  --bg-page:#f5f6f8;
  --bg-card:#ffffff;
  --border:#dcdfe4;
  --text-main:#1f2937;
  --text-muted:#6b7280;
  --radius:.5rem;
  --font-size:.9rem;

  --btn-dark:#1f2937;
  --btn-green:#10b981;
  --btn-blue:#3b82f6;
}

.keranjang#container{
  background:var(--bg-page);
  border-radius:var(--radius);
  padding:1rem;
}

.simple-section > [class*="col-"]{ display:flex; }
.simple-section > [class*="col-"] > .simple-card{ width:100%; }

.simple-card{
  background:var(--bg-card);
  border:1px solid var(--border);
  border-radius:var(--radius);
  padding:.75rem 1rem;
  margin-bottom:1rem;
  display:flex;
  flex-direction:column;
  height:100%;
  min-width:0;
  overflow:hidden;
}

.cust-header strong{
  font-weight:600;
  color:var(--text-main);
  line-height:1.4;
  font-size:.9rem;
  max-width:100%;
  display:block;
  text-overflow:ellipsis;
  white-space:nowrap;
  overflow:hidden;
}

.info-line{
  display:flex;
  justify-content:space-between;
  flex-wrap:wrap;
  gap:.35rem;
  font-size:var(--font-size);
  margin-bottom:.4rem;
}
.info-label{ color:var(--text-muted); font-weight:500; }
.info-value{ color:var(--text-main); font-weight:600; text-align:right; }

.mini-label{
  font-size:.8rem;
  font-weight:700;
  text-transform:uppercase;
  color:var(--text-muted);
  margin-bottom:.25rem;
  display:block;
}

.form-control,
.form-control-sm,
.input-group-text{
  font-size:var(--font-size);
  border-radius:.35rem !important;
}

input[readonly]{
  background:#f9fafb !important;
  color:#6b7280 !important;
  pointer-events:none;
}

.order-time-wrap #tgl_invoice,
.selesai-wrap #tgl_ambil{ flex:0 1 140px; max-width:140px; }
#jam_order,
#jam_ambil{ min-width:96px; text-align:center; font-variant-numeric:tabular-nums; }
.modern-date-input{
  padding-right:34px !important;
  background-color:#fff !important;
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='18' height='18' viewBox='0 0 24 24' fill='none' stroke='%232563eb' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3.5' y='5.5' width='17' height='15' rx='2'/%3E%3Cpath d='M8 3.5v4M16 3.5v4M3.5 10h17'/%3E%3C/svg%3E") !important;
  background-repeat:no-repeat !important;
  background-position:right 9px center !important;
  cursor:pointer;
}
.modern-picker-icon{
  min-width:38px;
  justify-content:center;
  border-color:#cfd9e8 !important;
  background:#f4f7fc !important;
  color:#2563eb !important;
}
.modern-picker-icon svg{ width:17px; height:17px; fill:none; stroke:currentColor; stroke-width:1.8; stroke-linecap:round; stroke-linejoin:round; }
.deadline-clock-trigger{ cursor:pointer; transition:background .18s,color .18s; }
.deadline-clock-trigger:hover{ background:#eaf1ff !important; color:#174fc4 !important; }
.modern-time-input{ cursor:pointer; letter-spacing:.035em; }
.modern-date-input:focus,.modern-time-input:focus{ position:relative; z-index:3; border-color:#2563eb !important; box-shadow:0 0 0 3px rgba(37,99,235,.12) !important; }

/* Datepicker modern, terbatas pada halaman keranjang. */
.datepicker-dropdown{
  padding:12px !important;
  border:1px solid #dce4f0 !important;
  border-radius:12px !important;
  box-shadow:0 16px 38px rgba(30,50,80,.18) !important;
  font-family:inherit;
}
.datepicker table tr td,.datepicker table tr th{ width:34px !important; height:32px !important; border-radius:8px !important; font-size:12px; }
.datepicker table tr th.datepicker-switch{ color:#17233a; font-weight:700; }
.datepicker table tr td.day:hover,.datepicker table tr td.focused{ background:#eef4ff !important; color:#1d5bd1 !important; }
.datepicker table tr td.active,.datepicker table tr td.active:hover{ background:#2563eb !important; color:#fff !important; text-shadow:none !important; }
.datepicker table tr td.today{ border:1px solid #93b6f4 !important; background:#f4f8ff !important; color:#174fc4 !important; }
.datepicker .datepicker-switch:hover,.datepicker .prev:hover,.datepicker .next:hover{ background:#eef4ff !important; }

/* Clockpicker modern untuk jam deadline. */
.clockpicker-popover{ overflow:hidden; border:1px solid #dce4f0 !important; border-radius:12px !important; box-shadow:0 16px 38px rgba(30,50,80,.18) !important; }
.clockpicker-popover .popover-title{ padding:12px 14px !important; border-bottom:1px solid #e7edf6 !important; background:#f7f9fc !important; color:#17233a; font-weight:700; }
.clockpicker-popover .popover-content{ padding:14px !important; background:#fff; }
.clockpicker-plate{ border-color:#dce4f0 !important; background:#f7f9fc !important; }
.clockpicker-tick{ color:#344159; }
.clockpicker-canvas line{ stroke:#2563eb !important; }
.clockpicker-canvas-bg,.clockpicker-canvas-bearing{ fill:#2563eb !important; }
.clockpicker-canvas-fg{ fill:#2563eb !important; }
.clockpicker-button{ border:0 !important; border-radius:7px !important; background:#2563eb !important; color:#fff !important; font-weight:700; }

.komisi-desain-wrap{
  position:relative;
  border:2px solid #f59e0b;
  border-radius:.55rem;
  padding:.55rem .65rem .6rem;
  background:#fffbeb;
  box-shadow:0 8px 20px rgba(245,158,11,.18);
}

.komisi-desain-label{
  display:flex;
  align-items:center;
  gap:.4rem;
  color:#92400e;
  letter-spacing:.02rem;
}

.komisi-desain-label i{
  color:#ea580c;
  font-size:.95rem;
}

.komisi-desain-control{
  box-shadow:0 6px 14px rgba(146,64,14,.16);
  border-radius:.45rem;
}

.komisi-desain-icon{
  background:#ea580c !important;
  border-color:#ea580c !important;
  color:#fff !important;
  min-width:38px;
  justify-content:center;
}

#sales_komisi{
  border-color:#ea580c !important;
  color:#111827;
  font-weight:700;
  background:#fff !important;
}

#sales_komisi:focus{
  border-color:#f97316 !important;
  box-shadow:0 0 0 .18rem rgba(249,115,22,.24) !important;
}

.komisi-desain-hint{
  margin-top:.35rem;
  font-size:.72rem;
  line-height:1.25;
  color:#92400e;
  font-weight:700;
}

.komisi-desain-missing{
  animation:komisiDesainPulse 1.35s ease-in-out infinite;
}

.komisi-desain-filled{
  border-color:#16a34a;
  background:#f0fdf4;
  box-shadow:0 8px 20px rgba(22,163,74,.16);
}

.komisi-desain-filled .komisi-desain-label,
.komisi-desain-filled .komisi-desain-hint{
  color:#166534;
}

.komisi-desain-filled .komisi-desain-label i{
  color:#16a34a;
}

.komisi-desain-filled .komisi-desain-icon{
  background:#16a34a !important;
  border-color:#16a34a !important;
}

.komisi-desain-filled #sales_komisi{
  border-color:#16a34a !important;
}

.komisi-desain-not-required{
  border-color:#d1d5db;
  background:#f9fafb;
  box-shadow:none;
}

.komisi-desain-not-required .komisi-desain-label,
.komisi-desain-not-required .komisi-desain-hint{
  color:#6b7280;
}

.komisi-desain-not-required .komisi-desain-label i{
  color:#6b7280;
}

.komisi-desain-not-required .komisi-desain-icon{
  background:#6b7280 !important;
  border-color:#6b7280 !important;
}

.komisi-desain-not-required #sales_komisi{
  border-color:#d1d5db !important;
}

@keyframes komisiDesainPulse{
  0%,100%{ box-shadow:0 8px 20px rgba(245,158,11,.18); }
  50%{ box-shadow:0 0 0 .22rem rgba(245,158,11,.22), 0 10px 24px rgba(245,158,11,.26); }
}

/* =========================
   Tombol pelanggan
   ========================= */
.cust-card .cust-actions{
  display:grid;
  grid-template-columns: 1fr 1fr;
  gap:.5rem;
}
.cust-card .cust-actions .cari{ grid-column: 1 / -1; }
.cust-card .cust-actions.cust-actions-no-dropship{
  grid-template-columns: 1fr;
}
.cust-card .cust-actions.cust-actions-no-dropship .tambah{
  grid-column: 1 / -1;
}

.cust-card .cust-actions .btn{
  display:flex;
  align-items:center;
  justify-content:center;
  gap:.45rem;
  border:none;
  border-radius:.45rem;
  font-size:.8rem;
  font-weight:800;
  line-height:1.2;
  padding:.55rem .7rem;
  color:#fff !important;
  box-shadow:0 6px 14px rgba(0,0,0,.12);
  text-transform:uppercase;
  letter-spacing:.02rem;
  white-space:nowrap;
  min-width:0;
}
.cust-card .cust-actions .btn i{ font-size:.85rem; line-height:1; }

.cust-card .cust-actions .cari{ background:var(--btn-dark); }
.cust-card .cust-actions .tambah{ background:var(--btn-green); }
.cust-card .cust-actions .cari_dropship{ background:var(--btn-blue); }

/* =========================================================
   FORM CARI PRODUK + 3 TOMBOL AKSI
   DEFAULT DESKTOP (PC normal): 1 baris rapi
   ========================================================= */
#formcheckin{ margin-top:.6rem; }

/* rapihin: jangan ada space kosong, jangan overflow */
#formcheckin .input-group{
  display:flex;
  align-items:stretch;
  flex-wrap:nowrap;     /* PC normal: tetap 1 baris */
  gap:.45rem;
  min-width:0;
}

/* =========================================================
   FORM CARI PRODUK + 3 TOMBOL AKSI
   DEFAULT DESKTOP (PC normal): 1 baris rapi
   ========================================================= */
#formcheckin{ margin-top:.6rem; }

/* rapihin: jangan overflow */
#formcheckin .input-group{
  display:flex;
  align-items:stretch;
  flex-wrap:nowrap;        /* default: 1 baris */
  gap:.45rem;
  min-width:0;
}

/* biarkan input bisa menyusut kalau ruang sempit (INI PENTING utk PC) */
#formcheckin .input-group > .form-control{
  flex: 1 1 0;
  min-width: 0;            /* sebelumnya 260px bikin overflow */
}

#formcheckin .produk-aksi{
  display:flex;
  align-items:stretch;
  flex-wrap:nowrap;
  gap:.45rem;
  margin-left:0;
  min-width:0;
}

#formcheckin .produk-aksi .btn{
  display:flex;
  align-items:center;
  justify-content:center;
  gap:.35rem;
  font-weight:700;
  font-size:.78rem;
  padding:.5rem .65rem;
  line-height:1.15;
  border-radius:.35rem !important;
  min-width:0;
  max-width:100%;
  overflow:hidden;         /* cegah teks keluar kotak */
}

/* =========================================================
   ✅ FIX KHUSUS PC (scale normal / 100%)
   - Target: layar PC lebar (umumnya >=1800px) & DPI normal
   - Teks tombol boleh wrap biar tidak keluar kotak
   - Tidak mengganggu laptop 150% / iPad / HP
   ========================================================= */
@media (hover:hover) and (pointer:fine) and (min-width:1800px) and (max-resolution:1.24dppx){

  /* pastikan input fleksibel dan tidak maksa lebar */
  #formcheckin .input-group > .form-control{
    flex: 1 1 0;
    min-width: 0;
  }

  /* izinkan teks tombol turun 2 baris (biar tidak “lari keluar”) */
}


/* =========================================================
   ✅ KHUSUS LAPTOP Windows scale 150% (DPI tinggi)
   - Buat mirip iPad: input full width, tombol grid 2 kolom, tombol ke-3 full
   - Tidak mengganggu iPad (pointer coarse) & smartphone
   ========================================================= */
@media (hover:hover) and (pointer:fine) and (min-width:1200px) and (max-width:1799.98px) and (min-resolution: 1.25dppx){

  #formcheckin .input-group{
    flex-wrap:wrap;         /* jadi 2 baris */
  }

  #formcheckin .input-group > .form-control{
    flex:1 0 100%;
    width:100%;
    min-width:0;
  }

  #formcheckin .produk-aksi{
    flex:1 0 100%;
    width:100%;
    display:grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap:.45rem;
  }

  #formcheckin .produk-aksi .btn{
    width:100%;
    padding:.52rem .55rem;
    font-size:.74rem;
  }

  #formcheckin .produk-aksi .show_harga{
    grid-column: 1 / -1;   /* Daftar Bahan & Harga full width */
  }
}

/* =========================================================
   iPad / tablet & device <=1199px (biarkan seperti sebelumnya)
   ========================================================= */
@media (max-width:1199.98px){

  #formcheckin .input-group{ flex-wrap:wrap; }
  #formcheckin .input-group > .form-control{
    flex:1 0 100%;
    width:100%;
    min-width:0;
  }

  #formcheckin .produk-aksi{
    flex:1 0 100%;
    width:100%;
    display:grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap:.45rem;
  }

  #formcheckin .produk-aksi .btn{
    width:100%;
    min-width:0;
    padding:.52rem .55rem;
    font-size:.74rem;
  }

  #formcheckin .produk-aksi .show_harga{
    grid-column: 1 / -1;
  }

  .pay-card .pay-2col{ flex-wrap:wrap !important; }
  .pay-card .pay-2col > .w-50{
    width:100% !important;
    padding-left:0 !important;
    padding-right:0 !important;
    margin-bottom:.35rem;
  }
  .pay-card .input-group{ min-width:0; }
  .pay-card .input-group .form-control{
    min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;
  }
  .pay-card .input-group-text{ white-space:nowrap; }
}

@media (max-width:1024px){
  .cust-card .cust-actions .btn{
    font-size:.78rem;
    padding:.55rem .6rem;
  }
}

/* Smartphone / iPhone (tetap) */
@media (max-width:576px){
  .keranjang#container{ padding:.75rem; }
  .simple-card{ padding:.75rem; margin-bottom:.75rem; }

  .info-line{ font-size:.78rem; }
  .form-control,.form-control-sm,.input-group-text{ font-size:.78rem; }
  .mini-label{ font-size:.68rem; }

  .cust-card .cust-actions{
    grid-template-columns: 1fr;
    gap:.5rem;
  }
  .cust-card .cust-actions .cari{ grid-column:auto; }
  .cust-card .cust-actions .btn{ width:100%; }

  #formcheckin .input-group{ flex-wrap:wrap; gap:.45rem; }
  #formcheckin .input-group > .form-control{
    flex: 1 0 100%;
    width:100%;
    min-width:0;
  }
  #formcheckin .produk-aksi{
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
  #formcheckin .produk-aksi .btn{
    font-size:.74rem;
    padding:.52rem .55rem;
  }
  #formcheckin .produk-aksi .show_harga{
    grid-column: 1 / -1;
  }

  .total-highlight .form-control{ min-width:0; }
}

/* footer buttons */
.modal-footer{
  display:flex;
  flex-wrap:wrap;
  align-items:center;
  gap:.5rem;
}
@media (max-width:576px){
  .modal-footer{ justify-content:center; }
  .modal-footer .btn{ flex: 1 1 auto; }
  #simpan, #bayarin, #pending, #print{ white-space:nowrap; }
}

.btn.flat,
.btn.flat:focus{
  border-radius:.35rem !important;
  box-shadow:none;
  outline:0;
}

.cart-printer-options{
  display:flex;
  flex-direction:column;
  gap:.55rem;
  text-align:left;
}

.cart-printer-option{
  width:100%;
  border:1px solid #d7dde6;
  background:#ffffff;
  border-radius:.35rem;
  padding:.7rem .85rem;
  text-align:left;
  cursor:pointer;
}

.cart-printer-option:hover{
  border-color:#17a2b8;
  background:#f4fbfd;
}

.cart-printer-option strong{
  color:#111827;
  font-size:.95rem;
  font-weight:700;
}

.cart-printer-option strong i{
  width:18px;
  color:#0ea5e9;
}

.cart-printer-option strong,
.cart-printer-option small{
  display:block;
}

.cart-printer-option small{
  color:#6b7280;
  margin-top:.2rem;
}

#tablein .cart-action-head,
#tablein .cart-action-cell{
  width:145px;
  min-width:145px;
  text-align:right;
  white-space:nowrap;
}

#tablein .cart-row-actions{
  display:flex;
  align-items:center;
  justify-content:flex-end;
  gap:.35rem;
  white-space:nowrap;
}

#tablein .cart-action-btn{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:.3rem;
  height:30px;
  line-height:1;
  border-radius:.35rem !important;
  white-space:nowrap;
}

#tablein .cart-duplicate-btn{
  width:30px;
  min-width:30px;
  padding:0;
}

#tablein .cart-note-btn{
  min-width:98px;
  padding:.35rem .55rem;
  font-weight:700;
}

#tablein .cart-note-btn .note-label{
  display:inline-block;
  white-space:nowrap;
}

.addmore{
  pointer-events:none;
  cursor:not-allowed !important;
  display:none;
}

/* =========================================================
   Tampilan keranjang POS — scoped agar tidak mengubah halaman lain
   ========================================================= */
#OpenCart-1 .modal-dialog{
  width:100%;
  max-width:100%;
  height:100%;
  min-height:100%;
  margin:0;
}

#OpenCart-1 .cart-modal-content{
  width:100%;
  min-height:100vh;
  border:0;
  border-radius:0;
  background:#f8fafc;
  overflow:hidden;
}

#OpenCart-1 .cart-modal-header{
  min-height:74px;
  padding:0 30px;
  display:flex;
  align-items:center;
  justify-content:flex-start;
  gap:20px;
  border:0;
  color:var(--app-theme-text-color,#fff);
  background-color:var(--app-theme-color,#000) !important;
  background-image:none !important;
  box-shadow:0 5px 18px rgba(15,46,100,.18);
}

#OpenCart-1 .cart-header-menu{
  width:28px;
  font-size:21px;
  text-align:center;
}

#OpenCart-1 .cart-header-brand{
  min-width:215px;
  display:flex;
  align-items:center;
  gap:10px;
}

#OpenCart-1 .cart-header-brand img{
  width:50px;
  height:46px;
  object-fit:contain;
  border-radius:9px;
  background:#fff;
}

#OpenCart-1 .cart-header-brand div{
  display:flex;
  flex-direction:column;
  line-height:1.05;
}

#OpenCart-1 .cart-header-brand strong{
  font-size:18px;
  font-weight:800;
  letter-spacing:.02em;
}

#OpenCart-1 .cart-header-brand small{
  margin-top:4px;
  font-size:10px;
  color:#e7efff;
}

#OpenCart-1 .cart-header-divider{
  width:1px;
  height:38px;
  background:rgba(255,255,255,.2);
}

#OpenCart-1 .cart-header-title{
  display:flex;
  align-items:center;
  gap:15px;
}

#OpenCart-1 .cart-header-title > i{
  font-size:27px;
  color:var(--app-theme-text-color,#fff);
}

#OpenCart-1 .cart-header-title .modal-title{
  color:var(--app-theme-text-color,#fff);
  font-size:27px;
  font-weight:600;
  letter-spacing:.01em;
}

#OpenCart-1 .cart-header-user{
  margin-left:auto;
  display:flex;
  align-items:center;
  gap:9px;
  font-size:14px;
  font-weight:600;
}

#OpenCart-1 .cart-header-user .fa-user-circle{
  font-size:31px;
}

#OpenCart-1 #keranjang{
  padding:0 !important;
  background:#f8fafc;
  overflow-x:hidden;
}

#OpenCart-1 .keranjang#container{
  min-height:100%;
  padding:18px 28px 14px;
  border-radius:0;
  color:#172033;
  background:#f8fafc;
}

#OpenCart-1 .simple-section{
  margin-right:-10px;
  margin-left:-10px;
}

#OpenCart-1 .simple-section > [class*="col-"]{
  padding-right:10px;
  padding-left:10px;
}

#OpenCart-1 .simple-card{
  margin-bottom:0;
  padding:20px 28px;
  border:1px solid #dce4ef;
  border-radius:11px;
  background:#fff;
  box-shadow:0 2px 7px rgba(30,64,120,.03);
}

#OpenCart-1 .simple-section .simple-card{
  min-height:285px;
}

#OpenCart-1 .cart-card-heading{
  min-height:52px;
  margin-bottom:13px;
  display:flex;
  align-items:center;
  gap:15px;
  color:#111a2e;
  font-size:16px;
  font-weight:700;
}

#OpenCart-1 .cart-card-icon{
  width:52px;
  height:52px;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  flex:0 0 52px;
  border-radius:11px;
  color:#1764e8;
  font-size:24px;
  background:#edf3ff;
}

#OpenCart-1 .cart-customer-content{
  padding-left:67px;
}

#OpenCart-1 .cust-header strong{
  color:#10182c;
  font-size:21px !important;
  font-weight:700;
}

#OpenCart-1 .info-line{
  justify-content:flex-start;
  flex-wrap:nowrap;
  gap:18px;
  margin-bottom:8px;
  font-size:14px;
}

#OpenCart-1 .info-label{
  width:64px;
  flex:0 0 64px;
  color:#526079;
}

#OpenCart-1 .info-value{
  color:#145fd7;
  text-align:left;
}

#OpenCart-1 #jenis_member{
  display:inline-block;
  padding:7px 13px;
  border-radius:9px;
  color:#145fd7;
  background:#eaf1ff;
}

#OpenCart-1 .cust-card .cust-actions{
  display:grid;
  grid-template-columns:1fr;
  gap:10px;
}

#OpenCart-1 .cust-card .cust-actions .cari,
#OpenCart-1 .cust-card .cust-actions .tambah,
#OpenCart-1 .cust-card .cust-actions .cari_dropship{
  grid-column:auto;
  min-height:43px;
  padding:10px 14px;
  border-radius:7px !important;
  font-size:14px;
  text-transform:none;
  box-shadow:none;
}

#OpenCart-1 .cust-card .cust-actions .cari{
  background:linear-gradient(105deg,#0f3375,#153f85);
}

#OpenCart-1 .cust-card .cust-actions .tambah{
  background:linear-gradient(105deg,#16963c,#25aa4b);
}

#OpenCart-1 .order-card .mb-2,
#OpenCart-1 .order-card .mb-0{
  margin-bottom:10px !important;
}

#OpenCart-1 .order-card .mini-label{
  margin-bottom:5px;
  color:#222d43;
  font-size:13px;
  font-weight:600;
  text-transform:none;
}

#OpenCart-1 .order-card .input-group,
#OpenCart-1 .order-card .form-control{
  min-height:38px;
}

#OpenCart-1 .order-card .form-control,
#OpenCart-1 .order-card .input-group-text{
  border-color:#d7e0ec;
  border-radius:7px !important;
  background:#fff !important;
}

#OpenCart-1 .komisi-desain-wrap{
  margin-top:8px !important;
  padding:0;
  border:0;
  background:transparent;
  box-shadow:none;
  animation:none;
}

#OpenCart-1 .komisi-desain-label{
  color:#222d43;
}

#OpenCart-1 .komisi-desain-control{
  border:1px solid #d7e0ec;
  border-radius:7px;
  box-shadow:none;
}

#OpenCart-1 .komisi-desain-icon{
  min-width:38px;
  border:0 !important;
  border-radius:6px 0 0 6px !important;
  background:#526078 !important;
}

#OpenCart-1 #sales_komisi{
  border:0 !important;
  border-radius:0 6px 6px 0 !important;
  font-weight:600;
}

#OpenCart-1 .komisi-desain-hint{
  display:none;
}

#OpenCart-1 .order-date-row{
  display:grid;
  grid-template-columns:repeat(2,minmax(0,1fr));
  gap:10px;
  margin-bottom:2px;
}

#OpenCart-1 .order-date-field{
  min-width:0;
}

#OpenCart-1 .order-date-field .mini-label{
  min-height:18px;
  margin-bottom:5px;
  color:#222d43;
  font-size:13px;
  font-weight:600;
  line-height:1.25;
  letter-spacing:0;
  text-transform:none;
}

#OpenCart-1 .order-date-field .input-group{
  display:flex;
  flex-wrap:nowrap;
  width:100%;
  min-width:0;
  min-height:38px;
  overflow:hidden;
  border:1px solid #d7e0ec;
  border-radius:8px;
  background:#fff;
  transition:border-color .18s ease,box-shadow .18s ease;
}

#OpenCart-1 .order-date-field .input-group:focus-within{
  border-color:var(--app-theme-color,#2563eb);
  box-shadow:0 0 0 3px rgba(37,99,235,.1);
}

#OpenCart-1 .order-date-field .modern-date-input{
  flex:1 1 50%;
  width:0;
  min-width:82px;
  max-width:none;
  height:36px;
  padding-right:25px !important;
  border:0 !important;
  border-radius:7px 0 0 7px !important;
  background-position:right 6px center !important;
  background-size:14px 14px !important;
  box-shadow:none !important;
}

#OpenCart-1 .order-date-field .modern-picker-icon{
  display:flex;
  align-items:center;
  justify-content:center;
  flex:0 0 32px;
  min-width:32px;
  height:36px;
  border-width:0 1px !important;
  border-radius:0 !important;
}

#OpenCart-1 .order-date-field #jam_order,
#OpenCart-1 .order-date-field #jam_ambil{
  flex:1 1 42%;
  width:0;
  min-width:68px;
  height:36px;
  border:0 !important;
  border-radius:0 7px 7px 0 !important;
  background:#fff !important;
  font-size:13px;
  line-height:1.25;
  box-shadow:none !important;
}

@media(max-width:575.98px){
  #OpenCart-1 .order-date-row{
    grid-template-columns:1fr;
  }
}

#OpenCart-1 .commission-inline-row{
  display:grid;
  grid-template-columns:repeat(2,minmax(0,1fr));
  gap:10px;
  margin-top:10px;
}

#OpenCart-1 .commission-inline-field{
  display:flex;
  flex-direction:column;
  min-width:0;
  margin:0 !important;
}

#OpenCart-1 .commission-inline-field:only-child{
  grid-column:1/-1;
}

#OpenCart-1 .commission-inline-field .komisi-desain-label{
  display:flex;
  align-items:center;
  min-height:18px;
  margin:0 0 5px;
  color:#222d43;
  font-size:13px;
  font-weight:600;
  line-height:1.25;
  letter-spacing:0;
  text-transform:none;
}

#OpenCart-1 .commission-inline-field .komisi-desain-control{
  display:flex;
  flex-wrap:nowrap;
  align-items:stretch;
  overflow:hidden;
  width:100%;
  min-height:38px;
  border:1px solid #d7e0ec;
  border-radius:8px;
  background:#fff;
  transition:border-color .18s ease,box-shadow .18s ease;
}

#OpenCart-1 .commission-inline-field .komisi-desain-control:focus-within{
  border-color:var(--app-theme-color,#2563eb);
  box-shadow:0 0 0 3px rgba(37,99,235,.1);
}

#OpenCart-1 .commission-inline-field .komisi-desain-icon{
  display:flex;
  align-items:center;
  justify-content:center;
  flex:0 0 37px;
  min-width:37px;
  border-radius:7px 0 0 7px !important;
  background:#f1f5fb !important;
  color:var(--app-theme-color,#2563eb) !important;
}

#OpenCart-1 .commission-inline-field #sales_komisi,
#OpenCart-1 .commission-inline-field #sales_penjualan{
  flex:1 1 0;
  width:auto;
  min-width:0;
  height:36px;
  border:0 !important;
  border-radius:0 7px 7px 0 !important;
  background:#fff !important;
  color:#344159;
  font-size:13px;
  font-weight:600;
  line-height:1.25;
  box-shadow:none !important;
}

@media(max-width:575.98px){
  #OpenCart-1 .commission-inline-row{
    grid-template-columns:1fr;
  }
}

#OpenCart-1 .pay-card{
  padding:20px 22px;
  box-shadow:0 7px 20px rgba(26,70,140,.08);
}

#OpenCart-1 .pay-card .cart-card-heading{
  margin-bottom:16px;
}

#OpenCart-1 .cart-summary-list{
  overflow:hidden;
  border:1px solid #e0e7f0;
  border-radius:12px;
  background:#fff;
  box-shadow:0 3px 12px rgba(30,54,90,.04);
}

#OpenCart-1 .cart-summary-list [hidden]{
  display:none !important;
}

#OpenCart-1 .cart-payment-total{
  min-height:58px;
  margin:0;
  padding:8px 14px;
  display:grid;
  grid-template-columns:34px minmax(0,1fr) minmax(145px,52%);
  align-items:center;
  gap:11px;
  border:0;
  border-bottom:1px solid #edf1f6;
  border-radius:0;
  background:#fff;
}

#OpenCart-1 .cart-payment-total:last-child{
  border-bottom:0;
}

#OpenCart-1 .cart-payment-icon{
  width:32px;
  height:32px;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  border-radius:8px;
  font-size:16px;
}

#OpenCart-1 .cart-payment-label{
  color:#38445a;
  font-size:13px;
  font-weight:650;
}

#OpenCart-1 .cart-payment-total input{
  width:100%;
  min-width:0;
  padding:0;
  border:0;
  font-size:clamp(17px,1.08vw,20px);
  font-weight:700;
  font-variant-numeric:tabular-nums;
  letter-spacing:-.01em;
  text-align:right;
  background:transparent !important;
}

#OpenCart-1 .cart-tax-value{
  width:100%;
  min-width:0;
  display:flex;
  align-items:center;
  justify-content:flex-end;
  gap:3px;
  color:#9a6500;
  font-size:clamp(17px,1.08vw,20px);
  font-weight:700;
  font-variant-numeric:tabular-nums;
}

#OpenCart-1 .cart-tax-value input{
  width:auto;
  min-width:0;
  flex:1 1 auto;
  color:#9a6500 !important;
}

#OpenCart-1 .cart-payment-total-order{
  color:#0e5fde;
  background:#f8fbff;
}

#OpenCart-1 .cart-payment-total-order .cart-payment-icon{ background:#e9f1ff; }
#OpenCart-1 .cart-payment-total-order input{ color:#0e5fde !important; }
#OpenCart-1 .cart-payment-total-order .cart-payment-label{ color:#0e5fde; }

#OpenCart-1 .cart-payment-tax{
  color:#9a6500;
}

#OpenCart-1 .cart-payment-tax .cart-payment-icon{
  color:#9a6500;
  background:#fff3d6;
}

#OpenCart-1 .cart-payment-tax .cart-payment-label{ color:#765410; }

#OpenCart-1 .cart-payment-discount{
  color:#d36b12;
}

#OpenCart-1 .cart-payment-discount .cart-payment-icon{
  color:#d36b12;
  background:#fff0e2;
}

#OpenCart-1 .cart-payment-discount .cart-payment-label{ color:#9a531d; }
#OpenCart-1 .cart-payment-discount input{ color:#d36b12 !important; }

#OpenCart-1 .cart-payment-paid{
  color:#15903c;
}

#OpenCart-1 .cart-payment-paid .cart-payment-icon{ background:#e5f6e9; }
#OpenCart-1 .cart-payment-paid input{ color:#15903c !important; }
#OpenCart-1 .cart-payment-paid .cart-payment-label{ color:#277044; }

#OpenCart-1 .cart-payment-due{
  color:#ef2c36;
}

#OpenCart-1 .cart-payment-due .cart-payment-icon{ background:#ffe8e9; }
#OpenCart-1 .cart-payment-due input{ color:#ef2c36 !important; }
#OpenCart-1 .cart-payment-due .cart-payment-label{ color:#a83d43; }

#OpenCart-1 .row.mt-3{
  margin-top:14px !important;
}

#OpenCart-1 .cart-items-card{
  padding:0;
  overflow:hidden;
}

#OpenCart-1 .cart-product-toolbar{
  padding:18px 18px 14px;
}

#OpenCart-1 #formcheckin .input-group{
  align-items:center;
  gap:12px;
}

#OpenCart-1 .cart-product-search{
  position:relative;
  width:340px;
  flex:0 0 340px;
}

#OpenCart-1 .cart-product-search > i{
  position:absolute;
  z-index:2;
  top:50%;
  left:15px;
  transform:translateY(-50%);
  color:#516078;
}

#OpenCart-1 .cart-product-search .form-control{
  width:100%;
  height:44px;
  padding-left:42px;
  border:1px solid #d5deea;
  border-radius:10px !important;
  background:#fff;
  box-shadow:0 2px 8px rgba(15,23,42,.04);
  transition:border-color .15s ease,box-shadow .15s ease;
}

#OpenCart-1 .cart-product-search .form-control:focus{
  border-color:var(--app-theme-color,#2563eb);
  box-shadow:0 0 0 3px color-mix(in srgb,var(--app-theme-color,#2563eb) 14%,transparent);
}

#OpenCart-1 #formcheckin .produk-aksi{
  display:flex;
  align-items:stretch;
  flex:0 0 auto;
  gap:12px;
}

#OpenCart-1 #formcheckin .produk-aksi .btn{
  min-height:44px;
  padding:9px 18px;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:8px;
  border:1px solid transparent;
  border-radius:10px !important;
  color:#354158;
  font-size:13px;
  font-weight:700;
  line-height:1;
  white-space:nowrap;
  overflow:visible;
  user-select:none;
  box-shadow:0 4px 10px rgba(15,23,42,.08);
  transition:transform .15s ease,box-shadow .15s ease,background-color .15s ease;
}

#OpenCart-1 #formcheckin .produk-aksi .btn > i{
  width:18px;
  flex:0 0 18px;
  text-align:center;
  font-size:14px;
  line-height:1;
}

#OpenCart-1 #formcheckin .show_qr{
  width:155px;
  flex:0 0 155px;
  border-color:#bdd2f4;
  color:#2058a8;
  background:#edf4ff;
}

#OpenCart-1 #formcheckin .show_harga{
  width:215px;
  flex:0 0 215px;
  border-color:#d4dce7;
  color:#354158;
  background:#f5f7fa;
}

#OpenCart-1 #formcheckin .produk-aksi .btn:hover,
#OpenCart-1 #formcheckin .produk-aksi .btn:focus{
  transform:translateY(-1px);
  box-shadow:0 7px 15px rgba(15,23,42,.13);
}

#OpenCart-1 .table-responsive{
  margin:0 18px 16px;
  border:1px solid #dce4ee;
  border-radius:8px;
  overflow:auto;
}

#OpenCart-1 #tablein{
  min-width:1180px;
  color:#26334a;
  table-layout:auto;
  background:#fff;
}

#OpenCart-1 #tablein thead td{
  height:46px;
  padding:10px 12px;
  border-top:0;
  border-bottom:1px solid #dce4ee;
  color:#202b40;
  font-size:13px;
  font-weight:700;
  background:#fbfcfe;
  vertical-align:middle;
}

#OpenCart-1 #tablein tbody td{
  height:60px;
  padding:10px 8px;
  border-top:1px solid #edf0f4;
  vertical-align:middle;
  background:#fff;
}

#OpenCart-1 #tablein tbody tr:nth-child(even) td{
  background:#fcfdff;
}

#OpenCart-1 #tablein .form-control{
  height:36px;
  border:1px solid #d8e0eb;
  border-radius:6px !important;
  color:#536079;
  background:#fff !important;
}

#OpenCart-1 #tablein thead td:nth-child(8),
#OpenCart-1 #tablein tbody td:nth-child(8){
  width:170px !important;
  min-width:170px;
}

#OpenCart-1 #tablein input[id^="harga_"]{
  padding-right:10px;
  padding-left:10px;
  font-variant-numeric:tabular-nums;
  text-align:right;
}

#OpenCart-1 #tablein input[readonly]{
  pointer-events:auto;
}

#OpenCart-1 #tablein .cart-row-number{
  color:#25324a;
  font-weight:600;
}

#OpenCart-1 #tablein .cart-action-head,
#OpenCart-1 #tablein .cart-action-cell{
  width:242px;
  min-width:242px;
  padding-right:24px;
  padding-left:6px;
  text-align:center;
  white-space:nowrap;
}

#OpenCart-1 #tablein .cart-row-actions{
  justify-content:center;
  gap:5px;
  width:100%;
}

#OpenCart-1 #tablein .cart-action-btn,
#OpenCart-1 #tablein .cart-duplicate-btn,
#OpenCart-1 #tablein .cart-delete-btn{
  width:34px;
  min-width:34px;
  height:34px;
  padding:0;
  border:0;
  border-radius:6px !important;
  color:#fff;
  box-shadow:0 2px 5px rgba(15,23,42,.12);
}

#OpenCart-1 #tablein .cart-note-btn{
  width:auto;
  min-width:126px;
  height:34px;
  padding:0 9px;
  border:0;
  border-radius:6px !important;
  gap:5px;
  color:#fff;
  font-size:11px;
  font-weight:700;
  letter-spacing:0;
  background:linear-gradient(180deg,#ffad32 0%,#f58a07 100%);
  box-shadow:0 2px 6px rgba(245,138,7,.28);
}

#OpenCart-1 #tablein .cart-action-btn:hover,
#OpenCart-1 #tablein .cart-action-btn:focus{
  transform:translateY(-1px);
  box-shadow:0 4px 8px rgba(15,23,42,.16);
}

#OpenCart-1 #tablein .cart-note-btn .note-label{
  display:inline-block;
  line-height:1;
  white-space:nowrap;
}

#OpenCart-1 #tablein tfoot td{
  height:53px;
  padding:12px 20px;
  border-top:1px solid #dce4ee;
  color:#2161ca;
  font-size:13px;
  background:#fff;
}

#OpenCart-1 #tablein .cart-subtotal-total{
  color:#46536a;
  text-align:right;
}

#OpenCart-1 #tablein .cart-subtotal-total strong{
  margin-left:48px;
  color:#0c5fdc;
  font-size:14px;
}

#OpenCart-1 .cart-modal-footer{
  min-height:90px;
  padding:15px 38px;
  display:flex;
  justify-content:space-between;
  align-items:center;
  border-top:1px solid #dde4ed;
  background:#fff;
  box-shadow:0 -3px 14px rgba(30,55,90,.04);
}

#OpenCart-1 .cart-footer-left,
#OpenCart-1 .cart-footer-right{
  display:flex;
  align-items:center;
  gap:16px;
}

#OpenCart-1 .cart-modal-footer .btn{
  min-height:48px;
  padding:0 22px;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:10px;
  border-radius:7px !important;
  font-size:14px;
  font-weight:600;
  box-shadow:none;
}

#OpenCart-1 .cart-close-btn{
  border:1px solid #ff4f55;
  color:#f1333b;
  background:#fff;
}

#OpenCart-1 .cart-cancel-btn{
  border:1px solid #ffb3b6;
  color:#e33a42;
  background:#fff6f6;
}

#OpenCart-1 .cart-settings-btn{
  width:54px;
  padding:0 !important;
  border:1px solid #cfd8e5;
  color:#5c6980;
  background:#fff;
}

#OpenCart-1 #print_pdf{
  display:none !important;
}

#OpenCart-1 .cart-print-btn{
  min-width:275px;
  border:0;
  color:#fff;
  background:linear-gradient(110deg,#0d5fe2,#176be7);
}

#OpenCart-1 .cart-pay-btn{
  min-width:145px;
  border:0;
  color:#fff;
  background:linear-gradient(110deg,#15913a,#23aa49);
}

#OpenCart-1 .cart-pending-btn{
  min-width:160px;
  border:0;
  color:#fff;
  background:linear-gradient(110deg,#f47b00,#fb8d00);
}

@media (max-width:1199.98px){
  #OpenCart-1 .cart-header-brand{ display:none; }
  #OpenCart-1 .cart-header-divider{ display:none; }
  #OpenCart-1 .cart-header-title .modal-title{ font-size:21px; }
  #OpenCart-1 .simple-section .simple-card{ min-height:0; }
  #OpenCart-1 .simple-section > [class*="col-"]{ margin-bottom:12px; }
  #OpenCart-1 .cart-product-search{ width:100%; flex:1 0 100%; }
  #OpenCart-1 #formcheckin .input-group{ flex-wrap:wrap; }
  #OpenCart-1 #formcheckin .produk-aksi{
    width:100%;
    flex:1 0 100%;
    display:grid;
    grid-template-columns:repeat(2,minmax(0,1fr));
  }
  #OpenCart-1 #formcheckin .produk-aksi .btn,
  #OpenCart-1 #formcheckin .show_qr,
  #OpenCart-1 #formcheckin .show_harga{
    width:100%;
    min-width:0;
    flex:auto;
  }
  #OpenCart-1 .cart-footer-left,
  #OpenCart-1 .cart-footer-right{ gap:8px; }
  #OpenCart-1 .cart-modal-footer .btn{ min-width:0; padding:0 12px; }
  #OpenCart-1 .cart-cancel-btn{ display:none; }
}

@media (max-width:767.98px){
  #OpenCart-1 .cart-modal-header{ min-height:62px; padding:0 14px; gap:10px; }
  #OpenCart-1 .cart-header-menu,
  #OpenCart-1 .cart-header-user span,
  #OpenCart-1 .cart-header-user .fa-angle-down{ display:none; }
  #OpenCart-1 .keranjang#container{ padding:10px; }
  #OpenCart-1 .simple-card{ padding:16px; }
  #OpenCart-1 #formcheckin .produk-aksi{ grid-template-columns:repeat(2,minmax(0,1fr)); }
  #OpenCart-1 #formcheckin .show_harga{ grid-column:1 / -1; }
  #OpenCart-1 .cart-customer-content{ padding-left:0; }
  #OpenCart-1 .cart-modal-footer{ padding:10px; flex-direction:column; }
  #OpenCart-1 .cart-footer-left,
  #OpenCart-1 .cart-footer-right{ width:100%; }
  #OpenCart-1 .cart-footer-right{ display:grid; grid-template-columns:1.5fr 1fr 1fr; }
  #OpenCart-1 .cart-footer-left .btn,
  #OpenCart-1 .cart-footer-right .btn{ width:100%; min-width:0; font-size:11px; }
  #OpenCart-1 .cart-settings-btn{ max-width:52px; }
}
</style>



