<script>
// =====================================================
// BUKU KAS PRODUKSI - JavaScript
// =====================================================

// ---------- Helper: isi dropdown ITEM di MODAL sesuai tipe ----------
function pcb_populate_modal_items(selected_id) {
    var type = jQuery('#f_type').val();
    var html = '<option value="">Pilih Item</option>';
    var count = 0;
    jQuery.each(CASH_ITEMS, function(i, item) {
        if (item.type == type) {
            html += '<option value="' + item.id + '">' + item.name + '</option>';
            count++;
        }
    });
    if (count == 0) {
        html += '<option value="" disabled>-- Belum ada item untuk tipe ini --</option>';
    }
    jQuery('#f_item').html(html);
    if (selected_id) { jQuery('#f_item').val(selected_id); }
}

// ---------- Helper: isi dropdown ITEM di FILTER (terpisah pemasukan/pengeluaran) ----------
function pcb_populate_filter_items(selected_id) {
    var type = jQuery('#type_filter').val();
    var html = '<option value="">Semua Item</option>';
    if (type == '') {
        var inc = '', exp = '';
        jQuery.each(CASH_ITEMS, function(i, item) {
            if (item.type == 'debit') { inc += '<option value="' + item.id + '">' + item.name + '</option>'; }
            else { exp += '<option value="' + item.id + '">' + item.name + '</option>'; }
        });
        html += '<optgroup label="── PEMASUKAN ──">' + inc + '</optgroup>';
        html += '<optgroup label="── PENGELUARAN ──">' + exp + '</optgroup>';
    } else {
        jQuery.each(CASH_ITEMS, function(i, item) {
            if (item.type == type) { html += '<option value="' + item.id + '">' + item.name + '</option>'; }
        });
    }
    jQuery('#iditem_filter').html(html);
    if (selected_id) { jQuery('#iditem_filter').val(selected_id); }
}

// ---------- Helper: ambil iduser yang aktif ----------
function pcb_get_iduser() {
    if (PCB_IS_ADMIN) {
        return jQuery('#iduser_filter').val() || '';
    }
    return PCB_MY_ID;
}

// ---------- Helper: konversi tanggal d-m-Y -> Y-m-d untuk input type=date ----------
function pcb_to_date_input(val) {
    var p = val.split('-');
    if (p.length == 3 && p[0].length == 2) { return p[2] + '-' + p[1] + '-' + p[0]; }
    return val;
}

// ---------- Helper: preview foto ----------
function pcb_read_preview(input, target) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            jQuery(target).html('<img src="' + e.target.result + '" style="width:90px;height:90px;object-fit:cover;margin-top:5px;border:1px solid #ddd;padding:2px;">');
        };
        reader.readAsDataURL(input.files[0]);
    }
}

// ---------- Load data tabel ----------
function load_data() {
    var iduser_filter = pcb_get_iduser();

    if (iduser_filter == '') {
        jQuery('#table_cash_book tbody').html('<tr><td colspan="10" align="center">Pilih user produksi terlebih dahulu</td></tr>');
        jQuery('#txt_opening').text('Rp 0');
        jQuery('#txt_total_debit').text('Rp 0');
        jQuery('#txt_total_credit').text('Rp 0');
        jQuery('#txt_closing').text('Rp 0');
        return;
    }

    show_loading();
    jQuery.ajax({
        url: app_url + 'production_cash_book/get_data',
        type: 'POST',
        dataType: 'JSON',
        data: {
            date_1: jQuery('#date_1').val(),
            date_2: jQuery('#date_2').val(),
            iduser_filter: iduser_filter,
            iditem_filter: jQuery('#iditem_filter').val(),
            type_filter: jQuery('#type_filter').val()
        },
        success: function(response) {
            hide_loading();
            if (response.err_code == 0) {
                pcb_render_table(response);
            } else {
                bootbox.alert(response.err_message);
            }
        },
        error: function() { hide_loading(); }
    });
}

// ---------- Render tabel ----------
function pcb_render_table(response) {
    jQuery('#txt_opening').text('Rp ' + response.opening_balance);
    jQuery('#txt_total_debit').text('Rp ' + response.total_debit);
    jQuery('#txt_total_credit').text('Rp ' + response.total_credit);
    jQuery('#txt_closing').text('Rp ' + response.closing_balance);

    var tbody = '';
    if (!response.data || response.data.length == 0) {
        tbody = '<tr><td colspan="10" align="center">Tidak ada data</td></tr>';
    } else {
        jQuery.each(response.data, function(i, row) {
            tbody += '<tr>';
            tbody += '<td align="center">' + row.no + '</td>';
            tbody += '<td align="center">' + row.date + '</td>';
            tbody += '<td align="center">' + row.time + '</td>';
            tbody += '<td>' + (row.item_name ? row.item_name : '-') + '</td>';
            tbody += '<td>' + (row.description ? row.description : '-') + '</td>';
            tbody += '<td align="right">' + row.debit + '</td>';
            tbody += '<td align="right">' + row.credit + '</td>';
            tbody += '<td align="right"><b>' + row.balance + '</b></td>';
            tbody += '<td>' + row.photos + '</td>';
            tbody += '<td align="center">';
            if (row.can_edit) {
                tbody += '<button class="btn btn-xs btn-default btn-edit-cash" data-id="' + row.id + '" title="Edit"><i class="fa fa-pencil"></i></button> ';
            }
            if (row.can_delete) {
                tbody += '<button class="btn btn-xs btn-danger btn-delete-cash" data-id="' + row.id + '" title="Hapus"><i class="fa fa-trash"></i></button>';
            }
            tbody += '</td>';
            tbody += '</tr>';
        });
    }
    jQuery('#table_cash_book tbody').html(tbody);
}

// ---------- Parameter untuk print / pdf ----------
function pcb_get_filter_params() {
    var params = 'date_1=' + encodeURIComponent(jQuery('#date_1').val());
    params += '&date_2=' + encodeURIComponent(jQuery('#date_2').val());
    params += '&iduser_filter=' + encodeURIComponent(pcb_get_iduser());
    params += '&iditem_filter=' + encodeURIComponent(jQuery('#iditem_filter').val() || '');
    params += '&type_filter=' + encodeURIComponent(jQuery('#type_filter').val() || '');
    return params;
}

// =====================================================
// INIT
// =====================================================
pcb_populate_filter_items();
pcb_populate_modal_items();
load_data();

// ---------- Event filter ----------
jQuery('#btn_filter').on('click', function() { load_data(); });
jQuery('#type_filter').on('change', function() { pcb_populate_filter_items(); load_data(); });
jQuery('#iditem_filter').on('change', function() { load_data(); });
jQuery('#iduser_filter').on('change', function() { load_data(); });

// ---------- Event modal: tipe berubah -> item ikut terfilter ----------
jQuery('#f_type').on('change', function() { pcb_populate_modal_items(); });

// ---------- Event modal: preview foto ----------
jQuery('#f_photo1').on('change', function() { pcb_read_preview(this, '#preview_photo1'); });
jQuery('#f_photo2').on('change', function() { pcb_read_preview(this, '#preview_photo2'); });
jQuery('#f_photo3').on('change', function() { pcb_read_preview(this, '#preview_photo3'); });

// ---------- Tombol TAMBAH TRANSAKSI ----------
jQuery('#btn_add_transaction').on('click', function() {
    var iduser = pcb_get_iduser();
    if (iduser == '') {
        bootbox.alert('Pilih user produksi terlebih dahulu');
        return;
    }
    jQuery('#form_transaction')[0].reset();
    jQuery('#f_id').val('');
    jQuery('#f_iduser').val(iduser);
    jQuery('#f_date').val(PCB_TODAY);
    jQuery('#preview_photo1, #preview_photo2, #preview_photo3').html('');
    pcb_populate_modal_items();
    show_modal('transaction');
});

// ---------- Tombol EDIT ----------
jQuery('body').on('click', '.btn-edit-cash', function() {
    var id = jQuery(this).attr('data-id');
    show_loading();
    jQuery.ajax({
        url: app_url + 'production_cash_book/edit',
        type: 'POST',
        dataType: 'JSON',
        data: { id: id },
        success: function(response) {
            hide_loading();
            if (response.err_code == 0) {
                var d = response.data;
                jQuery('#f_id').val(d.idproduction_cash_book);
                jQuery('#f_iduser').val(d.iduser);
                jQuery('#f_date').val(pcb_to_date_input(d.transaction_date));
                jQuery('#f_type').val(d.transaction_type);
                pcb_populate_modal_items(d.idproduction_cash_item);
                jQuery('#f_amount').val(d.amount);
                jQuery('#f_description').val(d.description);
                // Preview foto lama
                for (var i = 1; i <= 3; i++) {
                    var ph = d['photo' + i];
                    if (ph && ph.length > 0) {
                        jQuery('#preview_photo' + i).html('<img src="' + PCB_ASSET_URL + ph + '" style="width:90px;height:90px;object-fit:cover;margin-top:5px;border:1px solid #ddd;padding:2px;cursor:pointer;" onclick="window.open(this.src)">');
                    } else {
                        jQuery('#preview_photo' + i).html('');
                    }
                }
                show_modal('transaction');
            } else {
                bootbox.alert(response.err_message);
            }
        },
        error: function() { hide_loading(); }
    });
});

// ---------- Tombol HAPUS ----------
jQuery('body').on('click', '.btn-delete-cash', function() {
    var id = jQuery(this).attr('data-id');
    bootbox.confirm('Yakin ingin menghapus transaksi ini?', function(result) {
        if (result) {
            show_loading();
            jQuery.ajax({
                url: app_url + 'production_cash_book/delete',
                type: 'POST',
                dataType: 'JSON',
                data: { id: id },
                success: function(response) {
                    hide_loading();
                    if (response.err_code == 0) {
                        load_data();
                    } else {
                        bootbox.alert(response.err_message);
                    }
                },
                error: function() { hide_loading(); }
            });
        }
    });
});

// ---------- Tombol SIMPAN (di modal) ----------
jQuery('body').on('click', '.btn-action-save-transaction', function() {
    var id     = jQuery('#f_id').val();
    var iduser = jQuery('#f_iduser').val();
    var date   = jQuery('#f_date').val();
    var item   = jQuery('#f_item').val();
    var amount = jQuery('#f_amount').val();
    var desc   = jQuery('#f_description').val();

    // Validasi sisi klien
    if (PCB_IS_ADMIN && iduser == '') { bootbox.alert('Pilih user produksi terlebih dahulu'); return; }
    if (date == '') { bootbox.alert('Tanggal wajib diisi'); return; }
    if (item == '') { bootbox.alert('Item kas wajib dipilih'); return; }
    if (amount == '' || remove_separator(amount) == '0') { bootbox.alert('Nominal wajib diisi'); return; }
    if (desc == '' || desc == null) { bootbox.alert('Keterangan wajib diisi'); return; }

    // Foto WAJIB untuk transaksi baru
    if (id == '') {
        var total_files = jQuery('#f_photo1')[0].files.length +
                          jQuery('#f_photo2')[0].files.length +
                          jQuery('#f_photo3')[0].files.length;
        if (total_files == 0) {
            bootbox.alert('Foto bukti wajib diupload (minimal 1 foto)');
            return;
        }
    }

    var formData = new FormData(jQuery('#form_transaction')[0]);
    show_loading();
    jQuery.ajax({
        url: app_url + 'production_cash_book/save',
        type: 'POST',
        data: formData,
        dataType: 'JSON',
        processData: false,
        contentType: false,
        success: function(response) {
            hide_loading();
            if (response.err_code == 0) {
                hide_modal('transaction');
                load_data();
                bootbox.alert('Transaksi berhasil disimpan');
            } else {
                bootbox.alert(response.err_message);
            }
        },
        error: function() {
            hide_loading();
            bootbox.alert('Gagal menyimpan data. Periksa kembali koneksi / ukuran foto.');
        }
    });
});

// ---------- Tombol PRINT ----------
jQuery('#btn_print').on('click', function() {
    if (pcb_get_iduser() == '') { bootbox.alert('Pilih user produksi terlebih dahulu'); return; }
    window.open(app_url + 'production_cash_book/print_report/?' + pcb_get_filter_params(), '_blank');
});

// ---------- Tombol DOWNLOAD PDF ----------
jQuery('#btn_pdf').on('click', function() {
    if (pcb_get_iduser() == '') { bootbox.alert('Pilih user produksi terlebih dahulu'); return; }
    window.open(app_url + 'production_cash_book/download_pdf/?' + pcb_get_filter_params(), '_blank');
});
</script>