<script>
	jQuery('body').on('click', '.btn-add-sales_transaction', function() {
    var pop  = '<div class="trx-pop">';
    pop += '<button type="button" class="trx-pop-btn trx-pop-baju" data-type="baju">';
    pop += '<span class="trx-pop-ico">ðŸ‘•</span>';
    pop += '<span class="trx-pop-txt"><b>Transaksi Baju</b><small>Kategori B Â· Tgl selesai H+2 Â· 17:00</small></span>';
    pop += '<span class="trx-pop-arr">â†’</span></button>';
    pop += '<button type="button" class="trx-pop-btn trx-pop-linen" data-type="linen">';
    pop += '<span class="trx-pop-ico">ðŸ§º</span>';
    pop += '<span class="trx-pop-txt"><b>Transaksi Linen</b><small>Kategori L Â· Tgl selesai H+3 Â· 17:00</small></span>';
    pop += '<span class="trx-pop-arr">â†’</span></button>';
    pop += '</div>';
    pop += '<style>'
        + '.trx-pop{display:flex;flex-direction:column;gap:10px;padding:4px 0 2px;}'
        + '.trx-pop-btn{display:flex;align-items:center;gap:14px;width:100%;border:0;border-radius:12px;padding:14px 16px;color:#fff;cursor:pointer;text-align:left;position:relative;overflow:hidden;transition:transform .14s,box-shadow .14s,filter .14s;}'
        + '.trx-pop-btn::after{content:"";position:absolute;inset:0;background:repeating-linear-gradient(-55deg,rgba(255,255,255,.06) 0 12px,transparent 12px 26px);}'
        + '.trx-pop-baju{background:linear-gradient(120deg,#0c3b36,#138074);box-shadow:0 4px 14px rgba(12,59,54,.28);}'
        + '.trx-pop-linen{background:linear-gradient(120deg,#14324f,#2f6fb0);box-shadow:0 4px 14px rgba(20,50,79,.28);}'
        + '.trx-pop-btn:hover{transform:translateY(-2px);filter:brightness(1.07);box-shadow:0 9px 22px rgba(15,40,60,.35);}'
        + '.trx-pop-ico{font-size:26px;position:relative;z-index:1;}'
        + '.trx-pop-txt{flex:1;position:relative;z-index:1;line-height:1.3;}'
        + '.trx-pop-txt b{display:block;font-size:15px;font-family:"Trebuchet MS","Segoe UI",sans-serif;letter-spacing:.4px;}'
        + '.trx-pop-txt small{font-size:11px;opacity:.85;}'
        + '.trx-pop-arr{font-size:20px;font-weight:800;position:relative;z-index:1;transition:transform .15s;}'
        + '.trx-pop-btn:hover .trx-pop-arr{transform:translateX(5px);}'
        + '.trx-pop-dialog .modal-dialog{max-width:440px;}'
        + '.trx-pop-dialog .modal-content{border-radius:14px;border:0;}'
        + '.trx-pop-dialog .modal-header{border-bottom:1px solid #e6ebe9;font-family:"Trebuchet MS","Segoe UI",sans-serif;}'
        + '</style>';
    bootbox.dialog({
        title: 'Pilih Jenis Transaksi',
        message: pop,
        className: 'trx-pop-dialog',
        closeButton: true
    });
});

jQuery('body').on('click', '.trx-pop-btn', function() {
    location.href = app_url + 'sales_transaction/add/' + jQuery(this).attr('data-type');
});

// ===================== DETAIL BILL -> MODAL PRINT (MARKER / BILL) =====================
// Pembuka modal "Detail". Tanpanya, tombol Detail di History tidak melakukan apa-apa
// dan seluruh tombol cetak (marker / QR baju / bill) tidak bisa dijangkau.
jQuery('body').on('click', '.btn-detail', function() {
    var code = jQuery(this).attr('data-code');
    var id   = jQuery(this).attr('data-id');
    show_loading();
    jQuery.ajax({
        url: app_url + 'sales_transaction/get_invoice',
        type: 'POST',
        dataType: 'JSON',
        data: { code: code, id: id },
        success: function(response) {
            hide_loading();
            if (response.err_code == 0) {
                jQuery('.az-modal-detail .modal-body').html(response.data);
                show_modal('detail');
                if (response.is_hide_btn) {
                    jQuery('.az-modal-detail').find('.modal-footer').addClass('hide');
                } else {
                    jQuery('.az-modal-detail').find('.modal-footer').removeClass('hide');
                }
            } else {
                bootbox.alert({ title: "Error", message: response.err_message });
            }
        },
        error: function() { hide_loading(); }
    });
});

// ===================== BARBER (PANTAUAN PRODUKSI) =====================
jQuery('body').on('click', '.btn-barber-open', function(){
	var d1 = jQuery('#date_1').val() || '';
	var d2 = jQuery('#date_2').val() || '';
	var outlet = jQuery('#idoutlet').val();
	if (outlet === undefined || outlet === null) { outlet = jQuery('#outlet').val(); }
	outlet = outlet || '';
	var url = app_url + 'sales_transaction/barber_view2'
		+ '?date_1='   + encodeURIComponent(d1)
		+ '&date_2='   + encodeURIComponent(d2)
		+ '&idoutlet=' + encodeURIComponent(outlet);
	window.open(url, '_blank');
});
// ==================================================================

// ===================== CEK STOK =====================
function buka_cek_stok(jenis) {
    // ambil nilai filter TANGGAL yang sedang terisi di form history
    var d1 = jQuery('#date_1').val() || '';
    var d2 = jQuery('#date_2').val() || '';

    // ambil nilai filter OUTLET (id-nya bisa 'idoutlet' atau 'outlet' -> coba dua-duanya)
    var outlet = jQuery('#idoutlet').val();
    if (outlet === undefined || outlet === null) { outlet = jQuery('#outlet').val(); }
    outlet = outlet || '';

    // buka laporan di tab baru, hanya membawa 2 filter (tanggal + outlet)
    var url = app_url + 'sales_transaction/cek_stok_' + jenis
            + '?date_1='   + encodeURIComponent(d1)
            + '&date_2='   + encodeURIComponent(d2)
            + '&idoutlet=' + encodeURIComponent(outlet);
    window.open(url, '_blank');
}
jQuery('body').on('click', '.btn-cek-stok-view', function(){ buka_cek_stok('view'); });
jQuery('body').on('click', '.btn-cek-stok-pdf',  function(){ buka_cek_stok('pdf');  });
// ====================================================

// ===================== BARKOT (BARANG KOTOR) =====================
jQuery('body').on('click', '.btn-barkot-open', function(){
	var d1 = jQuery('#date_1').val() || '';
	var d2 = jQuery('#date_2').val() || '';
	var outlet = jQuery('#idoutlet').val();
	if (outlet === undefined || outlet === null) { outlet = jQuery('#outlet').val(); }
	outlet = outlet || '';
	var url = app_url + 'sales_transaction/barkot_view'
		+ '?date_1='   + encodeURIComponent(d1)
		+ '&date_2='   + encodeURIComponent(d2)
		+ '&idoutlet=' + encodeURIComponent(outlet);
	window.open(url, '_blank');
});

// ===================== STATUS PIUTANG =====================
jQuery('body').on('click', '.btn-piutang-open', function(){
    var d1 = jQuery('#date_1').val() || '';
    var d2 = jQuery('#date_2').val() || '';
    var outlet = jQuery('#idoutlet').val();
    if (outlet === undefined || outlet === null) { outlet = jQuery('#outlet').val(); }
    outlet = outlet || '';
    window.open(app_url + 'sales_transaction/piutang_view?date_1=' + encodeURIComponent(d1) + '&date_2=' + encodeURIComponent(d2) + '&idoutlet=' + encodeURIComponent(outlet), '_blank');
});
// ==========================================================

// ===================== ANALISA PER JAM =====================
jQuery('body').on('click', '.btn-jam-open', function(){
    var d1 = jQuery('#date_1').val() || '';
    var d2 = jQuery('#date_2').val() || '';
    var outlet = jQuery('#idoutlet').val();
    if (outlet === undefined || outlet === null) { outlet = jQuery('#outlet').val(); }
    outlet = outlet || '';
    var cust = jQuery('#customer').val() || '';
    var code = jQuery('#filter_code').val() || '';
    var st   = jQuery('select[name=status]').val() || '';
    var pr   = jQuery('select[name=process_status]').val() || '';
    var url = app_url + 'sales_transaction/jam_view'
        + '?date_1='        + encodeURIComponent(d1)
        + '&date_2='        + encodeURIComponent(d2)
        + '&idoutlet='      + encodeURIComponent(outlet)
        + '&customer='      + encodeURIComponent(cust)
        + '&filter_code='   + encodeURIComponent(code)
        + '&status='        + encodeURIComponent(st)
        + '&process_status='+ encodeURIComponent(pr);
    window.open(url, '_blank');
});
// ===========================================================

// ===================== EDIT TGL SELESAI =====================
// 1) tombol Edit Selesai diklik -> ambil tgl sekarang -> buka modal
jQuery('body').on('click', '.btn-edit-selesai', function() {
    var id   = jQuery(this).attr('data_id');
    var code = jQuery(this).attr('data_code');
    show_loading();
    jQuery.ajax({
        url: app_url + 'sales_transaction/get_selesai',
        type: 'POST',
        dataType: 'JSON',
        data: { id: id },
        success: function(response) {
            hide_loading();
            if (response.err_code == 0) {
                jQuery('#id_edit_selesai').val(id);
                jQuery('#code_edit_selesai').val(code);
                setDuedateEdit(response.duedate);
                show_modal('edit_selesai');
            } else {
                bootbox.alert(response.err_message);
            }
        },
        error: function() { hide_loading(); }
    });
});

// isi field tanggal (teks + sinkron kalender kalau tersedia)
function setDuedateEdit(val) {
    var $el = jQuery('#duedate_edit');
    $el.val(val || '');
    try {
        var dp = $el.data('DateTimePicker');
        if (dp) {
            if (val) { dp.date(moment(val, 'DD-MM-YYYY HH:mm:ss')); }
            else     { dp.clear(); }
        }
    } catch (e) {}
}

// 2) tombol Simpan di modal diklik -> simpan ke database -> refresh tabel
jQuery('body').on('click', '.btn-action-edit-selesai', function() {
    var id      = jQuery('#id_edit_selesai').val();
    var duedate = jQuery('#duedate_edit').val();
    if (!id)      { bootbox.alert('Data tidak valid'); return; }
    if (!duedate) { bootbox.alert('Tgl Selesai wajib diisi'); return; }
    show_loading();
    jQuery.ajax({
        url: app_url + 'sales_transaction/save_selesai',
        type: 'POST',
        dataType: 'JSON',
        data: { id: id, duedate: duedate },
        success: function(response) {
            hide_loading();
            if (response.err_code == 0) {
                hide_modal('edit_selesai');
                bootbox.alert({
                    message: 'Tgl Selesai berhasil diubah',
                    callback: function() {
                        var dtable = jQuery('#sales_transaction').dataTable({ bRetrieve: true });
                        dtable.fnDraw(false);
                    }
                });
            } else {
                bootbox.alert(response.err_message);
            }
        },
        error: function() { hide_loading(); }
    });
});
// ============================================================



    jQuery('.btn-action-standart-invoice').on('click', function() {
        var code = jQuery('.transaction-group-code').text();
        window.open(app_url + 'sales_transaction/invoice/?c=' + code, '_blank');
    });

    jQuery('.btn-action-small-invoice').on('click', function() {
        var code = jQuery('.transaction-group-code').text();
        window.open(app_url + 'sales_transaction/invoice/?c=' + code +'&t=small', '_blank');
    });

    jQuery('body').on('change keyup keydown', '#filter_code', function(e) {
        if (e.keyCode == 13) {
            var dtable = jQuery('#sales_transaction').dataTable({bRetrieve: true});
            dtable.fnDraw();
        }
    });

    jQuery('body').on('click', '.btn-process-sales_transaction', function() {
        var id = jQuery(this).attr('data_id');
        jQuery('#idtransaction_group').val(id);

        show_loading();
        jQuery.ajax({
            url: app_url + 'sales_transaction/get_detail',
            type: 'POST',
            dataType: 'JSON',
            data: {
                id: id
            },
            success: function(response) {
                hide_loading();
                
                jQuery('#pay').val(response.pay);
                jQuery('#pay_date').val(response.pay_date);
                jQuery('#transaction_group_status').val(response.transaction_group_status);
                check_pay();
            },
            error: function(response){}
        });

        show_modal('process');
    });

    jQuery('body').on('change', '#pay', function() {
        check_pay();
    });

    check_pay();
    function check_pay() {
        var pay = jQuery('#pay').val();
        if (pay == 'PAID') {
            jQuery('.container-pay-date').removeClass('hide');
        }
        else {
            jQuery('.container-pay-date').addClass('hide');
        }
    }

    jQuery('body').on('click', '.btn-action-process', function() {
        jQuery.ajax({
            url: app_url + 'sales_transaction/process',
            type: 'POST',
            dataType: 'JSON',
            data: jQuery('#form_process').serialize(),
            success: function(response) {
                if (response.err_code == 0) {
                    hide_modal('process');
                    var dtable = jQuery('#sales_transaction').dataTable({bRetrieve: true});
                    dtable.fnDraw();
                }
                else {
                    bootbox.alert(response.err_message);
                }
            },
            error: function(response) {}
        });
    });

    jQuery('body').on('click', '.btn-action-print-invoice', function() {
        var id = jQuery('#hd_idtrx').val();
        window.open(app_url + 'sales_transaction/print_bill/' + id, '_blank');
    });

    jQuery('body').on('click', '.btn-action-print-invoice-old', function() {
        var id = jQuery('#hd_idtrx').val();
        window.open(app_url + 'sales_transaction/print_bill/' + id + '/old', '_blank');
    });

    jQuery('body').on('click', '.btn-action-print-invoice-production', function() {
        var id = jQuery('#hd_idtrx').val();
        window.open(app_url + 'sales_transaction/print_bill/' + id + '/production', '_blank');
    });

    jQuery('body').on('click', '.btn-action-print-qr-baju', function() {
        var id = jQuery('#hd_idtrx').val();
        window.open(app_url + 'sales_transaction/print_bill/' + id + '/qr_baju', '_blank');
    });

    jQuery('body').on('click', '.btn-action-print-marker', function() {
        var id = jQuery('#hd_idtrx').val();
        window.open(app_url + 'sales_transaction/print_bill/' + id + '/marker', '_blank');
    });
    jQuery('body').on('click', '.btn-action-print-marker-old', function() {
        var id = jQuery('#hd_idtrx').val();
        window.open(app_url + 'sales_transaction/print_bill/' + id + '/marker_old', '_blank');
    });
    jQuery('body').on('click', '.btn-action-print-marker-sedang', function() {
        var id = jQuery('#hd_idtrx').val();
         window.open(app_url + 'sales_transaction/print_bill/' + id + '/marker_sedang', '_blank');
    });
    jQuery('body').on('click', '.btn-action-print-marker-point', function() {
        var id = jQuery('#hd_idtrx').val();
        window.open(app_url + 'sales_transaction/print_bill/' + id + '/marker_point', '_blank');
    });

    jQuery('body').on('click', '.btn-export-excel', function() {
        jQuery('#form_sales_transaction').submit();
    });
    
 

// ==================================================================
//  PU DI HISTORY TRANSAKSI (VERSI FINAL)
//  - ADA PU              : ORANYE + selalu paling atas (masih dipantau)
//  - END PROCESS LENGKAP : toska muda, posisi NORMAL (selesai dipantau)
//  - Punya PU lainnya    : kuning muda, posisi normal
// ==================================================================
function pu_paint_rows() {
    var $tbody = jQuery('#sales_transaction tbody');
    if ($tbody.length == 0) { return; }

    var adaPuRows = [];

    $tbody.find('tr').each(function() {
        var $row = jQuery(this);
        // Kolom Status = kolom ke-3 (index 2)
        var stText = jQuery.trim($row.find('td').eq(2).text());
        var hasPuBtn = ($row.find('.btn-lihat-pu').length > 0);

        if (stText.indexOf('END PROCESS LENGKAP') !== -1) {
            // Sudah lengkap → warna toska muda, TIDAK dipindah ke atas
            $row.find('td').css('background-color', '#e0f2f1');
        }
        else if (stText.indexOf('ADA PU') !== -1) {
            // Masih dipantau → oranye + naik ke paling atas
            $row.find('td').css({
                'background-color': '#ffe0b2',
                'border-left': '4px solid #e67e22'
            });
            adaPuRows.push(this);
        }
        else if (hasPuBtn) {
            // Punya riwayat PU tapi tidak dipantau → kuning muda, posisi normal
            $row.find('td').css('background-color', '#fff9c4');
        }
    });

    // HANYA baris ADA PU yang naik ke paling atas
    for (var j = adaPuRows.length - 1; j >= 0; j--) {
        $tbody.prepend(adaPuRows[j]);
    }
}

jQuery(document).ajaxComplete(function(event, xhr, settings) {
    if (settings.url && settings.url.indexOf('sales_transaction/get') !== -1) {
        setTimeout(pu_paint_rows, 150);
    }
});
// ===================== NWS HISTORY (KASIR) — FINAL =====================
// Hanya SATU popup: modal UNGU "Catatan NWS (Note We Are Sorry)"
jQuery('<style>.btn-nws-view.nws-unread{background:#6f42c1;color:#fff;border:none;}.btn-nws-view.nws-read{background:#eef1f5;color:#56657a;border:1px solid #d7dde6;}tr.nws-row-unread td{background:#f1ecfb !important;}</style>').appendTo('head');
function nws_paint_rows(){
    jQuery('#sales_transaction tbody tr').each(function(){
        var $tr = jQuery(this);
        if ($tr.find('.btn-nws-view.nws-unread').length > 0) { $tr.addClass('nws-row-unread'); }
        else { $tr.removeClass('nws-row-unread'); }
    });
}
jQuery(document).on('draw.dt', '#sales_transaction', function(){ nws_paint_rows(); });
jQuery(document).ajaxComplete(function(){ nws_paint_rows(); });
jQuery('body').on('click', '.btn-nws-view', function(){
    var $btn = jQuery(this);
    var id = $btn.attr('data-id');
    jQuery('#nws_modal_body').html('Memuat…');
    jQuery('#modal_nws').modal('show');
    jQuery.ajax({
        url: app_url + 'sales_transaction/get_nws_info',
        type: 'POST', dataType: 'JSON', data: { id: id },
        success: function(res) {
            if (res.err_code != 0) { jQuery('#nws_modal_body').html(res.err_message); return; }
            var h = '<p style="margin-bottom:10px;"><b>' + res.code + '</b> · ' + res.customer +
                '<br><small style="color:#888;">Informasi internal — siapkan jawaban bila pelanggan bertanya tentang nota permintaan maaf yang diterima.</small></p>';
            if (res.items.length == 0) { h += '<p>Tidak ada catatan NWS.</p>'; }
            for (var i = 0; i < res.items.length; i++) {
                var it = res.items[i];
                h += '<div style="border:1px solid #e3e8ef;border-radius:8px;padding:8px 10px;margin-bottom:8px;background:#fbfcfe;">';
                h += '<b>No. ' + it.num + ' — ' + (it.product || '(jenis tidak diketahui)') + '</b>';
                h += '<ul style="margin:4px 0 6px 18px;">';
                for (var j = 0; j < it.notes.length; j++) {
                    var n = it.notes[j];
                    h += '<li>' + n.kategori +
                        (n.keterangan ? ' · ' + n.keterangan : '') +
                        (n.posisi ? ' · di bagian ' + n.posisi : '') +
                        (n.note_manual ? ' · "' + n.note_manual + '"' : '') +
                        '</li>';
                }
                h += '</ul>';
                h += '<div style="font-size:12px;color:#5a32a3;background:#f1ecfb;border-radius:6px;padding:6px 8px;">Isi nota: …terdapat <b>' + it.sentence + '</b>…</div>';
                if (it.photo_url) {
                    h += '<div style="margin-top:8px;"><img src="' + it.photo_url + '" style="max-width:150px;max-height:150px;border-radius:8px;border:1px solid #d9c9f2;"><div style="font-size:10px;color:#888;margin-top:3px;">📷 Foto bukti QC</div></div>';
                }
                h += '</div>';
            }
            jQuery('#nws_modal_body').html(h);
            // tandai sudah dibaca -> tombol & baris kembali normal
            jQuery.ajax({ url: app_url + 'sales_transaction/nws_mark_read', type: 'POST', data: { id: id }, success: function(){
                $btn.removeClass('nws-unread').addClass('nws-read');
                nws_paint_rows();
            }});
        },
        error: function() { jQuery('#nws_modal_body').html('Gagal menghubungi server.'); }
    });
});

// ==================================================================
//  POPUP "DETAIL PU" : barang + alasan + foto + status
// ==================================================================
jQuery('body').on('click', '.btn-lihat-pu', function() {
    var id = jQuery(this).attr('data_id');
    show_loading();
    jQuery.ajax({
        url: app_url + 'sales_transaction/get_pu_list',
        type: 'POST',
        dataType: 'JSON',
        data: { id: id },
        success: function(response) {
            hide_loading();
            if (response.err_code == 0) {
                var items = response.items || [];
                var h = '<div style="max-height:420px;overflow:auto;">';
                h += '<table class="table table-condensed table-bordered">';
                h += '<tr><th width="10px">No</th><th>Barang</th><th>Alasan PU</th><th>Catatan</th><th width="90px">Foto</th><th>Est. Selesai</th><th>Status</th></tr>';
                if (items.length == 0) {
                    h += '<tr><td colspan="7" align="center">Tidak ada barang PU.</td></tr>';
                } else {
                    for (var i = 0; i < items.length; i++) {
                        var it = items[i];
                        var stLabel = '';
                        if (it.status == 2)      stLabel = '<span class="label label-success">Sudah Dikirim</span>';
                        else if (it.status == 1) stLabel = '<span class="label label-info">Selesai / Siap Kirim</span>';
                        else                     stLabel = '<span class="label label-warning">Proses Ulang</span>';

                        var foto = '-';
                        if (it.photo_url !== '') {
                            foto = '<a href="' + it.photo_url + '" target="_blank">'
                                 + '<img src="' + it.photo_url + '" style="width:80px;height:60px;object-fit:cover;border-radius:6px;border:1px solid #ddd;">'
                                 + '</a>';
                        }
                        h += '<tr>'
                           + '<td align="center">' + (i+1) + '</td>'
                           + '<td><b>' + it.product_name + '</b><br><small>(' + it.item_code + ')</small></td>'
                           + '<td>' + it.reason + '</td>'
                           + '<td>' + (it.trx_note || '-') + '</td>'
                           + '<td align="center">' + foto + '</td>'
                           + '<td>' + it.est + '</td>'
                           + '<td align="center">' + stLabel + '</td>'
                           + '</tr>';
                    }
                }
                h += '</table></div>';
                bootbox.alert({ title: 'Detail Barang Proses Ulang (PU)', message: h });
            } else {
                bootbox.alert(response.err_message);
            }
        },
        error: function() { hide_loading(); }
    });
});