"use strict";

// Class definition
var buyer = function () {
    let datatable;
    let table;
    let modalElement = document.getElementById('kt_modal_add_customer');
    let modalForm = modalElement.querySelector('#kt_modal_add_customer_form');
    let modal = new bootstrap.Modal(modalElement);
    let changingRow;
    let modalShowed = false;
    let currentPage = 0;
    // Public methods
    let initList = () => {
        // Init datatable --- more info on datatables: https://datatables.net/manual/
        datatable = $(table).DataTable({
            language: {
                url: '/media/fa.json'
            },
            "info": false,
            'order': [],
            'columnDefs': [
                {orderable: false, targets: 0}, // Disable ordering on column 0 (checkbox)
            ],
            'columns': [
                {"data": "id", "name": "Id", 'visible': true},
                {"data": "taxType", "name": "TaxType", 'visible': false},
                {"data": "nam", "name": "Nam", 'visible': true},
                {
                    "data": "active", "name": "Active", 'visible': true,
                    render: function (data) {
                        if (data == 0) {
                            return '<span class="badge badge-danger">غیرفعال</span>';
                        } else {
                            return '<span class="badge badge-success">فعال</span>';
                        }
                    }
                },
                {
                    "data": "taxTypeText", "name": "TaxTypeText", 'visible': 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;
                        }
                    },
                },
            ],
            stateSave: true,
            paging: true,
            autoWidth: true,
            processing: true,
            serverSide: true,
            scrollY: "50vh",
            scrollX: true,
            scrollCollapse: true,
            fixedHeader: true,
            filter: true,
            ajax: {
                url: "?handler=GetData",
                type: "POST",
                datatype: "json",
                headers: {"RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()},
                data: function (outData) {
                    return outData;
                },
                dataFilter: function (inData) {
                    return inData;
                },
                error: function (err, status) {
                    console.log(err);
                },
            },
            pageLength: 50,
        });

        // When a cell in the table is edited, send the updated data to the server
        // $('#customers_table td[contenteditable=true]').blur(function () {
        //     var row = $(this).parents('tr')[0];
        //     var data = {
        //         name: row.cells[1].innerText,
        //         age: row.cells[2].innerText,
        //         email: row.cells[3].innerText,
        //         userType: row.cells[4].querySelector('select[name="user-type"]').value
        //     };
        //     $.ajax({
        //         type: 'POST',
        //         url: '/update',
        //         data: data,
        //         success: function (response) {
        //             console.log(response);
        //         }
        //     });
        // });
        //

        $(document).on('dblclick', 'table tr', function () {
            var rowId = $(this).closest('tr').attr('data-edit-item');
            currentPage = datatable.page();

            let id = this.dataset['editItem'];
            let row = $(this).closest('tr');
            changingRow = row;
            let data = datatable.row(row).data();
            if (data.taxType) {
                let employeeOption = new Option(data.taxTypetext, data.taxType, false, true);
                let existingOption = $('#taxTypeSelect').find('option[value="' + data.taxType + '"]');
                if (existingOption.length) {
                    // If the option exists, select it and trigger the change event
                    existingOption.prop('selected', true);
                    $('#taxTypeSelect').trigger('change');
                } else {
                    // If the option doesn't exist, append it and select it
                    $('#taxTypeSelect').append(employeeOption);
                    employeeOption.prop('selected', true);
                }
            }

            modalForm.querySelector('[name="id"]').value = data.id;
            modal.show();
        });

    }
    // Search Datatable --- official docs reference: https://datatables.net/reference/api/search()
    const handleSearchDatatable = () => {
        const filterSearch = document.querySelector('[data-kt-customer-table-filter="search"]');
        filterSearch.addEventListener('keyup', function (e) {
            datatable.search(e.target.value).draw();
        });
    }
    const handleStatusFilter = () => {
        const filterStatus = document.querySelector('[data-filter="active_good"]');

        $(filterStatus).on('change', e => {
            let value = e.target.checked;
            datatable.column(3).search(value).draw();
        });
        const withoutIdentifier = document.querySelector('[data-filter="without_identifier"]');
        $(withoutIdentifier).on('change', e => {
            let value = e.target.checked;
            datatable.column(4).search(value).draw();
        });
    }
    let handleEdit = () => {
        let editButton = table.querySelectorAll('[data-edit-item1]');
        editButton.forEach((index) => {
            index.addEventListener('click', function (e) {
                e.preventDefault();

                let id = this.dataset['editItem'];
                let row = $(this).closest('tr');
                changingRow = row;
                let data = datatable.row(row).data();
                if (data.taxType) {
                    let employeeOption = new Option(data.taxTypeText, data.taxType, false, true);

                    let existingOption = $('#taxTypeSelect').find('option[value="' + data.taxType + '"]');
                    if (existingOption.length) {
                        // If the option exists, select it and trigger the change event
                        existingOption.prop('selected', true);
                        $('#taxTypeSelect').trigger('change');
                    } else {
                        // If the option doesn't exist, append it and select it
                        $('#taxTypeSelect').append(employeeOption);
                        employeeOption.prop('selected', true);
                    }

                }

                modalForm.querySelector('[name="id"]').value = data.id;
                modal.show();
            });
        });
        $(modalElement).on('hidden.bs.modal',
            function () {
                modalShowed = false;
            });
        let submitBtn = modalElement.querySelector('#kt_modal_add_customer_submit');
        submitBtn.addEventListener('click', function (e) {
            e.preventDefault();

            let id = $('#taxTypeSelect').select2('data')[0].id;
            if (id > 0) {
                if (!changingRow)
                    return;
                let text = $('#taxTypeSelect').select2('data')[0].text;
                datatable.cell(changingRow, 3).data(text).draw();
                datatable.cell(changingRow, 1).data(id).draw();

                modal.hide();
                modalShowed = false;

                $.ajax({
                    url: '?handler=UpdateCustomer',
                    method: 'POST',
                    data: {id: modalForm.querySelector('[name="id"]').value, taxType: id},
                    headers: {"RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()},
                    success: function (res) {
                        if (res == true) {
                            toastr.success('تغییرات اعمال شد')
                            datatable.page(currentPage).draw('page');
                        } else
                            toastr.error('عدم ثبت تغییرات')
                    },
                    error: function (err) {
                        console.log(err);
                    }
                })
                //submit to server
            }
        });
        // $(document).on("keydown", function (event) {
        //
        //     if (modalShowed)
        //         return;
        //     // if (event.which == 46)
        //     //     alert("delete is pressed at row level");
        //
        //     if (!datatable) return;
        //     let index = datatable.$('.selected').index();
        //
        //     switch (event.which) {
        //         case 38:
        //             //event.preventDefault();
        //             //up
        //             if (index > 0) {
        //
        //                 //datatable.row(`:eq(${index - 1})`, { page: 'current' }).select();
        //                 datatable.row(`:eq(${index - 1})`).select();
        //                 datatable.cell(datatable.row(`:eq(${index - 1})`), 0).focus();
        //                 $('dataTable').focus();
        //             }
        //             break;
        //         case 40:
        //             //event.preventDefault();
        //             //if (datatable.rows().eq(0).length > 0)
        //             if (datatable.data().count() > 0) {
        //                 //datatable.row(`:eq(${index + 1})`, { page: 'current' }).select().focus();
        //                 datatable.row(`:eq(${index + 1})`).select();
        //                 datatable.cell(datatable.row(`:eq(${index + 1})`), 0).focus();
        //                 $('dataTable').focus();
        //             }
        //
        //             break;
        //         case 67: {
        //             event.preventDefault();
        //             if (index < 0)
        //                 return;
        //             const idCost = modalForm.querySelector('[name="IdList"]').value;
        //             let row = datatable.$('.selected');
        //             changingRow = row;
        //             let tempId = row.data('tempid');
        //             let data = datatable.row(row).data();
        //
        //             //datatable.column(0).cells(7).data('New value for row 2 column 1');
        //             //datatable.column(0).cells('nameCharge').invalidate().render();
        //             //datatable.cell({ row: 0, column: 'nameCharge' }).data('New value for row 2 column 1');
        //             // load record for edit
        //
        //             let chargeOption = new Option(data.nameCharge, data.idCharge, false, true);
        //             $('#chargeSelector').append(chargeOption).trigger('change');
        //
        //             modalChargeBootstrap.show();
        //             modalShowed = true;
        //             datatable.row(`:eq(${index})`).select();
        //             datatable.cell(datatable.row(`:eq(${index})`), 0).focus();
        //             $('dataTable').focus();
        //         }
        //
        //             break;
        //         case 13:
        //
        //             event.preventDefault();
        //             if ($('#chargeSelector').select2('data')[0]) {
        //                 let id = $('#chargeSelector').select2('data')[0].id;
        //                 if (id > 0) {
        //                     if (!index)
        //                         return;
        //                     let text = $('#chargeSelector').select2('data')[0].text;
        //
        //                     datatable.cell(index, 7).data(text).draw();
        //                     datatable.cell(index, 3).data(id).draw();
        //                     //datatable.row(`:eq(${index})`, { page: 'current' }).select();
        //                     datatable.row(`:eq(${index})`).select();
        //                     datatable.cell(datatable.row(`:eq(${index})`), 0).focus();
        //
        //                 }
        //             }
        //             $('dataTable').focus();
        //             break;
        //     }
        //
        // });
    }
    return {
        init: function () {
            table = document.querySelector('#customers_table');

            if (!table) {
                return;
            }
            initList();
            handleSearchDatatable();
            handleEdit();
            handleStatusFilter();
        }
    };
}();

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


//
// function editRow(button) {
//     var row = button.parentNode.parentNode;
//     // var cells = row.getElementsByTagName("td");
//     var cells =$(row).find('td[contenteditable=true]');
//     for (var i = 0; i < cells.length - 1; i++) {
//         // cells[i].setAttribute("contenteditable", "true");
//         cells[i].style.backgroundColor = "lightgray";
//     }
//     button.innerHTML = "ذخیره";
//     button.onclick = function() { saveRow(this); };
// }
//
// function saveRow(button) {
//     var row = button.parentNode.parentNode;
//     var cells = row.getElementsByTagName("td");
//     var data = {
//         "firstName": cells[0].innerHTML,
//         "lastName": cells[1].innerHTML,
//         "age": cells[2].innerHTML
//     };
//     fetch('/api/UpdateData', {
//         method: 'POST',
//         body: JSON.stringify(data),
//         headers: {
//             'Content-Type': 'application/json'
//         }
//     })
//         .then(response => response.json())
//         .then(data => console.log(data))
//         .catch(error => console.error(error));
//     for (var i = 0; i < cells.length - 1; i++) {
//         // cells[i].setAttribute("contenteditable", "false");
//         cells[i].style.backgroundColor = "white";
//     }
//     button.innerHTML = "ویرایش";
//     button.onclick = function() { editRow(this); };
// }
