"use strict";

// Class definition
var products = function () {
    let datatable;
    let table;

    let initDatatable=()=>{
        datatable = $(table).DataTable({
            language: {
                url: '/media/fa.json'
            },
            ajax: {
                url: "?handler=GetData",
                type: "POST",
                datatype: "json",
                headers: {"RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()},
                data: function (outData) {
                    // what is being sent to the server
                    // console.log(outData);
                    return outData;
                },
                dataFilter: function (inData) {
                    // what is being sent back from the server (if no error)
                    // console.log(JSON.parse(inData));
                    return inData;
                },
                error: function (err, status) {
                    // what error is seen(it could be either server side or client side.
                    console.log(err);
                },
            },
            pageLength: 50,
            stateSave: true,
            autoWidth: true,
            processing: true,
            serverSide: true,
            scrollY: "300px",
            scrollX: true,
            scrollCollapse: true,
            fixedHeader: true,
            filter: true,
            order: [],
            columns: [
                {data: "id", name: "Id", autoWidth: true},
                {data: "nam", name: "Nam", autoWidth: false},
                {data: "taxVahedId", name: "Barcode", autoWidth: true,'sortable':false,
                    "render": function(data, type, row) {
                        if (!data) {
                            return '<i class="fa fa-search"></i>'; // Replace with your search icon HTML
                        } else {
                            return data;
                        }},
                },
                     ],
        });
      
// Listen for double click event on the second column of the table
        $(document).on('dblclick', 'table tr td:nth-child(3)', function() {
            // Store the current value of the cell
            var oldValue = $(this).text().trim();
            // Replace the cell contents with an input field containing the old value
            $(this).html(' <input type="number" min="0"  style="-moz-appearance: textfield; -webkit-appearance: none; appearance: none;" oninput="this.value = this.value.replace(/[^0-9]/g, \'\').replace(/^0+(?!\\.|$)/, \'\')" class="form-control" value="' + oldValue + '">');
            // Focus on the input field
            $(this).find('input').focus();
        });

// Listen for focusout event on the input field within the second column
        $(document).on('focusout keypress', 'table tr td:nth-child(3) input', function(event) {
            if (event.type === 'keypress' && event.which !== 13) {
                return; // Ignore keypress events other than Enter
            }
            // Get the new value from the input field
            var newValue = $(this).val().trim();
            // Get the ID of the corresponding row
            var rowId = $(this).closest('tr').attr('data-id');
            var row = $(this).closest('tr')[0];
            if(!newValue) {
                $(row).find('td:nth-child(3)').html(newValue);
                return;
            }

            $.ajax({
                type: 'POST',
                url: '?handler=UpdateProduct',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                data: { id: row.cells[0].innerText, value: newValue },
                success: function(data) {
                    // Replace the input field with the new value
                    // $('table tr[data-id="' + rowId + '"] td:nth-child(4)').text(newValue);
                    $(row).find('td:nth-child(3)').html(newValue);
                    if(data==true)
                        toastr.success('تغییرات اعمال شد')
                    else
                        toastr.error('عدم ثبت تغییرات')
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log('Error: ' + textStatus + ' - ' + errorThrown);
                }
            });
        });
        // datatable.buttons(0, null).container().insertAfter($('#button_container'));
        datatable.columns().every(function () {
            let that = this;
            $('[data-product-table-filter="search"] input').on('keyup change', function () {
                if (that.search() == this.value) {
                    that.search(this.value).draw();
                }
            });
        });

    }
    var handleSearchDatatable = () => {
        const filterSearch = document.querySelector('[data-product-table-filter="search"]');
        filterSearch.addEventListener('keyup', function (e) {
            datatable.search(e.target.value).draw();
        });
    }
    return {
        init: function () {
            table = document.querySelector('#products_table');

            if (!table) {
                return;
            }
            initDatatable();
            handleSearchDatatable();
        }
    };
}();

// On document ready
KTUtil.onDOMContentLoaded(function () {
    products.init();
});
